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>#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function import sublime from sublime import Region from sublime_plugin import WindowCommand, TextCommand, EventListener import os, re, shutil, tempfile, subprocess, itertools, sys, threading, glob from os.path import basename, dirname, isdir, isfile, exists, join, isabs, normpath, normcase ST3 = int(sublime.version()) >= 3000 if ST3: from .common import RE_FILE, DiredBaseCommand from . import prompt from .show import show from .show import set_proper_scheme from .jumping import jump_names MARK_OPTIONS = sublime.DRAW_NO_OUTLINE try: import Default.send2trash as send2trash except ImportError: send2trash = None else: # ST2 imports import locale from common import RE_FILE, DiredBaseCommand import prompt from show import show from show import set_proper_scheme from jumping import jump_names MARK_OPTIONS = 0 try: import send2trash except ImportError: send2trash = None PARENT_SYM = u"⠤" def print(*args, **kwargs): """ Redefine print() function; the reason is the inconsistent treatment of unicode literals among Python versions used in ST2. Redefining/tweaking built-in things is relatively safe; of course, when ST2 will become irrelevant, this def might be removed undoubtedly. """ if not ST3 and sublime.platform() != 'windows': args = (s.encode('utf-8') if isinstance(s, unicode) else str(s) for s in args) else: args = (s if isinstance(s, str if ST3 else unicode) else str(s) for s in args) sep, end = kwargs.get('sep', ' '), kwargs.get('end', '\n') sys.stdout.write(sep.join(s for s in args) + end) def reuse_view(): return sublime.load_settings('dired.sublime-settings').get('dired_reuse_view', False) def hijack_window(): settings = sublime.load_settings('dired.sublime-settings') command = settings.get("dired_hijack_new_window") if command: if command == "jump_list": sublime.set_timeout(lambda: sublime.windows()[-1].run_command("dired_jump_list"), 1) else: sublime.set_timeout(lambda: sublime.windows()[-1].run_command("dired", {"immediate": True}), 1) def plugin_loaded(): if len(sublime.windows()) == 1 and len(sublime.windows()[0].views()) == 0: hijack_window() window = sublime.active_window() if not ST3: global recursive_plugin_loaded # recursion limit is 1000 generally, so it will try to refresh for 100*1000 ms (100 s) # if no active_window in 100 s, then no refresh # if view still loading, refresh fail because view cant be edited if not window or any(view.is_loading() for view in window.views()): recursive_plugin_loaded += 1 try: return sublime.set_timeout(plugin_loaded, 100) except RuntimeError: print('\ndired.plugin_loaded run recursively %d time(s); and failed to refresh\n'%recursive_plugin_loaded) return for v in window.views(): if v.settings() and v.settings().get("dired_path"): v.run_command("dired_refresh") # if not ST3: # print('\ndired.plugin_loaded run recursively %d time(s); and call refresh command\n'%recursive_plugin_loaded) if not ST3: recursive_plugin_loaded = 1 plugin_loaded() class DiredCommand(WindowCommand): """ Prompt for a directory to display and display it. """ def run(self, immediate=False, single_pane=False, project=False, other_group=False): path, goto = self._determine_path() if project: folders = self.window.folders() if len(folders) == 1: path = folders[0] elif folders: names = [basename(f) for f in folders] longest_name = max([len(n) for n in names]) for i, f in enumerate(folders): name = names[i] offset = ' ' * (longest_name - len(name) + 1) names[i] = u'%s%s%s' % (name, offset, self.display_path(f)) self.window.show_quick_panel(names, lambda i: self._show_folder(i, path, goto, single_pane, other_group), sublime.MONOSPACE_FONT) return if immediate: show(self.window, path, goto=goto, single_pane=single_pane, other_group=other_group) else: prompt.start('Directory:', self.window, path, self._show) def _show_folder(self, index, path, goto, single_pane, other_group): if index != -1: choice = self.window.folders()[index] if path == choice: show(self.window, path, goto=goto, single_pane=single_pane, other_group=other_group) else: show(self.window, choice, single_pane=single_pane, other_group=other_group) def _show(self, path): show(self.window, path) def _determine_path(self): '''Return (path, fname) so goto=fname to set cursor''' # Use the current view's directory if it has one. view = self.window.active_view() path = view and view.file_name() if path: return os.path.split(path) # Use the first project folder if there is one. data = self.window.project_data() if ST3 else None if data and 'folders' in data: folders = data['folders'] if folders: return (folders[0]['path'], None) # Use window folder if possible folders = self.window.folders() if len(folders) > 0: return (folders[0], None) # Use the user's home directory. return (os.path.expanduser('~'), None) def display_path(self, folder): display = folder home = os.path.expanduser("~") if folder.startswith(home): display = folder.replace(home, "~", 1) return display class DiredRefreshCommand(TextCommand, DiredBaseCommand): """ Populates or repopulates a dired view. """ def run(self, edit, goto=None, to_expand=None, toggle=None): """ goto Optional filename to put the cursor on; used only from "dired_up" to_expand List of relative paths for direcories which shall be expanded toggle If true, marked/selected directories shall switch state, i.e. expand/collapse """ path = self.path self.sel = None expanded = self.view.find_all(u'^\s*▾') if not goto else [] names = [] if path == 'ThisPC\\': path = '' for s in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': disk = '%s:' % s if isdir(disk): names.append(disk) if expanded or to_expand: self.re_populate_view(edit, path, names, expanded, to_expand, toggle) else: if not path: self.continue_refreshing(edit, path, names) else: self.populate_view(edit, path, names, goto) def re_populate_view(self, edit, path, names, expanded, to_expand, toggle): root = path for i, r in enumerate(expanded): line = self.view.line(r) full_name = self._remove_ui(self.get_parent(line, self.view.substr(line))) expanded[i] = full_name.rstrip(os.sep) if toggle and to_expand: merged = list(set(expanded + to_expand)) expanded = [e for e in merged if not (e in expanded and e in to_expand)] else: expanded.extend(to_expand or []) if any(e for e in expanded if e == path.rstrip(os.sep)): # e.g. c:\ was expanded and user press enter on it return self.populate_view(edit, path, names, goto=None) self.show_hidden = self.view.settings().get('dired_show_hidden_files', True) tree = self.traverse_tree(root, root, '', names, expanded) if tree: self.set_status() text, _ = self.set_title(path) if root and self.show_parent(): text.extend(PARENT_SYM) text.extend(tree) marked = set(self.get_marked()) sels = self.get_selected() self.view.set_read_only(False) self.view.erase(edit, Region(0, self.view.size())) self.view.insert(edit, 0, '\n'.join(text)) self.view.set_read_only(True) fileregion = self.fileregion() count = len(self.view.lines(fileregion)) if fileregion else 0 self.view.settings().set('dired_count', count) self.restore_marks(marked) self.restore_sels(sels) CallVCS(self.view, path) else: return self.populate_view(edit, path, names, goto=None) def populate_view(self, edit, path, names, goto): try: if goto and goto[~0]==':': # c:\\ valid path, c: not valid goto += os.sep names = os.listdir(path) except OSError as e: error = str(e).split(':')[0].replace('[Error 5] ', 'Access denied') self.view.run_command("dired_up") self.view.set_read_only(False) self.view.insert(edit, self.view.line(self.view.sel()[0]).b, '\t<%s>' % error) self.view.set_read_only(True) else: self.continue_refreshing(edit, path, names, goto) CallVCS(self.view, path) def continue_refreshing(self, edit, path, names, goto=None, indent=''): self.set_status() f = self.prepare_filelist(names, path, '', '') marked = set(self.get_marked()) text, header = self.set_title(path) if path and (not f or self.show_parent()): text.append(PARENT_SYM) text.extend(f) self.view.set_read_only(False) self.view.erase(edit, Region(0, self.view.size())) self.view.insert(edit, 0, '\n'.join(text)) self.view.settings().set('dired_count', len(f)) self.view.set_read_only(True) self.restore_marks(marked) # Place the cursor. if f: pt = self.fileregion(with_parent_link=True).a if goto: if isdir(join(path, goto)) and not goto.endswith(os.sep): goto = u"▸ " + goto + os.sep else: goto = u"≡ " + goto try: line = f.index(goto) + (2 if header else 0) + (1 if self.show_parent() else 0) pt = self.view.text_point(line, 2) except ValueError: pass self.view.sel().clear() self.view.sel().add(Region(pt, pt)) self.view.show_at_center(Region(pt, pt)) elif not f: # empty folder? pt = self.view.text_point(2, 0) self.view.sel().clear() self.view.sel().add(Region(pt, pt)) else: self.view.sel().clear() self.view.sel().add(Region(name_point, name_point)) self.view.show_at_center(name_point) def traverse_tree(self, root, path, indent, tree, expanded): if not path: # special case for ThisPC, path is empty string files = [u'%s\\'%d for d in tree] tree = [] else: # basename return funny results for c:\\ so it is tricky b = os.path.basename(os.path.abspath(path)) or path.rstrip(os.sep) if root != path and b != os.path.basename(root.rstrip(os.sep)): tree.append(indent[:-1] + u'▾ ' + b + os.sep) try: if not self.show_hidden: files = [name for name in os.listdir(path) if not self.is_hidden(name, path)] else: files = os.listdir(path) except OSError as e: tree[~0] += '\t<%s>' % str(e).split(':')[0].replace('[Error 5] ', 'Access denied') return self.sort_nicely(files) if tree and not files: # expanding empty folder, so notify that it is empty tree[~0] += '\t<empty>' for f in files: new_path = join(path, f) check = isdir(new_path) if check and new_path.replace(root, '', 1).strip(os.sep) in expanded: self.traverse_tree(root, new_path, indent + '\t', tree, expanded) elif check: tree.append(u'%s▸ %s%s' % (indent, f, os.sep if f[~0] != os.sep else '')) else: continue for f in files: if not os.path.isdir(os.path.join(path, f)): tree.append(indent + u'≡ ' + f) return tree def set_status(self): status = u" 𝌆 [?: Help] " # if view isnot focused, view.window() may be None window = self.view.window() or sublime.active_window() path_in_project = any(folder == self.path[:-1] for folder in window.folders()) status += 'Project root, ' if path_in_project else '' show_hidden = self.view.settings().get('dired_show_hidden_files', True) status += 'Hidden: On' if show_hidden else 'Hidden: Off' self.view.set_status("__FileBrowser__", status) def set_title(self, path): header = self.view.settings().get('dired_header', False) name = jump_names().get(path or self.path) caption = u"{0} → {1}".format(name, path) if name else path or self.path text = [ caption, len(caption)*(u'—') ] if header else [] view_name = self.view.name()[:2] if not path: title = u'%s%s' % (view_name, name or 'This PC') else: norm_path = path.rstrip(os.sep) if self.view.settings().get('dired_show_full_path', False): title = u'%s%s (%s)' % (view_name, name or basename(norm_path), norm_path) else: title = u'%s%s' % (view_name, name or basename(norm_path)) self.view.set_name(title) return (text, header) # NAVIGATION ##################################################### class DiredNextLineCommand(TextCommand, DiredBaseCommand): def run(self, edit, forward=None): self.move(forward) class DiredMoveCommand(TextCommand, DiredBaseCommand): def run(self, edit, **kwargs): if kwargs and kwargs["to"]: self.move_to_extreme(kwargs["to"]) return elif kwargs and kwargs["duplicate"]: self.items = self._get_items(self.path) self.cursor = self.view.substr(self.view.line(self.view.sel()[0].a))[2:] self._duplicate(duplicate=kwargs["duplicate"]) else: files = self.get_marked() or self.get_selected() if files: prompt.start('Move to:', self.view.window(), self.path, self._move) def _get_items(self, path): files = self.get_marked() or self.get_selected() path = normpath(normcase(path)) for filename in files: fqn = normpath(normcase(join(self.path, filename))) yield fqn def _move(self, path): if not isabs(path): path = join(self.path, path) if not isdir(path): sublime.error_message(u'Not a valid directory: {0}'.format(path)) return for fqn in self._get_items(path): if fqn != path: shutil.move(fqn, path) self.view.run_command('dired_refresh') def _duplicate(self, duplicate=''): fqn = next(self.items) for i in itertools.count(2): p, n = os.path.split(fqn) cfp = u"{1} {0}.{2}".format(i, join(p, n.split('.')[0]), '.'.join(n.split('.')[1:])) if os.path.isfile(cfp) or os.path.isdir(cfp): pass else: break if duplicate == 'rename': prompt.start('New name:', self.view.window(), os.path.basename(cfp), self._copy_duplicate, rename=(fqn, cfp, self.cursor)) else: self._copy_duplicate(fqn, cfp, 0) def _copy_duplicate(self, fqn, cfp, int): if isdir(fqn): if not isdir(cfp): shutil.copytree(fqn, cfp) else: print(*("\nSkip! Folder with this name exists already:", cfp), sep='\n', end='\n\n') else: if not isfile(cfp): shutil.copy2(fqn, cfp) else: print(*("\nSkip! File with this name exists already:", cfp), sep='\n', end='\n\n') try: if int == 0: self._duplicate() elif int == 1: self._duplicate(duplicate='rename') except StopIteration: self.view.run_command('dired_refresh', {"goto": self.cursor}) class DiredSelect(TextCommand, DiredBaseCommand): def run(self, edit, new_view=0, other_group=0, preview=0, and_close=0, inline=0, toggle=0): path = self.path if inline: filenames = self.get_marked() or self.get_selected(parent=False) if len(filenames) == 1 and filenames[0][~0] == os.sep: return self.expand_single_folder(edit, path, filenames[0], toggle) elif filenames: # working with several selections at once is very tricky, # thus for reliability we should recreate the entire tree # despite it is slower self.view.run_command('dired_refresh', {'to_expand': [f.rstrip(os.sep) for f in filenames], 'toggle': toggle}) return else: return sublime.status_message('Item cannot be expanded') filenames = self.get_selected() if not (new_view or inline) else self.get_marked() or self.get_selected() # If reuse view is turned on and the only item is a directory, refresh the existing view. if not new_view and reuse_view(): fqn = join(path, filenames[0]) if len(filenames) == 1 and isdir(fqn): show(self.view.window(), fqn, view_id=self.view.id()) return elif len(filenames) == 1 and filenames[0] == PARENT_SYM: self.view.window().run_command("dired_up") return w = self.view.window() if other_group or preview or and_close: dired_view = self.view nag = self.view.window().active_group() if not and_close: target_group = self._other_group(w, nag) # set_view_index and focus are not very reliable # just focus target_group should do what we want w.focus_group(target_group) for filename in filenames: fqn = join(path, filename) if exists(fqn): # ignore 'item <error>' if isdir(fqn): show(w, fqn, ignore_existing=new_view) else: if preview: w.open_file(fqn, sublime.TRANSIENT) w.focus_view(dired_view) return # preview is possible for a single file only else: v = w.open_file(fqn) if and_close: w.focus_view(dired_view) w.run_command("close") w.focus_view(v) def _other_group(self, w, nag): ''' creates new group if need and return index of the group where files shall be opened ''' groups = w.num_groups() if groups == 1: w.set_layout({"cols": [0.0, 0.3, 1.0], "rows": [0.0, 1.0], "cells": [[0, 0, 1, 1], [1, 0, 2, 1]]}) if groups <= 4 and nag < 2: group = 1 if nag == 0 else 0 elif groups == 4 and nag >= 2: group = 3 if nag == 2 else 2 else: group = nag - 1 return group def expand_single_folder(self, edit, path, filename, toggle): marked = set(self.get_marked()) sels = self.get_selected() if toggle: line = self.view.line(self.view.get_regions('marked')[0] if marked else list(self.view.sel())[0]) content = self.view.substr(line).lstrip()[0] if content == u'▾': self.view.run_command('dired_fold') return self.view.run_command('dired_fold', {'update': True}) sel = self.view.get_regions('marked')[0] if marked else list(self.view.sel())[0] line = self.view.line(sel) fqn = join(path, filename) if isdir(fqn): self.sel = sel try: names = os.listdir(fqn) except OSError as e: error = str(e).split(':')[0].replace('[Error 5] ', 'Access denied') replacement = '%s\t<%s>' % (self.view.substr(line), error) else: path = self.path if self.path != 'ThisPC\\' else '' replacement = self.prepare_treeview(names, path, fqn, '\t') else: replacement = '%s\t<%s>' % (self.view.substr(line), 'Not exists, press r to refresh') self.view.set_read_only(False) self.view.replace(edit, line, replacement) self.view.set_read_only(True) self.restore_marks(marked) self.restore_sels(sels) CallVCS(self.view, path) class DiredFold(TextCommand, DiredBaseCommand): u''' This command used to fold/erase/shrink (whatever you like to call it) content of some [sub]directory (within current directory, see self.path). There are two cases when this command would be fired: 1. User mean to fold (key ←) 2. User mean to unfold (key →) In first case we just erase region and set dired_count; however, we need to figure out which region to erase: (a) if cursor placed on directory item and next line indented (representing content of the directory) — erase indented line; (b) next line is not indented, but the line of directory item is indented — erase directory item itself; (c) cursor placed on file item which is indented — erase file item. In second case we need to decide if erasing needed or not: (a) if directory was unfolded (as in 1.a) — erase that region, so then it’ll be filled (basically it is like update/refresh), also set dired_count; (b) directory was folded (as in 1.b) — do nothing ''' def run(self, edit, update=''): v = self.view self.marked = None self.seled = self.get_selected() marks = self.view.get_regions('marked') virt_sels = [] if marks: for m in marks: if 'directory' in self.view.scope_name(m.a): virt_sels.append(Region(m.a, m.a)) self.marked = list(set(self.get_marked())) sels = virt_sels lines = [v.line(s.a) for s in reversed(sels or list(v.sel()))] for line in lines: self.fold(edit, v, line, update) if self.marked: self.restore_marks(self.marked) if self.seled: self.restore_sels(self.seled) def fold(self, edit, v, line, update): current_region = v.indented_region(line.b) next_region = v.indented_region(line.b + 2) is_folder = 'directory' in v.scope_name(line.a) folded_subfolder = update and (next_region.contains(line) or next_region.empty() or next_region.contains(current_region)) folded_folder = update and current_region.empty() and next_region.empty() file_item_in_root = not is_folder and current_region.empty() if v.substr(line).endswith('<empty>'): indented_region = v.extract_scope(line.b - 1) elif folded_subfolder or folded_folder or file_item_in_root: return # folding is not supposed to happen, so we exit elif update or (is_folder and not next_region.empty() and not next_region.contains(line)): indented_region = next_region elif not current_region.empty(): indented_region = current_region line = v.line(indented_region.a - 2) else: return # this is not supposed to happen, but it does sometimes name_point = v.extract_scope(line.a).b if 'name' in v.scope_name(name_point): icon_region = Region(name_point - 2, name_point - 1) else: icon_region = Region(line.a, line.a + 1) # do not set count on empty folder if not line.contains(indented_region): dired_count = v.settings().get('dired_count', 0) v.settings().set('dired_count', int(dired_count) - len(v.lines(indented_region))) if indented_region.b == v.size(): # MUST avoid new line at eof indented_region = Region(indented_region.a - 1, indented_region.b) if self.marked or self.seled: folded_name = self._remove_ui(self.get_parent(line, self.view.substr(line))) if self.marked: self.marked.append(folded_name) elif self.seled: self.seled.append(folded_name) v.set_read_only(False) v.replace(edit, icon_region, u'▸') v.erase(edit, indented_region) v.set_read_only(True) class DiredUpCommand(TextCommand, DiredBaseCommand): def run(self, edit): path = self.path parent = dirname(path.rstrip(os.sep)) if parent != os.sep and parent[1:] != ':\\': # need to avoid c:\\\\ parent += os.sep if parent == path and sublime.platform()=='windows': parent = 'ThisPC' elif parent == path: return elif path == 'ThisPC\\': self.view.run_command('dired_refresh') return view_id = (self.view.id() if reuse_view() else None) show(self.view.window(), parent, view_id, goto=basename(path.rstrip(os.sep))) class DiredGotoCommand(TextCommand, DiredBaseCommand): """ Prompt for a new directory. """ def run(self, edit): prompt.start('Goto:', self.view.window(), self.path, self.goto) def goto(self, path): show(self.view.window(), path, view_id=self.view.id()) class DiredFindInFilesCommand(TextCommand, DiredBaseCommand): def run(self, edit): path = self.path if path == 'ThisPC\\': path = '' items = self.get_marked() or self.get_selected() else: items = self.get_marked() where = ', '.join(join(path, p) for p in items) or path or '' args = {"panel": "find_in_files", "where": where, "replace": "", "reverse": "false"} sublime.active_window().run_command("show_panel", args) # MARKING ########################################################### class DiredMarkExtensionCommand(TextCommand, DiredBaseCommand): def run(self, edit): filergn = self.fileregion() if filergn.empty(): return current_item = self.view.substr(self.view.line(self.view.sel()[0].a)) if current_item.endswith('/') or current_item == PARENT_SYM: ext = '' else: ext = current_item.split('.')[-1] pv = self.view.window().show_input_panel('Extension:', ext, self.on_done, None, None) pv.run_command("select_all") def on_done(self, ext): ext = ext.strip() if not ext: return if not ext.startswith('.'): ext = '.' + ext def _markfunc(oldmark, filename): return filename.endswith(ext) and True or oldmark self._mark(mark=_markfunc, regions=self.fileregion()) class DiredMarkCommand(TextCommand, DiredBaseCommand): """ Marks or unmarks files. The mark can be set to '*' to mark a file, ' ' to unmark a file, or 't' to toggle the mark. By default only selected files are marked, but if markall is True all files are marked/unmarked and the selection is ignored. If there is no selection and mark is '*', the cursor is moved to the next line so successive files can be marked by repeating the mark key binding (e.g. 'm'). """ def run(self, edit, mark=True, markall=False, forward=True): assert mark in (True, False, 'toggle') filergn = self.fileregion() if filergn.empty(): return # If markall is set, mark/unmark all files. Otherwise only those that are selected. if markall: regions = [ filergn ] else: regions = self.view.sel() def _toggle(oldmark, filename): return not oldmark if mark == 'toggle': # Special internal case. mark = _toggle self._mark(mark=mark, regions=regions) # If there is no selection, move the cursor forward so the user can keep pressing 'm' # to mark successive files. if not markall and len(self.view.sel()) == 1 and self.view.sel()[0].empty(): self.move(forward) # MANIPULATION ###################################################### class DiredCreateCommand(TextCommand, DiredBaseCommand): def run(self, edit, which=None): assert which in ('file', 'directory'), "which: " + which relative_path = self.get_selected(parent=False) or "" if relative_path: relative_path = relative_path[0] if relative_path[~0] != os.sep: relative_path = os.path.split(relative_path)[0] + os.sep if relative_path == os.sep: relative_path = "" # Is there a better way to do this? Why isn't there some kind of context? I assume # the command instance is global and really shouldn't have instance information. callback = getattr(self, 'on_done_' + which, None) pv = self.view.window().show_input_panel(which.capitalize() + ':', relative_path, callback, None, None) pv.run_command('move_to', {'to': 'eol', 'extend': False}) def on_done_file(self, value): self._on_done('file', value) def on_done_directory(self, value): self._on_done('directory', value) def _on_done(self, which, value): value = value.strip() if not value: return fqn = join(self.path, value) if exists(fqn): sublime.error_message(u'{0} already exists'.format(fqn)) return if which == 'directory': os.makedirs(fqn) else: open(fqn, 'wb') self.view.run_command('dired_refresh') class DiredDeleteCommand(TextCommand, DiredBaseCommand): def run(self, edit, trash=False): files = self.get_marked() or self.get_selected(parent=False) if files: # Yes, I know this is English. Not sure how Sublime is translating. if len(files) == 1: msg = u"Delete {0}?".format(files[0]) else: msg = u"Delete {0} items?".format(len(files)) if trash: need_confirm = self.view.settings().get('dired_confirm_send2trash') if trash and not send2trash: msg = u"Cannot delete to trash.\nPermanently " + msg.replace('D', 'd', 1) trash = False elif trash and need_confirm: msg = msg.replace('Delete', 'Delete to trash', 1) if trash and send2trash: if not need_confirm or (need_confirm and sublime.ok_cancel_dialog(msg)): self._to_trash(files) elif not trash and sublime.ok_cancel_dialog(msg): self._delete(files) else: print("Cancel delete or something wrong in DiredDeleteCommand") def _to_trash(self, files): path = self.path errors = [] def _status(filename='', done=False): if done: sublime.set_timeout(lambda: self.view.run_command('dired_refresh'), 1) if errors: sublime.error_message(u'Some files couldn’t be sent to trash (perhaps, they are being used by another process): \n\n' +'\n'.join(errors).replace('Couldn\'t perform operation.', '')) else: status = u'Please, wait… Removing ' + filename sublime.set_timeout(lambda: self.view.set_status("__FileBrowser__", status), 1) def _sender(files, event_for_wait, event_for_set): for filename in files: event_for_wait.wait() event_for_wait.clear() if event_for_wait is remove_event: try: send2trash.send2trash(join(path, filename)) except OSError as e: errors.append(u'{0}:\t{1}'.format(e, filename)) else: _status(filename) event_for_set.set() if event_for_wait is remove_event: _status(done=True) remove_event = threading.Event() report_event = threading.Event() t1 = threading.Thread(target=_sender, args=(files, remove_event, report_event)) t2 = threading.Thread(target=_sender, args=(files, report_event, remove_event)) t1.start() t2.start() report_event.set() def _delete(self, files): errors = [] if ST3: fail = (PermissionError, FileNotFoundError) else: fail = OSError sys_enc = locale.getpreferredencoding(False) for filename in files: fqn = join(self.path, filename) try: if isdir(fqn): shutil.rmtree(fqn) else: os.remove(fqn) except fail as e: e = str(e).split(':')[0].replace('[Error 5] ', 'Access denied') if not ST3: try: e = str(e).decode(sys_enc) except: # failed getpreferredencoding e = 'Unknown error' errors.append(u'{0}:\t{1}'.format(e, filename)) self.view.run_command('dired_refresh') if errors: sublime.error_message(u'Some files couldn’t be deleted: \n\n' + '\n'.join(errors)) class DiredRenameCommand(TextCommand, DiredBaseCommand): def run(self, edit): if self.filecount(): # Store the original filenames so we can compare later. self.view.settings().set('rename', self.get_all()) self.view.settings().set('dired_rename_mode', True) self.view.settings().set('color_scheme', 'Packages/FileBrowser/dired-rename-mode.hidden-tmTheme') self.view.set_read_only(False) self.set_ui_in_rename_mode(edit) self.view.set_status("__FileBrowser__", u" 𝌆 [enter: Apply changes] [escape: Discard changes] %s" % (u'¡¡¡DO NOT RENAME DISKS!!! you can rename their children though ' if self.path == 'ThisPC\\' else '')) # Mark the original filename lines so we can make sure they are in the same # place. r = self.fileregion() self.view.add_regions('rename', [ r ], '', '', MARK_OPTIONS) class DiredRenameCancelCommand(TextCommand, DiredBaseCommand): """ Cancel rename mode. """ def run(self, edit): self.view.settings().erase('rename') self.view.settings().set('color_scheme', 'Packages/FileBrowser/dired.hidden-tmTheme') self.view.settings().set('dired_rename_mode', False) self.view.run_command('dired_refresh') class DiredRenameCommitCommand(TextCommand, DiredBaseCommand): def run(self, edit): if not self.view.settings().has('rename'): # Shouldn't happen, but we want to cleanup when things go wrong. self.view.run_command('dired_refresh') return before = self.view.settings().get('rename') # We marked the set of files with a region. Make sure the region still has the same # number of files. after = [] for region in self.view.get_regions('rename'): for line in self.view.lines(region): after.append(self._remove_ui(self.get_parent(line, self.view.substr(line).strip()))) if len(after) != len(before): sublime.error_message('You cannot add or remove lines') return if len(set(after)) != len(after): sublime.error_message('There are duplicate filenames (see details in console)') self.view.window().run_command("show_panel", {"panel": "console"}) print(*(u'\n Original name: {0}\nConflicting name: {1}'.format(b, a) for (b, a) in zip(before, after) if b != a and a in before), sep='\n', end='\n\n') print('You can either resolve conflicts and apply changes or cancel renaming.\n') return diffs = [ (b, a) for (b, a) in zip(before, after) if b != a ] if diffs: existing = set(before) while diffs: b, a = diffs.pop(0) if a in existing: # There is already a file with this name. Give it a temporary name (in # case of cycles like "x->z and z->x") and put it back on the list. tmp = tempfile.NamedTemporaryFile(delete=False, dir=self.path).name os.unlink(tmp) diffs.append((tmp, a)) a = tmp print(u'dired rename: {0} → {1}'.format(b, a)) orig = join(self.path, b) if orig[~0] == '/' and os.path.islink(orig[:~0]): # last slash shall be omitted; file has no last slash, # thus it False and symlink to file shall be os.rename'd dest = os.readlink(orig[:~0]) os.unlink(orig[:~0]) os.symlink(dest, join(self.path, a)[:~0]) else: try: os.rename(orig, join(self.path, a)) except OSError: msg = (u'FileBrowser:\n\nError is occured during renaming.\n' u'Please, fix it and apply changes or cancel renaming.\n\n' u'\t {0} → {1}\n\n' u'Don’t rename\n' u' • parent and child at the same time\n' u' • non-existed file (cancel renaming to refresh)\n' u' • file if you’re not owner' u' • disk letter on Windows\n'.format(b, a)) sublime.error_message(msg) return existing.remove(b) existing.add(a) self.view.erase_regions('rename') self.view.settings().erase('rename') self.view.settings().set('color_scheme', 'Packages/FileBrowser/dired.hidden-tmTheme') self.view.settings().set('dired_rename_mode', False) self.view.run_command('dired_refresh') # HELP ############################################################## class DiredHelpCommand(TextCommand): def run(self, edit): view = self.view.window().new_file() view.settings().add_on_change('color_scheme', lambda: set_proper_scheme(view)) view.set_name("Browse: shortcuts") view.set_scratch(True) view.settings().set('color_scheme','Packages/FileBrowser/dired.hidden-tmTheme') view.settings().set('syntax','Packages/FileBrowser/dired-help.hidden-tmLanguage') view.settings().set('line_numbers',False) view.run_command('dired_show_help') sublime.active_window().focus_view(view) class DiredShowHelpCommand(TextCommand): def run(self, edit): COMMANDS_HELP = sublime.load_resource('Packages/FileBrowser/shortcuts.md') if ST3 else '' if not COMMANDS_HELP: dest = dirname(__file__) shortcuts = join(dest if dest!='.' else join(sublime.packages_path(), 'FileBrowser'), "shortcuts.md") COMMANDS_HELP = open(shortcuts, "r").read() self.view.erase(edit, Region(0, self.view.size())) self.view.insert(edit, 0, COMMANDS_HELP) self.view.sel().clear() self.view.set_read_only(True) # OTHER ############################################################# class DiredToggleHiddenFilesCommand(TextCommand): def run(self, edit): show = self.view.settings().get('dired_show_hidden_files', True) self.view.settings().set('dired_show_hidden_files', not show) self.view.run_command('dired_refresh') class DiredToggleProjectFolder(TextCommand, DiredBaseCommand): def run(self, edit): if not ST3: return sublime.status_message('This feature is available only in Sublime Text 3') path = self.path.rstrip(os.sep) data = self.view.window().project_data() data['folders'] = data.get('folders') or {} folders = [f for f in data['folders'] if f['path'] != path] if len(folders) == len(data['folders']): folders.insert(0, { 'path': path }) data['folders'] = folders self.view.window().set_project_data(data) self.view.window().run_command('dired_refresh') class DiredOnlyOneProjectFolder(TextCommand, DiredBaseCommand): def run(self, edit): if not ST3: return sublime.status_message('This feature is available only in Sublime Text 3') path = self.path.rstrip(os.sep) msg = u"Set '{0}' as only one project folder (will remove all other folders from project)?".format(path) if sublime.ok_cancel_dialog(msg): data = self.view.window().project_data() data['folders'] = [{ 'path': path }] self.view.window().set_project_data(data) self.view.window().run_command('dired_refresh') class DiredQuickLookCommand(TextCommand, DiredBaseCommand): """ quick look current file in mac or open in default app on other OSs """ def run(self, edit): files = self.get_marked() or self.get_selected(parent=False) if not files: return sublime.status_message('Nothing chosen') p = sublime.platform() if p == 'osx': cmd = ["qlmanage", "-p"] for filename in files: fqn = join(self.path, filename) cmd.append(fqn) subprocess.call(cmd) else: if p == 'windows': launch = lambda f: os.startfile(f) else: launch = lambda f: subprocess.call(['xdg-open', f]) for filename in files: fqn = join(self.path, filename) launch(fqn) class DiredOpenExternalCommand(TextCommand, DiredBaseCommand): """ open dir/file in external file explorer """ def run(self, edit): path = self.path files = self.get_selected(parent=False) fname = join(path, files[0] if files else '') p, f = os.path.split(fname.rstrip(os.sep)) if not exists(fname): return sublime.status_message(u'Directory doesn’t exist “%s”' % path) if sublime.platform() == 'windows' and path == 'ThisPC\\': if not ST3: fname = fname.encode(locale.getpreferredencoding(False)) return subprocess.Popen('explorer /select,"%s"' % fname) if files: self.view.window().run_command("open_dir", {"dir": p, "file": f}) else: self.view.window().run_command("open_dir", {"dir": path}) class DiredOpenInNewWindowCommand(TextCommand, DiredBaseCommand): def run(self, edit, project_folder=False): if project_folder: files = project_folder else: files = self.get_marked() or self.get_selected() items = [] if ST3: # sublime.executable_path() is not available in ST2 executable_path = sublime.executable_path() if sublime.platform() == 'osx': app_path = executable_path[:executable_path.rfind(".app/")+5] executable_path = app_path+"Contents/SharedSupport/bin/subl" items.append(executable_path) items.append("-n") for filename in files: fqn = join(self.path, filename) items.append(fqn) if sublime.platform() == 'windows': subprocess.Popen(items) else: subprocess.Popen(items, cwd=self.path) else: # ST2 items.append("-n") for filename in files: fqn = join(self.path or u'', filename) items.append(fqn) if sublime.platform() == 'osx': try: subprocess.Popen(['subl'] + items, cwd=self.path) except: try: subprocess.Popen(['sublime'] + items, cwd=self.path) except: app_path = subprocess.Popen(["osascript", "-e" "tell application \"System Events\" to POSIX path of (file of process \"Sublime Text 2\" as alias)"], stdout=subprocess.PIPE).communicate()[0].rstrip() subl_path = "{0}/Contents/SharedSupport/bin/subl".format(app_path) subprocess.Popen([subl_path] + items, cwd=self.path) elif sublime.platform() == 'windows': # 9200 means win8 shell = True if sys.getwindowsversion()[2] < 9200 else False items = [i.encode(locale.getpreferredencoding(False)) if sys.getwindowsversion()[2] == 9200 else i for i in items] try: subprocess.Popen(['subl'] + items, shell=shell) except: try: subprocess.Popen(['sublime'] + items, shell=shell) except: subprocess.Popen(['sublime_text.exe'] + items, shell=shell) else: try: subprocess.Popen(['subl'] + items, cwd=self.path) except: subprocess.Popen(['sublime'] + items, cwd=self.path) def run_on_new_window(): sublime.active_window().run_command("dired", { "immediate": True, "project": True, "other_group": "left"}) sublime.set_timeout(run_on_new_window , 200) if not ST3: sublime.set_timeout(lambda: sublime.active_window().run_command("toggle_side_bar") , 200) # EVENT LISTENERS ################################################### class DiredHijackNewWindow(EventListener): def on_window_command(self, window, command_name, args): if command_name != "new_window": return hijack_window() class DiredHideEmptyGroup(EventListener): def on_close(self, view): if not 'dired' in view.scope_name(0): return w = sublime.active_window() # check if closed view was a single one in group if ST3: single = not w.views_in_group(0) or not w.views_in_group(1) else: single = ([view.id()] == [v.id() for v in w.views_in_group(0)] or [view.id()] == [v.id() for v in w.views_in_group(1)]) if w.num_groups() == 2 and single: # without timeout ST may crash sublime.set_timeout(lambda: w.set_layout({"cols": [0.0, 1.0], "rows": [0.0, 1.0], "cells": [[0, 0, 1, 1]]}), 300) class DiredMoveOpenOrNewFileToRightGroup(EventListener): def on_activated(self, view): ''' Trick to prevent unexpected movements (e.g. when switching project in current window; or restart) Reason why the whole logic shall not be run on_activated, is user should be able to explicitly put any view in left group no matter what, e.g. using keybinding or drag&drop ''' w = sublime.active_window() if w and any(v for v in w.views_in_group(0) if 'dired' in v.scope_name(0)): self.MOVE = True else: self.MOVE = False def on_new(self, view): if not self.MOVE: return w = sublime.active_window() if w.num_groups() < 2: return if any(v for v in w.views_in_group(0) if 'dired' in v.scope_name(0)): if w.active_group() == 0: # at this point views are exist, so we cannot avoid the use of # set_view_index, but ST2 return None if group has no views # ST3 return None if group has active image’s view avig1 = w.active_view_in_group(1) if avig1: _group, active_view_index_in_other_group = w.get_view_index(avig1) index = active_view_index_in_other_group + 1 else: index = 0 sublime.set_timeout(lambda: w.set_view_index(view, 1, index), 1) def on_load(self, view): self.on_new(view) # MOUSE INTERATIONS ################################################# if ST3: class DiredDoubleclickCommand(TextCommand, DiredBaseCommand): def run_(self, view, args): s = self.view.settings() if s.get("dired_path") and not s.get("dired_rename_mode"): self.view.run_command("dired_select", {"other_group": True}) else: system_command = args["command"] if "command" in args else None if system_command: system_args = dict({"event": args["event"]}.items()) system_args.update(dict(args["args"].items())) self.view.run_command(system_command, system_args) else: class DiredDoubleclickCommand(TextCommand, DiredBaseCommand): def run_(self, args): s = self.view.settings() if s.get("dired_path") and not s.get("dired_rename_mode"): self.view.run_command("dired_select", {"other_group": True}) else: system_command = args["command"] if "command" in args else None if system_command: system_args = dict({"event": args["event"]}.items()) system_args.update(dict(args["args"].items())) self.view.run_command(system_command, system_args) # TOOLS ############################################################# class CallVCS(DiredBaseCommand): ''' this should be placed in common.py probably, but for some reason it doesnt work this way, so place it in main file for now ''' def __init__(self, view, path): self.view = view self.vcs_state = dict(path=path) self.view.erase_regions('M') self.view.erase_regions('?') self.call_git(path) self.watch_threads() def watch_threads(self): if not 'git' in self.vcs_state: sublime.set_timeout(self.watch_threads, 100) return if 'changed_items' in self.vcs_state: self.vcs_colorized(self.vcs_state['changed_items']) def call_git(self, path): git = self.view.settings().get('git_path', '') if git: # empty string disable git integration self.vcs_thread = threading.Thread(target=self.vcs_check, args=(path, git)) self.vcs_thread.start() else: self.vcs_state.update(git=False) def vcs_check(self, path, git='git'): if any(c for c in '~*?[]' if c in git): match = glob.glob(os.path.expanduser(git)) if match: git = match[0] else: sublime.error_message(u'FileBrowser:\n' u'It seems like you use wildcards in\n\n"git_path": "%s".\n\n' u'But the pattern cannot be found, please, fix it ' u'or use absolute path without wildcards.' % git) shell = True if sublime.platform()=='windows' else False try: p = subprocess.Popen([git, 'status', '-z'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, cwd=path, shell=shell) git_output = p.communicate()[0] p = subprocess.Popen([git, 'rev-parse', '--show-toplevel'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, cwd=path, shell=shell) root = p.communicate()[0].decode('utf-8').strip('\n') except: # on Windows exception is not being raised if cwd is not None and shell=True self.vcs_state.update(git=False) else: if git_output: git_output = str(git_output, 'utf-8').split('\x00') if ST3 else git_output.split('\00') new_values = dict((join(root, i[3:] if ST3 else unicode(i[3:], 'utf-8')), i[1]) for i in git_output if i != '') changed_items = self.vcs_state.get('changed_items', {}) changed_items.update(new_values) self.vcs_state.update(git=True, changed_items=changed_items) else: self.vcs_state.update(git=False) def vcs_colorized(self, changed_items): modified, untracked = [], [] path = normpath(self.vcs_state['path']) files_regions = dict((normpath(join(path, f)), r) for f, r in zip(self.get_all(), self.view.split_by_newlines(self.fileregion()))) colorblind = self.view.settings().get('vcs_color_blind', False) offset = 1 if not colorblind else 0 for fn in changed_items.keys(): full_fn = normpath(fn) r = files_regions.get(full_fn, 0) if r: content = self.view.substr(r) indent = len(re.match(r'^(\s*)', content).group(1)) icon = r.a + indent r = Region(icon, icon + offset) status = changed_items[fn] if status == 'M': modified.append(r) elif status == '?': untracked.append(r) if colorblind: self.view.add_regions('M', modified, 'item.colorblind.dired', '', MARK_OPTIONS | sublime.DRAW_EMPTY_AS_OVERWRITE) self.view.add_regions('?', untracked, 'item.colorblind.dired', '', MARK_OPTIONS | sublime.DRAW_EMPTY) else: self.view.add_regions('M', modified, 'item.modified.dired', '', MARK_OPTIONS) self.view.add_regions('?', untracked, 'item.untracked.dired', '', MARK_OPTIONS) <file_sep>#!/usr/bin/python # -*- coding: utf-8 -*- import re, os, fnmatch import sublime from sublime import Region from os.path import basename, dirname, isdir, isfile, exists, join, isabs, normpath, normcase if sublime.platform() == 'windows': import ctypes ST3 = int(sublime.version()) >= 3000 if ST3: MARK_OPTIONS = sublime.DRAW_NO_OUTLINE else: MARK_OPTIONS = 0 import locale RE_FILE = re.compile(r'^(\s*)([^\\//].*)$') def first(seq, pred): # I can't comprehend how this isn't built-in. return next((item for item in seq if pred(item)), None) class DiredBaseCommand: """ Convenience functions for dired TextCommands """ @property def path(self): return self.view.settings().get('dired_path') def _remove_ui(self, s): return s.replace(u"▸ ", "").replace(u"▾ ", "").replace(u"≡ ", "") def filecount(self): """ Returns the number of files and directories in the view. """ return self.view.settings().get('dired_count', 0) def move_to_extreme(self, extreme="bof"): """ Moves the cursor to the beginning or end of file list. Clears all sections. """ files = self.fileregion(with_parent_link=True) self.view.sel().clear() if extreme == "bof": ext_region = Region(files.a, files.a) else: name_point = self.view.extract_scope(self.view.line(files.b).a + 2).a ext_region = Region(name_point, name_point) self.view.sel().add(ext_region) self.view.show_at_center(ext_region) def move(self, forward=None): """ Moves the cursor one line forward or backwards. Clears all sections. """ assert forward in (True, False), 'forward must be set to True or False' files = self.fileregion(with_parent_link=True) if files.empty(): return sels = list(self.view.sel()) new_sels = [] for s in sels: pt = s.a if files.contains(pt): # Try moving by one line. line = self.view.line(pt) pt = forward and (line.b + 1) or (line.a - 1) if not files.contains(pt): # Not (or no longer) in the list of files, so move to the closest edge. pt = (pt > files.b) and files.b or files.a line = self.view.line(pt) scope = self.view.scope_name(line.a) if 'indent' in scope: name_point = self.view.extract_scope(line.a).b else: name_point = line.a + (2 if not 'parent_dir' in scope else 0) new_sels.append(name_point) self.view.sel().clear() for n in new_sels: self.view.sel().add(Region(n, n)) name_point = new_sels[~0] if forward else new_sels[0] surroundings = True if self.view.rowcol(name_point)[0] < 3 else False self.view.show(name_point, surroundings) def show_parent(self): return sublime.load_settings('dired.sublime-settings').get('dired_show_parent', False) def fileregion(self, with_parent_link=False): """ Returns a region containing the lines containing filenames. If there are no filenames None is returned. """ if with_parent_link: all_items = sorted(self.view.find_by_selector('dired.item')) else: all_items = sorted(self.view.find_by_selector('dired.item.directory') + self.view.find_by_selector('dired.item.file')) if not all_items: return None return Region(all_items[0].a, all_items[~0].b) def get_parent(self, line, text): ''' Returns relative path for text using os.sep, e.g. bla\\parent\\text\\ ''' indent = self.view.indented_region(line.b) if 'directory' in self.view.scope_name(line.a): # line may have inline error msg after os.sep text = text.split(os.sep)[0] + os.sep while not indent.empty(): parent = self.view.line(indent.a - 2) text = os.path.join(self.view.substr(parent).lstrip(), text.lstrip()) indent = self.view.indented_region(parent.a) return text def get_all(self): """ Returns a list of all filenames in the view. """ return [ self._remove_ui(RE_FILE.match(self.get_parent(l, self.view.substr(l))).group(2)) for l in self.view.lines(self.fileregion()) ] def get_selected(self, parent=True): """ Returns a list of selected filenames. """ names = set() fileregion = self.fileregion(with_parent_link=parent) if not fileregion: return None for sel in self.view.sel(): lines = self.view.lines(sel) for line in lines: if fileregion.contains(line): text = self.view.substr(line) if text: names.add(self._remove_ui(RE_FILE.match(self.get_parent(line, text)).group(2))) names = list(names) self.sort_nicely(names) return names def get_marked(self): lines = [] if self.filecount(): for region in self.view.get_regions('marked'): lines.extend(self.view.lines(region)) return [ self._remove_ui(RE_FILE.match(self.get_parent(line, self.view.substr(line))).group(2)) for line in lines ] def _mark(self, mark=None, regions=None): """ Marks the requested files. mark True, False, or a function with signature `func(oldmark, filename)`. The function should return True or False. regions Either a single region or a sequence of regions. Only files within the region will be modified. """ # Allow the user to pass a single region or a collection (like view.sel()). if isinstance(regions, Region): regions = [ regions ] filergn = self.fileregion() # We can't update regions for a key, only replace, so we need to record the existing # marks. previous = [m for m in self.view.get_regions('marked') if not m.empty()] marked = {} for r in previous: item = self._remove_ui(RE_FILE.match(self.get_parent(r, self.view.substr(r))).group(2)) marked[item] = r for region in regions: for line in self.view.lines(region): if filergn.contains(line): indent, text = RE_FILE.match(self.view.substr(line)).groups() filename = self._remove_ui(self.get_parent(line, text)) if mark not in (True, False): newmark = mark(filename in marked, filename) assert newmark in (True, False), u'Invalid mark: {0}'.format(newmark) else: newmark = mark if newmark: name_region = Region(line.a + len(indent) + 2, line.b) # do not mark UI elements marked[filename] = name_region else: marked.pop(filename, None) if marked: r = sorted(list(marked.values()), key=lambda region: region.a) self.view.add_regions('marked', r, 'dired.marked', '', MARK_OPTIONS) else: self.view.erase_regions('marked') def set_ui_in_rename_mode(self, edit): header = self.view.settings().get('dired_header', False) if header: regions = self.view.find_by_selector('text.dired header.dired punctuation.definition.separator.dired') else: regions = self.view.find_by_selector('text.dired dired.item.parent_dir') if not regions: return region = regions[0] start = region.begin() self.view.erase(edit, region) if header: new_text = u"——[RENAME MODE]——" + u"—"*(region.size()-17) else: new_text = u"⠤ [RENAME MODE]" self.view.insert(edit, start, new_text) def sort_nicely(self, names): """ Sort the given list in the way that humans expect. Source: http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html """ convert = lambda text: int(text) if text.isdigit() else text.lower() alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)] names.sort(key=alphanum_key) def ls(self, path, names, goto='', indent=''): f = [] tab = self.view.settings().get('tab_size') line = self.view.line(self.sel.a if self.sel!=None else self.view.sel()[0].a) content = self.view.substr(line).replace('\t', ' '*tab) ind = re.compile('^(\s*)').match(content).group(1) level = indent * int((len(ind) / tab) + 1) if ind else indent # generating dirs list first for name in names: if isdir(join(path, goto, name)): name = ''.join([level, u"▸ ", name, os.sep]) f.append(name) # generating files list for name in names: if not isdir(join(path, goto, name)): name = ''.join([level, u"≡ ", name]) f.append(name) return f def is_hidden(self, filename, path, goto=''): if not (path or goto): # special case for ThisPC return False tests = self.view.settings().get('dired_hidden_files_patterns', ['.*']) if isinstance(tests, str): tests = [tests] if any(fnmatch.fnmatch(filename, pattern) for pattern in tests): return True if sublime.platform() != 'windows': return False # check for attribute on windows: try: attrs = ctypes.windll.kernel32.GetFileAttributesW(join(path, goto, filename)) assert attrs != -1 result = bool(attrs & 2) except (AttributeError, AssertionError): result = False return result def prepare_filelist(self, names, path, goto, indent): show_hidden = self.view.settings().get('dired_show_hidden_files', True) if not show_hidden: names = [name for name in names if not self.is_hidden(name, path, goto)] self.sort_nicely(names) f = self.ls(path, names, goto=goto if indent else '', indent=indent) return f def prepare_treeview(self, names, path, goto, indent): f = self.prepare_filelist(names, path, goto, indent) line = self.view.line(self.sel if self.sel!=None else self.view.sel()[0]) # line may have inline error msg after os.sep dir_name = self.view.substr(line).split(os.sep)[0].replace(u'▸', u'▾', 1) + os.sep if f: dired_count = self.view.settings().get('dired_count', 0) self.view.settings().set('dired_count', int(dired_count) + len(f)) return '\n'.join([dir_name] + f) else: return '\t'.join([dir_name, '<empty>']) def restore_marks(self, marked=None): if marked: # Even if we have the same filenames, they may have moved so we have to manually # find them again. regions = [] for line in self.view.lines(self.fileregion()): indent, text = RE_FILE.match(self.view.substr(line)).groups() filename = self._remove_ui(self.get_parent(line, text)) if filename in marked: name_region = Region(line.a + len(indent) + 2, line.b) # do not mark UI elements regions.append(name_region) self.view.add_regions('marked', regions, 'dired.marked', '', MARK_OPTIONS) else: self.view.erase_regions('marked') def restore_sels(self, sels=None): if sels: regions = [] for line in self.view.lines(self.fileregion()): indent, text = RE_FILE.match(self.view.substr(line)).groups() filename = self._remove_ui(self.get_parent(line, text)) if filename in sels: name_point = line.a + len(indent) + 2 regions.append(name_point) if regions: self.view.sel().clear() for r in regions: self.view.sel().add(r) self.view.show_at_center(r) return # fallback: self.view.sel().clear() self.view.sel().add(Region(0, 0)) self.view.show_at_center(Region(0, 0))
2751f8b0f12062756bd1fda3631d84a3bcf89378
[ "Python" ]
2
Python
bbassett/sublime_packages
8e5931421c4f99658e5fe17474e0a093ad82d325
853839630010b3a506374934398b4fdbc5086b8a
refs/heads/master
<file_sep>#!/usr/bin/python from mininet.topo import Topo from mininet.net import Mininet from mininet.node import Node from mininet.log import setLogLevel, info from mininet.cli import CLI from time import sleep class SoftRouter( Node ): "A Node with IP forwarding enabled." def config( self, **params ): super( SoftRouter, self).config( **params ) # Enable forwarding on the router self.cmd( 'sysctl net.ipv4.ip_forward=1' ) def terminate( self ): self.cmd( 'sysctl net.ipv4.ip_forward=0' ) super( SoftRouter, self ).terminate() def runBGP( self ): print "*** eBGP starting ", self.name self.cmd("/usr/lib/quagga/zebra -f conf/zebra-%s.conf -d -i /tmp/zebra-%s.pid > logs/%s-zebra-stdout 2>&1" % (self.name, self.name, self.name)) self.waitOutput() self.cmd("/usr/lib/quagga/bgpd -f conf/bgpd-%s.conf -d -i /tmp/bgpd-%s.pid > logs/%s-bgpd-stdout 2>&1" % (self.name, self.name, self.name)) self.waitOutput() def stopQuagga( self ): print "*** Zebra, OSPF & BGP services are being terminated ", self.name self.cmd("pkill zebra") self.waitOutput() self.cmd("pkill ospfd") self.waitOutput() class NetworkTopo( Topo ): def build( self, **_opts ): defaultIP = '192.168.1.1/24' # IP address for r0-eth1 router = self.addNode( 'r0', cls=SoftRouter, ip=defaultIP ) s1, s2, s3, s4, s5 = [ self.addSwitch( s ) for s in ( 's1', 's2', 's3', 's4', 's5' ) ] self.addLink( s1, router, intfName2='r0-eth1', params2={ 'ip' : defaultIP } ) # for clarity self.addLink( s2, router, intfName2='r0-eth2', params2={ 'ip' : '172.16.0.1/12' } ) self.addLink( s3, router, intfName2='r0-eth3', params2={ 'ip' : '10.0.0.1/8' } ) h1 = self.addHost( 'h1', ip='192.168.1.100/24', defaultRoute='via 192.168.1.1' ) h2 = self.addHost( 'h2', ip='172.16.0.100/12', defaultRoute='via 172.16.0.1' ) for h, s in [ (h1, s1), (h2, s2), (h2, s3) ]: self.addLink( h, s ) def run(): topo = NetworkTopo() net = Mininet( topo=topo) net.start() info( '*** Routing Table on Router 1:\n' ) info( net[ 'r0' ].cmd( 'route' ) ) net[ 'r0' ].stopQuagga() bgpRouters = ['r0'] for router in bgpRouters: net [ router ].runBGP() sleep(2) CLI( net ) net.stop() if __name__ == '__main__': setLogLevel( 'info' ) run() <file_sep>#!/usr/bin/python from mininet.topo import Topo from mininet.net import Mininet from mininet.node import Node from mininet.log import setLogLevel, info from mininet.cli import CLI class LinuxRouter( Node ): "A Node with IP forwarding enabled." def config( self, **params ): super( LinuxRouter, self).config( **params ) # Enable forwarding on the router self.cmd( 'sysctl net.ipv4.ip_forward=1' ) def terminate( self ): self.cmd( 'sysctl net.ipv4.ip_forward=0' ) super( LinuxRouter, self ).terminate() class NetworkTopo( Topo ): "A LinuxRouter connecting three IP subnets" def build( self, **_opts ): defaultIP = '192.168.1.10/24' # IP address for r0-eth1 router = self.addNode( 'r0', cls=LinuxRouter, ip=defaultIP ) s1 = self.addSwitch('s1',bw=50) s2 = self.addSwitch('s2',bw=50) s3 = self.addSwitch('s3',bw=50) s4 = self.addSwitch('s4',bw=50) s5 = self.addSwitch('s5',bw=5, delay='100ms',max_queue=10, use_htb=True) self.addLink( s1, router, intfName2='r0-eth1', params2={ 'ip' : '192.168.1.10/24' } ) self.addLink( s2, router, intfName2='r0-eth2', params2={ 'ip' : '192.168.1.20/24' } ) self.addLink( s3, router, intfName2='r0-eth3', params2={ 'ip' : '192.168.1.30/24' } ) self.addLink( s4, router, intfName2='r0-eth4', params2={ 'ip' : '192.168.1.40/24' } ) self.addLink( s5, router, intfName2='r0-eth5', params2={ 'ip' : '192.168.1.50/24' } ) h1 = self.addHost( 'h1', ip='172.16.10.100/24', defaultRoute='via 192.168.1.10' ) h2 = self.addHost( 'h2', ip='172.16.20.100/24', defaultRoute='via 192.168.1.30' ) self.addLink(h1, s1) self.addLink(h2, s3) self.addLink(s1, s4) self.addLink(s4, s2) self.addLink(s2, s3) self.addLink(s3, s4) self.addLink(s3, s5) self.addLink(s5, s4) def run(): "Test linux router" topo = NetworkTopo() net = Mininet( topo=topo ) # controller is used by s1-s3 net.start() h1,h2 = net.get('h1','h2') #net['h1'].cmd('sysctl -w net.ipv4.tcp_congestion_control=vegas') #net['h2'].cmd('sysctl -w net.ipv4.tcp_congestion_control=reno') h1.cmd('iperf -c 172.16.10.100 -n 2000 &' ) h2.cmd('iperf -c 172.16.20.100 -n 2000 &' ) info( '* Routing Table on Router:\n' ) info( net[ 'r0' ].cmd( 'route' ) ) CLI( net ) net.stop() if _name_ == '_main_': setLogLevel( 'info' ) run()
e4ddce630cbe72ecaa91847d557b8f1501d75299
[ "Python" ]
2
Python
maqmal/mininet
69f5aace600c106fbd6dd0094e9677d6219db4c4
c69a9a7dae9bcd931b59874ac3c5b7166dd81d57
refs/heads/master
<repo_name>AndreasChendra/BeeFlix<file_sep>/app/Http/Controllers/BeeFlixController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\genres; use App\movies; use App\episodes; class BeeFlixController extends Controller { // public function mainPage() { $genre = genres::get(); $movie = movies::get(); return view('main', ['movie'=>$movie, 'genre'=>$genre]); } public function movieDetail($id) { $movie = movies::find($id); $genre = genres::find($movie->genre_id); $episode = episodes::where('movie_id', $movie->id)->paginate(3); return view('moviedetail', ['movie'=>$movie, 'genre'=>$genre, 'episode'=>$episode]); } public function movieCategory($name) { $genre = genres::where('name', $name)->first(); $movie = movies::where('genre_id', $genre->id)->get(); return view('moviecategory', ['genre'=>$genre, 'movie'=>$movie]); } } <file_sep>/database/seeds/MovieSeeder.php <?php use Illuminate\Database\Seeder; use App\movies; class MovieSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // $movieTitle = [ "Start Up", "Angel's Last Mission", "Sparkle Love", "Love In Time", "Detective Conan", "No Game No Life", "Sword Art Online", "Kimetsu No Yaiba", "My Little Old Boy", "The Morning Show", "Snowpiercer", "Running Man" ]; $moviePhoto = [ "image/drama/start_up.jpg", "image/drama/angels_last_mission.jpg", "image/drama/sparkle_love.jpg", "image/drama/love_in_time.jpg", "image/kids/detective_conan.jpg", "image/kids/no_game_no_life.jpg", "image/kids/sword_art_online.jpg", "image/kids/kimetsu_no_yaiba.jpg", "image/tvshow/my_little_old_boy.jpg", "image/tvshow/the_morning_show.jpg", "image/tvshow/snowpiercer.jpeg", "image/tvshow/running_man.jpg" ]; $movieDescription = [ "Start-Up berlatar belakang di kawasan fiksi Korea Selatan Silicon Valley yang disebut Sandbox dan menceritakan kisah orang-orang di dunia perusahaan startup.", "Lee Yeon-seo (Shin Hye-sun) adalah balerina yang sangat berbakat dan sukses dengan Fantasia Ballet Company milik keluarganya, tetapi mengalami kecelakaan yang membuatnya buta.", "Mei Wei Wei (Ling Mei Shi) terlahir dengan frekuensi alami. Ketika ia sedang tidak memperhatikan, hanya dengan satu pandangan saja bisa membuat seorang pria seakan “tersengat aliran listrik” dan jatuh cinta padanya.", "<NAME> (<NAME>) adalah seorang penulis tak dikenal yang keluarganya berada dalam kondisi sulit. Untuk meringankan situasinya, ia tidak mempunyai pilihan selain setuju untuk terikat pernikahan kontrak dengan Lu Boyan (Ren YanKai).", "<NAME>, seorang detektif SMA berusia 17 tahun yang biasanya membantu polisi memecahkan kasus, diserang oleh 2 anggota sindikat misterius ketika mengawasi sebuah pemerasan.", "No Game No Life adalah sebuah serial novel ringan Jepang yang ditulis dan diilustrasikan oleh Yū Kamiya. Sebuah adaptasi manga oleh Mashiro Hiiragi memulai serialisasi di majalah Monthly Comic Alive pada 27 Januari 2013. Sebuah serial anime yang diproduksi oleh Madhouse tayang sejak 9 April hingga 25 Juni 2014.", "Sword Art Online (ソードアート・オンライン Sōdo Āto Onrain) adalah seri novel ringan Jepang yang ditulis oleh Reki Kawahara dan diilustrasikan oleh ABEC. Serial ini berlangsung pada masa depan yang dekat dan berfokus pada berbagai dunia permainan virtual reality MMORPG . Sword Art Online mulai diterbitkan pada label ASCII Media Works Dengeki Bunko sejak 10 April 2009, dengan peluncuran seri spin-off di bulan Oktober 2012.", "Demon Slayer: Kimetsu no Yaiba: Mugen Train (bahasa Jepang: 鬼滅の刃 無限列車編, harfiah:'Film Pedang Penghancur Iblis: Kereta Iblis') adalah sebuah film animasi Jepang mendatang tahun 2020 bertema fantasi dan petualangan yang disutradarai oleh <NAME> dan diproduksi oleh Ufotable.", "My Little Old Boy (alias Mom's Diary: My Ugly Duckling; Hangul: 미운 우리 새끼; RR: <NAME>) adalah sebuah acara hiburan televisi Korea Selatan. Acara tersebut didistribusikan dan disindikasi oleh SBS setiap Minggu pukul 21:05 (KST).", "The Morning Show adalah serial televisi streaming drama Amerika yang dibintangi oleh <NAME>, <NAME>, dan <NAME>, yang ditayangkan perdana di Apple TV + pada 1 November 2019. Serial ini terinspirasi oleh buku <NAME>, Top of the Morning: Inside the Cutthroat World of TV pagi.", "Snowpiercer adalah sebuah film cerita seru fiksi ilmiah Korea Selatan berbahasa Inggris 2013 yang berdasarkan pada novel grafis Prancis Le Transperceneige karya <NAME>, <NAME> dan <NAME>. Film tersebut disutradarai oleh Bong Joon-ho, dan ditulis oleh Bong dan <NAME>.", "Running Man adalah sebuah acara varietas dari Korea Selatan. Pertama kali ditayangkan tanggal 11 Juli 2010 di SBS. Pembawa acara sekaligus pemainnya adalah Yoo Jae-suk. Acara ini menampilkan beberapa permainan yang dilakukan pertim, dapat 2 tim, 3 tim maupun 4 tim." ]; $movieRating = [ "5","4","5","3", "3","4","5","3", "5","3","5","3", ]; $count = 0; for($i=0; $i<3; $i++) { for($j=0; $j<4; $j++) { $movie = new movies; $movie->fill(["genre_id"=>$i+1, "title"=>$movieTitle[$count], "photo"=>$moviePhoto[$count], "description"=>$movieDescription[$count], "rating"=>$movieRating[$count]]); $movie->save(); $count = $count+1; } } } } <file_sep>/database/seeds/EpisodeSeeder.php <?php use Illuminate\Database\Seeder; use App\episodes; class EpisodeSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // $episodeNumber = [ "1", "2", "3", "4", "5", "6", "7", "8", "9" ]; $episodeTitle = [ "Kisahkan Kehidupan Seo Dal Mi & Won In Jae di Dunia Bisnis", "Pertemuan Seo Dal Mi dengan Nam Do Hyun", "Nam Do San dan Han Ji Pyeong yang Berbohong soal Cinta Pertama Mereka", "Kebohongan Berlanjut", "Dal Mi Jadi CEO?", "Bae Suzy hingga Nam Joo Hyuk Hadapi Tantangan Baru", "Do San Ingin Jujur pada Dal Mi", "Nam Do San Dituntut?", "Suzy, Nam Joo Hyuk, dan Kim Seon Ho Menghadapi Kenyataan", "Lee Yeon Seo Si Ballerina yang Buta", "Malaikat Kim Dan Menyelamatkan Yeon Seo", "Malaikat Dan Berubah Menjadi Manusia", "Kim Dan Kembali Menyelamatkan Lee Yeon Seo", "Ji Kang Woo Merasa Curiga Atas Kehadiran Kim Dan", "Kim Dan Mengetahui Keluarga Yeon Seo Sebenarnya", "Kim Dan Mengakui Perasaannya", "Kim Dan Meninggalkan Yeon Seo", "Yeon Seo Merindukan Kim Dan", "Assistant Manager Park's Private Life", "Chief B and the Love Letter", "History of Walking Upright", "The Picnic Day", "Today I Grab the Tambourine Again", "Anthology", "Not Played", "Our Place's Tasty Soybean Paste", "Fighter Choi Kang-soon", "The Woman Who Makes the Last Meal", "Withdrawal Person", "Water Scale", "Winter Is Coming", "The Wolf and the Lion", "You Win or You Die", "The North Remembers", "What Is Dead May Never Die", "The Old Gods and the New", "Detektif Paling Terkenal Abad Ini", "Detektif Terkenal yang Menciut", "Berhati-hatilah Terhadap Idola", "Kodenya Adalah Ikan yang Bersinar", "Ledakan Besar di Kereta Cepat", "Kasus Pembunuhan Valentine", "Kasus Ancaman Hadiah Sebulan Sekali", "Kasus Pembunuhan di Museum Seni", "Kasus Pembunuhan di Festival", "Beginner", "Challenger", "Expert", "Grandmaster", "Weak Square", "Interesting", "Sacrifice", "Fake End", "Sky Walk", "Underworld", "The Demon Tree", "The End Mountains", "Departure", "Ocean Turtle", "Project Alicization", "Swordcraft Academy", "Swordsman's Pride ", "Nobleman's Responsibilities", "Cruelty", "Trainer <NAME>", "Sabito and Makomo", "Final Selection", "My Own Steel", "Swordsman Accompanying a Demon", "Muzan Kibutsuji", "The Smell of Enchanting Blood", "Temari Demon and Arrow Demon", "New Sons Kim Gun-mo, Kim Je-dong, Heo Ji-woong appearance", "MC Shin Dong-yup, Seo Jang-hoon, Han Hye-jin appearance", "New Son Park Soo-hong appearance", "Kim Je-dong get off", "New Son Tony Ahn appearance", "Special host: Ahn Jae-wook, New Son Lee Sang-min appearance", "Special host: Park Myeong-su", "Special hosts: Kim Hee-sun, Kim Jong-kook", "New son Kim Jong-kook appearance", "The Morning Show Series-Premiere Recap: And We’re Live", "The Morning Show Recap: Co-Anchor Approval", "The Morning Show Recap: Timeless American Entertainment", "The Morning Show Recap: What Doesn't Kill You", "The Morning Show Recap: Let's Duet", "The Morning Show Recap: Natural Disaster", "The Morning Show Recap: Ambush Predators", "The Morning Show Recap: This Is How It Happens", "The Morning Show Recap: Mutiny, Ho!", "First, the Weather Changed", "Prepare to Brace", "Access Is Power", "Without Their Maker", "Justice Never Boarded", "Trouble Comes Sideways", "The Universe Is Indifferent", "These Are His Revolutions", "The Train Demanded Blood", "Temukan Kode Rahasia", "Mencari Celengan Uang Babi Emas", "Mengumpulkan Running Balls", "Secara individual dapatkan Running Balls", "Mengumpulkan Running Balls", "Dapatkan the Running Balls", "Kalahkan anggota lain", "Kumpulkan banyak uang", "Temukan pencurinya" ]; $count=0; for($i=0; $i<12; $i++) { for($j=0; $j<9; $j++) { $episode = new episodes; $episode->fill(["movie_id"=>$i+1, "episode"=>$episodeNumber[$j], "title"=>$episodeTitle[$count]]); $count = $count+1; $episode->save(); } } } } <file_sep>/database/seeds/GenreSeeder.php <?php use Illuminate\Database\Seeder; use App\genres; class GenreSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { // $genreName = ["Drama", "Kids", "TV Show"]; for($i=0; $i<3; $i++) { $genre = new genres; $genre->fill(["name"=>$genreName[$i]]); $genre->save(); } } }
485693b835ff1a6cfeb43310a9beb280b2d48da7
[ "PHP" ]
4
PHP
AndreasChendra/BeeFlix
e0aaf92e61ad67bb160cf8777cba05d5b016c52b
f3d01cc9e0866c939b9ebfca3e14383b4ae2fd00
refs/heads/master
<file_sep>import Vue from 'vue'; export declare class RadioButton extends Vue { value?: any; modelValue?: any; $emit(eventName: string, event: Event): this; }<file_sep>import Vue from 'vue'; export declare class Checkbox extends Vue { value?: null; modelValue?: null; binary?: boolean; $emit(eventName: string, event: Event): this; }<file_sep>import Vue from 'vue'; export declare class TriStateCheckbox extends Vue { modelValue?: any; $emit(eventName: string, event: Event): this; }<file_sep>import Vue from 'vue'; export declare class InputSwitch extends Vue { modelValue?: boolean; }
dddad184bc5ae4c1da6422aada1d2b6f50103ffe
[ "TypeScript" ]
4
TypeScript
MohanYadav1/primevue
2a6c90625a41560fa0a37e4c373d54312f06b921
62fb3c8d6f027cafb6ac2fb141eb39536a8e9b3c
refs/heads/master
<file_sep>import argparse from configparser import ConfigParser import telebot from pymysql import connect DEFAULT_CONFIG = "default.ini" PORTAL_SELECT_QUERY = """SELECT * FROM {db_ingress}.ingress_portals WHERE checked is NULL""" PORTAL_UPDATE_QUERY = """UPDATE {db_ingress}.ingress_portals SET checked=1 WHERE id = %s""" def create_config(config_path): """ Parse config. """ config = dict() config_raw = ConfigParser() config_raw.read(DEFAULT_CONFIG) config_raw.read(config_path) config['db_r_host'] = config_raw.get( 'DB', 'HOST') config['db_r_name'] = config_raw.get( 'DB', 'NAME') config['db_r_user'] = config_raw.get( 'DB', 'USER') config['db_r_pass'] = config_raw.get( 'DB', 'PASSWORD') config['db_r_port'] = config_raw.getint( 'DB', 'PORT') config['db_r_charset'] = config_raw.get( 'DB', 'CHARSET') config['db_ingress'] = config_raw.get( 'DB', 'DB_INGRESS') config['telegram_token'] = config_raw.get( 'Telegram', 'BOT_TOKEN') config['telegram_channel'] = config_raw.get( 'Telegram', 'CHANNEL') return config if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "-c", "--config", default="default.ini", help="Config file to use") args = parser.parse_args() config_path = args.config config = create_config(config_path) print("Initialize/Start DB Session") mydb_r = connect( host=config['db_r_host'], user=config['db_r_user'], passwd=config['db_r_pass'], database=config['db_ingress'], port=config['db_r_port'], charset=config['db_r_charset'], autocommit=True) mycursor_ingress = mydb_r.cursor() print("Connection clear") portal_select_query = PORTAL_SELECT_QUERY.format(db_ingress=config['db_ingress']) mycursor_ingress.execute(portal_select_query) portals = mycursor_ingress.fetchall() bot = telebot.TeleBot(config['telegram_token']) for id, external_id, lat, lon, name, url, updated, imported, checked in portals: message = 'Neues Portal: [{}](https://www.google.com/maps/search/?api=1&query={},{})'.format(name, str(lat), str(lon)) bot.send_photo(config['telegram_channel'], url, message, parse_mode='Markdown') portal_update_query = PORTAL_UPDATE_QUERY.format(db_ingress=config['db_ingress']) mycursor_ingress.execute(portal_update_query, id) <file_sep>requests[socks] lxml beautifulsoup4 pymysql soupsieve discord-webhook pyTelegramBotAPI
f28552cbb47b65844885ff5b77b99affbc8710d6
[ "Python", "Text" ]
2
Python
hzpz/ingress_scraper
b3c361d124d924565f7a4ca191c9ee44592ac29f
2d21668b3321853cd34c4d02fdffb06e7a242e93
refs/heads/master
<repo_name>Sandalmoth/thread-pool<file_sep>/thread_pool_test.cpp // Get rid of annoying MSVC warning. #ifdef _MSC_VER #define _CRT_SECURE_NO_WARNINGS #endif #include <fstream> #include <iomanip> #include <random> #include <string> #include <vector> #include "thread_pool.hpp" // Define short names for commonly-used integer types. typedef std::int_fast32_t i32; typedef std::uint_fast32_t ui32; typedef std::int_fast64_t i64; typedef std::uint_fast64_t ui64; // Define two global synced_streams objects: one prints to std::cout and the other to a file. synced_stream sync_cout(std::cout); std::ofstream log_file; synced_stream sync_file(log_file); // A global thread pool object. thread_pool pool; // A global random_device object used to seed some random number generators. std::random_device rd; // Global variables to measure how many checks succeeded and how many failed. ui32 tests_succeeded = 0; ui32 tests_failed = 0; /** * @brief Print any number of items into both std::cout and the log file, syncing both independently. * * @tparam T The types of the items. * @param items The items to print. */ template <typename... T> void dual_print(const T &...items) { sync_cout.print(items...); sync_file.print(items...); } /** * @brief Print any number of items into both std::cout and the log file, followed by a newline character, syncing both independently. * * @tparam T The types of the items. * @param items The items to print. */ template <typename... T> void dual_println(const T &...items) { dual_print(items..., '\n'); } /** * @brief Print a stylized header. * * @param text The text of the header. Will appear between two lines. * @param symbol The symbol to use for the lines. Default is '='. */ void print_header(const std::string &text, const char &symbol = '=') { dual_println(); dual_println(std::string(text.length(), symbol)); dual_println(text); dual_println(std::string(text.length(), symbol)); } /** * @brief Get a string representing the current time. * * @return The string. */ std::string get_time() { const std::time_t t = std::time(nullptr); char time_string[32]; std::strftime(time_string, sizeof(time_string), "%Y-%m-%d_%H.%M.%S", std::localtime(&t)); return std::string(time_string); } /** * @brief Check if a condition is met, report the result, and count the number of successes and failures. * * @param condition The condition to check. */ void check(const bool condition) { if (condition) { dual_println("-> PASSED!"); tests_succeeded++; } else { dual_println("-> FAILED!"); tests_failed++; } } /** * @brief Store the ID of the current thread in memory. Waits for a short time to ensure it does not get evaluated by more than one thread. * * @param location A pointer to the location where the thread ID should be stored. */ void store_ID(std::thread::id *location) { *location = std::this_thread::get_id(); std::this_thread::sleep_for(std::chrono::milliseconds(10)); } /** * @brief Count the number of unique threads in the thread pool to ensure that the correct number of individual threads was created. Pushes a number of tasks equal to four times the thread count into the thread pool, and count the number of unique thread IDs returned by the tasks. */ ui32 count_unique_threads() { std::vector<std::thread::id> thread_IDs(pool.get_thread_count() * 4); for (std::thread::id &id : thread_IDs) pool.push_task(store_ID, &id); pool.wait_for_tasks(); std::sort(thread_IDs.begin(), thread_IDs.end()); ui32 unique_threads = (ui32)(std::unique(thread_IDs.begin(), thread_IDs.end()) - thread_IDs.begin()); return unique_threads; } /** * @brief Check that the constructor works. */ void check_constructor() { dual_println("Checking that the thread pool reports a number of threads equal to the hardware concurrency..."); check(pool.get_thread_count() == std::thread::hardware_concurrency()); dual_println("Checking that the manually counted number of unique thread IDs is equal to the reported number of threads..."); check(pool.get_thread_count() == count_unique_threads()); } /** * @brief Check that reset() works. */ void check_reset() { pool.reset(std::thread::hardware_concurrency() / 2); dual_println("Checking that after reset() the thread pool reports a number of threads equal to half the hardware concurrency..."); check(pool.get_thread_count() == std::thread::hardware_concurrency() / 2); dual_println("Checking that after reset() the manually counted number of unique thread IDs is equal to the reported number of threads..."); check(pool.get_thread_count() == count_unique_threads()); pool.reset(std::thread::hardware_concurrency()); dual_println("Checking that after a second reset() the thread pool reports a number of threads equal to the hardware concurrency..."); check(pool.get_thread_count() == std::thread::hardware_concurrency()); dual_println("Checking that after a second reset() the manually counted number of unique thread IDs is equal to the reported number of threads..."); check(pool.get_thread_count() == count_unique_threads()); } /** * @brief Check that push_task() works. */ void check_push_task() { dual_println("Checking that push_task() works for a function with no arguments or return value..."); { bool flag = false; pool.push_task([&flag] { flag = true; }); pool.wait_for_tasks(); check(flag); } dual_println("Checking that push_task() works for a function with one argument and no return value..."); { bool flag = false; pool.push_task([](bool *flag) { *flag = true; }, &flag); pool.wait_for_tasks(); check(flag); } dual_println("Checking that push_task() works for a function with two arguments and no return value..."); { bool flag1 = false; bool flag2 = false; pool.push_task([](bool *flag1, bool *flag2) { *flag1 = *flag2 = true; }, &flag1, &flag2); pool.wait_for_tasks(); check(flag1 && flag2); } } /** * @brief Check that submit() works. */ void check_submit() { dual_println("Checking that submit() works for a function with no arguments or return value..."); { bool flag = false; auto my_future = pool.submit([&flag] { flag = true; }); check(my_future.get() && flag); } dual_println("Checking that submit() works for a function with one argument and no return value..."); { bool flag = false; auto my_future = pool.submit([](bool *flag) { *flag = true; }, &flag); check(my_future.get() && flag); } dual_println("Checking that submit() works for a function with two arguments and no return value..."); { bool flag1 = false; bool flag2 = false; auto my_future = pool.submit([](bool *flag1, bool *flag2) { *flag1 = *flag2 = true; }, &flag1, &flag2); check(my_future.get() && flag1 && flag2); } dual_println("Checking that submit() works for a function with no arguments and a return value..."); { bool flag = false; auto my_future = pool.submit([&flag] { flag = true; return 42; }); check(my_future.get() == 42 && flag); } dual_println("Checking that submit() works for a function with one argument and a return value..."); { bool flag = false; auto my_future = pool.submit([](bool *flag) { *flag = true; return 42; }, &flag); check(my_future.get() == 42 && flag); } dual_println("Checking that submit() works for a function with two arguments and a return value..."); { bool flag1 = false; bool flag2 = false; auto my_future = pool.submit([](bool *flag1, bool *flag2) { *flag1 = *flag2 = true; return 42; }, &flag1, &flag2); check(my_future.get() == 42 && flag1 && flag2); } } /** * @brief Check that wait_for_tasks() works. */ void check_wait_for_tasks() { ui32 n = pool.get_thread_count() * 10; std::vector<std::atomic<bool>> flags(n); for (ui32 i = 0; i < n; i++) pool.push_task([&flags, i] { std::this_thread::sleep_for(std::chrono::milliseconds(10)); flags[i] = true; }); pool.wait_for_tasks(); bool all_flags = true; for (ui32 i = 0; i < n; i++) all_flags = all_flags && flags[i]; check(all_flags); } /** * @brief Check that parallelize_loop() works for a specific number of indices split over a specific number of tasks. * * @param start The first index in the loop. * @param end The last index in the loop plus 1. * @param num_tasks The number of tasks. */ void check_parallelize_loop(i32 start, i32 end, const ui32 &num_tasks) { if (start == end) end++; dual_println("Verifying that a loop from ", start, " to ", end, " with ", num_tasks, num_tasks == 1 ? " task" : " tasks", " modifies all indices..."); ui64 num_indices = (ui64)std::abs(end - start); i32 offset = std::min(start, end); std::vector<std::atomic<bool>> flags((ui64)num_indices); pool.parallelize_loop( start, end, [&flags, &offset](const i32 &start, const i32 &end) { for (i32 i = start; i < end; i++) flags[(ui64)(i - offset)] = true; }, num_tasks); bool all_flags = true; for (ui64 i = 0; i < num_indices; i++) all_flags = all_flags && flags[i]; check(all_flags); } /** * @brief Check that parallelize_loop() works using several different random values for the range of indices and number of tasks. */ void check_parallelize_loop() { std::mt19937_64 mt(rd()); std::uniform_int_distribution<i32> index_dist((i32)pool.get_thread_count() * -100, (i32)pool.get_thread_count() * 100); std::uniform_int_distribution<ui32> task_dist(1, pool.get_thread_count()); for (ui32 i = 0; i < 10; i++) check_parallelize_loop(index_dist(mt), index_dist(mt), task_dist(mt)); } /** * @brief Check that task monitoring works. */ void check_task_monitoring() { ui32 n = std::min<ui32>(std::thread::hardware_concurrency(), 4); dual_println("Resetting pool to ", n, " threads."); pool.reset(n); dual_println("Submitting ", n * 3, " tasks."); std::vector<std::atomic<bool>> release(n * 3); for (ui32 i = 0; i < n * 3; i++) pool.push_task([&release, i] { while (!release[i]) std::this_thread::yield(); dual_println("Task ", i, " released."); }); std::this_thread::sleep_for(std::chrono::milliseconds(300)); dual_println("After submission, should have: ", n * 3, " tasks total, ", n, " tasks running, ", n * 2, " tasks queued..."); check(pool.get_tasks_total() == n * 3 && pool.get_tasks_running() == n && pool.get_tasks_queued() == n * 2); for (ui32 i = 0; i < n; i++) release[i] = true; std::this_thread::sleep_for(std::chrono::milliseconds(300)); dual_println("After releasing ", n, " tasks, should have: ", n * 2, " tasks total, ", n, " tasks running, ", n, " tasks queued..."); for (ui32 i = n; i < n * 2; i++) release[i] = true; check(pool.get_tasks_total() == n * 2 && pool.get_tasks_running() == n && pool.get_tasks_queued() == n); std::this_thread::sleep_for(std::chrono::milliseconds(300)); dual_println("After releasing ", n, " more tasks, should have: ", n, " tasks total, ", n, " tasks running, ", 0, " tasks queued..."); check(pool.get_tasks_total() == n && pool.get_tasks_running() == n && pool.get_tasks_queued() == 0); for (ui32 i = n * 2; i < n * 3; i++) release[i] = true; std::this_thread::sleep_for(std::chrono::milliseconds(200)); dual_println("After releasing the final ", n, " tasks, should have: ", 0, " tasks total, ", 0, " tasks running, ", 0, " tasks queued..."); check(pool.get_tasks_total() == 0 && pool.get_tasks_running() == 0 && pool.get_tasks_queued() == 0); dual_println("Resetting pool to ", std::thread::hardware_concurrency(), " threads."); pool.reset(std::thread::hardware_concurrency()); } /** * @brief Check that pausing works. */ void check_pausing() { ui32 n = std::min<ui32>(std::thread::hardware_concurrency(), 4); dual_println("Resetting pool to ", n, " threads."); pool.reset(n); dual_println("Pausing pool."); pool.pause(); dual_println("Submitting ", n * 3, " tasks, each one waiting for 200ms."); for (ui32 i = 0; i < n * 3; i++) pool.push_task([i] { std::this_thread::sleep_for(std::chrono::milliseconds(200)); dual_println("Task ", i, " done."); }); dual_println("Immediately after submission, should have: ", n * 3, " tasks total, ", 0, " tasks running, ", n * 3, " tasks queued..."); check(pool.get_tasks_total() == n * 3 && pool.get_tasks_running() == 0 && pool.get_tasks_queued() == n * 3); std::this_thread::sleep_for(std::chrono::milliseconds(300)); dual_println("300ms later, should still have: ", n * 3, " tasks total, ", 0, " tasks running, ", n * 3, " tasks queued..."); check(pool.get_tasks_total() == n * 3 && pool.get_tasks_running() == 0 && pool.get_tasks_queued() == n * 3); dual_println("Unpausing pool."); pool.resume(); std::this_thread::sleep_for(std::chrono::milliseconds(300)); dual_println("300ms later, should have: ", n * 2, " tasks total, ", n, " tasks running, ", n, " tasks queued..."); check(pool.get_tasks_total() == n * 2 && pool.get_tasks_running() == n && pool.get_tasks_queued() == n); dual_println("Pausing pool and using wait_for_tasks() to wait for the running tasks."); pool.pause(); pool.wait_for_tasks(); dual_println("After waiting, should have: ", n, " tasks total, ", 0, " tasks running, ", n, " tasks queued..."); check(pool.get_tasks_total() == n && pool.get_tasks_running() == 0 && pool.get_tasks_queued() == n); std::this_thread::sleep_for(std::chrono::milliseconds(200)); dual_println("200ms later, should still have: ", n, " tasks total, ", 0, " tasks running, ", n, " tasks queued..."); check(pool.get_tasks_total() == n && pool.get_tasks_running() == 0 && pool.get_tasks_queued() == n); dual_println("Unpausing pool and using wait_for_tasks() to wait for all tasks."); pool.resume(); pool.wait_for_tasks(); dual_println("After waiting, should have: ", 0, " tasks total, ", 0, " tasks running, ", 0, " tasks queued..."); check(pool.get_tasks_total() == 0 && pool.get_tasks_running() == 0 && pool.get_tasks_queued() == 0); dual_println("Resetting pool to ", std::thread::hardware_concurrency(), " threads."); pool.reset(std::thread::hardware_concurrency()); } /** * @brief Check that exception handling work. */ void check_exceptions() { bool caught = false; auto my_future = pool.submit([] { throw std::runtime_error("Exception thrown!"); }); try { my_future.get(); } catch (const std::exception &e) { if (e.what() == std::string("Exception thrown!")) caught = true; } check(caught); } /** * @brief A lightweight matrix class template for performance testing purposes. Not for general use; only contains the bare minimum functionality needed for the test. Based on https://github.com/bshoshany/multithreaded-matrix * * @tparam T The type to use for the matrix elements. */ template <typename T> class matrix { public: // ===================================== // Constructors and assignment operators // ===================================== /** * @brief Construct an uninitialized matrix. * * @param _rows The number of rows. * @param _cols The number of columns. */ matrix(const ui64 &_rows, const ui64 &_cols) : rows(_rows), cols(_cols), smart_elements(new T[rows * cols]) { elements = smart_elements.get(); } /** * @brief Construct a new matrix by copying the elements of an existing matrix. * * @param m The matrix to be copied. */ matrix(const matrix<T> &m) : rows(m.rows), cols(m.cols), smart_elements(new T[rows * cols]) { elements = smart_elements.get(); for (ui64 i = 0; i < rows * cols; i++) elements[i] = m.elements[i]; } /** * @brief Construct a new matrix by moving the elements of an existing matrix. * * @param m The matrix to be moved. */ matrix(matrix<T> &&m) : rows(m.rows), cols(m.cols), smart_elements(std::move(m.smart_elements)) { elements = smart_elements.get(); m.rows = 0; m.cols = 0; m.elements = nullptr; } /** * @brief Copy the elements of another matrix to this matrix. * * @param m The matrix to be copied. * @return A reference to this matrix. */ matrix<T> &operator=(const matrix<T> &m) { rows = m.rows; cols = m.cols; smart_elements.reset(new T[rows * cols]); elements = smart_elements.get(); for (ui64 i = 0; i < rows * cols; i++) elements[i] = m.elements[i]; return *this; } /** * @brief Move the elements of another matrix to this matrix. * * @param m The matrix to be moved. * @return A reference to this matrix. */ matrix<T> &operator=(matrix<T> &&m) { rows = m.rows; cols = m.cols; smart_elements = std::move(m.smart_elements); elements = smart_elements.get(); m.rows = 0; m.cols = 0; m.elements = nullptr; return *this; } // ==================== // Overloaded operators // ==================== /** * @brief Read or modify a matrix element. * * @param row The row index (starting from zero). * @param col The column index (starting from zero). * @return A reference to the element. */ inline T &operator()(const ui64 &row, const ui64 &col) { return elements[(cols * row) + col]; } /** * @brief Read a matrix element. * * @param row The row index (starting from zero). * @param col The column index (starting from zero). * @return The value of the element. */ inline T operator()(const ui64 &row, const ui64 &col) const { return elements[(cols * row) + col]; } /** * @brief Read or modify an element of the underlying 1-dimensional array. * * @param i The element index (starting from zero). * @return A reference to the element. */ inline T &operator[](const ui64 &i) { return elements[i]; } /** * @brief Read an element of the underlying 1-dimensional array. * * @param i The element index (starting from zero). * @return The value of the element. */ inline T operator[](const ui64 &i) const { return elements[i]; } /** * @brief Compare this matrix to another matrix. * * @param m The matrix to compare to. * @return Whether the matrices have the same elements. */ bool operator==(const matrix<T> &m) const { bool compare_result = true; for (ui64 i = 0; i < rows * cols; i++) compare_result = compare_result && (elements[i] == m.elements[i]); return compare_result; } // ======================= // Public member functions // ======================= /** * @brief Transpose a matrix. * * @param num_tasks The number of parallel tasks to use. If set to 0, no multithreading will be used. * @return The transposed matrix. */ matrix<T> transpose(const ui32 &num_tasks) const { matrix<T> out(cols, rows); if (num_tasks == 0) { for (ui64 i = 0; i < out.rows; i++) for (ui64 j = 0; j < out.cols; j++) out(i, j) = operator()(j, i); } else { pool.parallelize_loop( 0, out.rows, [this, &out](const ui64 &start, const ui64 &end) { for (ui64 i = start; i < end; i++) for (ui64 j = 0; j < out.cols; j++) out(i, j) = operator()(j, i); }, num_tasks); } return out; } // ================ // Friend functions // ================ /** * @brief Add two matrices using the specified number of parallel tasks. * * @param a The first matrix to be added. * @param b The second matrix to be added. * @param num_tasks The number of parallel tasks to use. If set to 0, no multithreading will be used. * @return The sum of the matrices. */ friend matrix<T> add_matrices(const matrix<T> &a, const matrix<T> &b, const ui32 &num_tasks) { matrix<T> c(a.rows, a.cols); if (num_tasks == 0) for (ui64 i = 0; i < a.rows * a.cols; i++) c[i] = a[i] + b[i]; else pool.parallelize_loop( 0, a.rows * a.cols, [&a, &b, &c](const ui64 &start, const ui64 &end) { for (ui64 i = start; i < end; i++) c[i] = a[i] + b[i]; }, num_tasks); return c; } /** * @brief Multiply two matrices using the specified number of parallel tasks. * * @param a The first matrix to be multiplied. * @param b The second matrix to be multiplied. * @param num_tasks The number of parallel tasks to use. If set to 0, no multithreading will be used. * @return The product of the matrices. */ friend matrix<T> multiply_matrices(const matrix<T> &a, const matrix<T> &b, const ui32 &num_tasks) { matrix<T> c(a.rows, b.cols); if (num_tasks == 0) { for (ui64 i = 0; i < a.rows; i++) for (ui64 j = 0; j < b.cols; j++) { c(i, j) = 0; for (ui64 k = 0; k < a.cols; k++) c(i, j) += a(i, k) * b(k, j); } } else { pool.parallelize_loop( 0, a.rows, [&a, &b, &c, &a_cols = a.cols, &b_cols = b.cols](const ui64 &start, const ui64 &end) { for (ui64 i = start; i < end; i++) for (ui64 j = 0; j < b_cols; j++) { c(i, j) = 0; for (ui64 k = 0; k < a_cols; k++) c(i, j) += a(i, k) * b(k, j); } }, num_tasks); } return c; } private: // ======================== // Private member variables // ======================== /** * @brief The number of rows. */ ui64 rows = 0; /** * @brief The number of columns. */ ui64 cols = 0; /** * @brief A pointer to an array storing the elements of the matrix in flattened 1-dimensional form. */ T *elements = nullptr; /** * @brief A smart pointer to manage the memory allocated for the matrix elements. */ std::unique_ptr<T[]> smart_elements; }; /** * @brief A class template for generating random matrices. * * @tparam T The type to use for the matrix elements. * @tparam D The distribution to use, e.g. std::uniform_real_distribution<double>. */ template <typename T, typename D> class random_matrix_generator { public: // ============ // Constructors // ============ /** * @brief Construct a new random matrix generator. * * @tparam P The types of the parameters to pass to the constructor of the distribution. * @param params The parameters to pass to the constructor of the distribution. The number of parameters and their types depends on the particular distribution being used. */ template <typename... P> random_matrix_generator(const P &...params) : dist(params...), rd() {} // ======================= // Public member functions // ======================= /** * @brief Generate a random matrix with the given number of rows and columns. * * @param rows The desired number of rows in the matrix. * @param cols The desired number of columns in the matrix. * @param num_tasks The number of parallel tasks to use. If set to 0, no multithreading will be used. * @return The random matrix. */ matrix<T> generate_matrix(const ui64 &rows, const ui64 &cols, const ui32 &num_tasks) { matrix<T> m(rows, cols); if (num_tasks == 0) { std::mt19937_64 mt(generate_seed()); for (ui64 i = 0; i < rows * cols; i++) m[i] = dist(mt); } else pool.parallelize_loop( 0, rows * cols, [this, &m](const ui64 &start, const ui64 &end) { std::mt19937_64 mt(generate_seed()); for (ui64 i = start; i < end; i++) m[i] = dist(mt); }, num_tasks); return m; } private: // ======================== // Private member functions // ======================== /** * @brief Generate a seed. The std::mt19937_64 in each block will be seeded using this function in order to avoid depleting the entropy of the random_device. * * @return A random unsigned 64-bit integer. */ ui64 generate_seed() { static std::mt19937_64 mt(rd()); return mt(); } // ======================== // Private member variables // ======================== /** * @brief The distribution to use for generating random numbers. */ D dist; /** * @brief The random device to be used for seeding the pseudo-random number generators. */ std::random_device rd; }; /** * @brief Check the matrix class template by comparing the results of adding, multiplying, and transposing matrices calculated in two ways: single-threaded and multithreaded. */ void check_matrix() { // Initialize a random_matrix_generator object to generates matrices with integers uniformly distributed between -1000 and 1000. random_matrix_generator<i64, std::uniform_int_distribution<i64>> rnd(-1000, 1000); // Define the size of the matrices to use. const ui32 thread_count = pool.get_thread_count(); const ui64 rows = thread_count * 10; const ui64 cols = rows; const ui64 total_size = rows * cols; dual_println("Using matrices of size ", rows, "x", cols, " with a total of ", total_size, " elements."); matrix<i64> A = rnd.generate_matrix(rows, cols, thread_count); matrix<i64> B = rnd.generate_matrix(rows, cols, thread_count); dual_println("Adding two matrices (single-threaded)..."); matrix<i64> ApB_single = add_matrices(A, B, 0); dual_println("Adding two matrices (multithreaded)..."); matrix<i64> ApB_multi = add_matrices(A, B, thread_count); dual_println("Comparing the results..."); check(ApB_single == ApB_multi); dual_println("Transposing a matrix (single-threaded)..."); matrix<i64> At_single = A.transpose(0); dual_println("Transposing a matrix (multithreaded)..."); matrix<i64> At_multi = A.transpose(thread_count); dual_println("Comparing the results..."); check(At_single == At_multi); dual_println("Multiplying two matrices (single-threaded)..."); matrix<i64> AxB_single = multiply_matrices(A, B, 0); dual_println("Multiplying two matrices (multithreaded)..."); matrix<i64> AxB_multi = multiply_matrices(A, B, thread_count); dual_println("Comparing the results..."); check(AxB_single == AxB_multi); } /** * @brief Print the timing of a specific test. * * @param num_tasks The number of tasks. * @param mean_sd std::pair containing the mean as the first member and standard deviation as the second member. */ void print_timing(const ui32 &num_tasks, const std::pair<double, double> &mean_sd) { if (num_tasks == 1) dual_print("With 1 task"); else dual_print("With ", std::setw(3), num_tasks, " tasks"); dual_println(", mean execution time was ", std::setw(6), mean_sd.first, " ms with standard deviation ", std::setw(4), mean_sd.second, " ms."); } /** * @brief Calculate and print the speedup obtained by multithreading. * * @param timings A vector of the timings corresponding to different numbers of tasks. * @return The maximum speedup obtained. */ double print_speedup(const std::vector<double> &timings) { const auto [min_time, max_time] = std::minmax_element(std::begin(timings), std::end(timings)); double max_speedup = *max_time / *min_time; dual_println("Maximum speedup obtained: ", max_speedup, "x."); return max_speedup; } /** * @brief Calculate the mean and standard deviation of a set of integers. * * @param timings The integers. * @return std::pair containing the mean as the first member and standard deviation as the second member. */ std::pair<double, double> analyze(const std::vector<i64> &timings) { double mean = 0; for (size_t i = 0; i < timings.size(); i++) mean += (double)timings[i] / (double)timings.size(); double variance = 0; for (size_t i = 0; i < timings.size(); i++) variance += ((double)timings[i] - mean) * ((double)timings[i] - mean) / (double)timings.size(); double sd = std::sqrt(variance); return std::pair(mean, sd); } /** * @brief Perform a performance test using some matrix operations. */ void check_performance() { // Set the formatting of floating point numbers. dual_print(std::fixed, std::setprecision(1)); // Initialize a random_matrix_generator object to generates matrices with real (floating-point) numbers uniformly distributed between -1000 and 1000. random_matrix_generator<double, std::uniform_real_distribution<double>> rnd(-1000, 1000); // Initialize a timer object to measure the execution time of various operations. timer tmr; // If the CPU has more than 8 threads, we leave 2 threads for the rest of the operating system. Otherwise, performance may suffer. const ui32 thread_count = pool.get_thread_count() <= 8 ? pool.get_thread_count() : pool.get_thread_count() - 2; dual_println("Using ", thread_count, " out of ", pool.get_thread_count(), " threads."); // Define the size of the matrices to use. const ui64 rows = thread_count * 200; const ui64 cols = rows; // The number of tasks to try for each operation. const ui32 try_tasks[] = {1, thread_count / 4, thread_count / 2, thread_count, thread_count * 2, thread_count * 4}; // Generate two random test matrices to be used for benchmarking addition, transposition, and random matrix generation. matrix<double> A = rnd.generate_matrix(rows, cols, thread_count); matrix<double> B = rnd.generate_matrix(rows, cols, thread_count); // Generate two random test matrices to be used for benchmarking multiplication. Since matrix multiplication is O(n^3), we reduce the size of the test matrices so that this operation completes within a reasonable time. constexpr ui64 mult_factor = 8; matrix<double> X = rnd.generate_matrix(rows / mult_factor, cols / mult_factor, thread_count); matrix<double> Y = rnd.generate_matrix(cols / mult_factor, rows / mult_factor, thread_count); // Vectors to store statistics. std::vector<double> different_n_timings; std::vector<i64> same_n_timings; std::vector<double> speedups; // How many times to run each test. constexpr ui32 repeat = 20; dual_println("\nAdding two ", rows, "x", cols, " matrices ", repeat, " times:"); for (ui32 n : try_tasks) { for (ui32 i = 0; i < repeat; i++) { tmr.start(); matrix<double> C = add_matrices(A, B, n); tmr.stop(); same_n_timings.push_back(tmr.ms()); } auto mean_sd = analyze(same_n_timings); print_timing(n, mean_sd); different_n_timings.push_back(mean_sd.first); same_n_timings.clear(); } speedups.push_back(print_speedup(different_n_timings)); different_n_timings.clear(); dual_println("\nTransposing one ", rows, "x", cols, " matrix ", repeat, " times:"); for (ui32 n : try_tasks) { for (ui32 i = 0; i < repeat; i++) { tmr.start(); matrix<double> C = A.transpose(n); tmr.stop(); same_n_timings.push_back(tmr.ms()); } auto mean_sd = analyze(same_n_timings); print_timing(n, mean_sd); different_n_timings.push_back(mean_sd.first); same_n_timings.clear(); } speedups.push_back(print_speedup(different_n_timings)); different_n_timings.clear(); dual_println("\nMultiplying two ", rows / mult_factor, "x", cols / mult_factor, " matrices ", repeat, " times:"); for (ui32 n : try_tasks) { for (ui32 i = 0; i < repeat; i++) { tmr.start(); matrix<double> C = multiply_matrices(X, Y, n); tmr.stop(); same_n_timings.push_back(tmr.ms()); } auto mean_sd = analyze(same_n_timings); print_timing(n, mean_sd); different_n_timings.push_back(mean_sd.first); same_n_timings.clear(); } speedups.push_back(print_speedup(different_n_timings)); different_n_timings.clear(); dual_println("\nGenerating random ", rows, "x", cols, " matrix ", repeat, " times:"); for (ui32 n : try_tasks) { for (ui32 i = 0; i < repeat; i++) { tmr.start(); matrix<double> C = rnd.generate_matrix(rows, cols, n); tmr.stop(); same_n_timings.push_back(tmr.ms()); } auto mean_sd = analyze(same_n_timings); print_timing(n, mean_sd); different_n_timings.push_back(mean_sd.first); same_n_timings.clear(); } speedups.push_back(print_speedup(different_n_timings)); const double max_speedup = *std::max_element(std::begin(speedups), std::end(speedups)); dual_println("\nOverall, multithreading provided speedups of up to ", max_speedup, "x."); } int main() { std::string log_filename = "thread_pool_test-" + get_time() + ".log"; log_file.open(log_filename); dual_println("A C++17 Thread Pool for High-Performance Scientific Computing"); dual_println("(c) 2021 <NAME> (<EMAIL>) (http://baraksh.com)"); dual_println("GitHub: https://github.com/bshoshany/thread-pool\n"); dual_println("Thread pool library version is ", THREAD_POOL_VERSION, "."); dual_println("Hardware concurrency is ", std::thread::hardware_concurrency(), "."); dual_println("Generating log file: ", log_filename, ".\n"); dual_println("Important: Please do not run any other applications, especially multithreaded applications, in parallel with this test!"); print_header("Checking that the constructor works:"); check_constructor(); print_header("Checking that reset() works:"); check_reset(); print_header("Checking that push_task() works:"); check_push_task(); print_header("Checking that submit() works:"); check_submit(); print_header("Checking that wait_for_tasks() works..."); check_wait_for_tasks(); print_header("Checking that parallelize_loop() works:"); check_parallelize_loop(); print_header("Checking that task monitoring works:"); check_task_monitoring(); print_header("Checking that pausing works:"); check_pausing(); print_header("Checking that exception handling works:"); check_exceptions(); print_header("Testing that matrix operations produce the expected results:"); check_matrix(); if (tests_failed == 0) { print_header("SUCCESS: Passed all " + std::to_string(tests_succeeded) + " checks!", '+'); print_header("Performing matrix performance test:"); check_performance(); print_header("Thread pool performance test completed!", '+'); } else { print_header("FAILURE: Passed " + std::to_string(tests_succeeded) + " checks, but failed " + std::to_string(tests_failed) + "!", '+'); dual_println("\nPlease submit a bug report at https://github.com/bshoshany/thread-pool/issues including the exact specifications of your system (OS, CPU, compiler, etc.) and the generated log file."); } return 0; }
20de1bf21c8e325455c3b7f3ae32ff82b485a8d8
[ "C++" ]
1
C++
Sandalmoth/thread-pool
f012a783a1752ce562d8c83b48c5675e318c60d8
6f8353cbe96c28c5410a7f99508f78d6fc3117ac
refs/heads/master
<file_sep><?php /** * @file * Handles counts of node views via Ajax with minimal bootstrap. */ /** * Root directory of Drupal installation. */ define('DRUPAL_ROOT', substr($_SERVER['SCRIPT_FILENAME'], 0, strpos($_SERVER['SCRIPT_FILENAME'], '/sites/all/modules/unick_statistics/unick_statistics.php'))); // Change the directory to the Drupal root. chdir(DRUPAL_ROOT); include_once DRUPAL_ROOT . '/includes/bootstrap.inc'; drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES); drupal_bootstrap(DRUPAL_BOOTSTRAP_SESSION); if (variable_get('statistics_count_content_views', 0) && variable_get('statistics_count_content_views_ajax', 0)) { $nid = $_POST['nid']; if (is_numeric($nid)) { drupal_session_start(); $first_time = true; if (isset($_SESSION['nodes'])){ $nodes = explode(',',$_SESSION['nodes']); if (!in_array($nid,$nodes)){ $nodes[] = $nid; }else{ $first_time = false; } }else{ $nodes = array(); } $_SESSION['nodes'] = implode(',',$nodes); if ($first_time){ db_merge('node_counter') ->key(array('nid' => $nid)) ->fields(array( 'daycount' => 1, 'totalcount' => 1, 'timestamp' => REQUEST_TIME, )) ->expression('daycount', 'daycount + 1') ->expression('totalcount', 'totalcount + 1') ->execute(); } } }
2192cf33f9bda8241392546e224fe23f5523ae48
[ "PHP" ]
1
PHP
alfaq/unick_statistics
d31d7311056aecf5bbd4c430f3bdfc3c33414666
18a3f1c8a76306a28b6aeab9b9045b2bf900e94c
refs/heads/master
<repo_name>IVMorozov/Lesson7<file_sep>/test.php <!DOCTYPE html> <html lang="ru"> <head> <meta charset="utf-8"> <title>Тестирование</title> <link rel="stylesheet" href="styles.css"> </head> <body> <section class="bgrnd-main"> <nav> <a class="navigation" href="admin.php">Загрузка теста</a> <a class="navigation" href="list.php">Выбор тестов</a> <a class="navigation active" href="test.php">Тестирование</a> </nav> <?php error_reporting(0); $pieces = explode("item=", $_SERVER['REQUEST_URI']); If (isset($pieces[1])) { $test_path = __DIR__ . DIRECTORY_SEPARATOR . Tests . DIRECTORY_SEPARATOR . $pieces[1]; if (!file_exists($test_path)) { header('HTTP/1.1 404 Not Found'); exit; } $tmp_path = file_get_contents($test_path); $test_json = json_decode($tmp_path, true); ?> <section class="testblock"> <form class="list" action="test.php" method="POST"> <?php $Test_index = count($test_json)-2; $Test_number; $item; $break='vs'; $index; $Ansers_checked; $Test_count = count($test_json)-1; echo'<h1 >Ответьте на вопросы теста:</h1>'; for ($Test_number = 0; $Test_number <= $Test_index; $Test_number++) { echo'<div class="test-part">'; $Correct_answer[$Test_number]=$test_json[$Test_number]['correct_answer']; echo'<h1 class="test-header">'. $test_json[$Test_number]['question'].'</h1>'; foreach ($test_json[$Test_number]['answers'] as $index => $item) { echo '<input class="item" type="radio" name="Answers['.$Test_number.']" value='.$item.$break.$test_json[$Test_number]['correct_answer'].$break.$Test_count.'>'.$item;} echo'</div>' ; } ?> <p><input class="testchoice" type="submit" value="Ответить"></p> </form> <?php } else { if (count($_POST) == 0 ) { echo'<p class="final">Вы не выбрали ни один вариант, начните заново с выбора теста (вкладка "выбор тестов")</p>'; exit; } $Ansers_checked=$_POST; $Result; $Test_count; $Result_count; $All_Test_count; $Final_result; $Missed_Count; foreach ($Ansers_checked['Answers'] as $index => $answer) { $Chek=explode('vs', $answer); If ($Chek[0]==$Chek[1]) { $Result[$answer]=1; $All_Test_count=$Chek[2]; } else { $Result[$answer]=0; $All_Test_count=$Chek[2]; } $Result_count=$Result_count+$Result[$answer]; } $Test_count=count($Result); $Missed_Count=$All_Test_count-$Test_count; IF ($Missed_Count==0) {unset($Missed_Count);} else {$Missed_Count= '<br> Проигнорировали вопросов - '.$Missed_Count;} if ($Result_count>0) { $Final_result= 'Вы ответили правильно на '.$Result_count.' из '.$All_Test_count.' вопросов!'; echo'<p class="final">'.$Final_result.$Missed_Count.'</p>'; Session_start(); $Mark = $Result_count/$All_Test_count*100; $_SESSION['mark']=$Mark; ?> <form action="sertificate.php" method="POST"> <label class="final">Введите Ваше имя</label> <p><input type="text" name="username"></p> <br> <input type="submit" value="Далее"> </form> <?php } else { $Final_result='Вы не ответили правильно ни на один вопрос!'; echo'<p class="final">'.$Final_result.$Missed_Count.'</p>'; } } ?> </section> </body> </html><file_sep>/sertificate.php <?php header("Content-type: image/png"); if (!$_POST['username']) { $name = 'Неизвестный пользователь'; $size=30; } else { $name = $_POST['username']; $size=50; } $font = (__DIR__. DIRECTORY_SEPARATOR .'times.ttf'); $sert = imagecreatetruecolor(800, 600); $textColor = imagecolorallocate($sert, 120, 220, 100); $bgrndColor=0; imagefill($sert, 0, 0, $bgrndColor); $sertPNG = imagecreatefrompng(__DIR__. DIRECTORY_SEPARATOR .'sertificate.png'); imagecopy($sert, $sertPNG, 0, 0, 0, 0, 800, 600); $sert_text = imagecreate(700, 500); $textColor = imagecolorallocate($sert, 255, 255, 255); Session_start(); imagettftext($sert, 50, 0, 180, 120, $textColor, $font, "СЕРТИФИКАТ"); imagettftext($sert, 25, 0, 250, 200, $textColor, $font, "выдан пользователю"); imagettftext($sert, $size, 0, 180, 320, $textColor, $font, $name); imagettftext($sert, 20, 0, 180, 420, $textColor, $font, "Результат прохождения теста - ".$_SESSION['mark']."%"); imagePNG($sert); imageDestroy($sert); <file_sep>/list.php <!DOCTYPE html> <html lang="ru"> <head> <meta charset="utf-8"> <title>Выбор теста</title> <link rel="stylesheet" href="styles.css"> </head> <body> <section class="bgrnd-main"> <nav> <a class="navigation" href="admin.php">Загрузка теста</a> <a class="navigation active" href="list.php">Выбор тестов</a> <a class="navigation" href="test.php">Тестирование</a> </nav> <p class="help-block">Выберете тест</p> </section> <?php error_reporting(0); $dir = (__DIR__ . DIRECTORY_SEPARATOR . Tests); $files = scandir($dir); foreach ($files as $index => $filetype) { If (strrpos($filetype, 'json')) {$Testlist[]= $filetype;} } ?> <section class="bgrnd-test"> <div class="testarea"> <form class="list" action="test.php" method="GET" > <?php foreach ($Testlist as $index => $file) { echo '<input class="item" type="radio" name="item" value='.$file.'>'.$file.'<Br>';} ?> <p><input class="testchoice" type="submit" value="Выбрать тест"></p> </form> </div> </section> </body> </html><file_sep>/admin.php <!DOCTYPE html> <html lang="ru"> <head> <meta charset="utf-8"> <title>title1</title> <link rel="stylesheet" href="styles.css"> </head> <body> <section class="bgrnd-main"> <nav> <a class="navigation active" href="admin.php">Загрузка теста</a> <a class="navigation" href="list.php">Выбор тестов</a> <a class="navigation" href="test.php">Тестирование</a> </nav> <p class="help-block">Выберете файл с тестом для загрузки (в формате ***.json)</p> <form action="admin.php" method="post" enctype="multipart/form-data"> <input class="btn" type="file" name="userfile" > <input type="submit" value="Загрузить тест"> </form> </section> <?php error_reporting(0); // Функция проверяет расширение файла. function extCheck($fileName, $ext) { return in_array(pathinfo($fileName, PATHINFO_EXTENSION), $ext); } // Проверяем загружен ли файл if(is_uploaded_file($_FILES['userfile']['tmp_name'])){ if (!extCheck($_FILES['userfile']['name'], ['json'])) { echo '<p class="help-block">Допускаются только файлы с расширением <strong>json</strong>.</p>'; exit; } $tmp_path=file_get_contents($_FILES['userfile']['tmp_name']); $tmp_json =json_decode($tmp_path, true); if (is_null($tmp_json['Test_Group_id'])) { echo '<p class="help-block">Неверный формат теста</p>'; exit; } if (is_null($tmp_json[0]['question'])) { echo '<p class="help-block">Неверный формат теста</p>'; exit; } // Если файл загружен успешно, перемещаем его из временной директории в конечную move_uploaded_file( $_FILES['userfile']['tmp_name'], __DIR__ . DIRECTORY_SEPARATOR . Tests . DIRECTORY_SEPARATOR . $_FILES['userfile']['name']); if(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . Tests . DIRECTORY_SEPARATOR . $_FILES["userfile"]["name"])){ echo '<p class="help-block">Файл успешно загружен</p>'; header('Location: list.php'); } } ?> </body> </html>
5b36e4126fea9bd697452eb6b0db3c85302e798d
[ "PHP" ]
4
PHP
IVMorozov/Lesson7
7fb8e0a386a165afc34b5d27fbee898a0c292e00
5cfa22aeed1a8258527a5626425e76b063285199
refs/heads/main
<repo_name>dura51/remasteredscan<file_sep>/README.md # remasteredscan this tool is most nearly of my last tool but it is remastered, this tool will make you make a scan for the websites with Nmap and let you ping any website you need, it will ping the website 10 times, I hope you like it and enjoy it (: <file_sep>/remasteredscan.sh #!/bin/bash nocolor="\033[0m" red="\033[0;31m" blue="\033[0;34m" yellow="\033[0;33m" purple="\033[0;35m" domain=$1 cat << "EOF" _____ _____ __ | __ \ | ____/_ | | | | |_ _ _ __ __ _| |__ | | | | | | | | | '__/ _` |___ \ | | | |__| | |_| | | | (_| |___) || | |_____/ \__,_|_| \__,_|____/ |_| . / \ / \ / | \ | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ____/| | |\____ /____/\___/\____/ ) (_______________)/ |/////| |/////| |/////| |/////| |/////| |/////| |/////| (_______) this is the same tool of ourfirstscan but this is remastered I hope you like it Buddy BY : Dura51 EOF if [ $(whoami) != "root" ]; then echo -e "${red}Dude! you have to be root${nocolor}" exit else if [ -z $domain ]; then echo -e "${red}Come on dude! where is your domain? enter your target domain${nocolor}" else echo -e "${yellow}.........[I am working on your $domain]........." gnome-terminal -e "ping -c15 $domain" sleep touch urscan.txt && gnome-terminal -e "tail -F urscan.txt" nmap -sS -O -oX nmap.xml $domain > urscan.txt echo -e "${purple}.........[The End]........." fi fi
6cc6dffab252514964d1a65709a36299eeb43f0a
[ "Markdown", "Shell" ]
2
Markdown
dura51/remasteredscan
e9e74906b1287f16d95142243f8f2104b070322a
dfdea5a06d025003a97a463117b76d4091c94427
refs/heads/master
<file_sep>Create table Movies ( movie_id int identity(1,1) not null primary key, --renamed to id name varchar(5000) not null, genre varchar(5000) not null, numberOfDiscs int not null, ); Create table TvShows ( show_id int identity(1,1) not null, -- renamed to id name varchar(5000) not null, genre varchar(5000) not null, numberOfDiscs int not null, hasMovie bit not null constraint pk_show_id Primary key (show_id) ); Alter Table TvShows Add FOREIGN KEY (id) REFERENCES Movies(id); Alter Table TvShows Add numberOfSeasons int; Insert into Movies (name, genre, numberOfDiscs) Values ('Harry Potter and the Sorcerers Stone', 'Adventure', 2), ('Harry Potter and the Chamber of Secrets', 'Adventure', 2), ('Harry Potter and the Prisoner of Azkaban', 'Adventure', 2), ('Harry Potter and the Goblet of Fire', 'Adventure', 2), ('Harry Potter and the Order of the Phoenix', 'Adventure', 1), ('Harry Potter and Half-Blood Prince', 'Adventure', 1), ('Harry Potter and Deathly Hallows Part 1', 'Adventure', 2), ('Harry Potter and Deathly Hallows Part 2', 'Adventure', 2); Insert into Movies (name, genre, numberOfDiscs) Values ('Beverly Hills Cop', 'Comedy', 1), ('Beverly Hills Cop II', 'Comedy', 1), ('Beverly Hills Cop III', 'Comedy', 1), ('The Blind Side', 'Drama(Based on a true story)', 1), ('Bend it Like Beckham', 'Drama', 1), ('Bedtime Stories', 'Comedy', 2), ('Disturbia', 'Suspense', 1), ('The Mighty Ducks', 'Comedy', 1), ('D2: The Mighty Ducks', 'Comedy', 1), ('D3: The Mighty Ducks', 'Comedy', 1), ('Good Luck Chuck', 'Comedy', 1), ('Herbie: Fully Loaded', 'Comedy', 1), ('Hitch', 'Romantic Comedy(Chick Flick)', 1), ('Happy Gilmore', 'Comedy', 1), ('It Could Happen to You', 'Romantic Comedy(Chick Flick)', 1), ('Journey to the Center of the Earth', 'Adventure', 1), ('Knocked Up', 'Comedy', 1), ('License to Wed', 'Romantic Comedy(Chick Flick)', 1); Insert into Movies (name, genre, numberOfDiscs) Values ('Supergirl', 'Action', 1), ('Superman', 'Action', 1), ('Superman II', 'Action', 1), ('Superman III', 'Action', 1), ('Superman IV: The Quest for Peace', 'Action', 1), ('Superman Returns', 'Action', 1), ('The Simpsons Movie', 'Animated Comedy', 1), ('Teenage Mutant Ninja Turtles', 'Action', 1), ('Teenage Mutant Ninja Turtles II', 'Action', 1), ('Teenage Mutant Ninja Turtles III', 'Action', 1), ('TMNT', 'Action', 1), ('The Wedding Singer', 'Comedy', 1), ('Monsters, Inc.', 'Pixar Comedy', 2), ('Enchanted', 'Romantic Comedy(Chick Flick)', 1), ('Yes Man', 'Comedy', 1), ('Under Siege', 'Action', 1), ('Under Siege 2: Dark Territory', 'Action', 1), ('Space Jam', 'Animated Comedy', 2), ('<NAME>: Prince of Thieves', 'Adventure', 1); Insert into Movies (name, genre, numberOfDiscs) Values('Glory Road', 'Drama(Based on a True Story)', 1), ('Facing the Giants', 'Drama', 1), ('Catch Me if You Can', 'Drama', 2), ('<NAME>', 'Comedy', 1), ('Cars', 'Pixar Comedy', 1), ('<NAME>', 'Comedy', 1), ('Blue Streak', 'Comedy', 1), ('<NAME>', 'Drama(Based on a True Story)', 1), ('Troy', 'Drama', 2), ('We Are Marshall', 'Drama(Based on a True Story)', 1), ('Stealth', 'Action', 1), ('Stranger than Fiction', 'Comedy', 1), ('The Express: The Ernie Davis Story', 'Drama(Based on a True Story)', 1), ('Hancock', 'Action', 1); Insert into Movies (name, genre, numberOfDiscs) Values ('<NAME>', 'Comedy', 1), ('Inspector Gadget 2', 'Comedy', 1), ('<NAME>', 'Comedy', 1), ('Major League', 'Comedy', 1), ('Major League II', 'Comedy', 1), ('Major League: Back to the Minors', 'Comedy', 1), ('The Incredibles', 'Pixar Comedy', 2), ('Garfield: The Movie', 'Comedy', 1), ('Garfield: A Tail of Two Kitties', 'Comedy', 1), ('Click', 'Comedy', 1), ('Eurotrip', 'Comedy', 1), ('The Karate Kid', 'Action', 1), ('The House Bunny', 'Comedy', 1), ('The Waterboy', 'Comedy', 1), ('The Tuxedo', 'Comedy', 1), ('Shes The Man', 'Comedy', 1), ('The Bucket List', 'Comedy', 1), ('Bloodsport', 'Action', 1), ('Timecop', 'Action', 1); Insert into Movies (name, genre, numberOfDiscs) Values ('Transformers', 'Action', 1), ('Transformers: Revenge of the Fallen', 'Action', 2), ('Transformers: Dark of the Moon', 'Action', 2), ('Harold & Kumar Go To White Castle', 'Comedy', 1), ('Harold & Kumar Escape From Guantanamo Bay', 'Comedy', 1), ('Ice', 'Action', 1), ('A Rage in Harlem', 'Action', 1), ('The Glass Shield', 'Action', 1), ('Malevolent', 'Action', 1), ('License to Kill', 'Action', 1), ('Road Ends', 'Action', 1), ('In Too Deep', 'Action', 1), ('Cry the Beloved Country', 'Action', 1), ('The Pacifier', 'Comedy', 1), ('Slumdog Millionaire', 'Drama', 1), ('Speed Racer', 'Action', 1), ('Get Smart', 'Comedy', 1), ('Accepted', 'Comedy', 1), ('October Sky', 'Drama(Based on a True Story)', 1), ('Raising Helen', 'Romantic Comedy(Chick Flick)', 1), ('Race to Witch Mountain', 'Adventure', 1), ('Philadelphia', 'Drama', 1), ('<NAME>', 'Comedy', 1), ('Monty Python and the Holy Grail', 'Comedy', 1), ('Remember the Titans', 'Drama(Based on a True Story)', 1), ('Love Wrecked', 'Comedy', 1), ('Night at the Museum', 'Romantic Comedy(Chick Flick)', 1), ('Night at the Museum: Battle of the Smithsonian', 'Comedy', 1), ('Convict 762', 'Action', 1), ('Fortress', 'Action', 1), ('Total Recall 2070: Machine Dreams', 'Action', 1), ('Cypher', 'Action', 1), ('Trancers I', 'Action', 1), ('Equilibrium', 'Action', 1), ('Impostor', 'Action', 1), ('The Prophecy', 'Action', 1), ('The Flintstones', 'Comedy', 1), ('The Game Plan', 'Comedy', 1), ('The Heartbreak Kid', 'Comedy', 1), ('Sweet Home Alabama', 'Romantic Comedy(Chick Flick)', 1), ('<NAME>', 'Romantic Comedy(<NAME>lick)', 1), ('<NAME>', 'Comedy', 2), ('<NAME>: The Rise of Taj', 'Comedy', 1), ('Live Free or Die Hard', 'Action', 1), ('Looney Tunes: Back in Action', 'Comedy', 1), ('A Time to Kill', 'Drama', 1), ('Rookie of the Year', 'Comedy', 1), ('<NAME>', 'Comedy', 1), ('<NAME>: The Squeakquel', 'Comedy', 1), ('Alvin and the Chipmunks: Chipwrecked', 'Comedy', 1), ('<NAME>', 'Comedy', 1), ('<NAME>: The Spy Who Shagged Me', 'Comedy', 1), ('<NAME>: Goldmember', 'Comedy', 1); Insert into Movies (name, genre, numberOfDiscs) Values ('X-men', 'Action', 1), ('X-men 2: X-men United', 'Action', 2), ('X-men 3: The Last Stand', 'Action', 1), ('The Mask of Zorro', 'Action', 1), ('The Legend of Zorro', 'Action', 2), ('The Terminal', 'Romantic Comedy (Chick Flick)', 1), ('Timeline', 'Action', 1), ('Batman', 'Action', 1), ('Batman Returns', 'Action', 1), ('Batman Forever', 'Action', 1), ('Batman & Robin', 'Action', 1), ('Shrek', 'Comedy', 1), ('Shrek 2', 'Comedy', 1), ('Shrek The Third', 'Comedy', 2), ('Shrek Forever After: The Final Chapter', 'Comedy', 1); Insert into Movies (name, genre, numberOfDiscs) Values ('Avengers', 'Action', 1), ('Armageddon', 'Action', 1), ('Bicentennial Man', 'Drama', 1), ('A Beautiful Mind', 'Drama(Based on a True Story)', 2), ('Bewitched', 'Comedy', 1), ('Broken Arrow', 'Action', 1), ('<NAME>', 'Comedy', 1), ('<NAME>', 'Comedy', 1), ('Captain America: The First Avenger', 'Action', 1), ('Cast Away', 'Drama', 1), ('Deep Impact', 'Drama', 1), ('<NAME>', 'Comedy', 2), ('The DaVinci Code', 'Drama', 2), ('Double Jeopardy', 'Action', 1), ('Enemy of the State', 'Action', 1), ('Face/Off', 'Action', 1), ('Independence Day', 'Action', 1), ('The Fugitive', 'Action', 1), ('US Marshals', 'Action', 1), ('Batman Begins', 'Action', 1), ('Batman: The Dark Knight', 'Action', 2), ('Lethal Weapon 4', 'Action', 1), ('Outbreak', 'Drama', 1), ('Spaceballs', 'Comedy', 1), ('The Girl Next Door', 'Romantic Comedy (Chick Flick)', 1), ('Maverick', 'Comedy', 1), ('Wild Wild West', 'Comedy', 1); Insert into Movies (name, genre, numberOfDiscs) Values ('Star Wars Episode I: The Phantom Menace', 'Action', 2), ('Star Wars Episode II: Attack of the Clones', 'Action', 2), ('Star Wars Episode III: Revenge of the Sith', 'Action', 2), ('Star Wars Episode IV: A New Hope', 'Action', 2), ('Stars Wars Episode V: The Empire Strikes Back', 'Action', 2), ('Star Wars Episode VI; Return of the Jedi', 'Action', 2), ('Sister Act', 'Comedy', 1), ('Sister Act 2: Back in the Habit', 'Comedy', 1), ('Spiderman', 'Action', 2), ('Spiderman 2', 'Action', 2), ('Spiderman 3', 'Action', 1), ('Fantastic Four', 'Action', 1), ('Fantastic Four: Rise of the Silver Surfer', 'Action', 1), ('National Treasure', 'Action', 1), ('National Treasure 2: Book of Secrets', 'Action', 1), ('The Mummy', 'Action', 2), ('The Mummy Returns', 'Action', 1), ('The Mummy: Tomb of the Dragon Emperor', 'Action', 2), ('The Mask', 'Comedy', 1), ('<NAME>', 'Comedy', 1), ('I Am Legend', 'Drama', 2), ('<NAME>: Licence to Kill', 'Action', 1), ('Last Action Hero', 'Action', 1), ('Looks Whos Talking Now!', 'Comedy', 1), ('Jumanji', 'Comedy', 1), ('<NAME>', 'Drama', 2), ('Gandhi', 'Drama(Based on a True Story)', 2); Insert into Movies (name, genre, numberOfDiscs) Values ('Robocop', 'Action', 1), ('The Replacements', 'Comedy', 1), ('The Rookie', 'Drama(Based on a True Story)', 1), ('Wild Hogs', 'Comedy', 1), ('Tooth Fairy', 'Comedy', 1), ('The Shawshank Redemption', 'Drama', 1), ('True Lies', 'Action', 1), ('Speed', 'Action', 1), ('Air Force One', 'Action', 1), ('Rush Hour', 'Comedy', 1), ('Rush Hour 2', 'Comedy', 1), ('Rush Hour 3', 'Comedy', 1), ('The Terminator', 'Action', 1), ('Terminator 2: Judgment Day', 'Action', 2), ('Terminator 3: Rise of the Machines', 'Action', 2), ('The Producers', 'Musical', 1), ('No Reservations', 'Romantic Comedy', 1), ('Little Big League', 'Comedy', 1), ('Little Giants', 'Comedy', 1), ('Star Trek Generations', 'Action', 1), ('Star Trek First Contact', 'Action', 1), ('Star Trek Insurrection', 'Action', 1), ('Star Trek Nemesis', 'Action', 1), ('Grown Ups', 'Comedy', 1), ('<NAME>: The Rise of Cobra', 'Action', 2), ('Back to the Future', 'Action', 1), ('Back to the Future II', 'Action', 1), ('Back to the Future III', 'Action', 1), ('Home Alone', 'Comedy', 1), ('Home Alone 2', 'Comedy', 1), ('Home Alone 3', 'Comedy', 1), ('Iron Man', 'Action', 2), ('Iron Man 2', 'Action', 2), ('Legally Blonde', 'Romantic Comedy(Chick Flick)', 1), ('Legally Blonde 2: Red, White, & Blonde', 'Romantic Comedy (Chick Flick)', 1), ('Men In Black(MIB)', 'Comedy', 2), ('Jurassic Park', 'Action', 1), ('American Pie', 'Comedy', 2), ('American Pie 2', 'Comedy', 1), ('American Wedding', 'Comedy', 1), ('Indiana Jones and the Kingdom of the Crystal Skull', 'Action', 1); Insert into TvShows(name, genre, numberOfDiscs, hasMovie, numberOfSeasons) Values ('MLB Bloopers', 'Sports', 1, 0, 1); Insert into TvShows(name, genre, numberOfDiscs, hasMovie, numberOfSeasons) Values ('Knight Rider 1982-1986', 'Action', 24, 1, 4), ('Knight Rider 2008', 'Action', 4, 1, 1), ('Pee-wees Playhouse', 'Comedy', 11, 1, 5), ('House', 'Drama', 36,0,8);
e0adad628bc45528cdafc02c0d2209a8487bb586
[ "SQL" ]
1
SQL
sekharmamidi97/DVD-Collection
1855df34655140adc5a9d5142092b6bc4e27c65c
9b4bf4f6adea2a610b717c1d11aa7dfec119a9b9
refs/heads/main
<file_sep>import cv2 import os import pandas as pd from sklearn.model_selection import train_test_split import numpy as np def organize(): folder_path = 'data/Thermal' set_folders = os.listdir(folder_path) faces_count = 0 new_folder = folder_path+'_organized' if not os.path.exists(new_folder): os.mkdir(new_folder) for set_single in set_folders: set_path = os.path.join(folder_path, set_single) participant_folders = os.listdir(set_path) print(set_single) for participant_folder in participant_folders: print(participant_folder) person_path = os.path.join(set_path, participant_folder) if os.path.isdir(person_path): image_names = os.listdir(person_path) for image_name in image_names: image_path = os.path.join(person_path, image_name) print(image_name) img = cv2.imread(image_path) cv2.imwrite(os.path.join(new_folder, set_single+'-'+participant_folder+'-'+image_name), img) def split(folder_path, new_folder): def save_images(data, folder_path, new_folder, image_names, dataset_type): csv_list = [] for d in data: image_id = str(d[0])+'-'+str(d[1])+'-'+str(d[2]) #image_id = str(d[0]) img = cv2.imread(os.path.join(folder_path, image_id)) # Salvando como Xmin, Xmax, Ymin, Ymax #csv_list.append([d[0], d[1], d[2], d[3], d[4], 'Face']) #csv_list.append([image_id, d[3], d[4], d[5], d[6], 'Face']) h, w, c = img.shape # csv_list.append([image_id, d[3]/w, d[4]/h, (d[3]+d[5])/w, (d[4]+d[6])/h, 'Face']) csv_list.append([image_id, d[3]/w, (d[3]+d[5])/w, d[4]/h, (d[4]+d[6])/h, 'Face']) cv2.imwrite(os.path.join(new_folder, dataset_type, image_id), img) df = pd.DataFrame(csv_list, columns= ['ImageID', 'XMin', 'XMax', 'YMin', 'YMax', 'ClassName']) df.to_csv(os.path.join(new_folder,'sub-'+dataset_type+'-annotations-bbox.csv'), index=False) if not os.path.exists(new_folder): os.mkdir(new_folder) os.mkdir(os.path.join(new_folder, 'train')) os.mkdir(os.path.join(new_folder, 'val')) os.mkdir(os.path.join(new_folder, 'test')) image_names = os.listdir(folder_path) csv_folder = 'data' #csv_path = os.path.join(csv_folder,'sub-'+'all'+'-annotations-bbox.csv') csv_path = os.path.join(csv_folder,'annotations.csv') csv = pd.read_csv(csv_path) headers = list(csv) print(headers) data = csv.values.tolist() # print(type(data['Set'])) print(data[0]) #data1, data2 = train_test_split(data, test_size=0.8, random_state=42) train_val_data, test_data = train_test_split(data, test_size=0.1, random_state=42) train_data, val_data = train_test_split(train_val_data, test_size=0.1, random_state=42) save_images(train_data, folder_path, new_folder, image_names, 'train') save_images(val_data, folder_path, new_folder, image_names, 'val') save_images(test_data, folder_path, new_folder, image_names, 'test') def convert_txt2csv(txt_path, csv_folder): f = open(txt_path) lines = f.readlines() # print(type(lines)) # print(lines[2]) # print(type(lines[1])) data = [] for line in lines: #print(line) line_replace= line.replace(' ', '-') line_split = line_replace.split('-') #print(data_dirty) # Filtra a string data_dirty = [] for l in line_split: if l != '': data_dirty.append(l) #print(data_dirty) d = [data_dirty[0], int(data_dirty[1]), int(data_dirty[2]), int(data_dirty[1])+int(data_dirty[3]), int(data_dirty[2])+int(data_dirty[4][:-1]), 'Face'] #print(d) data.append(d) f.close() print(len(data)) df = pd.DataFrame(data, columns= ['ImageID', 'XMin', 'XMax', 'YMin', 'YMax', 'ClassName']) df.to_csv(os.path.join(csv_folder,'sub-'+'all'+'-annotations-bbox.csv'), index=False) # txt_path = 'data/CelebA/list_bbox_celeba.txt' # csv_folder = 'data/CelebA' # convert_txt2csv(txt_path, csv_folder) #folder_path = 'data/CelebA/img_celeba' #new_folder = 'data/CelebA/img_celeba_splitted' folder_path = 'data/Thermal_organized' new_folder = 'data/Thermal_organized_splitted' split(folder_path, new_folder) #organize() #train_folder = folder_path+'train' <file_sep>import cv2 import os import numpy as np import pandas as pd from scipy.ndimage import zoom #from matplotlib import pyplot as plt def clipped_zoom(img, zoom_factor, **kwargs): h, w = img.shape[:2] # For multichannel images we don't want to apply the zoom factor to the RGB # dimension, so instead we create a tuple of zoom factors, one per array # dimension, with 1's for any trailing dimensions after the width and height. zoom_tuple = (zoom_factor,) * 2 + (1,) * (img.ndim - 2) # Zooming out if zoom_factor < 1: # Bounding box of the zoomed-out image within the output array zh = int(np.round(h * zoom_factor)) zw = int(np.round(w * zoom_factor)) top = (h - zh) // 2 left = (w - zw) // 2 # Zero-padding out = np.zeros_like(img) out[top:top+zh, left:left+zw] = zoom(img, zoom_tuple, **kwargs) # Zooming in elif zoom_factor > 1: # Bounding box of the zoomed-in region within the input array zh = int(np.round(h / zoom_factor)) zw = int(np.round(w / zoom_factor)) top = (h - zh) // 2 left = (w - zw) // 2 out = zoom(img[top:top+zh, left:left+zw], zoom_tuple, **kwargs) # `out` might still be slightly larger than `img` due to rounding, so # trim off any extra pixels at the edges trim_top = ((out.shape[0] - h) // 2) trim_left = ((out.shape[1] - w) // 2) out = out[trim_top:trim_top+h, trim_left:trim_left+w] # If zoom_factor == 1, just return the input array else: out = img return out def detect_dnn_frame(net, frame): frameOpencvDnn = frame.copy() frameHeight = frameOpencvDnn.shape[0] frameWidth = frameOpencvDnn.shape[1] blob = cv2.dnn.blobFromImage(frameOpencvDnn, 1.0, (300, 300), [104, 117, 123], False, False) conf_threshold = 0.7 net.setInput(blob) detections = net.forward() bboxes = [] for i in range(detections.shape[2]): confidence = detections[0, 0, i, 2] if confidence > conf_threshold: x1 = int(detections[0, 0, i, 3] * frameWidth) y1 = int(detections[0, 0, i, 4] * frameHeight) x2 = int(detections[0, 0, i, 5] * frameWidth) y2 = int(detections[0, 0, i, 6] * frameHeight) bboxes.append([x1, y1, x2, y2]) cv2.rectangle(frameOpencvDnn, (x1, y1), (x2, y2), (0, 255, 0), int(round(frameHeight/150)), 8) return frameOpencvDnn, bboxes def show_labels(folder_path): data = pd.read_csv(os.path.join(folder_path,'sub-'+'train'+'-annotations-bbox.csv')).values.tolist() # teste = np.array(annot[['Set', 'Participant', 'File']].astype(str)) # print(teste) # print('='*60) # folders.sort(key=int) train_folder =os.path.join(folder_path, 'train') image_names = os.listdir(train_folder) image_names.sort() #print(image_names) for d in data: #for i, image_name in enumerate(image_names): print(d) image_id = str(d[0]) image_path = os.path.join(train_folder, image_id) print(image_path) thermal = cv2.imread(image_path) print(thermal.shape) #print(image_path.split('/')[1:]) #(x,y,w,h) = np.array(d[['XMin', 'XMax', 'YMin', 'YMax']]) #(x,y,w,h) = (d[1], d[2], d[3], d[4]) (x,y,w,h) = (d[1], d[2], d[3], d[4]) print((x,y,w,h)) #thermal = cv2.rectangle(thermal,(x,y),(x+w,y+h),(255,0,0),2) thermal = cv2.rectangle(thermal,(x,y),(w,h),(255,0,0),2) cv2.imshow('Thermal', thermal) if cv2.waitKey(0) > 0: continue #break # cv2.imshow('Original', img) # cv2.imshow('Cinza', gray) # cv2.waitKey(0) folder_path = 'data/CelebA/img_celeba_splitted' #folder_path = 'data/Thermal_organized_splitted' show_labels(folder_path) #match_template(folder_path, rgb_folder_path)
f916eea16c2e647f88e8ed48c2e58d5e16f2e70d
[ "Python" ]
2
Python
thimabru1010/ssd-thermal-face-detection
02afe46c21258fc1c14e6d9a4d23805262a9ae05
250d4924a000be253effd2e49c7f2f754c7c83d5
refs/heads/master
<repo_name>mayaa6/rn-china-region-picker<file_sep>/README.md # rn-china-region-picker 中国的省市区的多重级联react-native组件 # show ![rn-china-region-picker](https://raw.githubusercontent.com/hufeng/rn-china-region-picker/master/screencast/region.png) # usage ```javascript var Region = require('rn-china-region-picker'); <Region visible={false} //true展示,false不展示 selectedProvince={'110000'} //初始化省,不传默认也是北京 selectedCity={'110100'} //初始化市,不传默认也是北京 selectedArea={'110101'} //初始化区,不传默认为东城区 onSubmit={(params) => console.log(params)} onCancel={() => console.log('cancel')} /> ``` <file_sep>/index.js //expose module.exports = require('./lib/region'); <file_sep>/lib/region.js /** * 省市区级联 */ var React = require('react-native'); var webapi = require('./webapi'); var { View, Text, Animated, PickerIOS, StyleSheet, TouchableOpacity, Dimensions } = React; var win = Dimensions.get('window') var HEIGHT = win.height; var WIDTH = win.width; //just do nothing var noop = () => {}; var Region = React.createClass({ getDefaultProps() { return { //默认不显示 visible: false, //默认显示北京(省) selectedProvince: '110000', //默认显示北京(市) selectedCity: '110100', //默认显示(区) selectedArea: '110101', //确定 onSubmit: noop, //取消 onCancel: noop } }, /** * 改变新属性 */ componentWillReceiveProps(nextProps) { if (nextProps.visible != this.props.visible) { //开始动画 Animated.spring(this.state.topValue, { toValue: nextProps.visible ? HEIGHT : 0, friction: 10, tension: 30 }).start(); } }, componentWillMount() { //开始动画 Animated.spring(this.state.topValue, { toValue: this.props.visible ? HEIGHT : 0, friction: 10, tension: 30 }).start(); }, /** * 初始化状态 */ getInitialState() { return { //距离顶部的距离 topValue: new Animated.Value(0), //省 province: [], //市 city: [], //地区 area: [], //选中的省 selectedProvince: this.props.selectedProvince, //选中的市 selectedCity: this.props.selectedCity, //选中的地区 selectedArea: this.props.selectedArea } }, componentDidMount() { webapi .fetchRegionData() .then((data) => { //cache it. this._data = data; //过滤省 var province = this._filter('086'); this._selectedProvinceName = this._data[this.state.selectedProvince][0]; //过滤省对于的市 var city = this._filter(this.state.selectedProvince); //市的名字 this._selectedCityName = ''; if (this.state.selectedCity) { this._selectedCityName = this._data[this.state.selectedCity][0]; } //过滤第一个市对应的区 var area = []; if (this.state.selectedCity) { area = this._filter(this.state.selectedCity); this._selectAreaName = ''; if (this.state.selectedArea) { this._selectAreaName = this._data[this.state.selectedArea][0]; } } this.setState({ province: province, city: city, area: area }); }); }, render() { return ( <Animated.View ref='region' style={[styles.container, { top: this.state.topValue.interpolate({ inputRange: [0, HEIGHT], outputRange: [HEIGHT, 0] }) }]}> <View style={styles.region}> {/*头部按钮*/} <View style={styles.nav}> <TouchableOpacity onPress={this._handleCancel}> <Text style={styles.text}>取消</Text> </TouchableOpacity> <TouchableOpacity onPress={this._handleSubmit}> <Text style={styles.text}>确认</Text> </TouchableOpacity> </View> {/*省市区级联*/} <View style={styles.regionArea}> {/*省*/} <PickerIOS style={styles.regionItem} onValueChange={this._handleProvinceChange} selectedValue={this.state.selectedProvince}> {this.state.province.map((v, k) => { return ( <PickerIOS.Item value={v[0]} label={v[1]} key={k}/> ); })} </PickerIOS> {/*市*/} <PickerIOS style={styles.regionItem} onValueChange={this._handleCityChange} selectedValue={this.state.selectedCity}> {this.state.city.map((v, k) => { return (<PickerIOS.Item value={v[0]} label={v[1]} key={k}/>); })} </PickerIOS> {/*区*/} <PickerIOS style={styles.regionItem} onValueChange={this._handleAreaChange} selectedValue={this.state.selectedArea}> {this.state.area.map((v, k) => { return (<PickerIOS.Item value={v[0]} label={v[1]} key={k}/>); })} </PickerIOS> </View> </View> </Animated.View> ); }, /** * 处理省的改变 */ _handleProvinceChange(province) { //设置选中的省的名称 this._selectedProvinceName = this._data[province][0]; if (__DEV__) { console.log('省发生改变:', province, this._selectedProvinceName); } //过滤出改变后,省对应的市 var city = this._filter(province); //省下面没有市,包括台湾,香港,澳门 if (city.length === 0) { this._selectAreaName = ''; this._selectedCityName = ''; this.setState({ selectedProvince: province, selectedCity: '', selectedArea: '', city: [], area: [] }); } else { this._selectedCityName = city[0][1]; //过滤区域 var area = this._filter(city[0][0]); //区域名称 this._selectAreaName = area[0][1]; this.setState({ selectedProvince: province, selectedCity: city[0][0], selectedArea: area[0][0], city: city, area: area, }); } }, /** * 处理市改变 */ _handleCityChange(city) { this._selectedCityName = this._data[city][0]; if (__DEV__) { console.log('市发生改变:', city, this._selectedCityName); } //过滤出市变化后,区 var area = this._filter(city); if (area.length === 0) { this._selectAreaName = ''; this.setState({ selectedCity: city, selectedArea: '', area: [] }); } else { this._selectAreaName = area[0][1]; this.setState({ selectedCity: city, selectedArea: area[0][0], area: area }); } }, /** * 处理区域改变 */ _handleAreaChange(area) { this._selectAreaName = this._data[area][0]; if (__DEV__) { console.log('区域发生改变:', area, this._selectAreaName); } this.setState({ selectedArea: area }) }, /** * 处理取消 */ _handleCancel() { this.props.onCancel() }, /** * 处理确定 */ _handleSubmit() { this.props.onSubmit({ province: this.state.selectedProvince, city: this.state.selectedCity, area: this.state.selectedArea, provinceName: this._selectedProvinceName, cityName: this._selectedCityName, areaName: this._selectAreaName }) }, /** * 根据pid查询子节点 */ _filter(pid) { var result = []; for (var code in this._data) { if (this._data.hasOwnProperty(code) && this._data[code][1] === pid) { result.push([code, this._data[code][0]]); } } return result; } }); var styles = StyleSheet.create({ container: { flex: 1, width: WIDTH, height: HEIGHT, left: 0, position: 'absolute', backgroundColor: 'rgba(0, 0, 0, 0.5)', }, nav: { height: 60, padding: 20, justifyContent: 'space-between', alignItems: 'center', backgroundColor: 'blue', flexDirection: 'row' }, text: { color: '#FFF', fontSize: 20, fontWeight: 'bold' }, region: { flex: 1, marginTop: HEIGHT/2, backgroundColor: '#FFF' }, regionArea: { flexDirection: 'row' }, regionItem: { flex: 1 } }); module.exports = Region;
dcaeb063eb1f69004e50218e4ade0526a8330d9a
[ "Markdown", "JavaScript" ]
3
Markdown
mayaa6/rn-china-region-picker
70d28193e3ccf235dc59b9817006e0918f58b19b
7165ee876b6d0a2fa893ad7a2e6f7ad0be629756
refs/heads/master
<file_sep>using System.Collections.Generic; using PhotoSharingCloudWeb.Models; namespace PhotoSharingCloudWeb.Services { public interface IEmployeeService { List<Employee> GetEmployees(); Employee GetEmployee(int employeeId); void UploadImage(byte[] image, string mimeType, int empNo); } }<file_sep>$(function () { var chat = $.connection.chatHub; $('#chat-message').focus(); $.connection.hub.start().done() = function () { $('#sendMessage').on('click', function () { chat.server.send('TestName', $('#chat-message').val()); $('#chat-messge').val('').focus(); }); }; chat.client.addMessage = function (name, message) { var encodedName = $("<div>" + name + "</div>"); var encodedMessage = $("<div>" + message + "</div>"); var listItem = $("<li>" + encodedName + " : " + encodedMessage + "</li>"); $('#discussion').append(listItem); }; }) <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; using PhotoSharingCloudWeb.Models; namespace PhotoSharingCloudWeb.ViewModels { public class EmployeeViewModel { public int BusinessEntityID { get; set; } public string NationalIDNumber { get; set; } public string LoginID { get; set; } public short? OrganizationLevel { get; set; } public string JobTitle { get; set; } public DateTime BirthDate { get; set; } public string MaritalStatus { get; set; } public string Gender { get; set; } public DateTime HireDate { get; set; } public bool SalariedFlag { get; set; } public short VacationHours { get; set; } public short SickLeaveHours { get; set; } public bool CurrentFlag { get; set; } public Guid rowguid { get; set; } public DateTime ModifiedDate { get; set; } public byte[] Photo { get; set; } public virtual Person Person { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using PhotoSharingCloudWeb.Models; namespace PhotoSharingCloudWeb.Repositories { public class EmployeeRepository : IEmployeeRepository { private readonly AdventureWorksContext _ctx; public EmployeeRepository() { _ctx = new AdventureWorksContext(); } public List<Employee> GetEmployees() { return _ctx.Employees.ToList(); } public Employee GetEmployeeById(int employeeId) { return _ctx.Employees.Find(employeeId); } public void UploadImage(byte[] image, string mimeType, int empNo) { var employee = _ctx.Employees.Find(empNo); if (employee != null) { employee.Photo = image; _ctx.SaveChanges(); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using PhotoSharingCloudWeb.Models; using PhotoSharingCloudWeb.Repositories; namespace PhotoSharingCloudWeb.Services { public class EmployeeService : IEmployeeService { private readonly IEmployeeRepository _employeeRepository; public EmployeeService(IEmployeeRepository employeeRepository) { _employeeRepository = employeeRepository; } public List<Employee> GetEmployees() { return _employeeRepository.GetEmployees(); } public Employee GetEmployee(int employeeId) { return _employeeRepository.GetEmployeeById(employeeId); } public void UploadImage(byte[] image, string mimeType, int empNo) { _employeeRepository.UploadImage(image,mimeType, empNo); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; using System.Web.Http.Results; using System.Web.Mvc; using PhotoSharingCloudWeb.Services; namespace PhotoSharingCloudWeb.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } } }<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web; using System.Web.Http; using System.Web.Http.Description; using AutoMapper; using PhotoSharingCloudWeb.Models; using PhotoSharingCloudWeb.Services; using PhotoSharingCloudWeb.ViewModels; namespace PhotoSharingCloudWeb.Controllers { public class EmployeeController : ApiController { private AdventureWorksContext db = new AdventureWorksContext(); private readonly IEmployeeService _employeeService; public EmployeeController(IEmployeeService employeeService) { _employeeService = employeeService; } // GET: api/EmployeesTest public List<EmployeeViewModel> GetEmployees() { var employees = new List<EmployeeViewModel>(); var config = new MapperConfiguration(x => x.CreateMap<Employee, EmployeeViewModel>()); var mapper = config.CreateMapper(); _employeeService.GetEmployees().ForEach( x => employees.Add( mapper.Map<EmployeeViewModel>(x) )); return employees; } // GET: api/EmployeesTest/5 [ResponseType(typeof(Employee))] public async Task<IHttpActionResult> GetEmployee(int id) { Employee employee = await db.Employees.FindAsync(id); if (employee == null) { return NotFound(); } return Ok(employee); } // PUT: api/EmployeesTest/5 [ResponseType(typeof(void))] public async Task<IHttpActionResult> PutEmployee(int id, Employee employee) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != employee.BusinessEntityID) { return BadRequest(); } db.Entry(employee).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!EmployeeExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/EmployeesTest [ResponseType(typeof(Employee))] public async Task<IHttpActionResult> PostEmployee(Employee employee) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Employees.Add(employee); try { await db.SaveChangesAsync(); } catch (DbUpdateException) { if (EmployeeExists(employee.BusinessEntityID)) { return Conflict(); } else { throw; } } return CreatedAtRoute("DefaultApi", new { id = employee.BusinessEntityID }, employee); } // DELETE: api/EmployeesTest/5 [ResponseType(typeof(Employee))] public async Task<IHttpActionResult> DeleteEmployee(int id) { Employee employee = await db.Employees.FindAsync(id); if (employee == null) { return NotFound(); } db.Employees.Remove(employee); await db.SaveChangesAsync(); return Ok(employee); } [ResponseType(typeof(Employee))] public async Task<IHttpActionResult> UploadImage(int id, HttpPostedFile image) { Employee employee = await db.Employees.FindAsync(id); if (employee == null) { return NotFound(); } var picArray = new byte[image.ContentLength]; await image.InputStream.ReadAsync(picArray, 0, image.ContentLength); employee.Photo = picArray; db.Entry(employee).Property(x => x.Photo).IsModified = true; await db.SaveChangesAsync(); return Ok(); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool EmployeeExists(int id) { return db.Employees.Count(e => e.BusinessEntityID == id) > 0; } } }<file_sep>using System; namespace PhotoSharingCloudWeb.StringExtensions { public static class StringExtensions { public static string ToShortDate(this DateTime date) { return date.ToString("dd-MM-yyyy"); } } }<file_sep>using System.Collections.Generic; using PhotoSharingCloudWeb.Models; namespace PhotoSharingCloudWeb.Repositories { public interface IEmployeeRepository { List<Employee> GetEmployees(); Employee GetEmployeeById(int employeeId); void UploadImage(byte[] image, string mimeType, int empNo); } }
b07fd29d6ff6e72ecc4deca142bac75abf5d121f
[ "JavaScript", "C#" ]
9
C#
judebabs/AdventureStuff
b34d31824cd717bba9b58eaf9358ac85bc28c597
00560bf01bc58a76d668efea6dc5ab9a159b6c4f
refs/heads/master
<file_sep>package com.example.great.lab9.view; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.animation.PropertyValuesHolder; import android.animation.ValueAnimator; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.animation.AccelerateDecelerateInterpolator; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.example.great.lab9.JellyInterpolator; import com.example.great.lab9.R; import com.example.great.lab9.db.UserDB; import com.example.great.lab9.model.User; import com.example.great.lab9.util.SharedPreferencesUtils; import com.example.great.lab9.util.ToastUtil; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; public class LoginActivity extends Activity { private TextView mBtnLogin; private View progress; private View mInputLayout; private float mWidth, mHeight; private LinearLayout mName, mPsw; EditText mUserName, mUserPwd; String userName = "";//记录输入的用户名 String userPwd = "";//记录用户输入的密码 User user; UserDB db; Connection cn; private int flag=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main2); initView(); } private void initView() { mBtnLogin = (TextView) findViewById(R.id.main_btn_login); progress = findViewById(R.id.layout_progress); mInputLayout = findViewById(R.id.input_layout); mName = (LinearLayout) findViewById(R.id.input_layout_name); mPsw = (LinearLayout) findViewById(R.id.input_layout_psw); //mBtnLogin.setOnClickListener(this); mUserName = (EditText)findViewById(R.id.input_name); mUserPwd = (EditText) findViewById(R.id.input_pwd); } public void signin(View v) throws InterruptedException { userName = mUserName.getText().toString(); userPwd = mUserPwd.getText().toString(); SharedPreferencesUtils.setParam(LoginActivity.this, "name", userName); SharedPreferencesUtils.setParam(LoginActivity.this, "password", <PASSWORD>); if (userName.isEmpty()) { Toast.makeText(this,"请输入用户名",Toast.LENGTH_SHORT).show(); return; } if (userPwd.isEmpty()) { Toast.makeText(this,"请输入密码",Toast.LENGTH_SHORT).show(); return; } mWidth = mBtnLogin.getMeasuredWidth(); mHeight = mBtnLogin.getMeasuredHeight(); mName.setVisibility(View.INVISIBLE); mPsw.setVisibility(View.INVISIBLE); inputAnimator(mInputLayout, mWidth, mHeight); new Thread(new Runnable() { @Override public void run() { try { Thread.currentThread().sleep(1000);//阻断2秒 } catch (InterruptedException e) { e.printStackTrace(); } new Handler(Looper.getMainLooper()); getServerData(userName); } }).start(); } private void inputAnimator(final View view, float w, float h) { AnimatorSet set = new AnimatorSet(); ValueAnimator animator = ValueAnimator.ofFloat(0, w); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { float value = (Float) animation.getAnimatedValue(); ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) view .getLayoutParams(); params.leftMargin = (int) value; params.rightMargin = (int) value; view.setLayoutParams(params); } }); ObjectAnimator animator2 = ObjectAnimator.ofFloat(mInputLayout, "scaleX", 1f, 0.5f); set.setDuration(1000); set.setInterpolator(new AccelerateDecelerateInterpolator()); set.playTogether(animator, animator2); set.start(); set.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { // TODO Auto-generated method stub } @Override public void onAnimationEnd(Animator animation) { progress.setVisibility(View.VISIBLE); progressAnimator(progress); mInputLayout.setVisibility(View.INVISIBLE); } @Override public void onAnimationCancel(Animator animation) { // TODO Auto-generated method stub } }); } private void progressAnimator(final View view) { PropertyValuesHolder animator = PropertyValuesHolder.ofFloat("scaleX", 0.5f, 1f); PropertyValuesHolder animator2 = PropertyValuesHolder.ofFloat("scaleY", 0.5f, 1f); ObjectAnimator animator3 = ObjectAnimator.ofPropertyValuesHolder(view, animator, animator2); animator3.setDuration(2000); animator3.setInterpolator(new JellyInterpolator()); animator3.start(); } private void getServerData(String name) { try { Class.forName("com.mysql.jdbc.Driver"); cn = DriverManager.getConnection("jdbc:mysql://172.18.187.230:53306/kingjames", "user", "123"); String tempSql = "select password from user where name='%s' "; String sql = String.format(tempSql, name); //Toast.makeText(this,"fuck you",Toast.LENGTH_SHORT).show(); Statement st = (Statement) this.cn.createStatement(); ResultSet rs = st.executeQuery(sql); Handler mHandler = new Handler(Looper.getMainLooper()){ @Override public void handleMessage(Message msg) { switch(msg.what){ case 1: Bundle data = msg.getData(); int error = data.getInt("error"); Toast.makeText(getApplicationContext(),"账号不存在",Toast.LENGTH_SHORT).show(); startActivity(new Intent(getApplicationContext(),LoginActivity.class)); break; case 2: //Bundle data2 = msg.getData(); //int error2 = data2.getInt("error"); Toast.makeText(getApplicationContext(),"密码错误",Toast.LENGTH_SHORT).show(); startActivity(new Intent(getApplicationContext(),LoginActivity.class)); break; } } }; if(rs.next()==false){ flag=1; Message msg = new Message(); msg.what = flag; Bundle data = new Bundle(); data.putInt("error",1); msg.setData(data); mHandler.sendMessage(msg); //Toast.makeText(this,"账号不存在",Toast.LENGTH_SHORT).show(); return; } else{ rs.first(); //while(rs.next()) //{ String pwd = rs.getString("password"); if(pwd.equals(userPwd)) { Intent intent_login_to_user = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent_login_to_user); } else { flag=2; Message msg = new Message(); msg.what = flag; Bundle data = new Bundle(); data.putInt("error",1); msg.setData(data); mHandler.sendMessage(msg); //Toast.makeText(getApplicationContext(),"密码错误",Toast.LENGTH_SHORT).show(); return; } // } } cn.close(); st.close(); rs.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } public void signup(View v) { Intent intent_login_to_user = new Intent(LoginActivity.this, Sign_upActivity.class); startActivity(intent_login_to_user); } } <file_sep>package com.example.great.lab9.view; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.view.View; import android.widget.Button; import com.example.great.lab9.R; import com.example.great.lab9.adapter.FragmentAdapter; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity implements View.OnClickListener { //fragment ViewPager fragmentViewPager; FragmentAdapter fragmentAdapter; List<Fragment> fragmentList = new ArrayList<>(); //选项卡 Button homeBtn, locationBtn, userBtn; List<Button> tabButtonList = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); setContentView(R.layout.activity_main); initFragment(); initButton(); initAdapter(); changAlpha(0); fragmentViewPager.setCurrentItem(0); } private void initButton() { homeBtn = (Button) findViewById(R.id.home_btn_true); homeBtn.setOnClickListener(this); locationBtn = (Button) findViewById(R.id.location_btn_true); locationBtn.setOnClickListener(this); userBtn = (Button) findViewById(R.id.user_btn_true); userBtn.setOnClickListener(this); tabButtonList.add(homeBtn); tabButtonList.add(locationBtn); tabButtonList.add(userBtn); Drawable drawable1 = getResources().getDrawable(R.mipmap.home1); drawable1.setBounds(0,0,10,10); Drawable drawable2 = getResources().getDrawable(R.mipmap.home2); drawable2.setBounds(0,0,10,10); } /** * 初始化fagment */ private void initFragment() { fragmentList.add(new LocationFragment()); fragmentList.add(new HomeFragment()); fragmentList.add(new UserFragment()); fragmentViewPager = (ViewPager) findViewById(R.id.m_main_viewpager); } /** * 初始化adapter */ private void initAdapter() { fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), fragmentList); fragmentViewPager.setAdapter(fragmentAdapter); //viewpager滑动监听 fragmentViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { changAlpha(position, positionOffset); } @Override public void onPageSelected(int position) { changAlpha(position); } @Override public void onPageScrollStateChanged(int state) { } }); } public void onClick(View view) { switch (view.getId()) { case R.id.home_btn_true: fragmentViewPager.setCurrentItem(0, false); break; case R.id.location_btn_true: fragmentViewPager.setCurrentItem(1, false); break; case R.id.user_btn_true: fragmentViewPager.setCurrentItem(2, false); break; } } /** * 一开始运行、滑动和点击tab结束后设置tab的透明度,fragment的透明度和大小 */ private void changAlpha(int postion) { for (int i = 0; i < tabButtonList.size(); i++) { if (i == postion) { tabButtonList.get(i).setAlpha(1.0f); if (null != fragmentList.get(i).getView()) { fragmentList.get(i).getView().setAlpha(1.0f); fragmentList.get(i).getView().setScaleX(1.0f); fragmentList.get(i).getView().setScaleY(1.0f); } } else { tabButtonList.get(i).setAlpha(0.0f); if (null != fragmentList.get(i).getView()) { fragmentList.get(i).getView().setAlpha(0.0f); fragmentList.get(i).getView().setScaleX(0.0f); fragmentList.get(i).getView().setScaleY(0.0f); } } } } /** * 根据滑动设置透明度 */ private void changAlpha(int pos, float posOffset) { int nextIndex = pos + 1; if (posOffset > 0 && nextIndex < 3) { Button nextButton = tabButtonList.get(nextIndex); Button curentButton = tabButtonList.get(pos); if (nextButton == null || curentButton == null) return; View nextView = fragmentList.get(nextIndex).getView(); View curentView = fragmentList.get(pos).getView(); if (nextView == null || curentView == null) return; //设置tab的颜色渐变效果 nextButton.setAlpha(posOffset); curentButton.setAlpha(1 - posOffset); //设置fragment的颜色渐变效果 nextView.setAlpha(posOffset); curentView.setAlpha(1 - posOffset); //设置fragment滑动视图由大到小,由小到大的效果 nextView.setScaleX(0.5F + posOffset / 2); nextView.setScaleY(0.5F + posOffset / 2); curentView.setScaleX(1 - (posOffset / 2)); curentView.setScaleY(1 - (posOffset / 2)); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { onBackPressed(); return true; } return super.onKeyDown(keyCode, event); } @Override public void onBackPressed() { //返回手机的主屏幕 Intent intent = new Intent(Intent.ACTION_MAIN); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addCategory(Intent.CATEGORY_HOME); startActivity(intent); } } <file_sep># Here A real-time location-based chat app. <file_sep>package com.example.great.lab9; /** * Created by wonggwan on 2018/1/6. */ import java.io.Serializable; import java.util.List; public class Transport implements Serializable { public List<Double> param; public Transport( List<Double> param) { this.param = param; } } <file_sep>package com.example.great.lab9.view; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Toast; import com.example.great.lab9.R; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; /** * Created by peter on 2017/12/28. */ public class Sign_upActivity extends AppCompatActivity { private EditText name; private EditText pwd; private EditText pwd_conf; private EditText nick; private View progress; private LinearLayout sign1; private LinearLayout sign2; private LinearLayout sign3; private LinearLayout sign4; Connection cn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sign_up); name = (EditText)findViewById(R.id.sign_name); pwd = (EditText) findViewById(R.id.sign_pwd); pwd_conf = (EditText) findViewById(R.id.sign_pwd_confirm); nick = (EditText) findViewById(R.id.nickname); progress = findViewById(R.id.layout_progress); sign1 = (LinearLayout) findViewById(R.id.sign1); sign2 = (LinearLayout) findViewById(R.id.sign2); sign3 = (LinearLayout) findViewById(R.id.sign3); sign4 = (LinearLayout) findViewById(R.id.sign4); } public void sign(View v){ final String get_name = name.getText().toString(); final String get_pwd = pwd.getText().toString(); final String get_pwd_conf = pwd_conf.getText().toString(); final String get_nick = nick.getText().toString(); setvisible(); if(get_pwd.equals(get_pwd_conf)&&get_pwd!=null&&get_name!=null) { new Thread(new Runnable() { @Override public void run() { new Handler(Looper.getMainLooper()); savaServerData(get_name, get_pwd, get_nick); } }).start(); Toast.makeText(this,"注册成功,3秒后跳转",Toast.LENGTH_SHORT).show(); new Handler(new Handler.Callback() { //处理接收到的消息的方法 @Override public boolean handleMessage(Message arg0) { //实现页面跳转 startActivity(new Intent(getApplicationContext(),LoginActivity.class)); return false; } }).sendEmptyMessageDelayed(0, 3000); //表示延时三秒进行任务的执行 } else{ Toast.makeText(this,"密码不一致",Toast.LENGTH_SHORT).show(); } } public void savaServerData(String name, String pwd, String nick) { try { Class.forName("com.mysql.jdbc.Driver"); cn = DriverManager.getConnection("jdbc:mysql://172.18.187.230:53306/kingjames", "user", "123"); String fmt = "insert into user(name,password,word) values('%s','%s','%s')"; String sql = String.format(fmt, name, pwd, nick); Log.d("fuck","fuck"); Statement st = (Statement) cn.createStatement(); int cnt = st.executeUpdate(sql); cn.close(); st.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } public void setvisible(){ sign1.setVisibility(View.INVISIBLE); sign2.setVisibility(View.INVISIBLE); sign3.setVisibility(View.INVISIBLE); sign4.setVisibility(View.INVISIBLE); progress.setVisibility(View.VISIBLE); } public void sign_back(View v){ startActivity(new Intent(getApplicationContext(),LoginActivity.class)); } } <file_sep>package com.example.great.lab9.view; import android.support.v4.app.Fragment; public abstract class BaseFragment extends Fragment { //是否可见 protected boolean isVisible; // 标志位,标志Fragment已经初始化完成。 public boolean isPrepared = false; /** * 实现Fragment数据的缓加载 * @param isVisibleToUser */ @Override public void setUserVisibleHint(boolean isVisibleToUser) { super.setUserVisibleHint(isVisibleToUser); if (getUserVisibleHint()) { isVisible = true; onVisible(); } else { isVisible = false; onInVisible(); } } protected void onInVisible() { } protected void onVisible() { //加载数据 loadData(); } protected abstract void loadData(); }<file_sep>package com.example.great.lab9.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.example.great.lab9.model.User; public class UserDB extends SQLiteOpenHelper { public final static String DATABASE_NAME = "user.db"; public final static int DATABASE_VERSION = 1; public final static String TABLE_NAME = "user_table"; public final static String user_id = "user_id"; public final static String name = "name"; public final static String password = "<PASSWORD>"; public final static String age = "age"; public final static String email = "email"; public final static String hobby = "hobby"; public UserDB(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } // 创建数据库 @Override public void onCreate(SQLiteDatabase db) { String sql = "CREATE TABLE " + TABLE_NAME + " (" + user_id + " INTEGER primary key autoincrement, " + age + " INTEGER, " + name + " text, " + password + " text, " + email + " text, " + hobby + " text);"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String sql = "DROP TABLE IF EXISTS " + TABLE_NAME; db.execSQL(sql); onCreate(db); } public User getUser(String userName, String userPassword) { User user = null; SQLiteDatabase db = this.getReadableDatabase(); String sql = "select * from tableName where nameKey='nameValue' and passwordKey='passwordValue'"; sql = sql.replace("tableName", TABLE_NAME).replace("nameKey", name).replace("passwordKey", password).replace("nameValue", userName).replace("passwordValue", userPassword); Cursor cursor = db.rawQuery(sql, null); // 是否存在数据 if (cursor.moveToFirst()) { for (int i = 0; i < cursor.getCount(); i++) { user = new User(); user.setName(cursor.getString(cursor .getColumnIndex(name))); user.setPassword(cursor.getString(cursor .getColumnIndex(password))); user.setAge(cursor.getInt(cursor .getColumnIndex(age))); user.setEmail(cursor.getString(cursor .getColumnIndex(email))); user.setHobby(cursor.getString(cursor .getColumnIndex(hobby))); } } return user; } //新增 public long insert(User user) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues cv = new ContentValues(); cv.put(name, user.getName()); cv.put(age, user.getAge()); cv.put(email, user.getEmail()); cv.put(password, <PASSWORD>()); cv.put(hobby, user.getHobby()); long row = db.insert(TABLE_NAME, null, cv); return row; } }<file_sep>package com.example.great.lab9.view; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Looper; import android.support.v7.app.AlertDialog; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import android.graphics.BitmapFactory; import android.util.Base64; import com.example.great.lab9.R; import com.example.great.lab9.util.SharedPreferencesUtils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import android.widget.EditText; import android.widget.Toast; import java.sql.Statement; public class UserFragment extends BaseFragment{ TextView txt_name,txt_wechat,txt_email,txt_qq,txt_signature,txt_nick; Connection cn; String getname; String wechat; String qq; String email; String signature; String nick; String image; private View upload; private View collection; private String userName; String result_photo; private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择 private static final int PHOTO_REQUEST_CUT = 3;// 结果 private ImageView iv_image; /* 头像名称 */ private static final String PHOTO_FILE_NAME = "temp_photo.jpg"; private File tempFile; private ByteArrayOutputStream baos = new ByteArrayOutputStream(); private byte [] bitmapByte; @Override protected void loadData() { if(!isPrepared || !isVisible) { return; } final String name = (String) SharedPreferencesUtils.getParam(getActivity(),"name",""); userName = name; //String password = (String) SharedPreferencesUtils.getParam(getActivity(),"password",""); //User user = new UserDB(getActivity()).getUser(name,password); //if (user==null)return; new Thread(new Runnable() { @Override public void run() { new Handler(Looper.getMainLooper()); getServerData(name); } }).start(); txt_name.setText(getname); txt_wechat.setText(wechat); txt_qq.setText(qq); txt_email.setText(email); txt_signature.setText(signature); txt_nick.setText(nick); } private void getServerData(String name) { try { Class.forName("com.mysql.jdbc.Driver"); cn = DriverManager.getConnection("jdbc:mysql://172.18.187.230:53306/kingjames", "user", "123"); String tempSql = "select * from user where name='%s' "; String sql = String.format(tempSql, name); //Toast.makeText(this,"fuck you",Toast.LENGTH_SHORT).show(); Statement st = (Statement) this.cn.createStatement(); ResultSet rs = st.executeQuery(sql); while(rs.next()) { getname = rs.getString("name"); wechat = rs.getString("wechat"); qq = rs.getString("QQ"); email = rs.getString("email"); signature = rs.getString("signature"); nick = rs.getString("word"); image = rs.getString("image"); } cn.close(); st.close(); rs.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_user, container, false); //初始化view的各控件 isPrepared = true; iv_image = (ImageView) view.findViewById(R.id.iv_image); txt_name = (TextView) view.findViewById(R.id.txt_name); txt_wechat = (TextView)view.findViewById(R.id.txt_email); txt_qq = (TextView)view.findViewById(R.id.txt_qq); txt_email = (TextView)view.findViewById(R.id.txt_email); txt_signature = (TextView)view.findViewById(R.id.txt_signature); txt_nick = (TextView)view.findViewById(R.id.txt_nickname); upload = (View) view.findViewById(R.id.upload); collection = view.findViewById(R.id.collection); loadData(); getServerData(userName); iv_image.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Intent.ACTION_PICK); intent.setType("image/*"); // 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_GALLERY startActivityForResult(intent, PHOTO_REQUEST_GALLERY); } }); upload.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View v) { AlertDialog.Builder mydialog = new AlertDialog.Builder(getActivity()); final View dialogview = LayoutInflater.from(getActivity()).inflate(R.layout.usereditor,null); mydialog.setView(dialogview); mydialog.setTitle("个人信息修改").setPositiveButton("保存修改", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { send1(dialogview); } }).create().show(); } }); collection.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(),MyCollection.class); intent.putExtra("user",userName); startActivityForResult(intent,0); } }); return view; } public void send1(final View v) { final EditText e1 = v.findViewById(R.id.new_pw); final String get1 = e1.getText().toString(); final EditText e2 = v.findViewById(R.id.new_nick); final String get2 = e2.getText().toString(); final EditText e3 = v.findViewById(R.id.new_em); final String get3 = e3.getText().toString(); final EditText e4 = v.findViewById(R.id.new_wechat); final String get4 = e4.getText().toString(); final EditText e5 = v.findViewById(R.id.new_qq); final String get5 = e5.getText().toString(); final EditText e6 = v.findViewById(R.id.new_sig); final String get6 = e6.getText().toString(); Log.d("get1",get1); new Thread(new Runnable() { @Override public void run() { new Handler(Looper.getMainLooper()); edit(get1,get2,get3,get4,get5,get6); } }).start(); } public void edit(String str1,String str2,String str3,String str4,String str5,String str6){ try { Class.forName("com.mysql.jdbc.Driver"); Log.i("mytag:","123"); cn = DriverManager.getConnection("jdbc:mysql://172.18.187.230:53306/kingjames", "user", "123"); Log.i("mytag:","321b"); String tempSql = "UPDATE user SET password='%s',word='%s',email='%s',wechat='%s',QQ='%s',signature='%s'where name ='%s' LIMIT 1"; Log.i("mytag:","666"); String sql = String.format(tempSql,str1,str2,str3,str4,str5,str6,userName); Statement st = cn.createStatement(); Log.i("mytag:",sql); int cnt = st.executeUpdate(sql); if (cnt > 0) cn.close(); st.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } private void crop(Uri uri) { // 裁剪图片意图 Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); intent.putExtra("crop", "true"); // 裁剪框的比例,1:1 intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); // 裁剪后输出图片的尺寸大小 intent.putExtra("outputX", 200); intent.putExtra("outputY", 200); intent.putExtra("outputFormat", "PNG");// 图片格式 intent.putExtra("noFaceDetection", true);// 取消人脸识别 intent.putExtra("return-data", true); // 开启一个带有返回值的Activity,请求码为PHOTO_REQUEST_CUT startActivityForResult(intent, PHOTO_REQUEST_CUT); } private boolean hasSdcard() { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { return true; } else { return false; } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == PHOTO_REQUEST_GALLERY) { // 从相册返回的数据 if (data != null) { // 得到图片的全路径 Uri uri = data.getData(); crop(uri); } } else if (requestCode == PHOTO_REQUEST_CUT) { // 从剪切图片返回的数据 if (data != null) { Bitmap bitmap1 = data.getParcelableExtra("data"); //ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap1.compress(Bitmap.CompressFormat.PNG,10,baos); int options = 90; while (baos.toByteArray().length / 1024 > 500) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩 baos.reset(); // 重置baos即清空baos bitmap1.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%,把压缩后的数据存放到baos中 options -= 10;// 每次都减少10 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中 Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片 //return bitmap; bitmapByte = baos.toByteArray(); result_photo = Base64.encodeToString(bitmapByte,Base64.DEFAULT); new Thread(new Runnable() { @Override public void run() { new Handler(Looper.getMainLooper()); setimage(result_photo); } }).start(); //Toast.makeText(UserFragment.this,result_photo,Toast.LENGTH_LONG).sho(); //System.out.println(result_photo); this.iv_image.setImageBitmap(bitmap); } try { // 将临时文件删除 tempFile.delete(); } catch (Exception e) { e.printStackTrace(); } } super.onActivityResult(requestCode, resultCode, data); } private void setimage(String result){ try { Class.forName("com.mysql.jdbc.Driver"); Log.i("mytag:","aaa"); cn = DriverManager.getConnection("jdbc:mysql://172.18.187.230:53306/kingjames", "user", "123"); Log.i("mytag:","bbb"); String tempSql = "UPDATE user SET image='%s' WHERE (name='123') LIMIT 1"; Log.i("mytag:","ccc"); String sql = String.format(tempSql, result_photo); Statement st = (Statement) this.cn.createStatement(); Log.i("mytag:",sql); int cnt = st.executeUpdate(sql); if (cnt > 0) //Toast.makeText(getActivity(),result_photo,Toast.LENGTH_LONG).show(); cn.close(); st.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } } }
d9491d099ef4b78fcea08030440968157331ab13
[ "Markdown", "Java" ]
8
Java
Wang-Shiyu/Here
8b072a8037a063cff68a0b1f7f83be2c36c0b84b
8d457c6393cb67931854c7e8ac7120499390edb8
refs/heads/master
<file_sep>package com.genix.tribalwarsnotifications import android.content.Context import android.content.Intent import android.service.notification.NotificationListenerService import android.service.notification.StatusBarNotification import android.util.Log class ListeningService : NotificationListenerService() { private val SharedWasLanuchedKey = "wasLaunched" override fun onCreate() { super.onCreate() openAskActivity() Log.d(App.TAG, "service started") } private fun openAskActivity() { val prefs = App.getAppContext().getSharedPreferences(App.PREFS_FILE, 0) if (!prefs.getBoolean(SharedWasLanuchedKey, false)) { startActivity(Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS")) val prefsEditor = prefs.edit() prefsEditor.putBoolean(SharedWasLanuchedKey, true).apply() App.getAppContext().openFileOutput(App.FILE_WORKMANAGER_TIMES, Context.MODE_APPEND).use { it.write("".toByteArray()) } } } override fun onNotificationPosted(sbn: StatusBarNotification?) { Log.d(App.TAG, getActiveNotifications().toString() + "SA") Log.i(App.TAG, "new notification: " + sbn.toString()) FileWriter.Companion.writeToFile(sbn.toString()) } override fun onNotificationRemoved(sbn: StatusBarNotification?) { Log.i(App.TAG, "notification removed") } override fun onListenerConnected() { super.onListenerConnected() Log.i(App.TAG, "Listener connected") Log.d(App.TAG, getActiveNotifications().toString() + "S") } }<file_sep>package com.genix.tribalwarsnotifications import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Build import android.os.Bundle import android.support.v4.app.NotificationCompat import android.support.v7.app.AppCompatActivity import android.text.method.ScrollingMovementMethod import android.util.Log import android.widget.Toast import androidx.work.ExistingPeriodicWorkPolicy import androidx.work.PeriodicWorkRequest import androidx.work.WorkManager import kotlinx.android.synthetic.main.activity_main.* import java.util.concurrent.TimeUnit class MainActivity : AppCompatActivity() { private val TAG = "HMM" private lateinit var notManager:NotificationManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) notManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager startNotificationService() btn_notify.setOnClickListener { sendNotification() } btn_getNotifications.setOnClickListener { getNotifications() } btn_askForPermissions.setOnClickListener { askForPermissions() } val periodicRequest:PeriodicWorkRequest = PeriodicWorkRequest.Builder(PeriodicWorker::class.java, PeriodicWorkRequest.MIN_PERIODIC_INTERVAL_MILLIS, TimeUnit.MILLISECONDS) .build() // WorkManager.getInstance().enqueue(periodicRequest) WorkManager.getInstance(). enqueueUniquePeriodicWork("checkEvery15min", ExistingPeriodicWorkPolicy.KEEP, periodicRequest) } /* UI methods */ private fun sendNotification() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val notChannelId = "some_channel_id" val notChannelName:CharSequence = "some_channel_name" val notDescription = "some_channel_description" val notImportance = NotificationManager.IMPORTANCE_HIGH val notChannel = NotificationChannel(notChannelId, notChannelName, notImportance) notChannel.description = notDescription notChannel.enableLights(true) notChannel.lightColor = Color.RED notChannel.enableVibration(true) notManager.createNotificationChannel(notChannel) val notTitle = "My notification" val notText = "Some text" val notBuilder = NotificationCompat.Builder(this) .setSmallIcon(R.drawable.notification_icon_background) .setContentTitle(notTitle) .setContentText(notText) .setPriority(Notification.PRIORITY_MAX) .setChannelId(notChannelId) notManager.notify(12, notBuilder.build()) } else { val notTitle = "My notification" val notText = "Some text" val notBuilder = NotificationCompat.Builder(this) .setSmallIcon(R.drawable.notification_icon_background) .setContentTitle(notTitle) .setContentText(notText) .setPriority(Notification.PRIORITY_MAX) notManager.notify(12, notBuilder.build()) } Log.d(TAG, "Notification should be sent") } private fun askForPermissions() { startActivity(Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS")) } private fun getNotifications() { var str = "" var stringList = App.getAppContext().openFileInput(App.FILE_WORKMANAGER_TIMES).bufferedReader().readLines() stringList.forEach { str += it + "\n\n" } tx_notInfo.text = str tx_notInfo.movementMethod = ScrollingMovementMethod() } private fun startNotificationService() { startService(Intent(this, ListeningService::class.java)) } /* Other methods */ private fun makeToast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } } <file_sep>package com.genix.tribalwarsnotifications import android.content.Context import java.text.SimpleDateFormat import java.util.* class FileWriter { companion object { fun writeToFile(message: String) { App.getAppContext().openFileOutput(App.FILE_NOTIFICATIONS, Context.MODE_APPEND).use { it.write((message + "\n").toByteArray()) } } fun writeTime() { val s = SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z") val format = s.format(Date()) App.getAppContext().openFileOutput(App.FILE_WORKMANAGER_TIMES, Context.MODE_APPEND).use { it.write((format + "\n").toByteArray()) } } } }
a5575cc4d7c84b6c3607a28a05c1358231e74ecf
[ "Kotlin" ]
3
Kotlin
GenixPL/Tribal-Wars-Notifications
999bf1f030ecff4ac3b5143523fc6779afc743ae
5409ab95b764f22863ddfa7462821035e7153917
refs/heads/master
<repo_name>ahernandez348/Stash<file_sep>/HelloWorld/HelloWorld/ViewController.swift // // ViewController.swift // HelloWorld // // Created by Project Exploration on 4/15/19. // Copyright © 2019 Project Exploration. All rights reserved. // import UIKit import AVFoundation class ViewController: UIViewController { var songPlayer = AVAudioPlayer() func prepareSongAndSession() { do { songPlayer = try AVAudioPlayer(contentsOf: URL.init(fileURLWithPath: Bundle.main.path (forResource: "<NAME> - Empty my-free", ofType: "mp3")!)) songPlayer.prepareToPlay() let audioSession = AVAudioSession.sharedInstance() do { try audioSession.setCategory(AVAudioSessionCategoryPlayback) } catch let sessionError { print(sessionError) } } catch let songPlayerError { print(songPlayerError) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. prepareSongAndSession() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var hasBeenPaused = false @IBAction func play(_ sender: Any) { songPlayer.play() } @IBAction func pause(_ sender: Any) { if songPlayer.isPlaying { songPlayer.pause() hasBeenPaused = true } else { hasBeenPaused = false } } @IBAction func restart(_ sender: Any) { if songPlayer.isPlaying || hasBeenPaused { songPlayer.stop() songPlayer.currentTime = 0 songPlayer.play() } else { songPlayer.play() } } } <file_sep>/README.md test for our stuffs
173f1deb39b0d77de7345e10f2766116af01ec15
[ "Swift", "Markdown" ]
2
Swift
ahernandez348/Stash
61ed24eeedac5e3332c2452c3b8f35b5326e6226
88544133833ed333b4a82fef90cf436a5adac671
refs/heads/master
<file_sep>// import React, { Component } from 'react'; import React from 'react'; // import Footer from './Footer'; // import Header from './Header'; // import Main from './Main'; import './App.css'; // class App2 extends Component { // // constructor() { // // super() // // this.state = { // // answer: "Yes" // // } // // } // // render() { // // return ( // // <div className="App"> // // {/* <Header /> // // <Main2 /> // // <Footer /> */} // // <h1>Is state important to know? {this.state.answer}</h1> // // </div> // // ); // // } // constructor() { // super() // this.state = { // name: "<NAME>", // age: 42 // } // } // render() { // return ( // <div> // <h3>{this.state.name}</h3> // <h4>{this.state.age} years old</h4> // </div> // ) // } // } class App2 extends React.Component { constructor() { super() this.state = { isLoggedIn: false } } render() { let wordDisplay if (this.state.isLoggedIn) { wordDisplay = "in" } else { wordDisplay = "out" } return ( <div> <h1>You care currently logged {wordDisplay}</h1> </div> ) } } export default App2; <file_sep>import React from 'react'; import ToDoItem from './ToDoItem'; import toDoData from './toDoData'; // import Joke from './Joke'; // import jokesData from './jokesData'; function Main() { // const jokeComponents = jokesData.map(joke => // <Joke key={joke.id} question={joke.question} punchline={joke.punchline} /> // ); const toDoItems = toDoData.map( item => <ToDoItem key={item.key} item={item} /> ); return ( <div className="todoList"> {toDoItems} {/* <ToDoItem item={{ task: "Option 1", priority: "High" }} /> <ToDoItem item={{ task: "Option 2", priority: "Medium" }} /> <ToDoItem item={{ task: "Option 3", priority: "High" }} /> <ToDoItem item={{ task: "Option 4", priority: "Low" }} /> */} </div> // <div className="jokes"> // {/* <Joke // setup={{ // question: "What do you call a cat in the desert during Christmas?", // punchline: "Sandy Claws" // }} /> // <Joke // setup={{ // question: "What did the big chimney say to the little chimney?", // punchline: "You're too young to smoke." // }} /> // <Joke // setup={{ // question: "What did the policeman say to the dalmation?", // punchline: "You've been spotted." // }} /> // <Joke // setup={{ // punchline: "Pen Island" // }} /> */} // {jokeComponents} // </div> ) } export default Main <file_sep>import React from "react" function Footer() { return ( <footer> <p>All honors and titles go to my dick.</p> </footer> ) } export default Footer<file_sep>import React from 'react' class Main5 extends React.Component { constructor() { super() this.state = { isLoggedIn: false } this.handleLogging = this.handleLogging.bind(this) } //did mount // click handler handleLogging() { this.setState(prevState => { return { isLoggedIn: !prevState.isLoggedIn } }) } render() { let loggedStatus = this.state.isLoggedIn ? "in" : "out" let logInButton = this.state.isLoggedIn ? "Log Out" : "Log In" return ( <div> <h1>You are logged {loggedStatus}.</h1> <br /> <button onClick={this.handleLogging}>{logInButton}</button> </div> ) } } export default Main5<file_sep>import React from 'react'; import FormContainer from './FormContainer'; function Main8() { return ( <FormContainer /> ) } export default Main8<file_sep>import React from "react" import logo from './logo.svg'; function Header() { return ( <nav> <h1>My TODOs</h1> <img src={logo} className="App-logo" alt="logo" /> </nav> ) } export default Header<file_sep>import React from 'react'; function ToDoItem(props) { const isCompleted = props.item.completed ? "completed" : ""; return ( <div> <input type="checkbox" checked={props.item.completed} onChange={(event) => props.handleChange(props.item.id)} /> <p className={isCompleted}>{props.item.task} ({props.item.priority})</p> </div> ) } export default ToDoItem
d4e0253c285e66bbda97a3efdc3d329b33129ce8
[ "JavaScript" ]
7
JavaScript
DanKheadies/derpsicle
9f840326649ab20ef473a95ba9e98c1d7a87f6cf
d43f87d7048728fe349f674209bf282741543d6d
refs/heads/main
<repo_name>mikodham/intellibots_spring21<file_sep>/read_zenodo.py import pandas as pd master_df = pd.DataFrame() file_urls = [ "https://zenodo.org/record/4543776/files/Redditors_and_posts_batch_1.xlsx", # 757 posts "https://zenodo.org/record/4543776/files/Redditors_and_posts_batch_2.xlsx", # 934 posts "https://zenodo.org/record/4543776/files/Redditors_and_posts_batch_3.xlsx", # 837 posts "https://zenodo.org/record/4543776/files/Redditors_and_posts_batch_4.xlsx", # 983 posts "https://zenodo.org/record/4543776/files/Redditors_and_posts_batch_5.xlsx", # 761 posts ] for file_url in file_urls: dfs = pd.read_excel(file_url,sheet_name=None,usecols="A:B") # 1 dataframe for each sheet within an excel file df = pd.concat(dfs,ignore_index=True) # merging the dataframes for each sheet master_df = pd.concat([master_df,df],ignore_index=True) # merging the dataframes for each file df_negatives = master_df[master_df['Suicide Risk'].isin(['supportive','uninformative'])] df_negatives.reset_index(drop=True,inplace=True) df_positives = master_df[master_df['Suicide Risk'].isin(['attempt','behavior','indicator','ideation'])] df_positives.reset_index(drop=True,inplace=True) <file_sep>/data_preprocess.py # import pandas as pd import numpy as np import csv import pathlib import os import pprint FILENAME = "master_data.csv" with open(os.path.join(os.getcwd(), "Dataset", FILENAME), 'r', newline='') as f: # spamreader = csv.reader(f, delimiter=' ', quotechar='|') lis = [line.split('|') for line in f] pprint.pprint(lis) # thewriter = csv.writer(f) # thewriter.writerow(['sentences','#of heteronyms','#of different heteronyms','#heteronyms with different pos','source-site']) <file_sep>/README.md # intellibots_spring21 Spring2021_IntrotoAI_CS470 - Suicidal Ideation Detection by Intellibots 1. <NAME> - 20180744 2. <NAME> - 20180848 3. <NAME> - 20170879 ## Building Baseline Code ## Load Data ## Pre-process Data 1. pos_tag 2. word_embedding ## LSTM ## CNN ## Future Direction 1. Adding more features 2. Tuning Hyperparameters https://www.tensorflow.org/tensorboard/hyperparameter_tuning_with_hparams 3. Combine LSTM, CNN methods, and average the results => Build our own models ## References: 1. https://github.com/shaoxiongji/sw-detection -> keras, use LSTM and RNN, features:LICW, POS_TAG, tf_idf, basic features 2. https://github.com/viniciosfaustino/suicide-detection -> fastai, use RNN, features: NOT-given 3. https://github.com/BarnesLab/Identification-of-Imminent-Suicide-Risk-Among-Young-Adults-using-Text-Messages -> use tf.keras and keras, simple DNN, features: text_cleaner (ignore emoticons), tf_idf 4. https://github.com/M-Ibtihaj/Suicidal-ideation-detection -> use scikit learn, logistic regression, features: using a lot of NLP features such as repetition, negative/positive words clustering, text cleaner(stopwords, punctuation) 5. https://github.com/cyash12/Depression-and-Suicidal-behvior-detection-on-Twitter-using-Machine-Learning <file_sep>/read_xlsx.py import pandas as pd master_df = pd.DataFrame() file_urls = [ "https://zenodo.org/record/4543776/files/Redditors_and_posts_batch_1.xlsx", # 757 posts "https://zenodo.org/record/4543776/files/Redditors_and_posts_batch_2.xlsx", # 934 posts "https://zenodo.org/record/4543776/files/Redditors_and_posts_batch_3.xlsx", # 837 posts "https://zenodo.org/record/4543776/files/Redditors_and_posts_batch_4.xlsx", # 983 posts "https://zenodo.org/record/4543776/files/Redditors_and_posts_batch_5.xlsx", # 761 posts ] for file_url in file_urls: dfs = pd.read_excel(file_url,sheet_name=None,usecols="A:B") # 1 dataframe for each sheet within an excel file df = pd.concat(dfs,ignore_index=True) # merging the dataframes for each sheet master_df = pd.concat([master_df,df],ignore_index=True) # merging the dataframes for each file master_df.to_csv(r'master_data.csv',sep='|',index=False)<file_sep>/read_reddit.py import pandas as pd df = pd.DataFrame() path = "./Dataset/reddit_mini.csv" df = pd.read_csv(path,usecols=[1,2]) df_negatives = df[df['class'].isin(['non-suicide'])] df_negatives.reset_index(drop=True,inplace=True) df_positives = df[df['class'].isin(['suicide'])] df_positives.reset_index(drop=True,inplace=True) <file_sep>/split_reddit_to_reddit_mini.py import pandas as pd df = pd.DataFrame() path = "./Dataset/reddit.csv" df = pd.read_csv(path,usecols=[1,2]) # ignore first column df_negatives = df[df['class'].isin(['non-suicide'])] df_negatives_mini = df_negatives.sample(n=10000) df_positives = df[df['class'].isin(['suicide'])] df_positives_mini = df_positives.sample(n=10000) df = pd.concat([df_negatives_mini,df_positives_mini],ignore_index=True) df.to_csv('./Dataset/reddit_mini.csv')
1c694159d84e0e2b389aac74eb80f73d990e609c
[ "Markdown", "Python" ]
6
Python
mikodham/intellibots_spring21
04508adf4037fdfae952711d071d8011e28f10ca
fe0b0aa149d19ddc76cb94c9499e4bdbcd0da5b4
refs/heads/master
<file_sep>''' Created on Jun 11, 2012 @author: utkarsh ''' import sys def calculateMaxFun(budget, fee, fun): numParties = len(fee) dp = [] for i in range(numParties+1): temp = [0] * (budget+1) dp.append(temp) # Iterate over the parties for i in range(numParties): for b in range(budget+1): leftover = b - fee[i] above = dp[i][b] # We'd still have some room if leftover>=0: possible = dp[i][leftover] + fun[i] dp[i+1][b] = possible if possible>above else above else: dp[i+1][b] = above lastRow = dp[-1] lastFun = lastRow[-1] outputBudget = budget while(lastRow.pop()==lastFun): outputBudget-=1 print("%d %d" % (outputBudget+1, lastFun)) while True: control = raw_input().split() budget = int(control[0]) parties = int(control[1]) if budget==0 and parties==0: sys.exit(0) fee = [] fun = [] while(parties>0): inp = raw_input().split() fee.append(int(inp[0])) fun.append(int(inp[1])) parties-=1 calculateMaxFun(budget, fee, fun) raw_input() if __name__ == '__main__': pass<file_sep>l="TDLF" x=10 while x>0: i=raw_input() c=0 for s in l: c+=i.count(s) print(2**c) x-=1<file_sep>''' Created on Jun 11, 2012 @author: utkarsh ''' def processExpression(expr): stack = [] ret = "" for i in range(len(expr)): char = expr[i:i+1] if char in ['+', '-', '/', '*', '^']: stack.append(char) elif char==')': ret += stack.pop() elif char!='(': ret += char while len(stack)>0: ret+=stack.pop() print(ret) n = int(input()) for i in range(n): exp = input() processExpression(exp) if __name__ == '__main__': pass
69df6d376888a489bd0f1d2848e5fccb813c8f62
[ "Python" ]
3
Python
imagedeep/spoj
a2fc22b9e5a6f3c588139590e6830c1f0e982cc9
9439b2e06aaac28ea7e77613beace18e27e85af3
refs/heads/master
<file_sep>//********************************************************************************************* // This code cannot be used without explicit permission. // Illegal use of this code may result in penal penalties. // For permissions and licencing please contact: // contib2012[ignore][at][ignore]gmail[ignore][dot][ignore]com[ignore] //********************************************************************************************* // This code is provided in raw form. // It should be modified according to javascript specification at any time. ; function optionSelectorEx(options) { "use strict"; var self = this; //Settings var _Settings = $.extend({}, { lists: [], defaultListIndex: 0, defaultIndex: -1, rootListClass: "mainselectorlist", rootListItemClass: "mainselectorlist-item", listTemplate: "<ul style='padding: 0; margin: 0; list-style-type: none; z-index: 999999;'></ul>", itemTemplate: "<li></li>", itemdataattribute: "index", events: { onClicked: null, OnSelectionChanged: null } }, options); if (_Settings.length == 0) { throw "There must be atleast one list defined in options."; } this.tag = null; //Properties var _IsVisible = true; var _Data = null; var _SelectedIndexes = []; var _UIRoot = $(_Settings.listTemplate).addClass(_Settings.rootListClass); var _DisplayType = _UIRoot.css("display"); var _UILists = []; $.each(_Settings.lists, function (index, listInfo) { _SelectedIndexes[index] = -1; var $list = $(_Settings.listTemplate).addClass(listInfo.listClass); var $rootItem = $(_Settings.itemTemplate).addClass(_Settings.rootListItemClass).append($list); _UIRoot.append($rootItem).addClass(_Settings.rootListClass); _UILists.push($list); }); var _ActiveListIndex = (_Settings.defaultListIndex > -1) ? _Settings.defaultListIndex : 0; this.getSettings = function () { return _Settings; } this.getUIRoot = function () { return _UIRoot; } this.getUILists = function () { return _UILists; } this.getData = function () { return _Data; } this.getSelectedIndex = function () { return _SelectedIndexes[_ActiveListIndex]; } this.getSelectedListIndex = function () { return _ActiveListIndex; } this.getListCount = function () { return _UILists.length; } this.getListItemCount = function (index) { if (_UILists[index]) { return _UILists[index].children().length; } } this.getDisplayType = function () { return _DisplayType; } this.getVisibility = function () { return _IsVisible; } //Public - Clears the list items. this.clear = function () { _Data = null; $.each(_UILists, function (index, item) { item.empty() }); $.each(_SelectedIndexes, function (index, item) { item = -1 }); _ActiveListIndex = (_Settings.defaultListIndex > -1) ? _Settings.defaultListIndex : 0; } //Public - Creates list items by removing previous. this.setData = function (data, formatter) { this.clear(); if (data && data.length === _UILists.length) { _Data = data; initialRender(this, formatter); this.setSelected(_Settings.defaultIndex); } } //public - return selected data item. this.getSelected = function () { if (_Data && _ActiveListIndex > -1 && _SelectedIndexes[_ActiveListIndex] > -1) { return _Data[_ActiveListIndex][_SelectedIndexes[_ActiveListIndex]]; } return null; } //Public - sets selected list item. this.setSelected = function (itemIndex, listIndex) { var $settings = _Settings; if (typeof listIndex != "number") { listIndex = _ActiveListIndex; } if (listIndex > -1 && listIndex < _UILists.length) { if (itemIndex > -1 && itemIndex < _UILists[listIndex].children().length) { $.each(_UILists, function (j, $list) { var $children = _UILists[j].children(); $children.each(function (i, item) { if (j != listIndex) { decorateItem($settings.lists[j].selectedItemClass, $(item), -1, i); } else { decorateItem($settings.lists[j].selectedItemClass, $(item), itemIndex, i); } }); _ActiveListIndex = listIndex; _SelectedIndexes[_ActiveListIndex] = itemIndex; }); if ($settings.events.OnSelectionChanged != null) { $settings.events.OnSelectionChanged.call(this); } } } } //Public - changes visibility of the list. this.setVisible = function (visible) { if (visible && !_IsVisible) { _UIRoot.css("display", _DisplayType); _IsVisible = true; } else if (!visible && _IsVisible) { _DisplayType = _UIRoot.css("display"); _UIRoot.css("display", "none"); _IsVisible = false; } } //Public - changes locatin of the list within the page. this.setPosition = function (location) { _UIRoot.css(location); } //Private Event - raised when a list item is clicked var onClicked = function (e) { var $listitem = $(e.target); var $settings = _Settings; this.setSelected(parseInt($listitem.data($settings.itemdataattribute), 10), getListIndex($listitem.parent())); if ($settings.events.onClicked != null) { $settings.events.onClicked.call(this, e); } } //Private Static - creates list items using data property // To use complete data item structure such as { name: "anyname", data: "anyhash" } change this method. // To use elements other than list change this method. var initialRender = function ($this, formatter) { var $settings = $this.getSettings(); $.each($settings.lists, function (j, listInfo) { var $list = $this.getUILists()[j]; var data = $this.getData(); if (data) { $.each(data[j], function (i, dataItem) { var $listItem = $($settings.itemTemplate).attr('data-' + $settings.itemdataattribute, i).addClass(listInfo.itemClass); if (formatter) { $listItem.append(formatter(dataItem)); } else { $listItem.text(dataItem); } decorateItem(listInfo.selectedItemClass, $listItem, -1, i); $list.append($listItem).addClass(listInfo.listClass); }); } }); } var getListIndex = function ($list) { for (var x = 0; x < _UILists.length; x++) { if (_UILists[x].is($list)) { _ActiveListIndex = x; break; } } } //Private Static - decorates item by adding/removing css classes var decorateItem = function (cssClass, item, selIndex, currIndex) { if (selIndex != currIndex) { item.removeClass(cssClass); } else if (!item.hasClass(cssClass)) { item.addClass(cssClass); } } //Private Static - changes function scope so that 'this' could point to source object var contextBinder = function (func, scope) { if (func.bind) { return func.bind(scope); } else { return function () { func.apply(scope, arguments); }; } }; // binds all list items to onClicked event in one go. // If we change the ui element from List to something else we need to handle the event binding below. $.each(_UILists, function (index, list) { list.on('click', 'li', contextBinder(onClicked, self)); }); } <file_sep>;(function ($) { "use strict"; $.customPlugin = function (element, options) { var $element = $(element); var $settings = $.extend({}, { key: null }, options); this.customFunction1 = function () { alert($settings.key); } this.customFunction2 = function () { alert($settings.key); } } $.fn.customPlugin = function (options) { return this.each(function () { if (typeof $(this).data("customPlugin") === "undefined") { var plugin = new $.customPlugin(this, options); $(this).data("customPlugin", plugin); } }); return this; } })(window.jQuery);<file_sep>;function HashTable() { var data = {} var keys = []; var values = []; var count = 0; var computeHash = function (value) { var hash = 0; if (value.length == 0) return hash; for (i = 0; i < value.length; i++) { char = value.charCodeAt(i); hash = ((hash << 5) - hash) + char; hash = hash & hash; // Convert to 32bit integer } return hash; } var removeFromArray = function (searchArray, item, parallelArray) { for (var i = 0; i < searchArray.length; i++) { if (item === keys[i]) { searchArray.splice(i, 1); parallelArray.splice(i, 1); break; } } } this.add = function (key, value) { if (typeof key != "string") { throw "keys can only be of type string."; } var internalKey = computeHash(key); var bucket = data[internalKey]; if (containsKeyInternal(key, bucket)) { throw "key already exists."; } if (typeof bucket === "undefined") { data[internalKey] = {}; data[internalKey][key] = value; } else { data[internalKey][key] = value; } keys.push(key); values.push(value); count++; } this.get = function (key) { var internalKey = computeHash(key); var bucket = data[internalKey]; if (!containsKeyInternal(key, bucket)) { throw "Invalid key provided."; } return bucket[key]; } this.getKeys = function () { return keys; } this.getValues = function () { return getValues; } this.clear = function () { data = {}; } this.count = function () { return count; } this.isEmpty = function () { return (data === {}) } this.remove = function (key) { var internalKey = computeHash(key); var bucket = data[internalKey]; if (!containsKeyInternal(key, bucket)) { throw "Unknown key provided."; } delete bucket[key]; if (Object.keys(bucket).length == 0) { delete data[internalKey]; } removeFromArray(keys, key, values); count--; } this.hashCode = function (value) { return computeHash(value); } this.containsKey = function (key) { var internalKey = computeHash(key); var bucket = data[internalKey]; return containsKeyInternal(key, bucket); } var containsKeyInternal = function (key, bucket) { return (typeof bucket != "undefined" && typeof bucket[key] != "undefined") } } <file_sep>//********************************************************************************************* // This code cannot be used without explicit permission. // Illegal use of this code may result in penal penalties. // For permissions and licencing please contact: // contib2012[ignore][at][ignore]gmail[ignore][dot][ignore]com[ignore] //********************************************************************************************* ; function inputManager(target, options) { "use strict"; // control type check (function (n) { if (n != "input" && n != 'textarea') { throw "unsupported element type '" + n + "' for inputManager"; } })(target.get(0).nodeName.toLowerCase()); // save settings var _Settings = $.extend({}, { containerClass: "inputmanager-main", divTemplate: "<div style='position: relative; display:inline-block;'></div>", events: { onKeyup: null, beforeKeydown: null, onKeydown: null }, }, options); this.tag = null; var _Target = $(target); var _UIRoot = _Target.wrap($(_Settings.divTemplate)).parent().addClass(_Settings.containerClass); this.getTarget = function () { return _Target; } this.getUIRoot = function () { return _UIRoot; } this.getSettings = function () { return _Settings; } var onKeyup = function (e) { if (_Settings.events.onKeyup) { var preText = getInitialText(_Target); var postText = _Target.val().substring(preText.length); var position = getCursorPostion(_Target, preText); var param = $.extend(e, { preText: preText, postText: postText, cursorPosition: position }); _Settings.events.onKeyup.call(this, param); } } var onKeydown = function (e) { if (_Settings.events.beforeKeydown) { if (!_Settings.events.beforeKeydown.call(this, e)) { return; } } if (_Settings.events.onKeydown) { var preText = getInitialText(_Target); var postText = _Target.val().substring(preText.length); var position = getCursorPostion(_Target, preText); var param = $.extend(e, { preText: preText, postText: postText, cursorPosition: position }); _Settings.events.onKeydown.call(this, param); } } var getInitialText = function ($this) { // Get Previous text var selectedText = ""; var index = $this.get(0).selectionEnd; if (typeof index === "number") { selectedText = $this.val().substring(0, index); } else if (document.selection) { var range = $this.createTextRange(); range.moveStart("character", 0); range.moveEnd("textedit"); selectedText = range.text; } return selectedText; } var getCursorPostion = function ($this, preText) { // Get textbox/textarea style. var styles = {}; $([ "font-family", "font-size", "font-weight", "font-style", "font-variant", "padding-top", "padding-left", "padding-bottom", "padding-right", "margin-top", "margin-left", "margin-bottom", "margin-right", "line-height", "letter-spacing", "word-spacing", "text-decoration", "text-align", "border-width", "border-style", "direction", "height", "width" ]).each(function (i, item) { styles[item] = $this.css(item); }); //fix borders. if (styles["border-width"] === "") { styles["border-width"] = "1px"; styles["border-style"] = "solid"; } //add aditional behavior. var css = $.extend({ "overflow": "auto", "box-sizing": "border-box", "white-space": "pre-wrap", "word-wrap": "break-word", "position": "absolute", "top": "0px", "left": "-9999px" }, styles); //create div as a copy and get cursor position. var $div = $("<div></div>").css(css).text(preText).appendTo(document.body); var $cursor = $("<span style='display:inline-block;'>.</span>").appendTo($div); var pos = $cursor.position(); if ($this.css("direction") === "rtl") { pos.right = $div.width() - pos.left; delete pos.left; } pos.top += $cursor.height() - $this.scrollTop(); $div.remove(); return pos; }; //Private Static - changes function scope so that 'this' could point to source object var contextBinder = function (func, scope) { if (func.bind) { return func.bind(scope); } else { return function () { func.apply(scope, arguments[2]); }; } }; _Target.on("keyup", contextBinder(onKeyup, this)); _Target.on("keydown", contextBinder(onKeydown, this)); } <file_sep>//********************************************************************************************* // This code cannot be used without explicit permission. // Illegal use of this code may result in penal penalties. // For permissions and licencing please contact: // contib2012[ignore][at][ignore]gmail[ignore][dot][ignore]com[ignore] //********************************************************************************************* // This code is provided in raw form. // It should be modified according to javascript specification at any time. ; function optionSelector(options) { "use strict"; //Settings var _Settings = $.extend({}, { defaultIndex: 0, listClass: "selectorlist", itemClass: "selectorlist-item", selectedItemClass: "selectorlist-selecteditem", listTemplate: "<ul style='padding: 0; margin: 0; list-style-type: none; z-index: 999999;'></ul>", itemTemplate: "<li></li>", itemdataattribute: "index", events: { onClicked: null, OnSelectionChanged: null } }, options); this.tag = null; //Properties var _IsVisible = true; var _Data = null; var _SelectedIndex = -1; var _UIRoot = $(_Settings.listTemplate).addClass(_Settings.listClass); var _DisplayType = _UIRoot.css("display"); this.getSettings = function () { return _Settings; } this.getUIRoot = function () { return _UIRoot; } this.getData = function () { return _Data; } this.getSelectedIndex = function () { return _SelectedIndex; } this.getItemCount = function (index) { return _UIRoot.children().length; } this.getDisplayType = function () { return _DisplayType; } this.getVisibility = function () { return _IsVisible; } //Public - Clears the list items. this.clear = function () { _Data = null; _UIRoot.empty(); _SelectedIndex = -1; } //Public - Creates list items by removing previous. this.setData = function (data, formatter) { this.clear(); if (data && data.length > 0) { _Data = data; initialRender(this, formatter); this.setSelected(_Settings.defaultIndex); } } //public - return selected data item. this.getSelected = function () { if (_Data && _SelectedIndex > -1) { return _Data[_SelectedIndex]; } return null; } //Public - sets selected list item. this.setSelected = function (index) { var $settings = _Settings; var $children = _UIRoot.children(); if (index > -1 && index < $children.length) { $children.each(function (i, item) { decorateItem($settings.selectedItemClass, $(item), index, i); }); _SelectedIndex = index; if ($settings.events.OnSelectionChanged != null) { $settings.events.OnSelectionChanged.call(this); } } } //Public - changes visibility of the list. this.setVisible = function (visible) { if (visible && !_IsVisible) { _UIRoot.css("display", _DisplayType); _IsVisible = true; } else if (!visible && _IsVisible) { _DisplayType = _UIRoot.css("display"); _UIRoot.css("display", "none"); _IsVisible = false; } } //Public - changes locatin of the list within the page. this.setPosition = function (location) { _UIRoot.css(location); } //Private Event - raised when a list item is clicked var onClicked = function (e) { var $listitem = $(e.target); var $settings = _Settings; this.setSelected(parseInt($listitem.data($settings.itemdataattribute), 10)); if ($settings.events.onClicked != null) { $settings.events.onClicked.call(this, e); } } //Private Static - creates list items using data property // To use complete data item structure such as { name: "anyname", data: "anyhash" } change this method. // To use elements other than list change this method. var initialRender = function ($this, formatter) { var $settings = $this.getSettings(); var $root = $this.getUIRoot(); var data = $this.getData(); $root.empty(); if (data) { $.each(data, function (i, dataItem) { var $listItem = $($settings.itemTemplate).attr('data-' + $settings.itemdataattribute, i).addClass($settings.itemClass); if (formatter) { $listItem.append(formatter(dataItem)); } else { $listItem.text(dataItem); } decorateItem($settings.selectedItemClass, $listItem, $this.getSelectedIndex(), i); $root.append($listItem); }); } } //Private Static - decorates item by adding/removing css classes var decorateItem = function (cssClass, item, selIndex, currIndex) { if (selIndex != currIndex) { item.removeClass(cssClass); } else if (!item.hasClass(cssClass)) { item.addClass(cssClass); } } //Private Static - changes function scope so that 'this' could point to source object var contextBinder = function (func, scope) { if (func.bind) { return func.bind(scope); } else { return function () { func.apply(scope, arguments); }; } }; // binds all list items to onClicked event in one go. // If we change the ui element from List to something else we need to handle the event binding below. _UIRoot.on('click', 'li', contextBinder(onClicked, this)); } <file_sep>///////////////////////////////////////////////////////////////////////////////////////////////////////// "use strict"; function TypeChecker() { } TypeChecker.TypeNames = [ "string", "integer", "float", "bool", "null", "undefined", "object" ]; TypeChecker.GetType = function (value) { if (typeof value == "string") { return TypeChecker.TypeNames[0]; } else if (typeof value == "number") { if (parseInt(value) == value) { return TypeChecker.TypeNames[1]; } else { return TypeChecker.TypeNames[2]; } } else if (typeof value == "boolean") { return TypeChecker.TypeNames[3]; } else if (typeof value == "null") { return TypeChecker.TypeNames[4]; } else if (typeof value == "undefined") { return TypeChecker.TypeNames[5]; } else { return TypeChecker.TypeNames[6]; } }; TypeChecker.IsString = function (value) { return (this.GetType(value) == TypeChecker.TypeNames[0]); } TypeChecker.IsInteger = function (value) { return (this.GetType(value) == TypeChecker.TypeNames[1]); } TypeChecker.IsFloat = function (value) { return (this.GetType(value) == TypeChecker.TypeNames[2]); } TypeChecker.IsBoolean = function (value) { return (this.GetType(value) == TypeChecker.TypeNames[3]); } TypeChecker.IsNull = function (value) { return (this.GetType(value) == TypeChecker.TypeNames[4]); } TypeChecker.IsUndefined = function (value) { return (this.GetType(value) == TypeChecker.TypeNames[5]); } TypeChecker.IsObject = function (value) { return (this.GetType(value) == TypeChecker.TypeNames[6]); } ///////////////////////////////////////////////////////////////////////////////////////////////////////// function FuzzyCharacterMapInfo(english, urdu, backspaces) { this.English = english; //char this.Urdu = urdu; //array of char this.Backspaces = backspaces; //int } ///////////////////////////////////////////////////////////////////////////////////////////////////////// function CharacterToken() { this.Value = 0; //char this.IsFirst = false; //bool this.IsLast = false; //bool this.IsVowel = false; //bool this.IsValid = false; //bool } ///////////////////////////////////////////////////////////////////////////////////////////////////////// function TrieNode() { this.Parent = null; //TrieNode this.Word = null; // string this.Character = 0; //char this.Children = []; // [{char: TrieNode}] } ///////////////////////////////////////////////////////////////////////////////////////////////////////// function Trie() { var data = { root: new TrieNode() }; Trie.prototype.GetRoot = function () { return data.root; } } Trie.prototype.AddWord = function (word) { //(string) if (TypeChecker.IsString(word) && word.length > 0) { var node = this.GetRoot(); for (var x = 0; x < word.length; x++) { var currChar = word.charCodeAt(x); if (node.Children[currChar] == null) { var child = new TrieNode(); child.Character = currChar; child.Parent = node; node.Children[currChar] = child; node = child; } else { node = node.Children[currChar]; } } if (node.Word == null) { node.Word = word; } } } Trie.prototype.GetMatches = function (word) { var result = []; if (TypeChecker.IsString(word) && word.length > 0) { var node = this.GetRoot(); for (var x = 0; x < word.length; x++) { var currChar = word.charCodeAt(x); if (node.Children[currChar] != null) { node = node.Children[currChar]; } else { node = null; break; } } if (node != null) { if (node.Word != null) { result.push(node.Word); } this.GetMatchesRecursive(node, result); } } return result; } Trie.prototype.GetMatchesRecursive = function me(node, result) { if (node != null) { node.Children.forEach(function (item, index, array) { if (item.Word != null) { result.push(item.Word); } me(item, result); }); } } ///////////////////////////////////////////////////////////////////////////////////////////////////////// function ParseState() { this.Node = null; //TrieNode this.PreviousIndex = -1; //int this.MissedStack = []; //char[] this.MissedIndex = -1; //int } ///////////////////////////////////////////////////////////////////////////////////////////////////////// function FuzzyTrie() { Trie.call(this); } FuzzyTrie.prototype = new Trie(); FuzzyTrie.prototype.constructor = FuzzyTrie; FuzzyTrie.prototype.GetExactMatchingCharacters = function (curr, prev, next) { var currChar = String.fromCharCode(curr.Value); var prevChar = (prev != null) ? String.fromCharCode(prev.Value) : 0; var currIsFirst = curr.IsFirst; var currIsLast = curr.IsLast; var prevIsFirst = (prev != null) ? prev.IsFirst : false; switch (currChar) { case '0': if (currIsFirst) { return [ new FuzzyCharacterMapInfo(currChar, [0], 0) ]; } else { return [ new FuzzyCharacterMapInfo(currChar, [0], 0) ]; } case 'a': if (currIsFirst) { return [ new FuzzyCharacterMapInfo(currChar, ['آ'], 0), new FuzzyCharacterMapInfo(currChar, ['ا'], 0), new FuzzyCharacterMapInfo(currChar, ['ع'], 0) ]; } else if (prevChar == 'a' && prevIsFirst) { return [ new FuzzyCharacterMapInfo(currChar, ['آ'], 0), new FuzzyCharacterMapInfo(currChar, ['ع', 'ا'], 0) ]; } else if (!currIsLast) { return [ new FuzzyCharacterMapInfo(currChar, ['ا'], 0), new FuzzyCharacterMapInfo(currChar, ['ی'], 0), new FuzzyCharacterMapInfo(currChar, ['ع'], 0), new FuzzyCharacterMapInfo(currChar, ['ع', 'ا'], 0), new FuzzyCharacterMapInfo(currChar, [0], 0) ]; } else { return [ new FuzzyCharacterMapInfo(currChar, ['ا'], 0), new FuzzyCharacterMapInfo(currChar, ['ع'], 0), new FuzzyCharacterMapInfo(currChar, ['ہ'], 0) ]; } case 'b': return [ new FuzzyCharacterMapInfo(currChar, ['ب'], 0) ]; case 'c': return [ new FuzzyCharacterMapInfo(currChar, ['ک'], 0), //new FuzzyCharacterMapInfo(currChar, ['س'], 0), //new FuzzyCharacterMapInfo(currChar, ['ث'], 0), //new FuzzyCharacterMapInfo(currChar, ['ص'], 0) ]; case 'd': return [ new FuzzyCharacterMapInfo(currChar, ['د'], 0), new FuzzyCharacterMapInfo(currChar, ['ڈ'], 0) ]; case 'e': if (currIsFirst) { return [ new FuzzyCharacterMapInfo(currChar, ['ا'], 0) ]; } else if (!currIsLast) { return [ new FuzzyCharacterMapInfo(currChar, ['ی'], 0), new FuzzyCharacterMapInfo(currChar, ['ے'], 0), new FuzzyCharacterMapInfo(currChar, ['ۓ'], 0), new FuzzyCharacterMapInfo(currChar, ['ع'], 0), new FuzzyCharacterMapInfo(currChar, [0], 0) ]; } else { return [ new FuzzyCharacterMapInfo(currChar, ['ے'], 0), new FuzzyCharacterMapInfo(currChar, ['ۓ'], 0), new FuzzyCharacterMapInfo(currChar, ['ی'], 0), new FuzzyCharacterMapInfo(currChar, ['ہ'], 0), new FuzzyCharacterMapInfo(currChar, [0], 0) ]; } case 'f': return [ new FuzzyCharacterMapInfo(currChar, ['ف'], 0) ]; case 'g': return [ new FuzzyCharacterMapInfo(currChar, ['گ'], 0), new FuzzyCharacterMapInfo(currChar, ['غ'], 0) ]; case 'h': if (prevChar == 'c') { return [ new FuzzyCharacterMapInfo(currChar, ['چ'], 1), new FuzzyCharacterMapInfo(currChar, ['ھ'], 0), new FuzzyCharacterMapInfo(currChar, ['ہ'], 0), new FuzzyCharacterMapInfo(currChar, ['ح'], 0) ]; } else if (prevChar == 'k') { return [ new FuzzyCharacterMapInfo(currChar, ['خ'], 1), new FuzzyCharacterMapInfo(currChar, ['ھ'], 0), new FuzzyCharacterMapInfo(currChar, ['ہ'], 0), new FuzzyCharacterMapInfo(currChar, ['ح'], 0) ]; } else if (prevChar == 's') { return [ new FuzzyCharacterMapInfo(currChar, ['ش'], 1), new FuzzyCharacterMapInfo(currChar, ['ھ'], 0), new FuzzyCharacterMapInfo(currChar, ['ہ'], 0), new FuzzyCharacterMapInfo(currChar, ['ح'], 0) ]; } else if (prevChar == 'g') { return [ new FuzzyCharacterMapInfo(currChar, ['غ'], 1), new FuzzyCharacterMapInfo(currChar, ['ھ'], 0), new FuzzyCharacterMapInfo(currChar, ['ہ'], 0), new FuzzyCharacterMapInfo(currChar, ['ح'], 0) ]; } else if (prevChar == 'p') { return [ new FuzzyCharacterMapInfo(currChar, ['ف'], 1), new FuzzyCharacterMapInfo(currChar, ['ھ'], 0), new FuzzyCharacterMapInfo(currChar, ['ہ'], 0), new FuzzyCharacterMapInfo(currChar, ['ح'], 0) ]; } else { return [ new FuzzyCharacterMapInfo(currChar, ['ہ'], 0), new FuzzyCharacterMapInfo(currChar, ['ھ'], 0), new FuzzyCharacterMapInfo(currChar, ['ح'], 0) ]; } case 'i': if (currIsFirst) { return [ new FuzzyCharacterMapInfo(currChar, ['ا'], 0), new FuzzyCharacterMapInfo(currChar, ['ع'], 0), new FuzzyCharacterMapInfo(currChar, ['آ', 'ئ'], 0), ]; } else if (prevChar == 'c') { return [ new FuzzyCharacterMapInfo(currChar, ['ش'], 1), new FuzzyCharacterMapInfo(currChar, ['ع'], 0), new FuzzyCharacterMapInfo(currChar, ['ی'], 0), new FuzzyCharacterMapInfo(currChar, [0], 0) ]; } if (prevChar == 'a') { return [ new FuzzyCharacterMapInfo(currChar, ['ئ', 'ی'], 0), new FuzzyCharacterMapInfo(currChar, ['ئ'], 0), new FuzzyCharacterMapInfo(currChar, ['ی'], 0), new FuzzyCharacterMapInfo(currChar, ['ے'], 1), new FuzzyCharacterMapInfo(currChar, [0], 0) ]; } else if (!currIsLast) { return [ new FuzzyCharacterMapInfo(currChar, ['ع'], 0), new FuzzyCharacterMapInfo(currChar, ['ی'], 0), new FuzzyCharacterMapInfo(currChar, ['ا', 'ئ'], 0), new FuzzyCharacterMapInfo(currChar, [0], 0) ]; } else { return [ new FuzzyCharacterMapInfo(currChar, ['ع'], 0), new FuzzyCharacterMapInfo(currChar, ['ی'], 0), new FuzzyCharacterMapInfo(currChar, ['ے'], 0), new FuzzyCharacterMapInfo(currChar, ['ئ', 'ی'], 0) ]; } case 'j': return [ new FuzzyCharacterMapInfo(currChar, ['ج'], 0) ]; case 'k': return [ new FuzzyCharacterMapInfo(currChar, ['ک'], 0) ]; case 'l': return [ new FuzzyCharacterMapInfo(currChar, ['ل'], 0) ]; case 'm': return [ new FuzzyCharacterMapInfo(currChar, ['م'], 0) ]; case 'n': return [ new FuzzyCharacterMapInfo(currChar, ['ن'], 0), new FuzzyCharacterMapInfo(currChar, ['ں'], 0) ]; case 'o': if (currIsFirst) { return [ new FuzzyCharacterMapInfo(currChar, ['ا'], 0), new FuzzyCharacterMapInfo(currChar, ['ع'], 0), new FuzzyCharacterMapInfo(currChar, ['ا', 'و'], 0) ]; } else if (prevChar == 'a') { return [ new FuzzyCharacterMapInfo(currChar, ['ؤ'], 0) ]; } else if (prevChar == 'w' || prevChar == 'v') { return [ new FuzzyCharacterMapInfo(currChar, [0], 0), ]; } else { return [ new FuzzyCharacterMapInfo(currChar, ['و'], 0) ]; } case 'p': return [ new FuzzyCharacterMapInfo(currChar, ['پ'], 0) ]; case 'q': return [ new FuzzyCharacterMapInfo(currChar, ['ق'], 0) ]; case 'r': if (currIsFirst) { return [ new FuzzyCharacterMapInfo(currChar, ['ر'], 0) ]; } else { return [ new FuzzyCharacterMapInfo(currChar, ['ر'], 0), new FuzzyCharacterMapInfo(currChar, ['ڑ'], 0) ]; } case 's': return [ new FuzzyCharacterMapInfo(currChar, ['س'], 0), new FuzzyCharacterMapInfo(currChar, ['ث'], 0), new FuzzyCharacterMapInfo(currChar, ['ص'], 0) ]; case 't': return [ new FuzzyCharacterMapInfo(currChar, ['ت'], 0), new FuzzyCharacterMapInfo(currChar, ['ٹ'], 0), new FuzzyCharacterMapInfo(currChar, ['ط'], 0) ]; case 'u': if (currIsFirst) { return [ new FuzzyCharacterMapInfo(currChar, ['ا'], 0), new FuzzyCharacterMapInfo(currChar, ['ع'], 0), new FuzzyCharacterMapInfo(currChar, ['ا', 'و'], 0) ]; } else if (!currIsLast) { return [ new FuzzyCharacterMapInfo(currChar, ['و'], 0), new FuzzyCharacterMapInfo(currChar, [0], 0), ]; } else { return [ new FuzzyCharacterMapInfo(currChar, ['و'], 0), ]; } case 'v': case 'w': if (prevChar == 'o') { return [ new FuzzyCharacterMapInfo(currChar, [0], 0), ]; } else { return [ new FuzzyCharacterMapInfo(currChar, ['و'], 0), new FuzzyCharacterMapInfo(currChar, ['و', 'و'], 0) ]; } case 'x': return [ new FuzzyCharacterMapInfo(currChar, ['ش'], 0) ]; case 'y': return [ new FuzzyCharacterMapInfo(currChar, ['ی'], 0), new FuzzyCharacterMapInfo(currChar, ['ے'], 0), new FuzzyCharacterMapInfo(currChar, ['ۓ'], 0), ]; case 'z': return [ new FuzzyCharacterMapInfo(currChar, ['ز'], 0), new FuzzyCharacterMapInfo(currChar, ['ذ'], 0), new FuzzyCharacterMapInfo(currChar, ['ض'], 0), new FuzzyCharacterMapInfo(currChar, ['ظ'], 0) ]; } return [ new FuzzyCharacterMapInfo(currChar, [currChar], 0) ]; } FuzzyTrie.prototype.GetResolvedCharacters = function (english, currIndex, prevIndex) { var _vowels = "aeiou"; var _acceptableCharacters = "abcdefghijklmnopqrstuvwxyz0123456789"; var curr = null; var prev = null; var next = null; curr = new CharacterToken(); curr.Value = english.charCodeAt(currIndex); curr.IsFirst = (currIndex == 0); curr.IsLast = (english.length == currIndex + 1), curr.IsVowel = (_vowels.indexOf(english.charCodeAt(currIndex)) > -1); if (currIndex > 0) { prev = new CharacterToken(); prev.Value = (prevIndex > -1) ? english.charCodeAt(prevIndex) : 0; prev.IsFirst = prevIndex == 0; prev.IsLast = false; prev.IsVowel = (_vowels.indexOf(english.charCodeAt(currIndex - 1)) > -1); } if (currIndex + 1 < english.length) { next = new CharacterToken(); next.Value = english.charCodeAt(currIndex + 1); next.IsFirst = false; next.IsLast = (english.length == currIndex + 2); next.IsVowel = (_vowels.indexOf(english.charCodeAt(currIndex + 1)) > -1); } return FuzzyTrie.prototype.GetExactMatchingCharacters(curr, prev, next); } FuzzyTrie.prototype.GetFuzzy = function (english, result) { var stateList = []; var baseState = new ParseState(); baseState.Node = FuzzyTrie.prototype.GetRoot(); baseState.PreviousIndex = -2; stateList.push(baseState); if (english.length > 0) { for (var x = 0; x < english.length; x++) { var states = stateList.slice(0); //console.log(states.length); states.forEach(function (state, index, states) { //console.log(stateList.length); for (var y = 0; y < stateList.length; y++) { if (stateList[y].Node == state.Node || stateList[y] == null) { stateList.splice(y--, 1); } } //console.log(stateList.length); var currentIndex = x; var previousIndex = state.PreviousIndex; var currChar = english.charCodeAt(currentIndex); var fuzzyChars = FuzzyTrie.prototype.GetResolvedCharacters(english, currentIndex, previousIndex); //console.log(fuzzyChars); fuzzyChars.forEach(function (fc, index, fuzzyChars) { var newNode = state.Node; if (fc.Backspaces > 0) { var bsp = fc.Backspaces; while (state.MissedIndex > -1) { state.MissedStack[state.MissedIndex--] = 0; bsp--; } // backspace tree while (bsp > 0) { newNode = newNode.Parent; bsp--; } } var charState = new ParseState(); charState.MissedIndex = state.MissedIndex; charState.MissedStack = state.MissedStack.splice(0); if (fc.Urdu[0] == 0) { var newPreviousIndex = currentIndex - fc.Backspaces - 1; charState.PreviousIndex = newPreviousIndex; charState.Node = newNode; stateList.push(charState); } else { var nx = newNode; for (var t = 0; t < fc.Urdu.length; t++) { //console.log(fc.Urdu[t]); if (charState.MissedIndex < 0 && nx.Children[fc.Urdu[t].charCodeAt(0)] != null) { nx = nx.Children[fc.Urdu[t].charCodeAt(0)]; } else { charState.MissedStack[++charState.MissedIndex] = fc.Urdu[t].charCodeAt(0); } } if (charState.MissedIndex < 5) { charState.PreviousIndex = currentIndex; charState.Node = nx; stateList.push(charState); //console.log(charState.MissedIndex); } } }); }); } //console.log(stateList); } stateList.forEach(function (i, index, list) { var word = i.Node.Word; //console.log(word); //console.log(result.indexOf(word)); //console.log(i.MissedIndex); if (word != null && i.MissedIndex < 0 && result.indexOf(word) < 0) { result.push(i.Node.Word); } }); } FuzzyTrie.prototype.GetFuzzyMatches = function (english) { //for (var x = 0; x < english.length; x++) //{ // if (char.IsControl(english[x])) // { // english = english.Remove(x--, 1); // } //} var result = []; FuzzyTrie.prototype.GetFuzzy(english, result); return result; } ///////////////////////////////////////////////////////////////////////////////////////////////////////// function Dictionary() { if (Dictionary.prototype._singletonInstance) { return Dictionary.prototype._singletonInstance; } Dictionary.prototype._singletonInstance = this; var trie = new FuzzyTrie(); this.GetMatches = function (urdu) { var results = []; if (TypeChecker.IsString(urdu) && urdu.length > 0) { results = trie.GetMatches(urdu); } return results; } this.GetEnglish2UrduFuzzyMatches = function (word) { var result = []; var en = EncodeWord(word); //result.push(en); result = trie.GetFuzzyMatches(en); ApplyRejectionFilter(word, result); return result; } function ApplyRejectionFilter(word, result) { } function EncodeWord(english) { var result = RemoveDuplicatesAndAddVowels(english); return result; } var vowels = "aeiou"; var compounds = "csgkp"; function RemoveDuplicatesAndAddVowels(english) { var res = []; if (TypeChecker.IsString(english) && english.length > 0) { var x = 0; var y = 0; var prevWsVowel = true; var currIsVowel = false; while (x < english.length) { if (x > 0) { var prevChar = english.charCodeAt(x - 1); var currChar = english.charCodeAt(x); if (prevChar == currChar) { if (x > 1) { var prevprevChar = english.charCodeAt(x - 2); if (!(currChar == 'h'.charCodeAt(0) && compounds.indexOf(String.fromCharCode(prevprevChar)) > -1)) { x++; continue; } } else { x++; continue; } } } currIsVowel = (vowels.indexOf(currChar) > -1); if (currIsVowel) { prevWsVowel = true; res[y++] = english.charAt(x++); continue; } if (!prevWsVowel) { res[y++] = '0'; } res[y++] = english.charAt(x++); prevWsVowel = false; } } return res.join(""); } var Initialize = function () { // Load dictionary from file LoadDictionary(); } var LoadDictionary = function () { var words = []; if (Dictionary.prototype.GetWords) { words = Dictionary.prototype.GetWords(); } words.forEach(function (word, index, array) { if (TypeChecker.IsString(word) && word.length > 0) { trie.AddWord(word); } }); } Initialize(); } Dictionary.prototype.GetWords = function () { // defined in a seprate file. return (words) ? words : []; } Dictionary.GetInstance = function () { var singletonClass = new Dictionary(); return singletonClass; };
17c86190611468d3016714679352f8f56fce4fcc
[ "JavaScript" ]
6
JavaScript
ahmadrabbani/ClientSideScripts
d5cc1cc91ca5367fafdf8147de4f207b9ee0cc8b
ee37824dca5e32a60f08527fafaaab3bde0c9bb1
refs/heads/master
<file_sep>class PagesController < ApplicationController def home @recent = Post.order("created_at desc").limit(3) end def about_me end def projects end end <file_sep>class User < ActiveRecord::Base has_many :posts mount_uploader :image, ImageUploader end <file_sep>require 'bundler/capistrano' set :application, "steveegordon.com" # Your application location on your server goes here default_run_options[:pty] = true set :repository, "." set :scm, :none set :deploy_via, :copy set :checkout, 'export' set :user, 'seg86' # Your username goes here set :use_sudo, false set :domain, 'steveegordon.com' # Your domain goes here set :applicationdir, "/home/#{user}/#{application}" set :deploy_to, applicationdir role :web, domain role :app, domain role :db, domain, :primary => true set :chmod755, "app config db lib public vendor script script/* public/disp*" namespace :deploy do task :start do ; end task :stop do ; end task :restart, :roles => :app, :except => { :no_release => true } do run "#{try_sudo} touch #{File.join(current_path,'tmp','restart.txt')}" end end<file_sep>$(document).on('turbolinks:load', function(){ var page = window.location.pathname; var loaded = $('.cover-text-lead'); if (loaded) {$('.cover-text-lead').remove(); $('.cover-text-sublead').remove(); console.log("deleted")}; if (page == "/"){ $('.fh5co-cover-intro').prepend('<h1 class="cover-text-lead wow fadeInUp" data-wow-duration="1s" data-wow-delay=".5s"><NAME><span class="subhead"></br>Web Developer</span> </h1><h2 class="cover-text-sublead wow fadeInUp" data-wow-duration="1s" data-wow-delay=".8s">Welcome to my personal webpage. Here you can find out who I am, look at some of my projects, and find out what i\'m learning/reading about.</h2>' ); } else if (page == "/posts"){ $('.fh5co-cover-intro').prepend('<h1 class="cover-text-lead wow fadeInUp" data-wow-duration="1s" data-wow-delay=".5s">Blog</h1><h2 class="cover-text-sublead wow fadeInUp" data-wow-duration="1s" data-wow-delay=".8s">I have lots of interests including coding, sports, movies, or tech that I occasionally post about. Here\'s what I\'ve recently learned, what bothers me, and things that just seem generally appealing to me.</h2><p class="wow fadeInUp" data-wow-duration="1s" data-wow-delay="1.1s">' ); } else if (page == "/about_me"){ $('.fh5co-cover-intro').prepend('<h1 class="cover-text-lead wow fadeInUp" data-wow-duration="1s" data-wow-delay=".5s">About Me</h1><h2 class="cover-text-sublead wow fadeInUp" data-wow-duration="1s" data-wow-delay=".8s">Considering my web adress it should be fairly obvious that my name is <NAME>. I am a 31 year old web developer who has had alot of stops along the way, from bartending to medical sales. Here is a little bit more about how I ended up finding programming, who I am, and what I can offer.</h2><p class="wow fadeInUp" data-wow-duration="1s" data-wow-delay="1.1s">' ); } else if (page == "/projects"){ $('.fh5co-cover-intro').prepend('<h1 class="cover-text-lead wow fadeInUp" data-wow-duration="1s" data-wow-delay=".5s">Projects</h1>' ); } else {} }); <file_sep>class PostsController < ApplicationController def show @post = Post.find(params[:id]) @position = @post.image.url.rindex('/') + 1 end def index @posts = Post.all end def new end def create @post = Post.new(post_params) # temporarily disables users. # @post.user_id = 1 if @post.save redirect_to '/posts' else render 'new' end end private def post_params params.require(:post).permit(:category, :image, :title, :text) end end <file_sep>module ApplicationHelper def full_title(page_title = "") base_title = "SteveEGordon.com" if page_title.empty? base_title else "#{page_title} | #{base_title}" end end def cover(page_title = "") unless page_title.empty? page_title.downcase!.gsub!(" ", "_") page_title end end def post_thumb(x) @post = Post.find(x) @position = @post.image.url.rindex('/') + 1 url = @post.image.url.insert(@position, 'sml_') return url end end
9129ec8439edc0bcc2af6deb6cd8606a163b0c3a
[ "JavaScript", "Ruby" ]
6
Ruby
steveegordon/segwebpage
a295bc281ecb5fa4b0207c57f0d313072130ed13
0c98156a27d5df434c32ec1d5b48fdd9f1e7102e
refs/heads/master
<repo_name>marrese/airdataset<file_sep>/Documentation.Rmd # AirShiny - Exploring Pollution Data in an Italian Province author: R.Marrese date: 2014 Nov 13th ## Description The **AirShiny** webapp let the user to browse through the environmental data (specifically air pollution chemical data). The dataset contains data taken from Apulian Environmental Agency among some monitoring stations during the first semester of 2014. >*The purpose is to facilitate users in exploring the dataset and operate* >*somefirst and simple visual correlation on pollution trend and causes.* A generalized plot is created as soon as the user put the query by mean of the available widgets. Starting from the overall picture the user may then focalize on a particular time period or monitoring station. Aside of a scatterplot, the graphic section also draws a smooth line and interval around the observed data. ## The Motivation ```{r,echo=FALSE,eval=TRUE,message=FALSE,fig.width=10,warning=FALSE} library(RCurl) library(ggplot2) url<-"https://dl.dropboxusercontent.com/s/bp94lv1b09s5x33/airdatTA.csv" myCsv <- getURL(url) w<-read.csv(textConnection(myCsv)) w$date=as.Date(w$date) w$day=weekdays(w$date) w$day = factor(w$day, ordered=TRUE, levels=c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday","Saturday")) names(w)[8]="month_no" ``` The dataset `airdata` contains `r nrow(w)` observations and `r ncol(w)` variables. Taking `PM10` pollutant for instance, the following plot syntetized the variability of data and the results of each station (see blue lines). On overall station the observed mean is **`r round(mean(w$PM10,na.rm=TRUE), 2)`** and the standard deviation is as large as **`r round(sd(w$PM10,na.rm=TRUE), 2)`**. This represents a good motivation of implementing a simple exploration dashboard. ```{r,echo=FALSE,eval=TRUE,message=FALSE,fig.width=10,warning=FALSE} qplot(date, PM10,data=w,facets=.~station, geom=c("point","smooth"),method="lm", main="2014 1° sem - PM10 value per station", ylab="PM10", xlab="date", alpha=I(0.2)) ``` ## Features and Functions The user can visualize and compare data for each of the following pollutant: - **PM10** and **PM2.5** - particulate matter - **CO** - carbonic anidride - **SO2** - sulfur dioxide - **O3** - ozone - **C6H6** - Benzene - **H2S** - hydrogen sulfide - **iqa** - general quality index (calculated on previous values) - by setting time period, color, station, an in-depth exploration is quite easy to perform. ## Using the App The app is managed by this simple control panel. ![dashboard](airshiny.jpg) Using the control panel the user can choose: - all stations or just one; - period of observation - comparison between pollutant playing with X & Y Axis. Furthermore: - a **jitter** box allows a better rendering - a **smooth** box trace tendency and confidence interval on scatterplot. A tipical plot is drawn as follows, where `PM10` pollutant data are drawn by `date`. Note that the color of points change according to `iqa` (quality index), showing evidence of correlation between `PM10` and averall quality index. Note also that the **smooth** option let the user to evaluate the data trend (blue line and grey interval). ```{r, echo=FALSE,eval=TRUE,message=FALSE, fig.width=10,warning=FALSE} p <- ggplot(w, aes_string(x="date", y="PM10")) + geom_point() p <- p + aes_string(color="iqa") p <- p + geom_jitter() p <- p + geom_smooth() p ``` ## Future development & References **Future developments** To further analyze the dataset some new tabs may be added: * boxplot * confidence interval between pollutant statistics * regression analysis, * and more.. **Reference** The web app may be launched at this [this](https://marrese.shinyapps.io/airshiny/) url. The related code may be inspected at [this](https://github.com/marrese/airdataset) url. More data can be downloaded at the [ArpaPuglia](http://www.arpa.puglia.it) website. **Enjoy the application** <file_sep>/README.md **AirShiny Application** This simple application browses through real pollution data taken by ArpaPuglia. The dataset contains the the first semester of 2014 pollutants as resulted from 10 stations in Taranto province. The App purpose is to facilitate users in exploring the dataset and operate some first and simple visual correlation on pollution trend and causes. A generalized plot is created as soon as the user put the query by mean of widgets. Starting from the overall picture the user may focalize on a particular time period or monitoring station. Aside of a scatterplot the graphic also draws a smooth line and interval around the observed data. The user can visualize and compare data for each of the following pollutant: - **PM10** and **PM2.5** - particulate matter - **CO** - carbonic anidride - **SO2** - sulfur dioxide - **O3** - ozone - **C6H6** - Benzene - **H2S** - hydrogen sulfide - **iqa** - general quality index (calculated on previous values) - by setting time period, color, station, an in-depth exploration is quite easy to perform.</small> For more informations follow this link https://rpubs.com/marrese52/40185. <file_sep>/server.R library(shiny) library(ggplot2) library (RCurl) ## reading dataset airdat url<-"https://dl.dropboxusercontent.com/s/bp94lv1b09s5x33/airdatTA.csv" myCsv <- getURL(url) w<-read.csv(textConnection(myCsv)) w$date=as.Date(w$date) w$day=weekdays(w$date) w$day = factor(w$day, ordered=TRUE, levels=c("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday","Saturday")) names(w)[8]="month_no" shinyServer(function(input, output) { dataset <- reactive({ if(input$station=='All') w[w$month_no>=input$range[[1]] & w$month_no<=input$range[[2]],] else w[w$month_no>=input$range[[1]] & w$month_no<=input$range[[2]] & w$station==input$station,] }) output$plot <- renderPlot({ p <- ggplot(dataset(), aes_string(x=input$x, y=input$y)) + geom_point() if (input$color != 'None') p <- p + aes_string(color=input$color) #facets <- paste(input$facet_row, '~', input$facet_col) #if (facets != '. ~ .') #p <- p + facet_grid(facets) if (input$jitter) p <- p + geom_jitter() if (input$smooth) { p <- p + geom_smooth() #p <- p+ geom_boxplot(aes(fill=input$x)) } print(p) }) }) <file_sep>/ui.R library(shiny) ## ######################### ## App Description ## ## This simple application browses through real pollution data taken by ArpaPuglia. ## The dataset contains the the first semester of 2014 pollutants as resulted from 10 stations in Taranto province. ## The App purpose is to facilitate users in exploring the dataset and operate some first and simple visual correlation ## on pollution trend and causes. ## A generalized plot is created as soon as the user put the query by mean of widgets. Starting from the overall picture ## the user may focalize on a particular time period or monitoring station. ## Aside of a scatterplot the graphic also draws a smooth line and interval around the observed data. ## The user can visualize and compare data for each of the following pollutant: ## - **PM10** and **PM2.5** - particulate matter ## - **CO** - carbonic anidride ## - **SO2** - sulfur dioxide ## - **O3** - ozone ## - **C6H6** - Benzene ## - **H2S** - hydrogen sulfide ## - **iqa** - general quality index (calculated on previous values) ## - by setting time period, color, station, an in-depth ## exploration is quite easy to perform.</small> ## For more informations follow this link https://rpubs.com/marrese52/40185. ######################### ######################### ## code start ######################### ## populate relevant tables used in ui.R df=c("station","date","day","month","month_no","PM10","NO2","O3","CO","SO2","PM2.5","C6H6","H2S","iqa") statlist=c("Grottaglie","<NAME>","Paolo VI","San Vito","Statte","Talsano","Via Alto Adige","Via Archimede","Via Machiavelli") # user interface code shinyUI(fluidPage( title = "ArpaPuglia - Air quality Explorer in Taranto Province", plotOutput('plot'), hr(), fluidRow( column(4, h4("Air Quality Explorer in Taranto Province"), p("This simple application browses through real pollution data taken by ArpaPuglia."), p("The dataset contains pollutant values as resulted from 10 stations in Taranto province during the first semester of 2014."), p("For more informations follow the ", a(href="https://rpubs.com/marrese52/40472", "presentation,")), p("or the ",a(href="AirshinyDoc.html","documentation")," page."), br(), img(src = "Logo.png", height = 72, width = 72), br(), p("Apulian Environment Protection Agency") ), column(3, sliderInput("range", "Month Range:", min = 1, max = 6, value = c(1,6)), br(), selectInput("station","Station",c("All",statlist),statlist[5]), checkboxInput('jitter', 'Jitter', value=TRUE), checkboxInput('smooth', 'Smooth (select date as X_Axis)', value=TRUE), br("Please note that in case of missing data some queries may produce error in the plot area.") ), column(4, offset = 1, selectInput('x', 'X Axis', df, df[[2]]), selectInput('y', 'Y Axis', df, df[[6]]), selectInput('color', 'Color', c('None', df, df[[3]])) ) # left for future developments #column(4, #selectInput('facet_row', 'Facet Row', #c(None='.', c("station","month")), #selectInput('facet_col', 'Facet Column', #c(None='.', c("station","month")) #) ) ))
166f11083a5b0ebaed112aaea4a24b8b369d5ce8
[ "Markdown", "R", "RMarkdown" ]
4
RMarkdown
marrese/airdataset
5167a4f59bae8ae89db0f35ae1513c678a0aa430
336ab10ae7380d5c216b96332151651638146a3d
refs/heads/main
<file_sep>from rest_framework import serializers from .models import MenuCart, Dish class DishSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Dish fields = [ 'name', 'description', 'price', 'preparation_time', 'created_at', 'updated_at', 'is_vegetarian', 'menu' ] class MenuCartSerializer(serializers.HyperlinkedModelSerializer): dish = DishSerializer(many=True, read_only=True) class Meta: model = MenuCart fields = [ 'name', 'description', 'created_at', 'updated_at', 'dish' ] class PublicMenuCartSerializer(serializers.HyperlinkedModelSerializer): dish = DishSerializer(many=True, read_only=True) num_dishes = serializers.IntegerField() class Meta: model = MenuCart fields = [ 'name', 'description', 'created_at', 'updated_at', 'dish', 'num_dishes' ] <file_sep>from django.test import TestCase from .. import models class TestModels(TestCase): def setUp(self): self.menu1 = models.MenuCart.objects.create( name='KebabHouse', description='Menu for KebabHouse', created_at='2020-01-01', updated_at='2020-01-01', ) self.dish1 = models.Dish.objects.create( name='Kebab Box', description='With French fries and meat', price=12.22, preparation_time='00:30', created_at='2020-01-01', updated_at='2020-01-01', is_vegetarian=False, menu=self.menu1 ) def test_should_create_menu_cart(self): self.assertEqual(str(self.menu1), 'KebabHouse') def test_should_create_dish(self): self.assertEqual(str(self.dish1), 'Kebab Box') <file_sep># menuapp ## Requirements ### All needed packages are in requirements.txt ```pip install requirements.txt ``` # SMTP ### All needed credentials are in setting.py (no needed setup) # Basic setup ### Linux ```brew install rabbitmq``` ### Windows <https://www.rabbitmq.com/install-windows.html#installer> ### Make a postgres server and paste credentials into menuapp/settings.py ``` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'XXXX', 'USER': 'XXXX', 'PASSWORD': '<PASSWORD>', 'HOST': 'XXXX', 'PORT': 'XXXX', } } ``` ``` python manage.py makemigrations``` \ ```python manage.py migrate ``` \ Create super user (App doesn't have a register functions) \ ```python manage.py createsuperuser``` ## Running a server ```python manage.py runserver``` ## Running a tests ```manage.py test``` ## Starting a Celery tasks (sending emails) ### Windows ```celery -A menuapp worker --pool=solo -l info``` ```celery -A menuapp beat -l INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler``` ### Linux (not sure about commands, didn't tested them) ```celery -A menuapp worker -l info``` ```celery -A menuapp beat -l info``` ## Urls <http://1172.16.31.10:8000/> Main view for API by browser \ <http://127.0.0.1:8000/docs/> Docs for API ## Linter I'm using flake8 with-max-line-length = 120 (for Django purposes) <file_sep>from django.db.models import Count from rest_framework import viewsets from rest_framework import permissions from .serializers import MenuCartSerializer, DishSerializer, \ PublicMenuCartSerializer from .models import MenuCart, Dish class MenuViewSet(viewsets.ModelViewSet): queryset = MenuCart.objects.all().order_by('-updated_at') serializer_class = MenuCartSerializer permission_classes = [permissions.IsAuthenticated] class DishViewSet(viewsets.ModelViewSet): queryset = Dish.objects.all().order_by('-updated_at') serializer_class = DishSerializer permission_classes = [permissions.IsAuthenticated] class PublicMenuViewSet(viewsets.ModelViewSet): queryset = MenuCart.objects.exclude(dish=None).annotate(num_dishes=Count('dish', distinct=True)) serializer_class = PublicMenuCartSerializer http_method_names = ['get', 'head', 'options'] filterset_fields = { 'name': ['exact'], 'created_at': ['gte', 'lte'], 'updated_at': ['gte', 'lte'], } ordering_fields = ['name', 'num_dishes'] <file_sep>from django.db import models class MenuCart(models.Model): name = models.CharField(max_length=200, primary_key=True) description = models.CharField(max_length=500) created_at = models.DateField() updated_at = models.DateField() def __str__(self): return self.name class Dish(models.Model): name = models.CharField(max_length=200) description = models.CharField(max_length=500) price = models.DecimalField(max_digits=8, decimal_places=2) preparation_time = models.TimeField() created_at = models.DateField() updated_at = models.DateField() is_vegetarian = models.BooleanField() menu = models.ForeignKey(MenuCart, on_delete=models.CASCADE, related_name='dish') def __str__(self): return self.name <file_sep>from rest_framework.test import APITestCase from django.contrib.auth.models import User from .. import models class TestMenuCart(APITestCase): url = '/menu/' def setUp(self): models.MenuCart.objects.create( name='Pizza Pellati', description='Menu for Pizza Pellati', created_at='2020-01-01', updated_at='2020-01-01', ) User.objects.create_user(username='testuser', password='<PASSWORD>') self.client.login(username='testuser', password='<PASSWORD>') def test_get_all_menu_cart(self): response = self.client.get(self.url, format='json') self.assertEqual(response.status_code, 200) def test_get_menu_cart(self): pk = 'Pizza Pellati' response = self.client.patch(f'{self.url}{pk}/', format='json') result = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(result['name'], 'Pizza Pellati') def test_post_menu_cart(self): data = { 'name': 'TestCart', 'description': 'TestDescription', 'created_at': '2020-12-29', 'updated_at': '2020-12-12', } response = self.client.post(self.url, data=data) result = response.json() self.assertEqual(response.status_code, 201) self.assertEqual(result['name'], 'TestCart') def test_patch_menu_cart(self): pk = 'Pizza Pellati' data = { 'name': 'Pizza Pellati1' } response = self.client.patch(f'{self.url}{pk}/', data=data, format='json') result = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(result['name'], 'Pizza Pellati1') def test_put_menu_cart(self): pk = 'Pizza Pellati' data = { 'name': 'Pizza Pellati2', 'description': 'Menu for Pizza Pellati', 'created_at': '2020-01-01', 'updated_at': '2020-01-01', } response = self.client.put(f'{self.url}{pk}/', data=data, format='json') result = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(result['name'], 'Pizza Pellati2') def test_delete_menu_cart(self): pk = 'Pizza Pellati' response = self.client.delete(f'{self.url}{pk}/', format='json') self.assertEqual(response.status_code, 204) class TestDish(APITestCase): url = '/dish/' def setUp(self): menu = models.MenuCart.objects.create( name='Istanbul Kebab', description='Menu for Kebab', created_at='2020-01-01', updated_at='2020-01-01', ) models.Dish.objects.create( name='Kebab Box', description='With French fries and meat', price=14.22, preparation_time='00:30', created_at='2020-01-01', updated_at='2020-01-01', is_vegetarian=False, menu=menu ) User.objects.create_user(username='testuser', password='<PASSWORD>') self.client.login(username='testuser', password='<PASSWORD>') def test_get_all_dish(self): response = self.client.get(self.url, format='json') self.assertEqual(response.status_code, 200) def test_get_dish(self): pk = '2' response = self.client.patch(f'{self.url}{pk}/', format='json') result = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(result['name'], 'Kebab Box') def test_post_dish(self): data = { 'name': 'TestDish', 'description': 'TestDescription', 'price': 15.00, 'preparation_time': '01:30', 'created_at': '2020-12-29', 'updated_at': '2020-12-12', 'is_vegetarian': True, 'menu': '/menu/Istanbul Kebab/' } response = self.client.post(self.url, data=data) result = response.json() self.assertEqual(response.status_code, 201) self.assertEqual(result['name'], 'TestDish') def test_patch_dish(self): pk = '3' data = { 'name': 'Kebab Box2' } response = self.client.patch(f'{self.url}{pk}/', data=data, format='json') result = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(result['name'], 'Kebab Box2') def test_put_menu_cart(self): pk = '6' data = { 'name': 'TestDish1', 'description': 'TestDescription1', 'price': 15.00, 'preparation_time': '01:30', 'created_at': '2020-12-29', 'updated_at': '2020-12-12', 'is_vegetarian': False, 'menu': '/menu/Istanbul Kebab/' } response = self.client.put(f'{self.url}{pk}/', data=data, format='json') result = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(result['name'], 'TestDish1') class TestPublic(APITestCase): url = '/public/menu/' def setUp(self): menu = models.MenuCart.objects.create( name='KFC', description='Menu for KFC', created_at='2020-01-01', updated_at='2020-01-01', ) models.Dish.objects.create( name='Twister', description='With chicken', price=10.00, preparation_time='00:15', created_at='2020-01-01', updated_at='2020-01-01', is_vegetarian=False, menu=menu ) def test_get_all_public(self): response = self.client.get(self.url, format='json') self.assertEqual(response.status_code, 200) def test_get_public_menu_cart(self): pk = 'KFC' response = self.client.get(f'{self.url}{pk}/', format='json') result = response.json() self.assertEqual(response.status_code, 200) self.assertEqual(result['name'], 'KFC') self.assertEqual(result['dish'][0]['name'], 'Twister') <file_sep>amqp==5.0.6 asgiref==3.4.1 billiard==3.6.4.0 cached-property==1.5.2 celery==5.1.2 certifi==2021.5.30 charset-normalizer==2.0.4 click==7.1.2 click-didyoumean==0.0.3 click-plugins==1.1.1 click-repl==0.2.0 coreapi==2.3.3 coreschema==0.0.4 Django==3.2.7 django-celery-beat==2.2.1 django-filter==2.4.0 django-rest-swagger==2.2.0 django-timezone-field==4.2.1 djangorestframework==3.12.4 drf-yasg==1.20.0 flake8==3.9.2 idna==3.2 importlib-metadata==4.8.1 inflection==0.5.1 itypes==1.2.0 Jinja2==3.0.1 kombu==5.1.0 MarkupSafe==2.0.1 mccabe==0.6.1 openapi-codec==1.3.2 packaging==21.0 prompt-toolkit==3.0.20 psycopg2==2.9.1 pycodestyle==2.7.0 pyflakes==2.3.1 pyparsing==2.4.7 python-crontab==2.5.1 python-dateutil==2.8.2 pytz==2021.1 requests==2.26.0 ruamel.yaml==0.17.16 ruamel.yaml.clib==0.2.6 simplejson==3.17.5 six==1.16.0 sqlparse==0.4.1 typing-extensions==3.10.0.2 uritemplate==3.0.1 urllib3==1.26.6 vine==5.0.0 wcwidth==0.2.5 zipp==3.5.0 <file_sep>from celery import shared_task from django.contrib.auth import get_user_model from django.core.mail import send_mail from django.conf import settings from .models import Dish import datetime @shared_task(bind=True) def send_mails(self): today = datetime.date.today() yesterday = today - datetime.timedelta(days=1) dish_created_obj = Dish.objects.filter(created_at__range=[yesterday, today]) dish_updated_obj = Dish.objects.filter(updated_at__range=[yesterday, today]) users = get_user_model().objects.all() dish_list = [] dish_updated_list = [] for dish in dish_updated_obj: dish_updated_list.append(dish.name) for dish in dish_created_obj: dish_list.append(dish.name) for user in users: mail_subject = 'MenuApp notification' message = f''' Newly added Dishes: {", ".join(str(x) for x in dish_list)} Recently modified Dishes: {", ".join(str(x) for x in dish_updated_list)} ''' to_email = user.email send_mail( subject=mail_subject, message=message, from_email=settings.EMAIL_HOST_USER, recipient_list=[to_email], fail_silently=True, ) return 'Emails Sent'
7bd5ed29c3e044f735c746988065fe63dad99bca
[ "Markdown", "Python", "Text" ]
8
Python
RafalPer/menuapp
6d3f04f049d02d4b2bb2eefccd86fed24ba0913a
63dbba6266dce8a2c63750d8e62c730832313536
refs/heads/master
<repo_name>LUC4SNUN3S/python<file_sep>/aula1.py np = input("INFORME A NOTA DA PROVA") print(np) nt = input ("INFORME A NOTA DO TRABALHO") print(nt) nq = input ("INFORME A NOTA DA QUALITATIVA") print(nq) media = ( float (np) * 6 + float (nt) * 3 + float (nq)) / 10 print(media)<file_sep>/numero par.py numero = input("fale um numero\n") resultado = int(numero) %2 if resultado ==0: print("o numero e par") else: print("o numero e impar")<file_sep>/idade.py mn = input ("INFORME O MÊS") print(mn) an = input ("O ANO QUE NASCEU") print(an) ma = input ("mês atual") print(ma) aa = input ("ano atual") print (aa) idade = -(float (an) - float (aa) + float (ma) - float (mn)) print( "você tem",idade, "anos")<file_sep>/media bimestral.py bin1 = input ("informe sua nota do primeiro bimestre") print(bin1) bin2 = input("informe sua nota do segundo bimestre") print(bin2) bin3 =input ("informe sua nota do terceiro bimestre") print(bin3) bin4 = input("informe sua nota do quarto bimestre") print(bin4) mf = (float (bin1) + float(bin2) + float(bin3) + float(bin4))/4 print(mf)<file_sep>/desafio.py import random num = int(input('DIGA O NUMERO ')) aux = num while aux <= 10: aux += 1<file_sep>/teste.py nome = input("NOME DO ALUNO (A) ") np = input("INFORME A NOTA DA PROVA") print(np) nt = input("INFORME A NOTA DO TRABALHO") print(nt) nq = input("INFORME A NOTA DA QUALITATIVA") print(nq) media = (float (np) * 6 + float(nt) * 3 + float (nq))/10 print("A MEDIA DO ALUNO(A)",nome,"e",media) if media >= 6: print("APROVADO") else: print("REPROVADO")<file_sep>/imc.py p = input("informe seu peso") print(p) a = input("informe sua altura") print(a) at = (float (a) * float(a)) imc = (float (p) / (at)) if imc <= 18.5: print("magro ou baixo peso") print("RISCO DE DOENÇA: NORMAL OU ELEVADO") if imc >= 18.6: print(imc) print("normal ou eutrofico") print("RISCO DE DOENÇA: POUCO ELEVADO") if imc >= 25: print(imc) print("sobre peso ou pre-obeso") print("normal") if imc >= 30: print(imc) print("obesidade I") print("RISCO DE DOENÇA: elevado") if imc >= 35: print(imc) print("OBESIDADE II") print("RISCO DE DOENÇA: MUITO ELEVADO") if imc >= 40: print(imc) print("OBESIDADE III") print("RISCO DE DOENÇA: muito elevado") <file_sep>/jokenpo.py import random player = input("<NAME>:") jogadas = ["pedra", "papel", "tesoura"] jogadacomputador = random.randrange(0,2) if player == jogadas[jogadacomputador]: print("empate") if player == "pedra" and jogadas[jogadacomputador] == "tesoura": print("player venceu") if player == "papel" and jogadas[jogadacomputador] == "pedra": print("player venceu") if player == "tesoura" and jogadas[jogadacomputador] == "papel": print("player venceu") if player == "tesoura" and jogadas[jogadacomputador] == "pedra": print("o PC venceu") if player == "pedra" and jogadas[jogadacomputador] == "papel": print("o PC venceu") if player == "papel" and jogadas[jogadacomputador] == "tesoura": print("o PC venceu") print(jogadas) <file_sep>/while.py num = int(input('DIGA O NUMERO ')) op = input("operacao[+|-|x|/]:\n") aux = num while aux <= 10: aux += 1 if op == "+": print(num,"+", aux,"=", num+aux) if op == "-": print(num,"-", aux,"=", num-aux) if op == "x": print(num,"x", aux,"=", num*aux) if op == "/": print(num,"/", aux,"=", num/aux) -
44e6a0922b429f98306eda59362b7f26a525d8ea
[ "Python" ]
9
Python
LUC4SNUN3S/python
794885f4dbf4da970a9adb04cbcf185795c088c0
81671736068fd334c2db648e1a2c62da4e1ca0de
refs/heads/master
<repo_name>sutd-research/sharp_robot_dock_task<file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 2.8.3) project(robot_dock_task) # we are using C++11 SET(CMAKE_CXX_FLAGS "-std=c++0x") # set if using ROS add_definitions(-DUSING_ROS) ## Find catkin macros and libraries find_package(catkin REQUIRED COMPONENTS roscpp roslib std_msgs message_generation actionlib actionlib_msgs robot_docker # dynamic reconfigure #dynamic_reconfigure #rospy ) ################################################ ## Declare ROS messages, services and actions ## ################################################ ## Generate messages in the 'msg' folder # add_message_files( # FILES # Message1.msg # Message2.msg # ) ## Generate services in the 'srv' folder # add_service_files( # FILES # Service1.srv # Service2.srv # ) ## Generate actions in the 'action' folder # add_action_files( # FILES # Action1.action # Action2.action # ) ## Generate added messages and services with any dependencies listed here # generate_messages( # DEPENDENCIES # std_msgs # ) ################################################ ## Declare ROS dynamic reconfigure parameters ## ################################################ ## Generate dynamic reconfigure parameters in the 'cfg' folder # generate_dynamic_reconfigure_options( # cfg/DynReconf1.cfg # cfg/DynReconf2.cfg # ) ################################### ## catkin specific configuration ## ################################### catkin_package( # INCLUDE_DIRS include # LIBRARIES task_handler_template CATKIN_DEPENDS roscpp roslib std_msgs actionlib_msgs robot_docker # DEPENDS system_lib ) ########### ## Build ## ########### ## Specify additional locations of header files include_directories( #include ${catkin_INCLUDE_DIRS} ) ## Declare a C++ executable add_executable(robot_dock_task_node src/main_node.cpp src/base.hpp src/task_handler.cpp ../../mrccc/common/mission/basedata.cpp ../../mrccc/common/mission/tasks_definition.cpp ../../mrccc/common/mission/task_definition_data.cpp ../../mrccc/common/utils/utils_tasks_definition.hpp ../../mrccc/common/logger.cpp ../../mrccc/common/logger4cxx.cpp ) ## Add cmake target dependencies of the executable add_dependencies(robot_dock_task_node ${${PROJECT_NAME}_EXPORTED_TARGETS} ${catkin_EXPORTED_TARGETS} robot_docker ) ## Specify libraries to link a library or executable target against target_link_libraries(robot_dock_task_node ${catkin_LIBRARIES} jsoncpp ) ############# ## Install ## ############# # all install targets should use catkin DESTINATION variables # See http://ros.org/doc/api/catkin/html/adv_user_guide/variables.html ## Mark executable scripts (Python etc.) for installation ## in contrast to setup.py, you can choose the destination # install(PROGRAMS # scripts/my_python_script # DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} # ) ## Mark executables and/or libraries for installation # install(TARGETS task_handler_template_node # ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} # LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} # RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} # ) ## Mark cpp header files for installation # install(DIRECTORY include/${PROJECT_NAME}/ # DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} # FILES_MATCHING PATTERN "*.h" # PATTERN ".svn" EXCLUDE # ) ## Mark other files for installation (e.g. launch and bag files, etc.) install(DIRECTORY launch/ DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/launch ) ## if you want finer control, the do file by file as follows # install(FILES # launch/start.launch # DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION}/launch # ) <file_sep>/src/main_node.cpp /** * Copyright 2017 by Institute for Infocomm Research, Singapore (I2R). All rights reserved. * @author <NAME> (<EMAIL>) */ #include <ros/ros.h> #include "task_handler.h" /// name of this ROS node const std::string kROSNodeName("task_handler_template"); /** * Main entry of application * @param argc Number of command line arguments * @param argv Command line arguments * @return always return 0 */ int main(int argc, char *argv[]) { // initialise ROS and start it ros::init(argc, argv, kROSNodeName); // create the handler handler::TaskHandler handler; handler.init(); ros::spin(); return 0; } <file_sep>/src/base.hpp /** * Copyright 2017 by Institute for Infocomm Research, Singapore (I2R). All rights reserved. * @author <NAME> (<EMAIL>) */ #ifndef BASE_HANDLER_HPP #define BASE_HANDLER_HPP #include <ros/ros.h> #include "mrccc_ros_messages/CommandPub2.h" #include "task_msgs/TaskStatus.h" #include "../../../mrccc/common/rosmsg_defs.hpp" #include "../../../mrccc/common/utils/utils_tasks_definition.hpp" namespace handler { /// our task ID is obtained from this ROS param #define K_STR_ROS_PARAM_TASK_ID "task_id" /** * This is the abstract virtual base class. To use this class, * 1. sub-class this class e.g. MyHandler() : BaseHandler() {}. * 2. call the init() method which will in turn call the reset of the InitXXX() methods. * The order of calling the methods are * PreInit() * InitROSParams() * InitROSPublishers() * InitROSSubscribers() * InitGeneric(); */ class BaseHandler { public: /** * Class constructor * */ BaseHandler(): m_task_id(-1), m_task_name("") { // initialise the private node handle m_nh_private = ros::NodeHandle("~"); m_nh_global = ros::NodeHandle(); } /// Class destructor virtual ~BaseHandler() {} /** * Returns the current task status * @return the current task status */ int getCurrentTaskStatus() const { return m_curr_task_status; } /** * Retrieves the global ROS param value * @param key Key to look for * @param value Value will be returned here * @return true if retrieved successfully, false otherwise */ template <typename T> bool getGlobalROSParamValue(const std::string &key, T &value) { bool isok = false; if (m_nh_global.hasParam(key)) { if (m_nh_global.getParam(key, value)) { isok = true; } else { ROS_ERROR_STREAM("Could not retrieve the global ROS parameter " << key); } } else { ROS_ERROR_STREAM("Global ROS parameter " << key << " is missing"); } return isok; } /** * Retrieves the ROS param value using the private node handle * @param key Key to look for * @param value Value will be returned here * @return true if retrieved successfully, false otherwise */ template <typename T> bool getPrivateROSParamValue(const std::string &key, T &value) { bool isok = false; if (m_nh_private.hasParam(key)) { if (m_nh_private.getParam(key, value)) { isok = true; } else { ROS_ERROR_STREAM("Could not retrieve the private ROS parameter " << key); } } else { ROS_ERROR_STREAM("Private ROS parameter " << key << " is missing"); } return isok; } /** * Returns the full ROS param key name task_name/ros_param. * @param ros_param ROS param key name * @return the full ROS param key name */ inline std::string GetROSParamFullKeyName(const std::string &ros_param) { return m_task_name + "/" + ros_param; } /** * Initialises the system * */ void init() { // pre-initialisation if any PreInit(); // read our ROS params InitROSParamTaskID(); InitROSParams(); // initialise our publishers InitROSPublisherTaskStatus(); InitROSPublishers(); // initialise our subscribers InitROSSubscriberCommandPub2(); InitROSSubscribers(); // other generic initialisation InitGeneric(); } /** * Publishes the task's status * @param status Status to publish */ void publishTaskStatus(const int &status) { m_curr_task_status = status; logg::ldebug() << ros::this_node::getName() << " - publishing task status " << m_curr_task_status; task_msgs::TaskStatus msg; msg.status = status; m_ros_pub_task_status.publish(msg); } protected: /// MUST be declared first, global Node Handle ros::NodeHandle m_nh_global; /// private node handle ros::NodeHandle m_nh_private; private: /// Generic initialisation method which is called last by init() virtual void InitGeneric() = 0; /// method called by init() to read all ROS params virtual void InitROSParams() = 0; /// method called by init() to initialise all the publishers virtual void InitROSPublishers() = 0; /// method called by init() to initialise all the subscribers virtual void InitROSSubscribers() = 0; /** * Always the first method called by init() for pre-initialisation. * Useful to perform checking for availability of service and actionserver */ virtual void PreInit() = 0; /** * Runs the task * @param jsonstr_data JSON data from CommandPub2 */ virtual void runTask(const std::string &jsonstr_data) = 0; /// stops the task virtual void stopTask() = 0; /// initialises the task ID void InitROSParamTaskID() { // retrieve the task ID int task_id; if (getPrivateROSParamValue(K_STR_ROS_PARAM_TASK_ID, task_id)) { if (task_id >= K_USER_TASK_ID_START) { m_task_id = task_id; // retrieve the navigation taskname as read from the task definition file InitTaskName(); } else { ROS_ERROR_STREAM("Task ID cannot be a system task ID for node " << ros::this_node::getName()); } } else { ROS_ERROR_STREAM("Failed to retrieve task ID for node " << ros::this_node::getName()); } } /// Initialises the ROS publisher for the task status void InitROSPublisherTaskStatus() { // only run if task id is valid if (m_task_id >= K_USER_TASK_ID_START) { ROS_DEBUG_STREAM("Executing ROS publishers initialization for " << ros::this_node::getName()); // task status std::string topicname; utils::TaskDefinitionData util_task_def; if (util_task_def.getTaskStatusTopicName(m_task_id, topicname)) { if (topicname.empty()) { ROS_ERROR_STREAM("TaskHandler::InitROSPublishers - topic name for task ID " << m_task_id << " is empty for node " << ros::this_node::getName()); } } else { ROS_ERROR_STREAM("TaskHandler::InitROSPublishers - topic name for task ID " << m_task_id << " cannot be found for node " << ros::this_node::getName()); } if (!topicname.empty()) { ROS_INFO_STREAM("The node " << ros::this_node::getName() << " is now publishing for task ID " << m_task_id); m_ros_pub_task_status = m_nh_global.advertise<task_msgs::TaskStatus>(topicname, 10); } } } /// initialises the subscriber for command pub2 void InitROSSubscriberCommandPub2() { // subscribe to command pub2 m_ros_sub_commandpub2 = m_nh_global.subscribe<mrccc_ros_messages::CommandPub2>(K_ROSTOPIC_NAME_MRCCC_ROS_MESSAGES_COMMAND_PUB2, 10, &BaseHandler::OnROSCommandPub2Callback, this); } /** * If we are using commandpub2, we need to know the task name so that we can * append the ROS params to it */ void InitTaskName() { utils::TaskDefinitionData util_task_def; if (!util_task_def.m_tasks_definition.getTaskDefinitionData().getTaskName(m_task_id, m_task_name)) { ROS_ERROR_STREAM(ros::this_node::getName() << " InitTaskName failed to read task name"); } else if (m_task_name.empty()) { ROS_ERROR_STREAM(ros::this_node::getName() << " InitTaskName task name is empty!"); } } /** * Callback when the Command Pub2 ROS message is received * @param msg Message received */ void OnROSCommandPub2Callback(const mrccc_ros_messages::CommandPub2::ConstPtr &msg) { if (msg->modes.size() == msg->targets.size()) { /// @todo ROSParam data in CommandPub2 if (msg->modes.size() == msg->data.size()) { for (unsigned int i = 0; i < msg->modes.size(); ++i) { if (msg->targets.at(i) == m_task_id) { if (msg->modes.at(i) == mrccc_ros_messages::CommandPub2::K_MODE_RUN) { /// @todo ROSParam data in CommandPub2 runTask(msg->data.at(i)); } else { stopTask(); } break; } else if (msg->targets.at(i) == mrccc_ros_messages::CommandPub2::K_TARGET_NODE_ALL && msg->modes.at(i) == mrccc_ros_messages::CommandPub2::K_MODE_IDLE) { // only support stop all nodes stopTask(); } } } else { ROS_ERROR_STREAM(ros::this_node::getName() << " CommandPub2 data and mode size not matching"); } } } /// the current task status int m_curr_task_status; /// ROS publisher for task status ros::Publisher m_ros_pub_task_status; /// ROS subscriber to the command pub2 message ros::Subscriber m_ros_sub_commandpub2; /// our task ID int m_task_id; /// name of our task as defined in the task definition file std::string m_task_name; }; } // handler #endif // BASE_HANDLER_HPP <file_sep>/src/task_handler.h /** * Copyright 2017 by Institute for Infocomm Research, Singapore (I2R). All rights reserved. * @author <NAME> (<EMAIL>) */ #include "base.hpp" #include <actionlib/client/simple_action_client.h> #include <actionlib/client/terminal_state.h> #include <robot_docker/DockAction.h> #include <jsoncpp/json/json.h> namespace handler { typedef actionlib::SimpleActionClient<robot_docker::DockAction> Client; /** * Sample template * */ class TaskHandler: public BaseHandler { public: TaskHandler(); ~TaskHandler() {} private: void InitGeneric() override; void InitROSParams() override; void InitROSPublishers() override; void InitROSSubscribers() override; void PreInit() override; void runTask(const std::string &jsonstr_data) override; void stopTask() override; /// true if task is running, false otherwise bool m_is_running; // Action server Client *ac; // Action complete callback void actionDoneCB(const actionlib::SimpleClientGoalState& state, const robot_docker::DockResultConstPtr& result); }; } // handler <file_sep>/README.md # visual_dock_task i2r task handler with action server - for visual docking Change the "task_id" in the launch file, according to the task <file_sep>/src/task_handler.cpp /** * Copyright 2017 by Institute for Infocomm Research, Singapore (I2R). All rights reserved. * @author <NAME> (<EMAIL>) */ #include "task_handler.h" namespace handler { /** * Class constructor * */ TaskHandler::TaskHandler() : BaseHandler(), m_is_running(false) { } /** * Perform generic initialisation * */ void TaskHandler::InitGeneric() { ROS_DEBUG_STREAM(ros::this_node::getName() << " - Executing generic initialization"); /// @todo add your generic initialization here } /** * Initialise all global and private ROS parameters * */ void TaskHandler::InitROSParams() { ROS_DEBUG_STREAM(ros::this_node::getName() << " - Executing ROS params initialization"); /// @todo retrieve your ROS params here } /** * Initialise all the publishers * */ void TaskHandler::InitROSPublishers() { ROS_DEBUG_STREAM(ros::this_node::getName() << " - Executing ROS publishers initialization"); // create the action client // true causes the client to spin its own thread ac = new actionlib::SimpleActionClient<robot_docker::DockAction>("/robot_docker/dock_server/", true); ROS_INFO("Waiting for action server to start."); // wait for the action server to start ac->waitForServer(); //will wait for infinite time ROS_INFO("Action server initialization complete"); } /** * Initialise all the subscribers * */ void TaskHandler::InitROSSubscribers() { ROS_DEBUG_STREAM(ros::this_node::getName() << " - Executing ROS subscribers initialization"); /// @todo add your subscribers here } /** * Perform initialisation before init() is called * */ void TaskHandler::PreInit() { ROS_DEBUG_STREAM(ros::this_node::getName() << " - Executing pre-initialization initialization"); /// @todo add your pre-initialization here } /** * Runs the idle task * @param jsonstr_data JSON data from CommandPub2 */ void TaskHandler::runTask(const std::string &jsonstr_data) { if (m_is_running) { ROS_WARN_STREAM(ros::this_node::getName() << " - The task is already running"); } else { Json::Reader reader; Json::Value params; if(!reader.parse(jsonstr_data, params)) { ROS_ERROR_STREAM("Error Parsing Task Parameters. Aborting task"); } else { ROS_INFO_STREAM(params["dock_command"]); } ROS_INFO_STREAM(ros::this_node::getName() << " - Running task"); // Note that when mission data contains ROS parameters for your task, and it is // passed in via the commandpub2 message jsonstr_data // publish running status publishTaskStatus(task_msgs::TaskStatus::K_TASK_STATUS_RUNNING); m_is_running = true; // send a goal to the action robot_docker::DockGoal goal; goal.dockingCommand = params["dock_command"].asInt(); ac->sendGoal(goal, boost::bind(&TaskHandler::actionDoneCB, this, _1, _2), Client::SimpleActiveCallback(), Client::SimpleFeedbackCallback()); } } /** * Stops the idle task * */ void TaskHandler::stopTask() { if (m_is_running) { ROS_INFO_STREAM(ros::this_node::getName() << " - Stopping task"); ac->cancelGoal(); publishTaskStatus(task_msgs::TaskStatus::K_TASK_STATUS_IDLE); m_is_running = false; } else { if (getCurrentTaskStatus() != task_msgs::TaskStatus::K_TASK_STATUS_IDLE) { publishTaskStatus(task_msgs::TaskStatus::K_TASK_STATUS_IDLE); } } } void TaskHandler::actionDoneCB(const actionlib::SimpleClientGoalState& state, const robot_docker::DockResultConstPtr& result) { ROS_INFO("Task finished in state [%s]", state.toString().c_str()); if(result->dockingStatus) { publishTaskStatus(task_msgs::TaskStatus::K_TASK_STATUS_DONE); // State = 2 } else { publishTaskStatus(task_msgs::TaskStatus::K_TASK_STATUS_EXCEPTION); // State = -1 } } } // handler
8f1478b8185339ccd42f9ed2414ef90715e93d40
[ "Markdown", "CMake", "C++" ]
6
CMake
sutd-research/sharp_robot_dock_task
b16400b70008bd8f8318d0130447a145c4b78eaf
e1202b65f7d499bcc003e4f99e46d2711fe10668
refs/heads/master
<repo_name>carlokg/WsSwift<file_sep>/000_Actividades_Entrega_T1/EjercicioOperadoresVariables.playground/Contents.swift import UIKit //Ejercicios operadores y variables //Ej1. Calcular el perí­metro y área de un rectángulo dada su base y su altura. var altura = 5 var base = 10 var area = base * altura var perimetro = (base*2) + (altura*2) print("area: ",area) print("perimetro: ", perimetro) //Ej2. Dados los catetos de un triángulo rectángulo, calcular su hipotenusa. var cateto1 = 3.0 var cateto2 = 4.0 var hipotenusa = sqrt(cateto1*cateto1 + cateto2 * cateto2) print("hipotenusa: ", hipotenusa) //Ej3. Dados dos números, mostrar la suma, resta, división y multiplicación de ambos. var num1 = 3 var num2 = 2 print("suma:", num1, num2) print("resta:", num1, num2) print("división:", num1 / num2) print("multiplicacion:", num1 * num2) //Ej4. Escribir un programa que convierta un valor dado en grados Fahrenheit a grados Celsius. //(5 °C × 9 / 5) + 32 var celsius = 5 var fahrenheit = (celsius * 9/5) + 32 print ("fahrenheit: ", fahrenheit) //Ej5. Calcular la media de tres números pedidos por teclado var num3 = 7 print("media", (num1 + num2 + num3) / 3) //Ej6. Un vendedor recibe un sueldo base mas un 10% extra por comision de sus ventas, // el vendedor desea saber cuanto dinero obtendrá por concepto de comisiones por // las tres ventas que realiza en el mes y el total que recibirá en el mes tomando // en cuenta su sueldo base y comisiones. var sueldoBase = 1000 var comision = ((sueldoBase/100) * 10) print("cada comisión:", comision) print("Total comisiones", comision * 3) //Ej7. Un alumno desea saber cual será su calificación final en la materia de IOS // Dicha calificación se compone de los siguientes porcentajes: // * 55% del promedio de sus tres calificaciones parciales. // * 30% de la calificación del examen final. // * 15% de la calificación de un trabajo final. var parcial = 5.0 var examen = 7.0 var trabajo = 6.0 print("media final:", (parcial * 0.55) + (examen * 0.3) + (trabajo * 0.15)) //Ej8. Escribir un algoritmo para calcular la nota final de un estudiante, considerando que: // por cada respuesta correcta 5 puntos, por una incorrecta -1 y por respuestas en // blanco 0. Imprime el resultado obtenido por el estudiante. var correctas = 10 var incorrectas = 5 print("resultado exámen: ", correctas * 5 - incorrectas) //Ej9. Calcula el sueldo de un trabajador, cuyo valor es su sueldo base más un numero de horas //extra trabajadas, pero teniendo en cuenta que el dicho numero de horas puede ser nulo var sueldo = 1000 var extra = 18 print("Sueldo de este mes:", sueldo + (extra * 20)) <file_sep>/000_Actividades_Entrega_T1/EjerciciosClases.playground/Contents.swift import UIKit struct ordenador{ var precio : Double var nombre : String lazy var ram = [Ram]() lazy var proc = Procesador() lazy var uA = [UnidadAlmacenamiento]() lazy var grafica = tarjetaGrafica() } class Ram{ var capacidad : Int! var fabricante : String! var rgb : Bool! } class Procesador{ var vel : Int! var nCores: Int! var nHilos : Int! var fabricante : String! } class UnidadAlmacenamiento{ var capacidad : Int! var fabricante : String! var tipoUnidad : String! } class tarjetaGrafica{ var ram : Int! var consumo : Int! var cores : Int! var velocidad : Int! } let ram1 = Ram() ram1.capacidad = 8 ram1.fabricante = "kigston" ram1.rgb = false let ram2 = Ram() ram2.capacidad = 16 ram2.fabricante = "hyperx" ram2.rgb = true let p1 = Procesador() p1.vel = 3400 p1.fabricante = "Intel" p1.nCores = 4 p1.nHilos = 8 let u1 = UnidadAlmacenamiento() u1.capacidad = 500 u1.fabricante = "Toshiba" u1.tipoUnidad = "SSD" let u2 = UnidadAlmacenamiento() u2.capacidad = 250 u2.fabricante = "WD" u2.tipoUnidad = "HD" let g1 = tarjetaGrafica() g1.velocidad = 100 g1.ram = 4 g1.cores = 2 var o1 = ordenador.init(precio: 1500, nombre: "Lenovo", ram: [ram1, ram2], proc: p1, uA: [u1, u2], grafica: g1) print(o1.grafica.ram) //print(o1) dump(o1) <file_sep>/000_Actividades_Entrega_T1/EjerciciosEstructuras.playground/Contents.swift import UIKit var str = "Hello, playground" //Alternativas //Ej1. Algoritmo que pida un número y diga si es positivo, negativo o 0. var num = 5; if num < 0{ print("El número es negativo") }else if (num > 0){ print("El número es positivo") }else{ print("El número es 0") } //Ej2. Escribe un programa que lea un número e indique si es par o impar. if (num%2)==0{ print("El número es par") }else{ print("El número es impar") } //Ej3. Escribe un programa que dado un nombre de usuario y una contraseña //y si se ha introducido "pepe" y "<PASSWORD>" se indica "Has entrado al sistema", var user = "pepe" var pass = "<PASSWORD>" if user == "pepe" && pass == "<PASSWORD>" { print("Has entrado en el sistema") }else{ print("Error de credenciales") } //Ej4. Programa que dada una cadena por teclado y compruebe si la primera letra es un "/" //y la segunda un "*", en caso afirmativo se escribira la palabra entera, en caso contrario //escribir "no es correcta". var cadena = "/*fff" //lo primer sacar el indice var indice = cadena.startIndex; //una vez sacado el indice lo podemos poner dentro del array var char1 = cadena[indice] indice = cadena.index(cadena.startIndex, offsetBy: 1) var char2 = cadena[indice] if(char1 == "/" && char2 == "*"){ print(cadena) }else{ print("error") } //Ej5. Algoritmo que dado tres números y los muestre ordenados (de mayor a menor); //var nums = [68,14,47] //var ordenados = Array(nums.sorted().reversed())//reverser para mayor a menor //print(ordenados) var num2 = 7 var num3 = 10 var num4 = 9 if num2 > num3 && num2 > num4 { print("El mayor es: ", num2) }else if num3 > num4 { print("El mayor es ", num3) }else{ print("El mayor es: ", num4) } var nums = [68,14,47] var ordenados = Array(nums.sorted().reversed())//reverser para mayor a menor print(ordenados) //Ej6. //Algoritmo que pida los puntos centrales x1,y1,x2,y2 y los radios r1,r2 de dos //circunferencias y las clasifique en uno de estos estados: //exteriores //tangentes exteriores //secantes //tangentes interiores //interiores //concéntricas //Repetitivas var x1 = 5.0 var y1 = 3.0 var x2 = 2.0 var y2 = 7.0 var r1 = 3.0 var r2 = 2.0 var sumaRadios = r1 + r2 var restaRadios = r2 - r1 //circunferencias y las clasifique en uno de estos estados: var distanciaCentros = sqrt(pow(x2 - x1,2) + pow(y2 - y1,2)) print(distanciaCentros) print("SumaRadios " , sumaRadios) print("Restaradios " ,restaRadios) if distanciaCentros > sumaRadios { //exteriores print("Exteriores") }else if distanciaCentros == sumaRadios{ //tangentes exteriores print("Tagentes Exteriores") }else if distanciaCentros < sumaRadios{ //secantes print("Secantes") }else if distanciaCentros == restaRadios{ //tangentes interiores print("Tangentes interiores") }else if distanciaCentros == 0 { //concéntricas print("Concentricas") }else{ //interiores print("Interiores") } //Ej7. //Crea una aplicación que pida un número y calcule su factorial (El factorial de //un número es el producto de todos los enteros entre 1 y el propio número y se //representa por el número seguido de un signo de exclamación. var n = 7 var factorial = 1 for i in 1...n { factorial = factorial * i } print("El factorial de \(n) es \(factorial)") //Ej8. //Algoritmo que cree un array con 10 numeros. Debe imprimir la suma // y la media de todos los números introducidos. var diezNumeros : [Int] = [] var suma = 0 var media : Double = 0 for _ in 1...10 { diezNumeros.append(Int(arc4random_uniform(200))) } print("Numeros generados ", diezNumeros) for miNum in diezNumeros{ suma+=miNum } media = Double(suma / diezNumeros.count) print("La suma de los numeros es \(suma) y su media es \(media)") //Ej9. //Algoritmo que cree un array con 10 numeros. El programa debe informar de cuantos números //introducidos son mayores que 0, menores que 0 e iguales a 0. var arraynumeros = [-1,2,3,4,0,0,-5,-9,9,0] var iguales = 0 var mayores = 0 var menores = 0 for index in arraynumeros { if index == 0{ iguales += 1 }else if index < 0{ menores += 1 }else{ mayores += 1 } } print(arraynumeros) print("Total de numeros menores a: ", menores) print("Total de numeros mayores a 0: ", mayores) print("Total de numeros iguales a 0: ", iguales) //Ej 10 //Escribir un programa que imprima todos los números pares entre dos números var numeroUno = 3 var numeroDos = 15 var numpar = 0 var listaNumerosPares = [Int]() for index in numeroUno...numeroDos { if index % 2 == 0 { numpar += 1 listaNumerosPares.append(index) } } print("Total de Numeros pares " , numpar) print("Lista de numeros pares: ", listaNumerosPares) //Ej 11 ////Una empresa tiene el registro de las horas que trabaja diariamente un empleado //durante la semana (seis días), así como el sueldo que recibirá por las horas trabajadas. //Las horas estan en un array y el precio hora esta en 30€ var horas = ["lunes" : 3, "Martes": 4, "Miercoles" : 2, "Jueves" : 5, "Viernes" : 8, "Sabado" : 6] let precioHora = 30 var salario = 0 //iterar por valor for horas in horas.values { salario += precioHora * horas } print("Salario Total ",salario) <file_sep>/08.Properties.playground/Contents.swift ///////////////// // Stored Properties //////////////// //una stored property es una constante o una variable que se almacena como parte de una instancia de una clase o una estructura //Esto seria equivalente a las propiedades NO estaticas de java, es decir, dinamicas struct FixedLengthRange { var firstValue: Int//propiedad variable let length: Int//propiedad constante } var rangeOfThreeItems = FixedLengthRange(firstValue: 0, length: 3) rangeOfThreeItems.firstValue = 6 print(rangeOfThreeItems.firstValue) //rangeOfThreeItems.length = 3 //Error, length está como let -> constante //crearmos una nueva estructura pero esta vez como constante //la variable de la estructura let rangeOfFourItems = FixedLengthRange(firstValue: 0, length: 4) //rangeOfFourItems.firstValue = 6 //Error, rangeOfFourItems está como let -> constante print(rangeOfFourItems.length) //Tampoco podría modificarla, ya que es constante print(rangeOfFourItems.firstValue) ///////////////// // Propiedades de Clase, cuando queremos que una propiedad NO pertenezca a la instancia. Equivaldría a las propiedades estaticas de java //////////////// class Persona { static var edadMaximaDeLasPersonas = 100 var nombre : String? var edad : Int = 0 //Tambien podemos hacer una propiedad computada como estatica. Ver más abajo "Computed Properties" static var computedTypeProperty: Int { return 27 } } var persona = Persona() //accedemos a las propiedades de objeto o stored properties //a traves del objeto persona.nombre = "Fulano" //accedemos a las propiedades de clase a traves de la clase persona.edad = Persona.edadMaximaDeLasPersonas dump(persona)//nos permite imprimir los valores de un objeto ///////////////// // Computed Properties //////////////// //Este tipo de propiedades no almacenan ningún valor, sino que proporcionan getter y setter a otras propiedades. Estan tanto en estructuras como en clases //Obligatorio -> Si ponemos un Set, necesitamos un Get, pero si ponemos un Get no tenemos porque poner un Set struct User { //estas dos variables tendrían el getter y setter por defecto //y son capaces de almacenar valores var name: String //esta propiedad guarda el nombre var surname: String //esta propiedad guarda el apellido //ahora vamos a declarar una computed property con nuestro propio getter y setter //En este caso será equivalente a hacer un getCompleteName y un setCompleteName en java var completeName: String { get {//user.completeName return name + " " + surname } set(username) {//user.completeName = "A<NAME>" let values = username.split(separator: " ") name = String(values[0]) surname = String(values[1]) } } //tambien el setter se puede declarar sin parametro, entonces el parametros de entrada será "newValue" //este metodo es equivalente al anterior var username: String { get { return name + " " + surname } set {//se crearia automaticamente el parametro "newValue" let values = newValue.split(separator: " ") name = String(values[0]) surname = String(values[1]) } } //podemos hacer solo get en una computed propertie var readOnlyProperty: String { //get { //la palabra get seria optional return "Esta es solo de lectura" //} } } var user = User(name: "fulano", surname: "de tal") print(user.completeName)//invocamos el get de la propiedad user.completeName = "Aitor Menta"//invocamos el set de la propiedad print(user.name) print(user.surname) print(user.completeName) user.username = "Harry Potter" print(user.username) print(user.name) print(user.readOnlyProperty)//solo podemos acceder, no modificar ///////////////// // Lazy Stored Properties //////////////// // Son Propiedades que su valor inicial no es calculado hasta que no se utiliza por primera vez. Por lo tanto SIEMPRE tienen que ir como variables (var) //Este tipo de propiedades son útiles cuando su valor inicial depende de factores externos cuyos valores no los conocemos hasta después de instanciar la clase, y no queremos crear memoria hasta entonces //En swift podemos utilizar la palabra reservada "lazy" en las propiedades para proporcionar este comportamiento class DataImporter { var filename = "data.txt" } class DataManager { lazy var importer = DataImporter() var data = [String]()//un array de String } let manager = DataManager() manager.data.append("Some data") manager.data.append("Some more data") // La instancia de DataImporter para la propiedad de importer todavía no se ha creado ya que todavía no se ha utilizado dump(manager) //Cuando accedemos a ella por primera vez se crea print(manager.importer.filename) dump(manager) ///////////////// // Property Observers //////////////// //Se utilizan para detectar cambios en las propiedades, son llamadas siempre que alguna cambia de valor. No son necesarias poner las dos //Las podemos usar en cualquier propiedad menos en las de tipo Lazy class StepCounter { //queremos que totalStep cada vez que cambie de valor //se ejecute un metodo var totalSteps: Int = 0 { willSet(newTotalSteps) {//este metodo será llamado justo antes de llamar a la propiedad, es decir, antes de que se cambie el valor de la propiedad totalStep. Si no damos parametro (newTotalStpes) en esta funcion se crea por defecto "newValue" print("About to set totalSteps to \(newTotalSteps)") } didSet (oldTotalSteps) {//Este metodo sera llamado justo despues de que el viejo valor se haya cambiado, si no damos parametro en esta funcion se crea por defecto "oldValue" if totalSteps > oldTotalSteps { print("Added \(totalSteps - oldTotalSteps) steps") } } } } let stepCounter = StepCounter() stepCounter.totalSteps = 200 stepCounter.totalSteps = 360 <file_sep>/Actividades/SolucionEjerciciosOperadores.playground/Contents.swift import UIKit //Ejercicio 1: Calcula el perímetro y el área de un rectángulo, dada su base y su altura var ancho = 20 var alto = 10 var area = (ancho * alto) var perim = (ancho * 2) + (alto * 2) print("Área ejercicio 1: \(area)") print("Perímetro ejercicio 1: \(perim)") //Ejercicio 2: dados los catetos de un triángulo rectángulo, calcular su hipotenusa var cateto1 = 20.0 var cateto2 = 30.0 var hipotenusa = sqrt((cateto1 * cateto1) + (cateto2 * cateto2)) print("la hipotenusa es: \(hipotenusa)") //Ejercicio 3: dados dos números, mostrar la suma, resta, división y multiplicación de ambos var num1 = 15 var num2 = 30 var sum = num1+num2 var resta = num1 - num2 var divis = (num2 / num1) var mult = (num1 * num2) print("\nSuma Ejercicio 3: \(sum)") print("Resta Ejercicio 3: \(resta)") print("División Ejercicio 3: \(divis)") print("Multiplicación Ejercicio 3: \(mult)") //Ejercicio 4: escribir un programa que convierta un valor dado en grados Farenheit a grados Celsius var farenheit = 54 var celsius = (farenheit - 32) * 5 / 9 print("\nGrados Celsius Ejercicio 4: \(celsius)") //Ejercicio 5: Calcular la media de 3 números dados por teclado var media1 = 20 var media2 = 43 var media3 = 12 var media = (media1 + media2 + media3) / 3 print("Media Ejercicio 5: \(media)") //Ejercicio 6: Un vendedor recibe un sueldo base mas un 10% extra por comision de sus ventas, el vendedor desea saber cuanto dinero obtendrá por concepto de comisiones por las tres ventas que realiza en el mes y el total que recibirá en el mes tomando en cuenta su sueldo base y comisiones. var venta1 = 1000.0 var venta2 = 2000.0 var venta3 = 500.0 var comision1 = venta1 * 1.1 print("Comisión venta: ") var comision2 = venta2 * 1.1 var comision3 = venta3 * 1.1 var sueldo = comision1 + comision2 + comision3 print("\nSueldo Total Ejercicio 6: \(sueldo)") //Ejercicio 7: un alumno desea saber cual será su calificación final en la materia de IOS. Dicha calificación se compone de los siguientes porcentajes: * 55% del promedio de sus tres calificaciones parciales. * 30% de la calificación del examen final. * 15% de la calificación de un trabajo final. var exParcial = 8.3 var exFinal = 6.4 var calTrabajo = 7.8 var mediaParcial = (exParcial * 0.55) var mediaFinal = (exFinal * 0.3) var mediaTrabajo = (calTrabajo * 0.15) var nota = mediaFinal + mediaParcial + mediaTrabajo print("\nNota Final Ejercicio 7: \(nota)") //Ejercicio 8: escribir un algoritmo para calcular la nota final de un estudiante, considerando que: por cada respuesta correcta 5 puntos, por una incorrecta -1 y por respuestas en blanco 0. Imprime el resultado obtenido por el estudiante. var respuCorrec = 5 var respuFall = 4 var respu0 = 1 var puntos = (respuCorrec * 5) + (respuFall * -1) + (respu0 * 0) print("\nPuntuación Final Ejercicio 8: \(puntos)") //Ejercicio 9: calcula el sueldo de un trabajador, cuyo valor es su sueldo base más un numero de horas extra trabajadas, pero teniendo en cuenta que el dicho numero de horas puede ser nulo var sueldoOrig = 2000 var horas : Int? = 5 let precioHora = 50 var totalExtra = precioHora * (horas ?? 0)//operador nil coalsing var sueldoFinal = sueldoOrig + totalExtra print ("\nSueldo Final Ejercicio 9 \(sueldoFinal)") <file_sep>/ExamenCarlosGarcia.playground/Contents.swift import UIKit //ej1 var num = 10 var dias : Int? = 0 switch num { case 1, 3, 5, 7, 8, 10, 12: dias = 31 case 4, 6, 9: dias = 30 case 2: dias = 28 default: dias = nil } if dias == nil{ print("No se puede mostrar los dias del mes correspondiente") }else{ print("El mes", num, "tiene", dias!, "dias") } //ej2 var diccionario : [Int: String] = [1: "valor1", 2: "Valor2", 3: "valor3"] print(diccionario) var claves = [Int] () var valores = [String]() for (key, value) in diccionario{ claves.append(key) valores.append(value) } print("Recorriendo las claves:") for i in claves{ print(i) } print("Recorriendo los valores:") for i in valores{ print(i) } //Ej3 func manejarArray (array : [String]) -> (num: Int, cad: String){ let num = array.count var cont = 0 var cont2 = 0 var cad = "" for i in array{ for _ in i{ cont += 1 } if cont > cont2{ cad = i cont2 = cont } cont = 0 } return (num, cad) } let res = manejarArray(array: ["Hola", "Pepe", "cadenaMuyLarga"]) print("La cadena mas larga es: ", res.cad) print("El array tiene:", res.num, "strings") <file_sep>/Actividades/SolucionEjerciciosEstructuras.playground/Contents.swift import UIKit //Ej1. Algoritmo que pida un número y diga si es positivo, negativo o 0.\ var num1 = 3 if num1 > 0 { print("Es Positivo") }else if num1 == 0{ print("Es cero") }else { print("Es negativo") } //Ej2. Escribe un programa que lea un n\'famero e indique si es par o impar.\ if num1 % 2 == 0 { print("Es par") }else{ print("Es impar") } //Ej3. Escribe un programa que dado un nombre de usuario y una contrase\'f1a \ //y si se ha introducido "pepe" y "asdasd" se indica "Has entrado al sistema", \ var user1 = "pepe" var pass1 = "<PASSWORD>" if user1 == "pepe" && pass1 == "<PASSWORD>" { print("Has entrado en el sistema") }else{ print("Error de credenciales") } //Ej4. Programa que dada una cadena por teclado y compruebe si la primera letra es un "/"\ //y la segunda un "*", en caso afirmativo se escribira la palabra entera, en caso contrario\ //escribir "no es correcta".\ var cadena = "/*fff" //lo primer sacar el indice var indice = cadena.startIndex; //una vez sacado el indice lo podemos poner dentro del array var char1 = cadena[indice] indice = cadena.index(cadena.startIndex, offsetBy: 1) var char2 = cadena[indice] if(char1 == "/" && char2 == "*"){ print(cadena) }else{ print("error") } //Ej5. Algoritmo que dado tres n\'fameros y los muestre ordenados (de mayor a menor);\ var num2 = 7 var num3 = 10 var num4 = 9 if num2 > num3 && num2 > num4 { print("El mayor es: ", num2) }else if num3 > num4 { print("El mayor es ", num3) }else{ print("El mayor es: ", num4) } var nums = [68,14,47] var ordenados = Array(nums.sorted().reversed())//reverser para mayor a menor print(ordenados) //Ej6. //Algoritmo que pida los puntos centrales x1,y1,x2,y2 y los radios r1,r2 de dos \ //circunferencias y las clasifique en uno de estos estados:\ //exteriores\ //tangentes exteriores\ //secantes\ //tangentes interiores\ //interiores\ //conc\'e9ntricas\ //Repetitivas\ var x1 = 5.0 var y1 = 3.0 var x2 = 2.0 var y2 = 7.0 var r1 = 3.0 var r2 = 2.0 var sumaRadios = r1 + r2 var restaRadios = r2 - r1 //circunferencias y las clasifique en uno de estos estados: var distanciaCentros = sqrt(pow(x2 - x1,2) + pow(y2 - y1,2)) print(distanciaCentros) print("SumaRadios " , sumaRadios) print("Restaradios " ,restaRadios) if distanciaCentros > sumaRadios { //exteriores print("Exteriores") }else if distanciaCentros == sumaRadios{ //tangentes exteriores print("Tagentes Exteriores") }else if distanciaCentros < sumaRadios{ //secantes print("Secantes") }else if distanciaCentros == restaRadios{ //tangentes interiores print("Tangentes interiores") }else if distanciaCentros == 0 { //concéntricas print("Concentricas") }else{ //interiores print("Interiores") } //Ej7. //Crea una aplicaci\'f3n que pida un n\'famero y calcule su factorial (El factorial de \ //un n\'famero es el producto de todos los enteros entre 1 y el propio n\'famero y se \ //representa por el n\'famero seguido de un signo de exclamaci\'f3n. \ var n = 7 var factorial = 1 for i in 1...n { factorial = factorial * i } print("El factorial de \(n) es \(factorial)") //Ej8. //Algoritmo que cree un array con 10 numeros. Debe imprimir la suma\ // y la media de todos los n\'fameros introducidos.\ var diezNumeros : [Int] = [] var suma = 0 var media : Double = 0 for _ in 1...10 { diezNumeros.append(Int(arc4random_uniform(200))) } print("Numeros generados ", diezNumeros) for miNum in diezNumeros{ suma+=miNum } media = Double(suma / diezNumeros.count) print("La suma de los numeros es \(suma) y su media es \(media)") //Ej9. //Algoritmo que cree un array con 10 numeros. El programa debe informar de cuantos n\'fameros \ //introducidos son mayores que 0, menores que 0 e iguales a 0.\ var arraynumeros = [-1,2,3,4,0,0,-5,-9,9,0] var iguales = 0 var mayores = 0 var menores = 0 for index in arraynumeros { if index == 0{ iguales += 1 }else if index < 0{ menores += 1 }else{ mayores += 1 } } print(arraynumeros) print("Total de numeros menores a: ", menores) print("Total de numeros mayores a 0: ", mayores) print("Total de numeros iguales a 0: ", iguales) //Ej 10 //Escribir un programa que imprima todos los n\'fameros pares entre dos n\'fameros\ var numeroUno = 3 var numeroDos = 15 var numpar = 0 var listaNumerosPares = [Int]() for index in numeroUno...numeroDos { if index % 2 == 0 { numpar += 1 listaNumerosPares.append(index) } } print("Total de Numeros pares " , numpar) print("Lista de numeros pares: ", listaNumerosPares) //Ej 11 ////Una empresa tiene el registro de las horas que trabaja diariamente un empleado \ //durante la semana (seis d\'edas), as\'ed como el sueldo que recibir\'e1 por las horas trabajadas.\ //Las horas estan en un array y el precio hora esta en 30\'80} var horas = ["lunes" : 3, "Martes": 4, "Miercoles" : 2, "Jueves" : 5, "Viernes" : 8, "Sabado" : 6] let precioHora = 30 var salario = 0 //iterar por valor for horas in horas.values { salario += precioHora * horas } print("Salario Total ",salario)
2d47aff2589f3d149eccf256c45f8e08f2b3b727
[ "Swift" ]
7
Swift
carlokg/WsSwift
18ef49cfcb17cd312be8a6707fe3dedafaacd012
1f26413027165448df51a95f784422f820243dea
refs/heads/master
<repo_name>igorpodosonov/Cat-Facts<file_sep>/CatFacts/Controllers/SignupController.swift // // SignupController.swift // CatFacts // // Created by Игорь on 04/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import CoreData import SCLAlertView class SignupController: UIViewController, UITextFieldDelegate { @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! @IBOutlet weak var confirmPasswordTextField: UITextField! let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext override func viewDidLoad() { super.viewDidLoad() emailTextField.setBottomBorder() passwordTextField.setBottomBorder() confirmPasswordTextField.setBottomBorder() emailTextField.delegate = self passwordTextField.delegate = self confirmPasswordTextField.delegate = self self.hideKeyboardWhenTappedAround() } @IBAction func backToLoginScreen(_ sender: Any) { self.dismiss(animated: true) } @IBAction func registerButtonPressed(_ sender: Any) { var errors = [String]() //Check if email is valid if !isValidEmail(testStr: emailTextField.text!) { errors.append("Please enter a valid email") } //Check if email is uniqe let request: NSFetchRequest<User> = User.fetchRequest() let predicate = NSPredicate(format: "mail MATCHES %@", emailTextField.text!) if !fetchRequest(request, predicate: predicate).isEmpty { errors.append("This email has already been taken") } //Check password if passwordTextField.text! != confirmPasswordTextField.text! { errors.append("Passwords do not match") } else if !isValidPassword(testStr: passwordTextField.text!) { if passwordTextField.text!.count < 6 { errors.append("Your password should be at least 6 symbols long") } errors.append("Password should have at least one letter and one number") } //Create new user or show error if errors.isEmpty { let newUser = User(context: context) newUser.mail = emailTextField.text! newUser.password = <PASSWORD>TextField.text! saveContext() //Set user as logged in UserDefaults.standard.set(true, forKey: "userlogin") //Go to main view performSegue(withIdentifier: "registerSegue", sender: self) } else { //Display error SCLAlertView().showError("Ooops...", subTitle: "\(errors[0])", closeButtonTitle: "Ok") } } //MARK: - TextField Delegate Functions func textFieldShouldReturn(_ textField: UITextField) -> Bool { if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField { nextField.becomeFirstResponder() } else { textField.resignFirstResponder() } return false } //MARK: - Validation functions func isValidEmail(testStr:String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: testStr) } func isValidPassword(testStr:String) -> Bool { let passwordRegEx = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{6,}$" let emailTest = NSPredicate(format:"SELF MATCHES %@", passwordRegEx) return emailTest.evaluate(with: testStr) } //MARK: - Core data functions func saveContext(){ do { try context.save() } catch { print("Error saving context \(error)") } } func fetchRequest(_ request: NSFetchRequest<User>, predicate: NSPredicate? = nil) -> [User] { if let currentPredicate = predicate { request.predicate = currentPredicate } var usersArray = [User]() do { usersArray = try context.fetch(request) } catch { print("Error fetching request \(error)") } return usersArray } } <file_sep>/CatFacts/Model/CellObject.swift // // CellObject.swift // CatFacts // // Created by Игорь on 06/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit class CellObject { let userName: String let catFact: String init(_ userName: String, _ catFact: String) { self.userName = userName self.catFact = catFact } } <file_sep>/CatFacts/Controllers/CatFactsController.swift // // CatFactsController.swift // CatFacts // // Created by Игорь on 06/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import SVProgressHUD import SwiftyJSON import SCLAlertView import Alamofire class CatFactsController: UITableViewController { let CATS_URL = "https://cat-fact.herokuapp.com/facts" var dataArray = [CellObject]() override func viewDidLoad() { super.viewDidLoad() self.tableView.register(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "customFactCell") self.tableView.rowHeight = UITableView.automaticDimension; self.tableView.estimatedRowHeight = 120.0; getFactsData(url: CATS_URL) } @IBAction func logoutButtonPressed(_ sender: Any) { UserDefaults.standard.set(false, forKey: "userlogin") performSegue(withIdentifier: "logOutSegue", sender: nil) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "customFactCell", for: indexPath) as! CustomCell cell.userNameLabel.text! = dataArray[indexPath.row].userName cell.catFactLabel.text! = dataArray[indexPath.row].catFact return cell } //MARK: - Table view delegate methods override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } //MARK: - Get data from API func getFactsData(url: String) { SVProgressHUD.show() Alamofire.request(url, method: .get).validate().responseJSON { response in switch response.result { case .success(let value): let json = JSON(value) if let facts = json["all"].array { for fact in facts { //fact["text"] //fact["user"]["name"]["first"] //fact["user"]["name"]["last"] let text = fact["text"].string! let userName = "\(fact["user"]["name"]["first"]) \(fact["user"]["name"]["last"])" self.dataArray.append(CellObject(userName, text)) } self.tableView.reloadData() } case .failure(let error): print(error) SCLAlertView().showError("Ooops...", subTitle: "Some problems with connection, please try again later", closeButtonTitle: "Ok") } SVProgressHUD.dismiss() } } } <file_sep>/CatFacts/Controllers/LoginController.swift // // LoginController.swift // CatFacts // // Created by Игорь on 04/01/2019. // Copyright © 2019 <NAME>. All rights reserved. // import UIKit import SCLAlertView import CoreData class LoginController: UIViewController, UITextFieldDelegate { @IBOutlet weak var mailTextField: UITextField! @IBOutlet weak var passwordTextField: UITextField! let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext override func viewDidLoad() { super.viewDidLoad() mailTextField.setBottomBorder() passwordTextField.setBottomBorder() mailTextField.delegate = self passwordTextField.delegate = self self.hideKeyboardWhenTappedAround() } override func viewDidAppear(_ animated: Bool) { let isLoggedIn : Bool = UserDefaults.standard.bool(forKey: "userlogin") if isLoggedIn { performSegue(withIdentifier: "loginSegue", sender: self) } } @IBAction func loginButtonPressed(_ sender: Any) { var errors = [String]() let request: NSFetchRequest<User> = User.fetchRequest() let predicate = NSPredicate(format: "mail MATCHES %@", mailTextField.text!) let user = fetchRequest(request, predicate: predicate) //Check email if !isValidEmail(testStr: mailTextField.text!) { errors.append("Please enter a valid email") } //Check password if !isValidPassword(testStr: passwordTextField.text!) { if passwordTextField.text!.count < 6 { errors.append("Password should be at least 6 symbols long") } errors.append("Password should have at least one letter and one number") } if errors.isEmpty { if !user.isEmpty { if passwordTextField.text! == user[0].password { //Auth true UserDefaults.standard.set(true, forKey: "userlogin") performSegue(withIdentifier: "loginSegue", sender: self) } else { SCLAlertView().showError("Ooops...", subTitle: "Wrong password, please try again", closeButtonTitle: "Ok") } } else { SCLAlertView().showError("Ooops...", subTitle: "Looks like there is no user with this email", closeButtonTitle: "Ok") } } else { //Display an error SCLAlertView().showError("Ooops...", subTitle: "\(errors[0])", closeButtonTitle: "Ok") } } //MARK: - TextField Delegate Functions func textFieldShouldReturn(_ textField: UITextField) -> Bool { if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField { nextField.becomeFirstResponder() } else { textField.resignFirstResponder() } return false } //MARK: - Validation functions func isValidEmail(testStr:String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailTest.evaluate(with: testStr) } func isValidPassword(testStr:String) -> Bool { let passwordRegEx = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{6,}$" let emailTest = NSPredicate(format:"SELF MATCHES %@", passwordRegEx) return emailTest.evaluate(with: testStr) } //MARK: - Core data functions func saveContext(){ do { try context.save() } catch { print("Error saving context \(error)") } } func fetchRequest(_ request: NSFetchRequest<User>, predicate: NSPredicate? = nil) -> [User] { if let currentPredicate = predicate { request.predicate = currentPredicate } var usersArray = [User]() do { usersArray = try context.fetch(request) } catch { print("Error fetching request \(error)") } return usersArray } } extension UITextField { func setBottomBorder() { self.borderStyle = .none self.layer.backgroundColor = UIColor.white.cgColor self.layer.masksToBounds = false //self.layer.shadowColor = UIColor.gray.cgColor self.layer.shadowColor = UIColor.lightGray.cgColor self.layer.shadowOffset = CGSize(width: 0.0, height: 1.0) self.layer.shadowOpacity = 1.0 self.layer.shadowRadius = 0.0 } } extension UIViewController { func hideKeyboardWhenTappedAround() { let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } @objc func dismissKeyboard() { view.endEditing(true) } } <file_sep>/README.md # Cat Facts - Persisting users data with CoreData - Networking with Alamofire - Working with API using SwiftyJSON ## Demo gif ![N|Solid](http://g.recordit.co/wpIkvEftqG.gif)
93b825df98f0b5c7c6cc798cbc94e6f642987d6c
[ "Swift", "Markdown" ]
5
Swift
igorpodosonov/Cat-Facts
3cf4009aa73fb931c49913edf61f0802ae8ed4ba
9a67deb7297a2996128d8622514d7c956f716ccf
refs/heads/master
<repo_name>johnebarita/ptbcsi<file_sep>/application/controllers/Leave.php <?php /** * Created by PhpStorm. * User: User * Date: 05/02/2020 * Time: 6:52 PM */ class Leave extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library(array('pagination', 'session')); $this->load->model(array("leave_model", "employee_model")); $this->load->helper('url'); if (!$_SESSION['is_logged_in'] ) { redirect(base_url('')); } } public function view() { $leaves = $this->leave_model->get_one($_SESSION['user_id']); $data['leaves'] = $leaves; $data['page_load'] = 'admin/leave'; $data['my_leave'] = true; $data['active'] = "leave"; $this->load->view('includes/template', $data); } public function add() { if (!empty($_POST)) { $leave = new stdClass(); $leave->employee_id = $_POST['user_id']; $leave->date_request = date('Y-m-d'); $leave->type = $_POST['leave_type']; $leave->request_start_time = $_POST['date_from']; $leave->request_duration = $_POST['date_to']; $leave->status = 'Pending'; $this->leave_model->add($leave); } if ($_SESSION['user_type'] != "Employee") { if ($_SESSION['user_id'] == $_POST['user_id']) { redirect(base_url('leave')); } else { redirect(base_url('employee-leave')); } } else { redirect(base_url('leave')); } } public function delete() { if ($_SESSION['user_type'] == "Employee") { redirect(base_url('404')); } if (!empty($_POST)) { $this->leave_model->delete($_POST['leave_id']); } redirect(base_url('leave')); } public function update() { if ($_SESSION['user_type'] == "Employee") { redirect(base_url('404')); } if (!empty($_POST)) { $leave = new stdClass(); $leave->type = $_POST['leave_type']; $leave->request_start_time = $_POST['date_from']; $leave->request_duration = $_POST['date_to']; $this->leave_model->update_request($leave, $_POST['leave_id']); } redirect(base_url('leave')); } public function update_status() { if ($_SESSION['user_type'] == "Employee") { redirect(base_url('404')); } if (!empty($_POST)) { $this->leave_model->update_status($_POST['leave_id'], $_POST['status']); } redirect(base_url('employee-leave')); } public function employee_view() { if ($_SESSION['user_type'] == "Employee") { redirect(base_url('404')); } $leaves = $this->leave_model->get_all(); $users = $this->employee_model->get_employees(); $data['users'] = $users; $data['leaves'] = $leaves; $data['my_leave'] = false; $data['active'] = "leave"; $data['page_load'] = 'admin/employees_leave'; $this->load->view('includes/template', $data); } }<file_sep>/application/controllers/Calendar.php <?php /** * Created by PhpStorm. * User: Administrator * Date: 2/6/2020 * Time: 6:10 PM */ class Calendar extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('pagination', 'session'); $this->load->model(array("event_model","holiday_model")); if (!$_SESSION['is_logged_in']) { redirect(base_url('')); } } public function view() { $data['result'] = $this->db->get("event")->result(); foreach ($data['result'] as $key => $value) { $data['data'][$key]['title'] = $value->content; $data['data'][$key]['start'] = $value->date; $data['data'][$key]['end'] = $value->status; $data['data'][$key]['backgroundColor'] = "#00a65a"; } $data['active'] = 'calendar'; $data['page_load'] = 'admin/calendar'; $this->load->view('includes/template', $data); } public function AddEvent(){ $datas = array( 'date' => $this->input->post('date'), 'content' => $this->input->post('event'), ); $this->db->insert('Event', $datas); $data['result'] = $this->db->get("event")->result(); foreach ($data['result'] as $key => $value) { $data['data'][$key]['title'] = $value->content; $data['data'][$key]['start'] = $value->date; $data['data'][$key]['end'] = $value->status; $data['data'][$key]['backgroundColor'] = "#00a65a"; } redirect(base_url('calendar')); } }<file_sep>/application/views/includes/sidebar.php <?php /** * Created by PhpStorm. * User: <NAME> * Date: 1/15/2020 * Time: 2:25 PM */ ?> <?php $landing = base_url(); $user_type = $_SESSION['user_type']; if ($user_type == "Admin"): $landing .= "dashboard"; elseif ($user_type == "Payroll Master"): $landing .= "dtr"; elseif ($user_type == "Employee"): $landing .= "dtr"; endif; ?> <ul class="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar"> <a class="sidebar-brand d-flex align-items-center justify-content-center" href="<?= $landing; ?>"> <div class="sidebar-brand-icon rotate-n-15"> <i class="fas fa-laugh-wink"></i> </div> <div class="sidebar-brand-text mx-3">PTBCSI <?= $user_type; ?></div> </a> <?php if ($user_type == "Admin"): ?> <hr class="sidebar-divider my-0"> <div class="sidebar-heading"> <br> REPORTS </div> <hr class="sidebar-divider my-1"> <li class="nav-item <?=($active =='dashboard'? 'active':'');?>"> <a class="nav-link" href="dashboard"> <i class="fas fa-fw fa-tachometer-alt"></i> <span>Dashboard</span></a> </li> <?php endif; ?> <hr class="sidebar-divider"> <div class="sidebar-heading"> MANAGE </div> <!-- DTR--> <li class="nav-item <?=($active =='dtr'? 'active':'');?>"> <a class="nav-link " href="dtr"> <i class="fas fa-fw fa-user-clock"></i> <span>DTR</span></a> </li> <!-- REQUESTS--> <?php if ($user_type != "Employee"): ?> <li class="nav-item <?=($active =='overtime'||$active =='leave'? 'active':'');?> "> <a class="nav-link collapsed " href="#" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseTwo"> <i class="fas fa-fw fa-retweet"></i> <span>Requests</span> </a> <div id="collapseOne" class="collapse <?=($active =='overtime'||$active =='leave'? 'show':'');?>" aria-labelledby="headingTwo" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <h6 class="collapse-header">Request Management :</h6> <a class="collapse-item <?=($active =='overtime'? 'active':'');?> " href="overtime">Overtime</a> <a class="collapse-item <?=($active =='leave'? 'active':'');?>" href="leave">Leave</a> </div> </div> </li> <?php else: ?> <li class="nav-item <?=($active =='leave'? 'active':'');?>"> <a class="nav-link" href="leave"> <i class="fas fa-fw fa-user-clock"></i> <span>Leaves</span></a> </li> <?php endif; ?> <!-- SCHEDULE--> <?php if ($user_type == "Admin"): ?> <li class="nav-item <?=($active =='schedule'? 'active':'');?>"> <a class="nav-link" href="schedule"> <i class="fas fa-fw fa-clock"></i> <span>Schedule</span></a> </li> <?php endif; ?> <!-- CALENDAR--> <li class="nav-item <?=($active =='calendar'? 'active':'');?>"> <a class="nav-link" href="calendar"> <i class="fas fa-fw fa-calendar-alt"></i> <span>Calendar</span></a> </li> <!-- EMPLOYEES--> <?php if ($user_type == "Admin"): ?> <li class="nav-item <?=($active =='employee'? 'active':'');?>"> <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="true" aria-controls="collapseTwo"> <i class="fas fa-fw fa-cog"></i> <span>Employees</span> </a> <div id="collapseTwo" class="collapse <?=($active =='position'||$active =='employee'? 'show':'');?> " aria-labelledby="headingTwo" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <h6 class="collapse-header">Employee Management :</h6> <a class="collapse-item <?=($active =='employee'? 'active':'');?>" href="employee">Employee List</a> <a class="collapse-item <?=($active =='position'? 'active':'');?>" href="position">Position</a> </div> </div> </li> <?php endif; ?> <!-- PAYROLL--> <li class="nav-item <?=($active =='payroll'? 'active':'');?>"> <a class="nav-link" href="payroll"> <i class="fas fa-fw fa-money-bill"></i> <span>Payroll</span></a> </li> <!-- CASH ADVANCE--> <?php if ($user_type != "Employee"): ?> <li class="nav-item <?=($active =='cash advance'? 'active':'');?>"> <a class="nav-link" href="cash-advance"> <i class="fas fa-fw fa-cash-register"></i> <span>Cash Advance</span></a> </li> <?php endif; ?> <!-- DEDUCTIONS--> <?php if ($user_type != "Employee"): ?> <li class="nav-item <?=($active =='deduction'? 'active':'');?>"> <a class="nav-link" href="#"> <i class="fas fa-fw fa-receipt"></i> <span>Deductions</span></a> </li> <?php endif; ?> <!-- REPORTS--> <?php if ($user_type != "Employee"): ?> <li class="nav-item <?=($active =='attendance report'||$active =='payroll report'? 'active':'');?>"> <a class="nav-link collapsed" href="#" data-toggle="collapse" data-target="#collapseThree" aria-expanded="true" aria-controls="collapseTwo"> <i class="fas fa-fw fa-retweet"></i> <span>Reports</span> </a> <div id="collapseThree" class="collapse <?=($active =='attendance report'||$active =='payroll report'? 'show':'');?> " aria-labelledby="headingTwo" data-parent="#accordionSidebar"> <div class="bg-white py-2 collapse-inner rounded"> <h6 class="collapse-header">Employee Summary Report :</h6> <a class="collapse-item <?=($active =='attendance report'? 'active':'');?>" href="attendance_report">Attendance Report</a> <a class="collapse-item <?=($active =='payroll report'? 'active':'');?>" href="payroll_report">Payroll Report</a> </div> </div> </li> <?php endif; ?> <hr class="sidebar-divider d-none d-md-block"> <div class="text-center d-none d-md-inline"> <button class="rounded-circle border-0" id="sidebarToggle"></button> </div> </ul><file_sep>/application/views/includes/modals/add/add_schedule_modal.php <?php /** * Created by PhpStorm. * User: capstonestudent * Date: 2/19/2020 * Time: 2:42 AM */ ?> <div class="modal fade" id="addSched" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Add Schedule</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="add-schedule" method="post"> <div class="form-group row"> <label for="in" class="col-sm-3 col-form-label">Time in</label> <div class="col-sm-5"> <input type="time" class="form-control" id="in" name="time-in" value=<?php echo date('H:i a ', mktime(8, 00)); ?> required> </div> </div> <div class="form-group row"> <label for="out" class="col-sm-3 col-form-label">Time out</label> <div class="col-sm-5"> <input type="time" class="form-control" id="out" name="time-out" value=<?php echo date('G:i a ', mktime(17, 00)); ?> required> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <input type="submit" class="btn btn-primary" name="addSchedule" value="Add Schedule"> </div> </form> </div> </div> </div> </div><file_sep>/application/models/Schedule_model.php <?php /** * Created by PhpStorm. * User: User * Date: 05/02/2020 * Time: 9:48 PM */ class Schedule_model extends CI_Model { public function __construct() { parent::__construct(); } public function add($timein, $timeout) { $query = "insert into tbl_schedule values ('', '$timein', '$timeout','')"; $this->db->query($query); } public function get_all() { $query = $this->db->query("select * from tbl_schedule"); return $query->result(); } public function update($id, $sched) { $this->db->where('schedule_id', $id); $this->db->update('tbl_schedule', $sched); } public function delete($id) { $this->db->where('schedule_id', $id); $this->db->delete('tbl_schedule'); } public function get_references($schedule_id){ $result = $this->db->select('*') ->from('tbl_schedule as schedule') ->join('tbl_position as position','schedule.schedule_id = position.schedule_id') ->where('schedule.schedule_id ',$schedule_id) ->get() ->result(); return $result; } }<file_sep>/application/views/includes/modals/add_overtime_modal.php <div class="modal fade" id="add-overtime" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title kulay" id="exampleModalLabel">Request Overtime</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body mod"> <div class="card"> <div class="card-body px-lg-5 pt-0 border"> <br> <form method="post" action="add-overtime"> <?php if($_SESSION['user_type']!="Employee"):?> <select name="user_id" id="month" class="input input-sm monthName" style="width: 100%;padding: 5px"> <?php foreach ($users as $user):?> <?php if($user->employee_id!=$_SESSION['user_id']):?> <option value="<?=$user->employee_id;?>" ><?= strtoupper($user->lastname." ".$user->firstname);?></option> <?php endif; endforeach;?> </select>&nbsp; <?php else:?> <input type="text" name="user_id" value="<?= $_SESSION['user_id']; ?>" hidden/> <?php endif;?> <div class="form-group"> <label for="formGroupExampleInput">Reason</label> <input type="text" class="form-control" id="formGroupExampleInput" name="reason" placeholder="Please state your reason" required/> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> </div> </div> </div> </div> </div> </div><file_sep>/application/models/Dashboard_model.php <?php /** * Created by PhpStorm. * User: User * Date: 11/02/2020 * Time: 6:20 PM */ class Dashboard_model extends CI_Model { public function __construct() { parent::__construct(); } // public function get_late() // { // $this->db-> // } }<file_sep>/application/models/Employee_model.php <?php /** * Created by PhpStorm. * User: User * Date: 24/01/2020 * Time: 5:48 PM */ class Employee_model extends CI_Model { public function __construct() { parent::__construct(); } public function get_users() { $type = array('7', '2', '16', '4'); $result = $this->db->select('*') ->from('tbl_user') ->where_in('account_type', $type) ->where('stillworking', 1) ->where('isarchived', 0) ->where('last_name IS NOT NULL') ->order_by('last_name', 'asc') ->get() ->result(); return $result; } public function get_employees() { // ->from('tbl_employee') // ->order_by('lastname', 'asc') // ->get() // ->result(); // return $result; $result = $this->db->select('*') $result = $this->db->select('*') ->from('tbl_employee as employee') ->join('tbl_position as position', 'employee.position_id = position.position_id') ->join('tbl_schedule as schedule', 'position.schedule_id = schedule.schedule_id') ->join('tbl_address as address', 'employee.address_id = address.address_id') ->order_by('lastname', 'asc') ->get() ->result(); return $result; } public function get_one($employee_id) { $result = $this->db->select('*') ->from('tbl_employee as employee') ->join('tbl_position as position', 'employee.position_id = position.position_id') ->join('tbl_schedule as schedule', 'position.schedule_id = schedule.schedule_id') ->where('employee.employee_id', $employee_id) ->get() ->result(); return $result; } public function add_employee($employee, $address) { $this->db->insert('tbl_address', $address); //kuhaon nmo ang id sa kanang imong bag-ong g add $a_id = $this->db->select('address_id') ->from('tbl_address') ->order_by('address_id', 'desc') ->get() ->result(); $employee->address_id = $a_id[0]; $this->db->insert('tbl_employee', $employee); } public function update_employee($employee_id, $employee,$address) { $ad = $this->db->select('*') ->from('tbl_address') ->where('address_id',$employee->address_id) ->get() ->result(); $ad = $ad[0]; $ad->city =$address; $this->db->where('address_id', $ad->address_id) ->update('tbl_address', $ad); $this->db->where('employee_id', $employee_id) ->update('tbl_employee', $employee); } public function get_last_id() { $result = $this->db->select('employee_id') ->from('tbl_employee') ->order_by('employee_id', 'desc') ->get() ->result(); if (sizeof($result) > 0) { return $result[0]; } } public function delete($employee_id) { $this->db->where('employee_id', $employee_id); $this->db->delete('tbl_employee'); } }<file_sep>/application/models/Dbmodel.php <?php /** * Created by PhpStorm. * User: User * Date: 28/01/2020 * Time: 9:24 AM */ class Dbmodel extends CI_Model { public function __construct() { parent::__construct(); } //get specific user public function getUser($user, $pass) { $account = $this->db->select('*') ->from('tbl_employee') ->where('username', $user) ->get() ->result(); if (!empty($account)) { $verified = password_verify($pass, $account[0]->password); if ($verified) { $role = $this->db->select('*,user_role') ->from('tbl_employee as employee') ->join('tbl_user_role as role', 'employee.user_role_id=role.user_role_id') ->where('username', $user) ->get() ->result(); return $role; } return false; } return false; } //all users who are still working public function getUsers() { $type = array('7', '2', '16', '4'); $result = $this->db->select('*') ->from('tbl_user') ->where_in('account_type', $type) ->where('stillworking', 1) ->where('isarchived', 0) ->where('last_name IS NOT NULL') ->order_by('last_name', 'asc') ->get() ->result(); return $result; } //get DTR for each employee public function getUserDTR($user_id, $start_day, $end_day) { $res = $this->db->select('*') ->from('tbl_loginsheet') ->where('staff_id', $user_id) ->where('date between "' . $start_day . '" and "' . $end_day . '"') ->order_by('date', 'asc') ->get() ->result(); return $res; } public function getAllAttendance($start_day, $end_day) { $result = $this->db->select('*') ->from('tbl_employee as employee') ->join('tbl_loginsheet as loginsheet', 'employee.employee_id = loginsheet.staff_id') ->where('date between "' . $start_day . '" and "' . $end_day . '"') ->get() ->result(); return $result; } public function getHolidays($start_day, $end_day) { $result = $this->db->select('*') ->from('tbl_holiday') ->where('date between "' . $start_day . '" and "' . $end_day . '"') ->get() ->result(); return $result; } public function getEmployees() { $result = $this->db->select('*') ->from('tbl_employee') ->order_by('lastname', 'asc') ->get() ->result(); return $result; } public function getLeave($user_id) { $result = $this->db->select('*') ->from('tbl_leave_request') ->where('employee_id', $user_id) ->order_by('date_request', 'desc') ->get() ->result(); return $result; } public function getLeaves() { $result = $this->db->select('*,firstname,lastname') ->from('tbl_leave_request as leave') ->join('tbl_employee as employee', 'leave.employee_id=employee.employee_id') ->order_by('date_request', 'desc') ->get() ->result(); return $result; } public function addLeave($leave_request) { $this->db->insert('tbl_leave_request', $leave_request); } public function updateLeaveStatus($leave_id, $status) { $this->db->set('status', $status); $this->db->where('leave_request_id', $leave_id); $this->db->update('tbl_leave_request'); } public function getOvertimes() { $result = $this->db->select('*,firstname,lastname') ->from('tbl_overtime_request as overtime') ->join('tbl_employee as employee', 'overtime.employee_id=employee.employee_id') ->order_by('date_request', 'desc') ->get() ->result(); return $result; } public function addOvertime($overtime) { $this->db->insert('tbl_overtime_request', $overtime); } public function canRequestOvertime($user_id) { $result = $this->db->select('*') ->from('tbl_overtime_request') ->where('employee_id', $user_id) ->where('date_request', date('Y-m-d')) ->get() ->result(); if (count($result) > 0) { return false; } else { return true; } } public function updateOvertimeStatus($overtime_id, $status) { $this->db->set('status', $status); $this->db->where('overtime_request_id', $overtime_id); $this->db->update('tbl_overtime_request'); } public function updateLeaveRequest($leave, $leave_id) { $this->db->where('leave_request_id', $leave_id); $this->db->update('tbl_leave_request', $leave); } public function deleteLeave($leave_id) { $this->db->where('leave_request_id', $leave_id); $this->db->delete('tbl_leave_request'); } public function schedule_insert($timein, $timeout) { $query = "insert into tbl_schedule values ('', '$timein', '$timeout','')"; $this->db->query($query); } public function get_schedule() { $query = $this->db->query("select * from tbl_schedule"); return $query->result(); } public function update_schedule($id, $sched) { $this->db->where('schedule_id', $id); $this->db->update('tbl_schedule', $sched); } public function delete_schedule($id) { $this->db->where('schedule_id', $id); $this->db->delete('tbl_schedule'); } public function addCashAdvance($cash) { $this->db->insert('tbl_cash_advance', $cash); } public function getCashAdvances() { $result = $this->db->select('*,firstname,lastname') ->from('tbl_cash_advance as cash') ->join('tbl_employee as employee', 'cash.employee_id=employee.employee_id') ->order_by('date_advance', 'desc') ->get() ->result(); return $result; } public function updateCashAdvance($cash,$id) { $this->db->where('cash_advance_id', $id); $this->db->update('tbl_cash_advance', $cash); } public function addEmployee($firstname, $lastname, $middlename, $birth_date, $marital_status, $email, $username, $password, $phone_number, $home_no, $contact_person, $employee_status, $monthly_pay, $isFixed_salary, $basic_pay, $tin_no, $sss_no, $philhealth_no, $pagibig_no, $bank_name, $user_role_id, $employee_login_id, $address_id, $position_id, $isActive, $office_location, $transportation_allowance, $internet_allowance, $meal_allowance, $phone_allowance, $total_allowance, $date_modified) { $query="insert into tbl_employee values('','$firstname','$lastname','$middlename', '$birth_date', '$marital_status', '$email', '$username', '$password', '$phone_number', '$home_no', '$contact_person', '$employee_status', '$monthly_pay', '$isFixed_salary', '$basic_pay', '$tin_no', '$sss_no', '$philhealth_no', '$pagibig_no', '$bank_name', '$user_role_id', '$employee_login_id', '$address_id', '$position_id', '$isActive', '$office_location', '$transportation_allowance', '$internet_allowance', '$meal_allowance', '$phone_allowance', '$total_allowance', '$date_modified')"; $this->db->query($query); return $query; } public function editEmployee($employee_id) { $info = $this->getUsers(); $this->db->where('employee_id', $employee_id); $this->db->update('tbl_employee', $info); } public function getEmployeeList() { $result = $this->db->select('*') ->from('tbl_employee') ->get() ->result(); return $result; } public function delete_cash_advance($cash_advance_id) { $this->db->where('cash_advance_id', $cash_advance_id); $this->db->delete('tbl_cash_advance'); } }<file_sep>/application/controllers/Employee.php <?php /** * Created by PhpStorm. * User: D20 * Date: 2/6/2020 * Time: 6:28 PM */ class Employee extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('pagination', 'session'); $this->load->model(array("cash_model", "employee_model", "position_model")); if (!$_SESSION['is_logged_in']) { redirect(base_url('')); } include(getcwd() . '/application/libraries/zklib/ZKLib.php'); } public function view() { if ($_SESSION['user_type'] == "Employee") { redirect(base_url('404')); } $employees = $this->employee_model->get_employees(); $positions = $this->position_model->get_all(); $data['employees'] = $employees; $data['positions'] = $positions; $data['page_load'] = 'admin/employee_list'; $data['active'] = 'employee'; $this->load->view('includes/template', $data); } public function add() { if (!empty($_POST)) { $employee = new stdClass(); $employee->firstname = strtoupper($_POST['firstname']); $employee->lastname = strtoupper($_POST['lastname']); $employee->middlename = strtoupper($_POST['middlename']); $employee->birth_date = $_POST['birth_date']; $employee->marital_status = $_POST['marital_status']; $employee->email = $_POST['email']; $employee->phone_number = $_POST['phone_number']; $employee->home_no = $_POST['home_no']; $employee->contact_person = $_POST['contact_person']; $employee->contact_phone_number = $_POST['contact_phone_number']; // $employee->employee_status = $_POST['employee_status']; $employee->date_hire = $_POST['date_hired']; $employee->monthly_pay = $_POST['monthly_pay']; $employee->isFixed_salary = $_POST['isFixed_salary']; // $employee->basic_pay = $_POST['basic_pay']; $employee->tin_no = $_POST['tin_no']; $employee->sss_no = $_POST['sss_no']; $employee->philhealth_no = $_POST['philhealth_no']; $employee->pagibig_no = $_POST['pagibig_no']; $employee->bank_name = $_POST['bank_name']; // $employee->user_role_id = $_POST['user_role_id']; $employee->position_id = $_POST['position_id']; $employee->isActive = $_POST['active']; $employee->gender = $_POST['gender']; $employee->transportation_allowance = $_POST['transportation_allowance']; $employee->internet_allowance = $_POST['internet_allowance']; $employee->meal_allowance = $_POST['meal_allowance']; $employee->phone_allowance = $_POST['phone_allowance']; // $employee->total_allowance = $_POST['total_allowance']; $employee->date_modified = new DateTime('now'); $employee->username = str_replace(' ', '', strtolower($_POST['firstname'])); $employee->password = <PASSWORD>_hash("<PASSWORD>", PASSWORD_<PASSWORD>); $user_role = 3; if ($_POST['position_id'] == 'Admin') { $user_role = 1; } elseif ($_POST['position_id'] == "Payroll Master") { $user_role = 2; } $employee->user_role_id = $user_role; $address = new stdClass(); $address->city = ($_POST['address']??''); $zk = new ZKLib('172.16.17.32'); $ip = '192.168.1.172'; $port = 4370; // if (@socket_connect($this->_zkclient, $ip, $port)) { $ret = $zk->connect(); if ($ret) { $this->employee_model->add_employee($employee, $address); $em = $this->employee_model->get_last_id(); if (!empty($em)) { $uid = $em->employee_id; $b = $zk->setUser($uid, $uid, $employee->firstname . " " . $employee->lastname, ''); if ($b==="") { echo json_encode(true); }else{ echo 'unable to connect to the biometric device 2'; $this->employee_model->delete($uid); } } } else { echo 'unable to connect to the biometric device 1'; } $zk->disconnect(); // } else { // $error_credentials = "<h6 id='error' style='color: rgba(255,0,0,0.7)' hidden>Incorrect username or password, Please try gain!</h6>"; // echo $error_credentials; // } } // redirect(base_url('employee')); } public function update() { if (!empty($_POST)) { $employee = new stdClass(); $employee->employee_id = $_POST['employee_id']; $employee->firstname = strtoupper($_POST['firstname']); $employee->lastname = strtoupper($_POST['lastname']); $employee->middlename = strtoupper($_POST['middlename']); $employee->birth_date = $_POST['birth_date']; $employee->marital_status = $_POST['marital_status']; $employee->email = $_POST['email']; $employee->address_id = $_POST['address_id']; $employee->phone_number = $_POST['phone_number']; $employee->home_no = $_POST['home_no']; $employee->contact_person = $_POST['contact_person']; // $employee->employee_status = $_POST['employee_status']; $employee->date_hire = $_POST['date_hired']; $employee->monthly_pay = $_POST['monthly_pay']; $employee->isFixed_salary = $_POST['isFixed_salary']; // /\ $employee->basic_pay = $_POST['basic_pay']; $employee->tin_no = $_POST['tin_no']; $employee->sss_no = $_POST['sss_no']; $employee->philhealth_no = $_POST['philhealth_no']; $employee->pagibig_no = $_POST['pagibig_no']; $employee->bank_name = $_POST['bank_name']; // $employee->employee_login_id = $_POST['employee_login_id']; $employee->position_id = $_POST['position_id']; $employee->isActive = $_POST['active']; $employee->gender = $_POST['gender']; $employee->transportation_allowance = $_POST['transportation_allowance']; $employee->internet_allowance = $_POST['internet_allowance']; $employee->meal_allowance = $_POST['meal_allowance']; $employee->phone_allowance = $_POST['phone_allowance']; // $employee->total_allowance = $_POST['total_allowance']; $employee->date_modified = new DateTime('now'); $user_role = 3; if ($_POST['position_id'] == 'Admin') { $user_role = 1; } elseif ($_POST['position_id'] == "Payroll Master") { $user_role = 2; } $employee->user_role_id = $user_role; $this->employee_model->update_employee($_POST['employee_id'], $employee, $_POST['address']); } redirect(base_url('employee')); } public function delete() { // TODO: Implement delete() method. } }<file_sep>/application/backup/EventCalendar.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class EventCalendar extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('eventcalendar_model', 'em'); } public function index() { $this->load->view('Calendar'); } public function load_data() { $events = $this->em->get_event_list(); if($events !== NULL) { echo json_encode(array('success' => 1, 'result' => $events)); } else { echo json_encode(array('success' => 0, 'error' => 'Event not found')); } } }<file_sep>/application/views/includes/modals/add/add_employee_modal.php <?php /** * Created by PhpStorm. * User: capstonestudent * Date: 2/19/2020 * Time: 2:43 AM */ ?> <div class="modal fade" id="addEmp" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-xl modku" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title kulay" id="exampleModalLabel">Add Employee</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <?php echo validation_errors(); ?> <!-- <form method="post" action="add-employee">--> <form> <div class="modal-body mod"> <div class="card"> <div class="card-body px-lg-5 pt-0 border"> <br> <div class="font-weight-bold">BASIC INFORMATION</div> <div class="row mt-2"> <div class="col-3"> <label for="formGroupExampleInput">First Name</label> <input type="text" class="form-control" id="firstname" name="firstname" required> </div> <div class="col-3"> <label for="formGroupExampleInput2">Middle Name</label> <input type="text" class="form-control" id="middlename" name="middlename"> </div> <div class="col-4"> <label for="formGroupExampleInput2">Last Name</label> <input type="text" class="form-control" id="lastname" name="lastname" required> </div> <div class="col-2"> <label for="formGroupExampleInput">Gender</label> <select required name="gender" id="gender" class="form-control input input-sm monthName" style="width: 100%;padding: 5px" required> <option value="Male">Male</option> <option value="Female">Female</option> </select> </div> </div> <div class="row mt-2"> <div class="col-3"> <label for="formGroupExampleInput2">Birth Date</label> <input onfocus=" (this. type='date')" type="text" class="form-control" id="birth_date" name="birth_date" required> </div> <div class="col-3"> <label for="formGroupExampleInput2">Marital Status</label> <select required name="marital_status" id="marital_status" class="form-control input input-sm monthName" style="width: 100%;padding: 5px" required> <option value="Single">Single</option> <option value="Married">Married</option> <option value="Widow">Widow</option> </select> </div> <div class="col-6"> <label for="formGroupExampleInput">Address</label> <input type="text" class="form-control" id="address" name="address" required> </div> </div> <div class="row mt-2"> <div class="col-3"> <label for="formGroupExampleInput2">Mobile Number</label> <input type="text" class="form-control" id="phone_number" name="phone_number" required> </div> <div class="col-3"> <label for="formGroupExampleInput">Telephone Number</label> <input type="text" class="form-control" id="home_no" name="home_no"> </div> <div class="col-6"> <label for="formGroupExampleInput">Email Address</label> <input type="email" class="form-control" id="email" name="email"> </div> </div> <div class="row mt-2"> <div class="col-3"> <label for="formGroupExampleInput">Contact Person</label> <input type="text" class="form-control" id="contact_person" name="contact_person"> </div> <div class="col-3"> <label for="formGroupExampleInput2">Contact Person / Mobile Number</label> <input type="text" class="form-control" id="contact_phone_number" name="phone_number" > </div> <!-- <div class="col-3">--> <!-- <label for="formGroupExampleInput">Employee Type</label>--> <!-- <input type="text" class="form-control" id="formGroupExampleInput"--> <!-- name="employee_status">--> <!-- </div>--> <div class="col-3"> <label for="formGroupExampleInput">Date Hired</label> <input onfocus=" (this. type='date')" type="text" class="form-control" id="date_hired" name="date_hired"> </div> <div class="col-3"> <label for="formGroupExampleInput2">Bank</label> <input type="text" class="form-control" id="bank_name" name="bank_name"> </div> </div> <div class="row mt-2"> <div class="col-3"> <label for="formGroupExampleInput">Tin Number</label> <input type="text" class="form-control" id="tin_no" name="tin_no"> </div> <div class="col-3"> <label for="formGroupExampleInput2">Philhealth No.</label> <input type="text" class="form-control" id="philhealth_no" name="philhealth_no"> </div> <div class="col-3"> <label for="formGroupExampleInput">SSS Number</label> <input type="text" class="form-control" id="sss_no" name="sss_no"> </div> <div class="col-3"> <label for="formGroupExampleInput">Pag-ibig No.</label> <input type="text" class="form-control" id="pagibig_no" name="pagibig_no"> </div> </div> <div class="row mt-2"> <div class="col-2"> <label for="formGroupExampleInput">Active</label> <select required name="active" class="form-control input input-sm monthName" style="width: 100%;padding: 5px" required> <option value="1">Yes</option> <option value="0">No</option> </select> </div> </div> <br> <div class="font-weight-bold"> MONTHLY SALARY AND DEDUCTION </div> <div class="row mt-2"> <div class="col-3"> <label for="formGroupExampleInput">Position</label> <select required name="position_id" id="position_id" class="form-control input input-sm monthName" style="width: 100%;padding: 5px"> <?php foreach ($positions as $position): ?> <option value="<?= $position->position_id; ?>"><?= $position->position; ?></option> <?php endforeach; ?> <option value="Admin">Admin</option> <option value="Admin">Payroll Master</option> </select> </div> <div class="col-6"> <label for="formGroupExampleInput">Salary</label> <input type="number" class="form-control" id="monthly_pay" value=<?= $position->rate ?> placeholder="Monthly Pay" name="monthly_pay"> </div> <div class="col-3"> <label for="formGroupExampleInput">Fixed Salary</label> <select required name="isFixed_salary" id="isFixed_salary" class="form-control input input-sm monthName" style="width: 100%;padding: 5px"> <option value="0">No</option> <option value="1">Yes</option> </select> </div> </div> <br> <div class="font-weight-bold">ALLOWANCE</div> <div class="row"> <div class="col-3"> <label for="formGroupExampleInput">Transportation</label> <input type="text" class="form-control" id="transportation_allowance" name="transportation_allowance"> </div> <div class="col-3"> <label for="formGroupExampleInput2">Internet</label> <input type="text" class="form-control" id="internet_allowance" name="internet_allowance"> </div> <div class="col-3"> <label for="formGroupExampleInput">Meal</label> <input type="text" class="form-control" id="meal_allowance" name="meal_allowance"> </div> <div class="col-3"> <label for="formGroupExampleInput2">Phone</label> <input type="text" class="form-control" id="phone_allowance" name="phone_allowance"> </div> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary" name="add-employee" id="add-employee">Submit</button> </div> </form> <div class="modal fade" id="loading" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="lds-facebook">Loading...</div> </div> </div> </div> </div> </div> <script> $('#add-employee').on('click', function (e) { e.preventDefault(); var firstname = $('#firstname').val(); var middlename = $('#middlename').val(); var lastname = $('#lastname').val(); var gender = $('#gender').val(); var birth_date = $('#birth_date').val(); var marital_status = $('#marital_status').val(); var address = $('#address').val(); var phone_number = $('#phone_number').val(); var home_no = $('#home_no').val(); var email = $('#email').val(); var contact_person = $('#contact_person').val(); var contact_phone_number = $('#contact_phone_number').val(); var date_hired = $('#date_hired').val(); var bank_name = $('#bank_name').val(); var tin_no = $('#tin_no').val(); var philhealth_no = $('#philhealth_no').val(); var sss_no = $('#sss_no').val(); var pagibig_no = $('#pagibig_no').val(); var active = $('.active').val(); var position_id = $('#position_id').val(); var monthly_pay = $('#monthly_pay').val(); var isFixed_salary = $('#isFixed_salary').val(); var transportation_allowance = $('#transportation_allowance').val(); var internet_allowance = $('#internet_allowance').val(); var meal_allowance = $('#meal_allowance').val(); var phone_allowance = $('#phone_allowance').val(); $.ajax({ url: "<?=base_url('add-employee');?>", method: 'post', dataType: "JSON", data: { firstname:firstname, middlename:middlename, lastname:lastname, gender:gender, birth_date:birth_date, marital_status:marital_status, address:address, phone_number:phone_number, home_no:home_no, email:email, contact_person:contact_person, contact_phone_number:phone_number, date_hired:date_hired, bank_name:bank_name, tin_no:tin_no, philhealth_no:philhealth_no, sss_no:sss_no, pagibig_no:pagibig_no, active:active, position_id:position_id, monthly_pay:monthly_pay, isFixed_salary:isFixed_salary, transportation_allowance:transportation_allowance, internet_allowance:internet_allowance, meal_allowance:meal_allowance, phone_allowance:phone_allowance, }, beforeSend: function () { $('#addEmp').modal('hide'); // $('#loading').modal('show'); }, complete: function () { $('#loading').modal('hide'); }, success: function (response) { toastr.success("Employee added successfully!", 'Success :)'); }, error: function () { toastr.error('Unable to connect to the biometric device!', 'Errorssss :('); } }); }); </script><file_sep>/application/controllers/Schedule.php <?php /** * Created by PhpStorm. * User: User * Date: 05/02/2020 * Time: 8:08 PM */ class Schedule extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('pagination', 'session'); $this->load->model("schedule_model"); if (!$_SESSION['is_logged_in'] ) { redirect(base_url('')); } } public function view() { if ($_SESSION['user_type'] !="Admin") { redirect(base_url('404')); } $schedules = $this->schedule_model->get_all(); $data['schedules'] = $schedules; $data['page_load'] = 'admin/schedule'; $data['active'] = "schedule"; $this->load->view('includes/template', $data); } public function add() { if (!empty($_POST)) { $time_in = date('h:m A', strtotime($_POST['time-in'])); $time_out = date('h:m A', strtotime($_POST['time-out'])); $this->schedule_model->add($time_in, $time_out); } redirect(base_url('schedule')); } public function update() { if (!empty($_POST)) { $time_in = date('h:m A', strtotime($_POST['time_in'])); $time_out = date('h:m A', strtotime($_POST['time_out'])); $schedule = new stdClass(); $schedule->time_in = $time_in; $schedule->time_out = $time_out; $schedule->date_modified = date('Y-m-d'); $this->schedule_model->update($_POST['schedule_id'], $schedule); } redirect(base_url('schedule')); } public function delete() { if (!empty($_POST)) { $res = $this->schedule_model->get_references($_POST['schedule_id']); if (empty($res)) { $this->schedule_model->delete($_POST['schedule_id']); echo json_encode(true); } else { } } // redirect(base_url('schedule')); } }<file_sep>/application/backup/payroll_master/reports.php <link href="<?=base_url()?>assets/css/custom.css" rel="stylesheet"> <link href="../assets/css/custom.css" rel="stylesheet"> <div class="container-fluid"> <h1 class="h3 mb-3 text-gray-800"><strong>TDZ</strong> <i class="divider"> / </i> <span>Employee Summary Report</span></h1> <div class="card shadow mb-4"> <div class="card-body py-3"> <button type="button" class="btn btn-facebook btn-md"><a href="attendance_report" class="report">Attendance Report</a></button>&nbsp; <button type="button" class="btn btn-facebook btn-md"><a href="payroll_report" class="report">Payroll Report</a></button> </div> <div class="table-responsive"> <table class="table table-bordered"> <thead> <tr> </tr> </thead> </table> </div> </div> </div><file_sep>/application/models/Event_model.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Event_model extends CI_Model { private $event = 'event'; function get_event_list() { $this->db->select("id, title, url, class, UNIX_TIMESTAMP(start_date)*1000 as start, UNIX_TIMESTAMP(end_date)*1000 as end"); $query = $this->db->get($this->event); if ($query) { return $query->result(); } return NULL; } }<file_sep>/application/controllers/Payroll.php <?php /** * Created by PhpStorm. * User: User * Date: 05/02/2020 * Time: 8:33 PM */ class Payroll extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('pagination', 'session'); $this->load->model(array("employee_model", "holiday_model", "dtr_model")); if (!$_SESSION['is_logged_in']) { redirect(base_url('')); } } public function view() { if ($_SESSION['user_type'] == "Employee") { redirect(base_url('404')); } if (!empty($_POST)) { $month = $_POST['month']; $half_month = $_POST['half_month']; $year = $_POST['year']; } else { $month = date('m'); $year = date('Y'); $half_month = 'A'; if (date('d') > 15) { $half_month = 'B'; } } $start_day = $year . "-" . $month; $end_day = $start_day; if ($half_month == 'A') { $start_day .= '-01'; $end_day .= -'15'; } else { $start_day .= '-16'; $end_day .= '-' . date('t', strtotime($start_day)); } //setting month name for the month dropdown in the view -> to be reconsidered $month_name = date('F', strtotime($start_day)); $users = $this->employee_model->get_users();// get all employees that are active $holidays = $this->holiday_model->get_holidays($start_day, $end_day);//get the holidays for the specific payroll period //this code if for checking if the given date is a holiday or not //really needs to be improved.. $hol_day = array(); $hol_type = array(); foreach ($holidays as $hol) { $hol_day[] = substr($hol->date, -2); $hol_type [] = $hol->type; } $payrolls = array(); foreach ($users as $user) { //getting DTR details for the payroll period $result = $this->dtr_model->get_one($user->id, $start_day, $end_day); //creating another start_day and end_day variables to avoid overwriting the payroll period $start = date("Y-m-d", strtotime($start_day)); $end = date("Y-m-d", strtotime($end_day)); if (count($result) > 0) { $payrolls[] = $this->calculate_payroll($user, $result, $start, $end, $hol_day, $hol_type); } else { $payroll = new stdClass();//payroll object $payroll->id = $user->id; $payroll->name = $user->last_name . " " . $user->name; $payroll->monthly_rate = 10068.10;//to get from user data $payroll->daily_rate = round(($payroll->monthly_rate * 12) / 313, 2);//to get from user data // $payrolls[] = $payroll; } } $data['users'] = $users; $data['payrolls'] = $payrolls; $data['half_month'] = $half_month; $data['month'] = $month_name; $data['year'] = $year; $data['active'] = 'payroll'; $data['page_load'] = 'admin/payroll'; $this->load->view('includes/template', $data); } public function view2() { if ($_SESSION['user_type'] == "Employee") { redirect(base_url('404')); } if (!empty($_POST)) { $month = $_POST['month']; $half_month = $_POST['half_month']; $year = $_POST['year']; } else { $month = date('m'); $year = date('Y'); $half_month = 'A'; if (date('d') > 15) { $half_month = 'B'; } } $start_day = $year . "-" . $month; $end_day = $start_day; if ($half_month == 'A') { $start_day .= '-01'; $end_day .= -'15'; } else { $start_day .= '-16'; $end_day .= '-' . date('t', strtotime($start_day)); } //setting month name for the month dropdown in the view -> to be reconsidered $month_name = date('F', strtotime($start_day)); $users = $this->employee_model->get_employees();// get all employees that are active $holidays = $this->holiday_model->get_holidays($start_day, $end_day);//get the holidays for the specific payroll period //this code if for checking if the given date is a holiday or not //really needs to be improved.. $hol_day = array(); $hol_type = array(); foreach ($holidays as $hol) { $hol_day[] = substr($hol->date, -2); $hol_type [] = $hol->type; } $payrolls = array(); foreach ($users as $user) { //getting the time sheets for the payroll period $result = $this->dtr_model->get_one2($user->employee_id, $start_day, $end_day); //creating another start_day and end_day variables to avoid overwriting the payroll period $start = date("Y-m-d", strtotime($start_day)); $end = date("Y-m-d", strtotime($end_day)); // echo "<pre>"; // var_dump($user); // var_dump($result); // echo "<br>"; if (count($result) > 0) { $payrolls[] = $this->calculate_payroll2($user, $result, $start, $end, $hol_day, $hol_type); } else { $payroll = new stdClass();//payroll object $payroll->id = $user->employee_id; $payroll->name = $user->lastname . " " . $user->firstname; $payroll->monthly_rate = 10068.10;//to get from user data $payroll->daily_rate = round(($payroll->monthly_rate * 12) / 313, 2);//to get from user data // $payrolls[] = $payroll; } } // foreach ($payrolls as $pay){ // var_dump($pay->name.' '.number_format($pay->res_sun_ot,2).' '.$pay->res_sun_ot_pay); // } $data['users'] = $users; $data['payrolls'] = $payrolls; $data['half_month'] = $half_month; $data['month'] = $month_name; $data['year'] = $year; $data['active'] = 'payroll'; $data['page_load'] = 'admin/payroll'; $this->load->view('includes/template', $data); } function calculate_payroll($user, $time_data, $start, $end, $hol_day, $hol_type) { $payroll = new stdClass(); $payroll->id = $user->id; $payroll->name = $user->last_name . " " . $user->name; $payroll->monthly_rate = 12000;//to get from user data $payroll->daily_rate = round(($payroll->monthly_rate * 12) / 313, 2);//to get from user data $payroll->allowance = 0; $payroll->dtr_time = 0; $payroll->nor_ot = 0; $payroll->nor_ot_pay = 0; $payroll->res_sun = 0; $payroll->res_sun_pay = 0; $payroll->res_sun_ot = 0; $payroll->res_sun_ot_pay = 0; $payroll->res_reg_hol = 0; $payroll->res_reg_hol_pay = 0; $payroll->res_reg_hol_ot = 0; $payroll->res_reg_hol_ot_pay = 0; $payroll->res_dob_hol = 0; $payroll->res_dob_hol_pay = 0; $payroll->res_dob_hol_ot = 0; $payroll->res_dob_hol_ot_pay = 0; $payroll->res_spe_hol = 0; $payroll->res_spe_hol_pay = 0; $payroll->res_spe_hol_ot = 0; $payroll->res_spe_hol_ot_pay = 0; $payroll->reg_hol = 0; $payroll->reg_hol_pay = 0; $payroll->reg_hol_ot = 0; $payroll->reg_hol_ot_pay = 0; $payroll->dob_hol = 0; $payroll->dob_hol_pay = 0; $payroll->dob_hol_ot = 0; $payroll->dob_hol_ot_pay = 0; $payroll->spe_hol = 0; $payroll->spe_hol_pay = 0; $payroll->spe_hol_ot = 0; $payroll->spe_hol_ot_pay = 0; $payroll->absent = 0; $payroll->late = 0; $payroll->total_ot = 0; $count = 0; $total_ot = 0; $total_res_ot_pay = 0; $total_hol_ot_pay = 0; $total_res_pay = 0; $total_hol_pay = 0; // echo "<br/>"; while (strtotime($start) <= strtotime($end)) { $a = date('d', strtotime($start)); $b = date('d', strtotime($time_data[$count]->date)); $name = date('D', strtotime($start)); // echo "<br/>"; // echo $a." ".$b; if ($a == $b) { $morning_time = $this->getTimeDiff($time_data[$count]->morning_in_hour, $time_data[$count]->morning_in_minute, $time_data[$count]->morning_out_hour, $time_data[$count]->morning_out_minute); $afternoon_time = $this->getTimeDiff($time_data[$count]->afternoon_in_hour, $time_data[$count]->afternoon_in_minute, $time_data[$count]->afternoon_out_hour, $time_data[$count]->afternoon_out_minute); $over_time = $this->getTimeDiff($time_data[$count]->over_in_hour, $time_data[$count]->over_in_minute, $time_data[$count]->over_out_hour, $time_data[$count]->over_out_minute); $com_time = $morning_time + $afternoon_time; $obj = $this->calculate_time($com_time); $obj->ot += $over_time; var_dump($over_time); $total_ot += $over_time + $obj->ot; $payroll->late += $obj->late; //still need to get the list of holidays in order to proceed if ($name == "Sun") { if (in_array($a, $hol_day)) { $ndx = array_search($a, $hol_day); switch ($hol_type[$ndx]) { case 'Regular': $payroll->res_reg_hol += $obj->pre; $payroll->res_reg_hol_ot += $obj->ot; $payroll->res_reg_hol_pay += ($payroll->daily_rate * (260 / 100)) * ($obj->pre / 8); $payroll->res_reg_hol_ot_pay += (($payroll->daily_rate / 8) * 3.38) * $obj->ot; $total_res_pay += ($payroll->daily_rate * (260 / 100)) * ($obj->pre / 8); $total_res_ot_pay += (($payroll->daily_rate / 8) * 3.38) * $obj->ot; echo "REGULAR"; break; case 'Double': $payroll->res_dob_hol += $obj->pre; $payroll->res_dob_hol_ot += $obj->ot; $payroll->res_dob_hol_pay += ($payroll->daily_rate * (390 / 100)) * ($obj->pre / 8); $payroll->res_dob_hol_ot_pay += (($payroll->daily_rate / 8) * 5.07) * $obj->ot; $total_res_pay += ($payroll->daily_rate * (390 / 100)) * ($obj->pre / 8); $total_res_ot_pay += (($payroll->daily_rate / 8) * 5.07) * $obj->ot; break; case 'Special': $payroll->res_spe_hol += $obj->pre; $payroll->res_spe_hol_ot += $obj->ot; $payroll->res_spe_hol_pay += ($payroll->daily_rate * (150 / 100)) * ($obj->pre / 8); $payroll->res_spe_hol_ot_pay += (($user->daily_rate / 8) * 1.95) * $obj->ot; $total_res_pay += ($payroll->daily_rate * (150 / 100)) * ($obj->pre / 8); $total_res_ot_pay += (($user->daily_rate / 8) * 1.95) * $obj->ot; break; } } else { $payroll->res_sun += $obj->pre; $payroll->res_sun_pay += ($payroll->daily_rate * (130 / 100)) * ($obj->pre / 8); $payroll->res_sun_ot += $obj->ot; $payroll->res_sun_ot_pay += (($payroll->daily_rate / 8) * 1.69) * $obj->ot; $total_res_pay += ($payroll->daily_rate * (130 / 100)) * ($obj->pre / 8); $total_res_ot_pay += (($payroll->daily_rate / 8) * 1.69) * $obj->ot; } } else { if (in_array($a, $hol_day)) { $ndx = array_search($a, $hol_day); switch ($hol_type[$ndx]) { case 'Regular': $payroll->reg_hol += $obj->pre; $payroll->reg_hol_ot += $obj->ot; $payroll->reg_hol_pay += ($payroll->daily_rate * (200 / 100)) * ($obj->pre / 8); $payroll->reg_hol_ot_pay += (($payroll->daily_rate / 8) * 2.6) * $obj->ot; $total_hol_pay += ($payroll->daily_rate * (200 / 100)) * ($obj->pre / 8); $total_hol_ot_pay += (($payroll->daily_rate / 8) * 2.6) * $obj->ot; break; case 'Double': $payroll->dob_hol += $obj->pre; $payroll->dob_hol_ot += $obj->ot; $payroll->dob_hol_pay += ($payroll->daily_rate * (300 / 100)) * ($obj->pre / 8); $payroll->dob_hol_ot_pay += (($payroll->daily_rate / 8) * 3.9) * $obj->ot; $total_hol_pay += ($payroll->daily_rate * (300 / 100)) * ($obj->pre / 8); $total_hol_ot_pay += (($payroll->daily_rate / 8) * 3.9) * $obj->ot; break; case 'Special': $payroll->spe_hol += $obj->pre; $payroll->spe_hol_ot += $obj->ot; $payroll->spe_hol_pay += ($payroll->daily_rate * (130 / 100)) * ($obj->pre / 8); $payroll->spe_hol_ot_pay += (($payroll->daily_rate / 8) * 1.69) * $obj->ot; $total_hol_pay += ($payroll->daily_rate * (130 / 100)) * ($obj->pre / 8); $total_hol_ot_pay += (($payroll->daily_rate / 8) * 1.69) * $obj->ot; break; } } else { $payroll->dtr_time += $obj->pre; $payroll->nor_ot += $obj->ot; $payroll->nor_ot_pay += (($payroll->daily_rate / 8) * 1.25) * $obj->ot; } } if ($count < count($time_data) - 1) { $count++; } } elseif ($name != "Sun") { $payroll->absent++; } $start = date("Y-m-d", strtotime("+1 day", strtotime($start))); } $absent_pay = $payroll->daily_rate * $payroll->absent; $late_pay = ($payroll->daily_rate / 8) * ($payroll->late / 60); $payroll->basic_salary = ($payroll->monthly_rate / 2) - ($absent_pay + $late_pay); $payroll->total_ot = $total_ot; $payroll->gross_pay = $total_res_ot_pay + $total_hol_ot_pay + $total_res_pay + $total_hol_pay + $payroll->nor_ot_pay + $payroll->basic_salary; $payroll->pagibig_con = ($payroll->monthly_rate * .02) / 2; $payroll->philhealth_con = (($payroll->monthly_rate / 2) * (2.75 / 100)) / 2; $payroll->sss_con = 0; $payroll->cash_advance = 0; $payroll->sss_loan = 0; $payroll->pagibib_loan = 0; $payroll->other_deductions = 0; $payroll->total_deductions = $payroll->pagibig_con + $payroll->sss_con + $payroll->philhealth_con + $payroll->cash_advance + $payroll->sss_loan + $payroll->pagibib_loan + $payroll->other_deductions; $payroll->net_pay = $payroll->gross_pay - $payroll->total_deductions; return $payroll; } function calculate_payroll2($user, $time_data, $start, $end, $hol_day, $hol_type) { $today = intval(date('d')); $payroll = new stdClass(); $payroll->id = $user->employee_id; $payroll->name = $user->lastname . " " . $user->firstname; $payroll->monthly_rate = $user->monthly_pay;//to get from user data $payroll->daily_rate = round(($payroll->monthly_rate * 12) / 313, 2);//to get from user data $payroll->allowance = 0; $payroll->dtr_time = 0; $payroll->nor_ot = 0; $payroll->nor_ot_pay = 0; $payroll->res_sun = 0; $payroll->res_sun_pay = 0; $payroll->res_sun_ot = 0; $payroll->res_sun_ot_pay = 0; $payroll->res_reg_hol = 0; $payroll->res_reg_hol_pay = 0; $payroll->res_reg_hol_ot = 0; $payroll->res_reg_hol_ot_pay = 0; $payroll->res_dob_hol = 0; $payroll->res_dob_hol_pay = 0; $payroll->res_dob_hol_ot = 0; $payroll->res_dob_hol_ot_pay = 0; $payroll->res_spe_hol = 0; $payroll->res_spe_hol_pay = 0; $payroll->res_spe_hol_ot = 0; $payroll->res_spe_hol_ot_pay = 0; $payroll->reg_hol = 0; $payroll->reg_hol_pay = 0; $payroll->reg_hol_ot = 0; $payroll->reg_hol_ot_pay = 0; $payroll->dob_hol = 0; $payroll->dob_hol_pay = 0; $payroll->dob_hol_ot = 0; $payroll->dob_hol_ot_pay = 0; $payroll->spe_hol = 0; $payroll->spe_hol_pay = 0; $payroll->spe_hol_ot = 0; $payroll->spe_hol_ot_pay = 0; $payroll->absent = 0; $payroll->late = 0; $payroll->total_ot = 0; $count = 0; $total_ot = 0; $total_res_ot_pay = 0; $total_hol_ot_pay = 0; $total_res_pay = 0; $total_hol_pay = 0; while (strtotime($start) <= strtotime($end)) { $a = date('d', strtotime($start)); $b = date('d', strtotime($time_data[$count]->date)); $name = date('D', strtotime($start)); if ($a == $b) { $com_time = $time_data[$count]->morning_time + $time_data[$count]->afternoon_time; $obj = $this->calculate_time($com_time, $time_data[$count]); $obj->ot += $time_data[$count]->overtime_time; $total_ot += $obj->ot; $payroll->late += $obj->late; // var_dump($obj->ot); //still need to get the list of holidays in order to proceed if ($name == "Sun") { if (in_array($a, $hol_day)) { $ndx = array_search($a, $hol_day); switch ($hol_type[$ndx]) { case 'Regular': $payroll->res_reg_hol += $obj->pre; $payroll->res_reg_hol_ot += $obj->ot; $payroll->res_reg_hol_pay += ($payroll->daily_rate * (260 / 100)) * ($obj->pre / 8); $payroll->res_reg_hol_ot_pay += (($payroll->daily_rate / 8) * 3.38) * $obj->ot; $total_res_pay += ($payroll->daily_rate * (260 / 100)) * ($obj->pre / 8); $total_res_ot_pay += (($payroll->daily_rate / 8) * 3.38) * $obj->ot; echo "REGULAR"; break; case 'Double': $payroll->res_dob_hol += $obj->pre; $payroll->res_dob_hol_ot += $obj->ot; $payroll->res_dob_hol_pay += ($payroll->daily_rate * (390 / 100)) * ($obj->pre / 8); $payroll->res_dob_hol_ot_pay += (($payroll->daily_rate / 8) * 5.07) * $obj->ot; $total_res_pay += ($payroll->daily_rate * (390 / 100)) * ($obj->pre / 8); $total_res_ot_pay += (($payroll->daily_rate / 8) * 5.07) * $obj->ot; break; case 'Special': $payroll->res_spe_hol += $obj->pre; $payroll->res_spe_hol_ot += $obj->ot; $payroll->res_spe_hol_pay += ($payroll->daily_rate * (150 / 100)) * ($obj->pre / 8); $payroll->res_spe_hol_ot_pay += (($user->daily_rate / 8) * 1.95) * $obj->ot; $total_res_pay += ($payroll->daily_rate * (150 / 100)) * ($obj->pre / 8); $total_res_ot_pay += (($user->daily_rate / 8) * 1.95) * $obj->ot; break; } } else { $payroll->res_sun += $obj->pre; $payroll->res_sun_pay += ($payroll->daily_rate * (130 / 100)) * ($obj->pre / 8); $payroll->res_sun_ot += $obj->ot; $payroll->res_sun_ot_pay += (($payroll->daily_rate / 8) * 1.69) * $obj->ot; $total_res_pay += ($payroll->daily_rate * (130 / 100)) * ($obj->pre / 8); $total_res_ot_pay += (($payroll->daily_rate / 8) * 1.69) * $obj->ot; } } elseif (in_array($a, $hol_day)) { $ndx = array_search($a, $hol_day); switch ($hol_type[$ndx]) { case 'Regular': $payroll->reg_hol += $obj->pre; $payroll->reg_hol_ot += $obj->ot; $payroll->reg_hol_pay += ($payroll->daily_rate * (200 / 100)) * ($obj->pre / 8); $payroll->reg_hol_ot_pay += (($payroll->daily_rate / 8) * 2.6) * $obj->ot; $total_hol_pay += ($payroll->daily_rate * (200 / 100)) * ($obj->pre / 8); $total_hol_ot_pay += (($payroll->daily_rate / 8) * 2.6) * $obj->ot; break; case 'Double': $payroll->dob_hol += $obj->pre; $payroll->dob_hol_ot += $obj->ot; $payroll->dob_hol_pay += ($payroll->daily_rate * (300 / 100)) * ($obj->pre / 8); $payroll->dob_hol_ot_pay += (($payroll->daily_rate / 8) * 3.9) * $obj->ot; $total_hol_pay += ($payroll->daily_rate * (300 / 100)) * ($obj->pre / 8); $total_hol_ot_pay += (($payroll->daily_rate / 8) * 3.9) * $obj->ot; break; case 'Special': $payroll->spe_hol += $obj->pre; $payroll->spe_hol_ot += $obj->ot; $payroll->spe_hol_pay += ($payroll->daily_rate * (130 / 100)) * ($obj->pre / 8); $payroll->spe_hol_ot_pay += (($payroll->daily_rate / 8) * 1.69) * $obj->ot; $total_hol_pay += ($payroll->daily_rate * (130 / 100)) * ($obj->pre / 8); $total_hol_ot_pay += (($payroll->daily_rate / 8) * 1.69) * $obj->ot; break; } } else { $payroll->dtr_time += $obj->pre; $payroll->nor_ot += $obj->ot; $payroll->nor_ot_pay += (($payroll->daily_rate / 8) * 1.25) * $obj->ot; } if ($count < count($time_data) - 1) { $count++; } } elseif ($name != "Sun" && !in_array($a, $hol_day) && $a < $today) { $payroll->absent++; } $start = date("Y-m-d", strtotime("+1 day", strtotime($start))); } $absent_pay = $payroll->daily_rate * $payroll->absent; $late_pay = ($payroll->daily_rate / 8) * ($payroll->late); $payroll->basic_salary = (($payroll->daily_rate /8)* $payroll->dtr_time) - ($absent_pay + $late_pay); $payroll->allowance = $user->total_allowance; $payroll->total_ot = $total_ot; $payroll->gross_pay = $total_res_ot_pay + $total_hol_ot_pay + $total_res_pay + $total_hol_pay + $payroll->nor_ot_pay + $payroll->basic_salary + $payroll->allowance; $payroll->pagibig_con = ($payroll->monthly_rate * .02) / 2; $payroll->philhealth_con = (($payroll->monthly_rate / 2) * (2.75 / 100)) / 2; $payroll->sss_con = 0; $payroll->cash_advance = 0; $payroll->sss_loan = 0; $payroll->pagibib_loan = 0; $payroll->other_deductions = 0; $payroll->total_deductions = $payroll->pagibig_con + $payroll->sss_con + $payroll->philhealth_con + $payroll->cash_advance + $payroll->sss_loan + $payroll->pagibib_loan + $payroll->other_deductions; $payroll->net_pay = $payroll->gross_pay - $payroll->total_deductions; return $payroll; } function getTimeDiff($start_hr, $start_mn, $end_hr, $end_mn) { if ($start_hr != null && $start_hr != null && $end_hr != null && $end_mn != null) { if ($start_hr == 12) { $start_hr = 1; $end_hr += 1; } $start_date = new DateTime($start_hr . ':' . $start_mn . ':00'); $end_date = new DateTime($end_hr . ':' . $end_mn . ':00'); $interval = $end_date->diff($start_date); $hours = $interval->format('%h'); $minutes = $interval->format('%i'); return round((($hours * 60 + $minutes) / 60), 2); } else { return 0.0; } } function getTimeDiff2($start, $end) { if ($start != null && $end) { $start_date = new DateTime($start); $end_date = new DateTime($end); $interval = $end_date->diff($start_date); $hours = $interval->format('%h'); $minutes = $interval->format('%i'); return number_format(round((($hours * 60 + $minutes) / 60), 2), 2); } else { return 0.0; } } function calculate_time($com_time, $time) { // echo "<pre>"; // var_dump($time); $obj = new stdClass(); $obj->late = 0; $obj->ot = 0; if ($com_time > 8) { $obj->pre = 8; $obj->ot = $com_time - 8; } else { $obj->pre = $com_time; // $obj->late = 8 - $com_time; } $employee = $this->employee_model->get_one($time->employee_id); $s = str_replace(" ", "", $employee[0]->time_in); $s = str_replace(":", ".", $s); $s = str_split($s, 5); $t = str_replace(":", ".", $time->morning_in); if (doubleval($t) <= doubleval($s[0])) { return $obj; } if (doubleval($t) > doubleval($s[0])) { $obj->late = (doubleval($t) - doubleval($s[0])); return $obj; } $t = str_replace(":", ".", $time->afternoon_in); if (doubleval($t) > doubleval($s[0])) { $obj->late = (doubleval($t) - doubleval($s[0])); } return $obj; } public function add() { // TODO: Implement add() method. } public function update() { // TODO: Implement update() method. } public function delete() { // TODO: Implement delete() method. } }<file_sep>/application/models/Overtime_model.php <?php /** * Created by PhpStorm. * User: User * Date: 05/02/2020 * Time: 9:32 PM */ class Overtime_model extends CI_Model { public function __construct() { parent::__construct(); } public function get_all() { $result = $this->db->select('*,firstname,lastname') ->from('tbl_overtime_request as overtime') ->join('tbl_employee as employee', 'overtime.employee_id=employee.employee_id') ->order_by('date_request', 'desc') ->get() ->result(); return $result; } public function add($overtime) { $this->db->insert('tbl_overtime_request', $overtime); } public function update_status($overtime_id, $status) { $this->db->set('status', $status); $this->db->where('overtime_request_id', $overtime_id); $this->db->update('tbl_overtime_request'); } }<file_sep>/application/backup/employee/payslip.php <?php /** * Created by PhpStorm. * User: capstonestudent * Date: 1/25/2020 * Time: 5:06 PM */ ?> <div class="container-fluid"> <!-- Page Heading --> <h1 class="h3 mb-4 text-gray-800">Page Under Construction </h1> </div> <file_sep>/application/models/Leave_model.php <?php /** * Created by PhpStorm. * User: User * Date: 05/02/2020 * Time: 9:42 PM */ class Leave_model extends CI_Model { public function __construct() { parent::__construct(); } public function get_one($user_id) { $result = $this->db->select('*') ->from('tbl_leave_request') ->where('employee_id', $user_id) ->order_by('date_request', 'desc') ->get() ->result(); return $result; } public function get_all() { $result = $this->db->select('*,firstname,lastname') ->from('tbl_leave_request as leave') ->join('tbl_employee as employee', 'leave.employee_id=employee.employee_id') ->order_by('date_request', 'desc') ->get() ->result(); return $result; } public function add($leave_request) { $this->db->insert('tbl_leave_request', $leave_request); } public function update_status($leave_id, $status) { $this->db->set('status', $status); $this->db->where('leave_request_id', $leave_id); $this->db->update('tbl_leave_request'); } public function update_request($leave, $leave_id) { $this->db->where('leave_request_id', $leave_id); $this->db->update('tbl_leave_request', $leave); } public function delete($leave_id) { $this->db->where('leave_request_id', $leave_id); $this->db->delete('tbl_leave_request'); } }<file_sep>/application/controllers/Cash.php <?php /** * Created by PhpStorm. * User: User * Date: 05/02/2020 * Time: 8:42 PM */ class Cash extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('pagination', 'session'); $this->load->model(array("cash_model", "employee_model")); if (!$_SESSION['is_logged_in'] ) { redirect(base_url('')); } } public function view() { if ($_SESSION['user_type'] == "Employee") { redirect(base_url('404')); } $users = $this->employee_model->get_employees(); $cashAdvances = $this->cash_model->get_all(); $data['users'] = $users; $data['cashAdvances'] = $cashAdvances; $data['page_load'] = 'admin/cash_advance'; $data['active'] = "cash advance"; $this->load->view('includes/template', $data); } public function add() { if (!empty($_POST)) { $cash_advance = new stdClass(); $cash_advance->employee_id = $_POST['user_id']; $cash_advance->date_Advance = date('Y-m-d'); $cash_advance->amount = $_POST['amount']; $cash_advance->repay_amount = $_POST['repay_amount']; $cash_advance->purpose = $_POST['purpose']; $cash_advance->date_modified = date('Y-m-d'); $cash_advance->status = "Unpaid"; $cash_advance->balance = $_POST['amount']; $this->cash_model->add($cash_advance); } redirect(base_url('cash-advance')); } public function update() { if (!empty($_POST)) { $cash_advance = new stdClass(); $cash_advance->amount = $_POST['amount']; $cash_advance->repay_amount = $_POST['repay_amount']; $this->load->model('Dbmodel'); $this->DBModel->update($cash_advance, $_POST['cash_advance_id']); } redirect(base_url('cash-advance')); } public function delete() { if (!empty($_POST)) { $this->cash_model->delete($_POST['cash_advance_id']); } redirect(base_url('cash-advance')); } }<file_sep>/application/views/admin/dtr.php <link href="<?= base_url() ?>assets/css/custom.css" rel="stylesheet"> <div class="container-fluid"> <!-- <h1 class="h3 mb-4 text-gray-800">Attendance - TODO ( Mariel) </h1>--> <h1 class="h3 mb-3 text-gray-800"><strong>TDZ</strong> <i class="divider"> / </i> <span>Daily Time Record</span> </h1> <!-- DataTales Example --> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary"><strong>TDZ</strong> <i class="divider"> / </i> <span>Daily Time Record</span> </h6> </div> <div class="card-body"> <div class="sec_head"> <div class="row row-full"> <div class="col-md-7"> <form action="dtr" method="post"> <label for="half_month">Filter: </label>&nbsp;&nbsp;&nbsp; <select name="half_month" id="half_month" class="input input-sm half_month"> <option value="A" <?= ($half_month == 'A' ? 'selected' : ''); ?>>A</option> <option value="B" <?= ($half_month == 'B' ? 'selected' : ''); ?>>B</option> </select>&nbsp;&nbsp; <select name="month" id="month" class="input input-sm monthName "> <option value="01" <?= ($month == 'January' ? 'selected' : ''); ?>>January</option> <option value="02" <?= ($month == 'February' ? 'selected' : ''); ?>>February</option> <option value="03" <?= ($month == 'March' ? 'selected' : ''); ?>>March</option> <option value="04" <?= ($month == 'April' ? 'selected' : ''); ?>>April</option> <option value="05" <?= ($month == 'May' ? 'selected' : ''); ?>>May</option> <option value="06" <?= ($month == 'June' ? 'selected' : ''); ?>>June</option> <option value="07" <?= ($month == 'July' ? 'selected' : ''); ?>>July</option> <option value="08" <?= ($month == 'August' ? 'selected' : ''); ?>>August</option> <option value="09" <?= ($month == 'September' ? 'selected' : ''); ?>>September</option> <option value="10" <?= ($month == 'October' ? 'selected' : ''); ?>>October</option> <option value="11" <?= ($month == 'November' ? 'selected' : ''); ?>>November</option> <option value="12" <?= ($month == 'December' ? 'selected' : ''); ?>>December</option> </select>&nbsp;&nbsp; <select name="year" id="year" class="input input-sm year"> <option value="2020" <?= ($year == '2020' ? 'selected' : ''); ?>>2020</option> <option value="2019" <?= ($year == '2019' ? 'selected' : ''); ?>>2019</option> <option value="2018" <?= ($year == '2018' ? 'selected' : ''); ?>>2018</option> <option value="2017" <?= ($year == '2017' ? 'selected' : ''); ?>>2017</option> <option value="2016" <?= ($year == '2016' ? 'selected' : ''); ?>>2016</option> <option value="2015" <?= ($year == '2015' ? 'selected' : ''); ?>>2015</option> <option value="2014" <?= ($year == '2014' ? 'selected' : ''); ?>>2014</option> <option value="2013" <?= ($year == '2013' ? 'selected' : ''); ?>>2013</option> <option value="2012" <?= ($year == '2012' ? 'selected' : ''); ?>>2012</option> </select>&nbsp;&nbsp; <?php if ($_SESSION['user_type'] != "Employee"): ?> <select name="user_id" id="name" class="input input-sm empName"> <?php foreach ($users as $user): ?> <option value="<?= $user->id; ?>" <?= ($user->id == $user_id ? 'selected' : ''); ?> ><?= $user->last_name . ' ' . $user->name; ?></option> <?php endforeach; ?> </select>&nbsp;&nbsp; <?php endif; ?> <button type="submit" class="btn btn-sm btn-primary">GO</button> <?php if ($_SESSION['user_type'] == "Employee"): ?> <input type="text" name="user_id" value="<?= $_SESSION['user_id']; ?>" hidden/> <button type="button" class="btn btn-facebook btn-md center" data-toggle="modal" data-target="#add-overtime" <?= (!$request_ot ? 'disabled' : ''); ?>>Request Overtime </button> <?php endif; ?> </form> </div> <div id="timestamp"> </div> <span class="date_time"> <span class="time" > <span class="iconn" ><i class="fa fa-clock icon pr-1" ></i>Time: </span><span id="span" ></span> </span> <span class="iconn"><i class="fa fa-calendar icon">&nbsp;&nbsp;&nbsp;</i>Date: <?= date('l F d, Y'); ?></span> </span> </div> </div> <div class="details iconn"> <div class="rh tb_rh text_center"> <span class="show_leave_details">Leave: <span class="text-primary">___</span> <div style="display: none;"> <span class="width-200"></span> </div> </span>&nbsp;&nbsp;&nbsp; <span class="show_absent">Absent: <span class="text-primary">___</span> <div style="display: none;"> <span class="width-200"></span> </div> </span>&nbsp;&nbsp;&nbsp; <span>Over Time: <span class="text-primary">___</span> <div style="display: none"> <span class="width-200"></span> </div> </span>&nbsp;&nbsp;&nbsp; <span>Under Time: <span class="text-primary">___</span> <div style="display: none"> <span class="width-200"></span> </div> </span>&nbsp;&nbsp;&nbsp; <span>Late: <span class="text-primary">___</span> <div style="display: none"> <span class="width-200"></span> </div> </span> </div> </div> <div class="table-responsive"> <table id="attendance" class="table table-sm table-bordered"> <thead> <tr> <th colspan="2" class=" text_center border-left">Half-Month</th> <th colspan="2" class="text_center">Morning</th> <th class="width1"></th> <th colspan="2" class="text_center">Afternoon</th> <th class="width1"></th> <th colspan="2" class="text_center">OverTime</th> <th class="width1"></th> <th colspan="3" class="text_center border-right">Total Time</th> </tr> <tr class=""> <td class="width1 no_hover" colspan="2">Days</td> <td class="width1 no_hover">In</td> <td class="width1 no_hover">Out</td> <td class="width1 no_hover">Time</td> <td class="width1 no_hover">In</td> <td class="width1 no_hover">Out</td> <td class="width1 no_hover">Time</td> <td class="width1 no_hover">In</td> <td class="width1 no_hover">Out</td> <td class="width1 no_hover tc" title="Time Convention" data-toggle='tooltip' data-container='body'>TC </td> <td class="width1 no_hover">Time</td> <td class="width1 no_hover">Pre</td> <td class="width1 no_hover">OT</td> <td class="width1 no_hover">Late</td> </tr> </thead> <tbody> <?php $i; $j = 0; $is_hol = false; $is_sun = false; for ($i = 0; $i < count($days); $i++): ?> <tr class= <?php if (in_array($days[$i][0], $hol_day)): echo "holiday"; $ndx = array_search($days[$i][0], $hol_day); $hol = $hol_name [$ndx]; $is_hol = true; elseif ($days[$i][1] == 'Sun'): echo "sunday"; $is_sun = true; endif; ?> <?= ($is_hol ? ' data-toggle="tooltip" data-placement="top" title="' . $hol . '"' : ''); ?>> <td width="40"><?= $days[$i][0]; ?></td> <td width="40"><?= $days[$i][1]; ?></td> <?php if (count($dtrs) == 0 || $j == -1): ?> <td align="center"> <input value="" style="width: 30px;text-align: center;border: 0">: <input value="" style="width: 30px;text-align: center;border: 0"> </td> <td align="center"> <input value="" style="width: 30px;text-align: center;border: 0">: <input value="" style="width: 30px;text-align: center;border: 0"> </td> <td class="text_center"></td> <td align="center"> <input value="" style="width: 30px;text-align: center;border: 0">: <input value="" style="width: 30px;text-align: center;border: 0"> </td> <td align="center"> <input value="" style="width: 30px;text-align: center;border: 0">: <input value="" style="width: 30px;text-align: center;border: 0"> </td> <td class="text_center"></td> <td align="center"> <input value="" style="width: 30px;text-align: center;border: 0">: <input value="" style="width: 30px;text-align: center;border: 0"> </td> <td align="center"> <input value="" style="width: 30px;text-align: center;border: 0">: <input value="" style="width: 30px;text-align: center;border: 0"> </td> <td class="text_center"></td> <td class="text_center"></td> <td class="text_center"></td> <td class="text_center"></td> <?php elseif ($days[$i][0] == date('d', strtotime($dtrs[$j]->date))): ?> <td align="center"> <input value="<?= ($dtrs[$j]->morning_in_hour ?? ''); ?>" style="width: 30px;text-align: center;border: 0">: <input value="<?= ($dtrs[$j]->morning_in_minute ??''); ?>" style="width: 30px;text-align: center;border: 0"> </td> <td align="center"> <input value="<?= ($dtrs[$j]->morning_out_hour ?? ''); ?>" style="width: 30px;text-align: center;border: 0">: <input value="<?= ($dtrs[$j]->morning_out_minute ?? ''); ?>" style="width: 30px;text-align: center;border: 0"> </td> <td class="text_center"><?= ($dtrs[$j]->morning_time??'') ?> </td> <td align="center"> <input value="<?= $dtrs[$j]->afternoon_in_hour; ?>" style="width: 30px;text-align: center;border: 0">: <input value="<?= $dtrs[$j]->afternoon_in_minute; ?>" style="width: 30px;text-align: center;border: 0"> </td> <td align="center"> <input value="<?= $dtrs[$j]->afternoon_out_hour; ?>" style="width: 30px;text-align: center;border: 0">: <input value="<?= $dtrs[$j]->afternoon_out_minute; ?>" style="width: 30px;text-align: center;border: 0"> </td> <td class="text_center"><?= ($dtrs[$j]->afternoon_time??''); ?> </td> <td align="center"> <input value="<?= $dtrs[$j]->over_in_hour; ?>" style="width: 30px;text-align: center;border: 0">: <input value="<?= $dtrs[$j]->over_in_minute; ?>" style="width: 30px;text-align: center;border: 0"> </td> <td align="center"> <input value="<?= $dtrs[$j]->over_out_hour; ?>" style="width: 30px;text-align: center;border: 0">: <input value="<?= $dtrs[$j]->over_out_minute; ?>" style="width: 30px;text-align: center;border: 0"> </td> <td class="text_center"> <td class="text_center"><?= $dtrs[$j]->pre_time == 0 ? '' : $dtrs[$j]->pre_time; ?> </td> <td class="text_center"><?= $dtrs[$j]->ot == 0 ? '' : $dtrs[$j]->ot; ?> </td> <td class="text_center"><?= $dtrs[$j]->late == 0 ? '' : $dtrs[$j]->late; ?> </td> <?php ($j < count($dtrs) - 1 ? $j++ : $j = -1); ?> <?php elseif (!$is_sun && !$is_hol): ?> <td class="text_center absent" colspan="12">ABSENT</td> <?php else: ?> <td class="text_center " colspan="12"></td> <?php endif; ?> <?php $is_hol = false; $is_sun = false; endfor; ?> </tr> <tr> <td style="text-align: right" colspan="11">Total Time:</td> <td class="text_center"><?= $total_pre == 0 ? ' ' : $total_pre; ?></td> <td class="text_center"><?= $total_ot == 0 ? ' ' : $total_ot; ?></td> <td class="text_center"><?= $total_late == 0 ? ' ' : $total_late; ?></td> </tr> </tbody> </table> </div> </div> </div> </div> <!--test--> <script type="javascript"> window.onload = function () { console.log('ahhhh'); } </script> <?php include getcwd() . '\application\views\includes\modals\add\add_overtime_modal.php'; ?> <file_sep>/application/libraries/zklib/src/Realtime.php <?php /** * Created by PhpStorm. * User: capstonestudent * Date: 2/24/2020 * Time: 9:13 PM */ namespace ZK; use Couchbase\Exception; use ZKLib; class Realtime { public function enable_realtime(ZKLib $self) { $self->_section = __METHOD__; $command = Util::CMD_REG_EVENT; $command_string = 'ffff0000'; $session = $self->_command($command, $command_string, Util::COMMAND_TYPE_DATA); if ($session === false) { return false; } $ret = Util::checkValid($self->_data_recv); return $ret; } public function recv_event(ZKLib $self){ echo "<pre/>"; var_dump($self->_zkclient); // $ret = socket_recv($self->_zkclient, $dataRec, 4096, 0); // var_dump($ret); } }<file_sep>/application/views/admin/employee_list.php <?php /** * Created by PhpStorm. * User: capstonestudent * Date: 2/06/2020 * Time: 6:38 PM */ ?> <link href="<?= base_url() ?>assets/css/custom.css" rel="stylesheet"> <div class="container-fluid"> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">Employee Lists</h6> </div> <div id="error_div"></div> <div class="card-body"> <div class="table-responsive"> <input type="button" class="btn btn-facebook" value="Add Employee" data-toggle="modal" data-target="#addEmp"><br><br> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <td class="text-center">Employee ID</td> <td class="text-center">Name</td> <td class="text-center">Position</td> <td class="text-center">Schedule</td> <td class="text-center">Member Since</td> <td class="text-center">Tools</td> </tr> </thead> <tbody> <?php foreach ($employees as $employee): ?> <tr> <td class="text-center"><?= $employee->employee_id; ?> <i class="btn fa fa-eye float-right" data-toggle="modal" data-target="#employeeView<?= $employee->employee_id; ?>" id="<?= $employee->employee_id; ?>"></i> </td> <td><?= $employee->firstname . ' ' . $employee->middlename . ' ' . $employee->lastname; ?></td> <td><?= $employee->position; ?></td> <td><?= $employee->time_in . " - " . $employee->time_out ?></td> <td><?= $employee->date_hire; ?></td> <td class="text-center text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#employeeEdit<?= $employee->employee_id; ?>" id="<?= $employee->employee_id; ?>">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; </td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> <?php include getcwd() . '/application/views/includes/modals/add/add_employee_modal.php'; ?> <?php foreach ($employees as $employee): ?> <div class="modal fade" id="employeeView<?= $employee->employee_id; ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-xl modku" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title kulay" id="exampleModalLabel">View Employee Details</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body mod"> <div class="card"> <div class="card-body px-lg-5 pt-0 border"> <br> <div class="font-weight-bold">BASIC INFORMATION</div> <div class="row mt-2"> <div class="col-1"> <label for="formGroupExampleInput">ID</label> <input type="text" class="form-control" value="<?= $employee->employee_id; ?>" readonly> </div> <div class="col-3"> <label for="formGroupExampleInput">First Name</label> <input type="text" class="form-control" value="<?= $employee->firstname; ?>" readonly> </div> <div class="col-3"> <label for="formGroupExampleInput2">Last Name</label> <input type="text" class="form-control" value="<?= $employee->middlename; ?>" readonly> </div> <div class="col-3"> <label for="formGroupExampleInput2">Middle Name</label> <input type="text" class="form-control" value="<?= $employee->lastname; ?>" readonly> </div> <div class="col-2"> <label for="formGroupExampleInput">Gender</label> <input type="text" class="form-control" value="<?= $employee->gender; ?>" readonly> </div> </div> <div class="row mt-2"> <div class="col-3"> <label for="formGroupExampleInput2">Birth Date</label> <input class="form-control" value="<?= $employee->birth_date; ?>" readonly> </div> <div class="col-3"> <label for="formGroupExampleInput2">Marital Status</label> <input class="form-control" value="<?= $employee->marital_status; ?>" readonly> </div> <div class="col-6"> <label for="formGroupExampleInput">Address</label> <input type="text" class="form-control" value="<?= $employee->city; ?>" readonly> <input type="text" class="form-control" value="<?= $employee->address_id; ?>" hidden> </div> </div> <div class="row mt-2"> <div class="col-3"> <label for="formGroupExampleInput2">Mobile Number</label> <input type="text" class="form-control" value="<?= $employee->phone_number; ?>" readonly> </div> <div class="col-3"> <label for="formGroupExampleInput">Telephone No.</label> <input type="text" class="form-control" readonly> </div> <div class="col-6"> <label for="formGroupExampleInput">Email</label> <input type="email" class="form-control" value="<?= $employee->email; ?>" readonly> </div> </div> <div class="row mt-2"> <div class="col-3"> <label for="formGroupExampleInput">Contact Person</label> <input type="text" class="form-control" value="<?= $employee->contact_person; ?>" readonly> </div> <div class="col-3"> <label for="formGroupExampleInput2">Contact Person / Mobile Number</label> <input type="text" class="form-control" value="<?= $employee->phone_number; ?>" readonly> </div> <div class="col-3"> <label for="formGroupExampleInput">Date Hired</label> <input type="text" class="form-control" value="<?= $employee->date_hire; ?>" readonly> </div> <div class="col-3"> <label for="formGroupExampleInput2">Bank</label> <input type="text" class="form-control" value="<?= $employee->bank_name; ?>" readonly> </div> </div> <div class="row"> <div class="col-3"> <label for="formGroupExampleInput">Tin Number</label> <input type="text" class="form-control" value="<?= $employee->tin_no; ?>" readonly> </div> <div class="col-3"> <label for="formGroupExampleInput2">Philhealth No.</label> <input type="text" class="form-control" value="<?= $employee->philhealth_no; ?>" readonly> </div> <div class="col-3"> <label for="formGroupExampleInput">SSS Number</label> <input type="text" class="form-control" value="<?= $employee->sss_no; ?>" readonly> </div> <div class="col-3"> <label for="formGroupExampleInput">Pag-ibig No.</label> <input type="text" class="form-control" value="<?= $employee->pagibig_no; ?>" readonly> </div> </div> <div class="row mt-2"> <div class="col-3"> <label for="formGroupExampleInput">Active</label> <input type="text" class="form-control" value="<?= ($employee->isActive == 1 ? 'Yes' : 'No'); ?>" readonly> </div> </div> <br> <div class="font-weight-bold">MONTHLY SALARY AND DEDUCTION</div> <div class="row mt-2"> <div class="col-3"> <label for="formGroupExampleInput">Position</label> <input type="text" class="form-control" value="<?= $employee->position; ?>" readonly> </div> <div class="col-6"> <label for="formGroupExampleInput">Salary</label> <input type="number" class="form-control" value="<?= $employee->monthly_pay; ?>" readonly> </div> <div class="col-3"> <label for="formGroupExampleInput">Fixed Salary</label> <input type="text" class="form-control" value="<?= ($employee->isFixed_salary == 1 ? 'Yes' : 'No'); ?>" readonly> </div> </div> <br> <div class="font-weight-bold">ALLOWANCE</div> <div class="row"> <div class="col-3"> <label for="formGroupExampleInput">Transportation</label> <input type="text" maxlength="10" class="form-control" placeholder="Transportation" name="transportation_allowance" value="<?= $employee->transportation_allowance; ?>" readonly> </div> <div class="col-3"> <label for="formGroupExampleInput2">Internet</label> <input type="text" class="form-control" placeholder="Internet" name="internet_allowance" value="<?= $employee->internet_allowance; ?>" readonly> </div> <div class="col-3"> <label for="formGroupExampleInput">Meal</label> <input type="text" class="form-control" placeholder="Meal" name="meal_allowance" value="<?= $employee->meal_allowance; ?>" readonly> </div> <div class="col-3"> <label for="formGroupExampleInput2">Phone</label> <input type="text" class="form-control" placeholder="Phone" name="phone_allowance" value="<?= $employee->phone_allowance; ?>" readonly> </div> </div> </div> </div> </div> </div> </div> </div> <?php endforeach; ?> <?php foreach ($employees as $employee): ?> <div class="modal fade" id="employeeEdit<?= $employee->employee_id; ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog modal-xl modku" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title kulay" id="exampleModalLabel">View Employee Details</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form method="post" action="update-employee"> <div class="modal-body mod"> <div class="card"> <div class="card-body px-lg-5 pt-0 border"> <br> <div class="font-weight-bold">BASIC INFORMATION</div> <div class="row mt-2"> <div class="col-3"> <label for="formGroupExampleInput">First Name</label> <input type="text" class="form-control" value="<?= $employee->firstname; ?>" name="firstname" required> <input type="text" name="employee_id" value="<?= $employee->employee_id; ?>" hidden> </div> <div class="col-3"> <label for="formGroupExampleInput2">Middle Name</label> <input type="text" class="form-control" value="<?= $employee->middlename; ?>" name="middlename"> </div> <div class="col-4"> <label for="formGroupExampleInput2">Last Name</label> <input type="text" class="form-control" name="lastname" value="<?= $employee->lastname; ?>" required> </div> <div class="col-2"> <label for="formGroupExampleInput">Gender</label> <select required name="gender" class="form-control input input-sm monthName" style="width: 100%;padding: 5px" required> <option <?= ($employee->gender == "Male" ? 'selected' :''); ?> value="Male">Male </option> <option <?= ($employee->gender == "Female"? 'selected' :''); ?> value="Female"> Female </option> </select> </div> </div> <div class="row mt-2"> <div class="col-3"> <label for="formGroupExampleInput2">Birth Date</label> <input onfocus=" (this. type='date')" type="text" value="<?= $employee->birth_date; ?>" class="form-control" " name="birth_date" required> </div> <div class="col-3"> <label for="formGroupExampleInput2">Marital Status</label> <select required name="marital_status" class="form-control input input-sm monthName" style="width: 100%;padding: 5px" required> <option <?= ($employee->gender == "Single"? 'selected':''); ?>value="Single"> Single </option> <option <?= ($employee->gender == "Married" ?'selected':''); ?>value="Married"> Married </option> <option <?= ($employee->gender == "Widow"?'selected':''); ?>value="Widow">Widow </option> </select> </div> <div class="col-6"> <label for="formGroupExampleInput">Address</label> <input type="text" class="form-control" name="address" value="<?=$employee->city;?>" required> <input type="text" class="form-control" name="address_id" value="<?=$employee->address_id;?>" hidden> </div> </div> <div class="row mt-2"> <div class="col-3"> <label for="formGroupExampleInput2">Mobile Number</label> <input type="text" class="form-control" value="<?=$employee->phone_number;?>" name="phone_number" required> </div> <div class="col-3"> <label for="formGroupExampleInput">Telephone Number</label> <input type="text" class="form-control" name="home_no" value="<?= $employee->home_no; ?>"> </div> <div class="col-6"> <label for="formGroupExampleInput">Email Address</label> <input type="email" class="form-control" name="email" value="<?= $employee->email; ?>"> </div> </div> <div class="row mt-2"> <div class="col-3"> <label for="formGroupExampleInput">Contact Person</label> <input type="text" class="form-control" value="<?= $employee->contact_person; ?>" name="contact_person"> </div> <div class="col-3"> <label for="formGroupExampleInput2">Contact Person / Mobile Number</label> <input type="text" class="form-control" name="phone_number2"> </div> <!-- <div class="col-3">--> <!-- <label for="formGroupExampleInput">Employee Type</label>--> <!-- <input type="text" class="form-control" --> <!-- name="employee_status">--> <!-- </div>--> <div class="col-3"> <label for="formGroupExampleInput">Date Hired</label> <input onfocus=" (this. type='date')" type="text" class="form-control" name="date_hired" value="<?= $employee->date_hire; ?>"> </div> <div class="col-3"> <label for="formGroupExampleInput2">Bank</label> <input type="text" class="form-control" value="<?= $employee->bank_name; ?>" name="bank_name"> </div> </div> <div class="row mt-2"> <div class="col-3"> <label for="formGroupExampleInput">Tin Number</label> <input type="text" class="form-control" name="tin_no" value="<?= $employee->tin_no; ?>"> </div> <div class="col-3"> <label for="formGroupExampleInput2">Philhealth No.</label> <input type="text" class="form-control" value="<?= $employee->philhealth_no; ?>" name="philhealth_no"> </div> <div class="col-3"> <label for="formGroupExampleInput">SSS Number</label> <input type="text" class="form-control" name="sss_no" value="<?= $employee->sss_no; ?>"> </div> <div class="col-3"> <label for="formGroupExampleInput">Pag-ibig No.</label> <input type="text" class="form-control" value="<?= $employee->pagibig_no; ?>" name="pagibig_no"> </div> </div> <div class="row mt-2"> <div class="col-2"> <label for="formGroupExampleInput">Active</label> <select required name="active" class="form-control input input-sm monthName" style="width: 100%;padding: 5px" required> <option <?= ($employee->isActive == "1"?'selected':''); ?>value="1" >Yes</option> <option value="0">No</option> </select> </div> </div> <br>d <div class="font-weight-bold"> MONTHLY SALARY AND DEDUCTION </div> <div class="row mt-2"> <div class="col-3"> <label for="formGroupExampleInput">Position</label> <select required name="position_id" class="form-control input input-sm monthName" style="width: 100%;padding: 5px"> <?php foreach ($positions as $position): ?> <option <?= ($employee->position == $position->position ? 'selected' : ''); ?> value="<?= $position->position_id; ?>"><?= $position->position; ?></option> <?php endforeach; ?> <option value="Admin">Admin</option> <option value="Admin">Payroll Master</option> </select> </div> <div class="col-6"> <label for="formGroupExampleInput">Salary</label> <input type="number" class="form-control" value=<?= $employee->monthly_pay ?> placeholder="Monthly Pay" name="monthly_pay"> </div> <div class="col-3"> <label for="formGroupExampleInput">Fixed Salary</label> <select required name="isFixed_salary" class="form-control input input-sm monthName" style="width: 100%;padding: 5px"> <option <?= ($employee->isFixed_salary == 0 ? 'Yes' : ''); ?>value="No"> No </option> <option <?= ($employee->isFixed_salary == 1 ? 'Yes' : ''); ?>value="Yes"> Yes </option> </select> </div> </div> <br> <div class="font-weight-bold">ALLOWANCE</div> <div class="row"> <div class="col-3"> <label for="formGroupExampleInput">Transportation</label> <input type="text" class="form-control" value="<?= $employee->transportation_allowance; ?>" name="transportation_allowance"> </div> <div class="col-3"> <label for="formGroupExampleInput2">Internet</label> <input type="text" class="form-control" value="<?= $employee->internet_allowance; ?>" name="internet_allowance"> </div> <div class="col-3"> <label for="formGroupExampleInput">Meal</label> <input type="text" class="form-control" value="<?= $employee->meal_allowance; ?>" name="meal_allowance"> </div> <div class="col-3"> <label for="formGroupExampleInput2">Phone</label> <input type="text" class="form-control" value="<?= $employee->phone_allowance; ?>" name="phone_allowance"> </div> </div> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary" name="add-employee">Submit</button> </div> <input hidden value=<?= $employee->employee_id ?>> </form> </div> </div> </div> </div> <?php endforeach; ?> <script> error(); function error() { $("#error").appendTo("#error_div").prop('hidden', false); } </script> <file_sep>/application/models/Cash_model.php <?php /** * Created by PhpStorm. * User: User * Date: 05/02/2020 * Time: 9:52 PM */ class Cash_model extends CI_Model { public function __construct() { parent::__construct(); } public function get_all() { $result = $this->db->select('*,firstname,lastname') ->from('tbl_cash_advance as cash') ->join('tbl_employee as employee', 'cash.employee_id=employee.employee_id') ->order_by('date_advance', 'desc') ->get() ->result(); return $result; } public function add($cash) { $this->db->insert('tbl_cash_advance', $cash); } public function update($cash, $id) { $this->db->where('cash_advance_id', $id); $this->db->update('tbl_cash_advance', $cash); } public function get_one() { // TODO: Implement get_one() method. } }<file_sep>/application/models/Login_model.php <?php /** * Created by PhpStorm. * User: User * Date: 05/02/2020 * Time: 9:23 PM */ class Login_model extends CI_Model { public function __construct() { parent::__construct(); } public function validate($user, $pass) { $account = $this->db->select('*') ->from('tbl_employee') ->where('username', $user) ->get() ->result(); if (!empty($account)) { $verified = password_verify($pass, $account[0]->password); if ($verified) { $role = $this->db->select('*,user_role') ->from('tbl_employee as employee') ->join('tbl_user_role as role', 'employee.user_role_id=role.user_role_id') ->where('username', $user) ->get() ->result(); return $role; } return false; } return false; } }<file_sep>/application/views/admin/position.php <link rel="stylesheet" href="<?=base_url();?>assets/css/position.css"> <div class="container-fluid"> <h1 class="h3 mb-3 text-gray-800"><strong>TDZ</strong> <i class="divider"> / </i> <span>Position</span></h1> <div class="card shadow mb-4"> <div class="card-header py-3"> <input type="button" class="btn btn-facebook" value="Add Position" data-toggle="modal" data-target="#addPosition"> </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable"> <thead> <tr> <td class="text_center">Position</td> <td class="text_center">Wage</td> <td class="text_center">Schedule</td> <td class="text_center">Tools</td> </tr> </thead> <tbody> <?php foreach ($positions as $position):?> <tr class="text_center"> <td><?=$position->position;?></td> <td><?=number_format($position->rate, 2);?></td> <td><?=$position->time_in.' - '.$position->time_out;?></td> <td> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#positionEdit<?=$position->position_id;?>">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#positionDelete<?=$position->position_id;?>">&nbsp;&nbsp;Delete</i> </td> </tr> <?php endforeach;?> </tbody> </table> </div> </div> </div> </div> <!--Modal for Adding Schedule--> <!-- Modal --> <?php include getcwd().'/application/views/includes/modals/add/add_position_modal.php';?> <!-- Edit Modal --> <?php foreach ($positions as $position):?> <div class="modal fade" id="positionEdit<?=$position->position_id;?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Edit Position</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="update-position" method="post"> <div class="form-group row"> <label for="posTitle" class="col-sm-5 col-form-label">Position Title</label> <div class="col-sm-6"> <input type="text" class="form-control" name="position" required value="<?=$position->position;?>"> <input type="text" name="position_id" value="<?= $position->position_id ?>" hidden/> </div> </div> <div class="form-group row"> <label for="rph" class="col-sm-5 col-form-label">Wage</label> <div class="col-sm-6"> <input type="text" class="form-control" min="1" required name="rate" value="<?=($position->rate);?>"> </div> </div> <div class="form-group row"> <label for="sched" class="col-sm-5 col-form-label">Schedule</label> <div class="col-sm-6"> <select class="form-control" name="schedule_id" id="sched" data-style="btn-light"> <?php foreach ($schedules as $schedule){?> <option <?php if ($position->position_id == $schedule->schedule_id) echo "selected" ;?> value="<?=$schedule->schedule_id;?>"><?=$schedule->time_in." - ".$schedule->time_out ;?></option> <?php }?> </select> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save</button> </div> </form> </div> </div> </div> </div> <!-- Modal for delete--> <div class="modal fade" id="positionDelete<?=$position->position_id;?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Delete Schedule</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form> <div class="modal-body"> <input type="text" name="position_id" id="position_id<?=$position->position_id ;?>" class="form-control" value =<?=$position->position_id;?> hidden> <p class="text_center">Do you want to delete this position?</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">No</button> <button type="submit" class="btn btn-primary" id="delete<?=$position->position_id ;?>">Yes</button> </div> </form> </div> </div> </div> <script> $("#delete<?=$position->position_id ;?>").on('click', function (e) { e.preventDefault(); var position_id = $('#position_id<?=$position->position_id;?>').val(); $.ajax({ url: "<?=base_url('delete-position');?>", method: 'post', dataType: "JSON", data: { position_id: position_id }, // complete: function () { // $('#loading').modal('hide'); // }, beforeSend: function () { $('#positionDelete<?=$position->position_id;?>').modal('hide'); // $('#loading').modal('show'); }, success: function (response) { toastr.success("Position deleted successfully", 'Success'); window.setTimeout(function(){location.reload()},3000) }, error: function () { toastr.error('Unable to delete the selected position. The position is currently being used!', 'Error!'); } }); }); </script> <?php endforeach;?><file_sep>/application/views/admin/schedule.php <link href="<?= base_url(); ?>assets/css/schedule.css" rel="stylesheet"> <div class="container-fluid"> <h1 class="h3 mb-3 text-gray-800"><strong>TDZ</strong> <i class="divider"> / </i> <span>Schedule</span></h1> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary"><strong>TDZ</strong> <i class="divider"> / </i> <span>Schedule</span></h6> </div> <div class="card-body"> <div class="table-responsive"> <input type="button" class="btn btn-facebook" value="Add New Schedule" data-toggle="modal" data-target="#addSched"><br><br> <table class="table table-bordered" id="dataTable" width="100%" style="max-height: 50vh;overflow: auto" cellspacing="0"> <thead> <tr> <td class="text_center">Time in</td> <td class="text_center">Time out</td> <td class="text_center">Tools</td> </tr> </thead> <tbody> <?php foreach ($schedules as $schedule): ?> <tr> <td><?= $schedule->time_in; ?></td> <td><?= $schedule->time_out; ?></td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#scheduleEdit<?= $schedule->schedule_id ?>" id='<?= $schedule->schedule_id ?>'>&nbsp;&nbsp;Edit</i>&nbsp;&nbsp; &nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#scheduleDelete<?= $schedule->schedule_id; ?>" id='<?= $schedule->schedule_id ?>'>&nbsp;&nbsp;Delete</i> </td> </tr> <?php endforeach; ?> </tbody> </table> </div> </div> </div> </div> <!--Modal for Adding Schedule--> <!-- Modal --> <?php include getcwd() . '/application/views/includes/modals/add/add_schedule_modal.php'; ?> <!-- Modal for edit--> <?php foreach ($schedules as $schedule): ?> <div class="modal fade" id="scheduleEdit<?= $schedule->schedule_id; ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Edit Schedule</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="update-schedule" method="POST"> <div class="form-group row"> <label for="in" class="col-sm-3 col-form-label">Time in</label> <div class="col-sm-5"> <input type="text" name="schedule_id" class="form-control" value=<?= $schedule->schedule_id; ?> hidden> <input type="time" class="form-control" name="time_in" required value=<?= $schedule->time_in; ?>/> </div> </div> <div class="form-group row"> <label for="out" class="col-sm-3 col-form-label">Time out</label> <div class="col-sm-5"> <input type="time" name="time_out" class="form-control" id="out" value=<?= $schedule->time_out; ?>> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save</button> </div> </form> </div> </div> </div> </div> <!-- Modal for delete--> <div class="modal fade" id="scheduleDelete<?= $schedule->schedule_id; ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Delete Schedule</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form> <div class="modal-body"> <input type="text" name="schedule_id" id="schedule_id<?= $schedule->schedule_id; ?>" class="form-control" value=<?= $schedule->schedule_id; ?> hidden> <p class="text_center">Do you want to delete this schedule?</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">No</button> <button type="submit" class="btn btn-primary" id="delete<?= $schedule->schedule_id ;?>">Yes</button> </div> </form> </div> </div> </div> <script> $("#delete<?=$schedule->schedule_id?>").on('click', function (e) { e.preventDefault(); var schedule_id = $('#schedule_id<?=$schedule->schedule_id;?>').val(); $.ajax({ url: "<?=base_url('delete-schedule');?>", method: 'post', dataType: "JSON", data: { schedule_id: schedule_id }, // complete: function () { // $('#loading').modal('hide'); // }, beforeSend: function () { $('#scheduleDelete<?=$schedule->schedule_id;?>').modal('hide'); // $('#loading').modal('show'); }, success: function (response) { toastr.success("Schedule deleted successfully", 'Success'); window.setTimeout(function(){location.reload()},3000) }, error: function () { toastr.error('Unable to delete the selected schedule. The schedule is currently being used!', 'Error!'); } }); }); </script> <?php endforeach; ?> for(int i = 0; i<3;i++){ //months start_date = ... end_data = ... holidays = .... employees = ... for(employees){ dtrs = get time_sheets of each employee from start to end dates. since kabalo naman ka if pila ka days ang month (days_in_month()) int ndx= 0; for(int j = 0 ; j<days_in_month(); j++){ //Lates per month check sa dtr na controller //Absences per month if(dtr[ndx]->date == j){ //date is in YYYY-mm-dd you just need to get the d part (ask me if nana ka dri na part) }elseif(j !=="sun" || j!= holiday || j != today){// compare the d part of the date (ask me nalang sad dri na part) absent ++; } } } }<file_sep>/application/controllers/Errors.php <?php /** * Created by PhpStorm. * User: User * Date: 06/02/2020 * Time: 9:49 AM */ class Errors extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library(array('pagination', 'session')); $this->load->model(array("leave_model", "employee_model")); $this->load->helper('url'); } public function show_404() { if (isset($_SESSION)) { $this->load->view('errors/html/error_404.php'); } } }<file_sep>/application/backup/payroll_master/employee_list.php <?php /** * Created by PhpStorm. * User: capstonestudent * Date: 1/15/2020 * Time: 9:23 PM */ ?> <link href="<?=base_url()?>assets/css/custom.css" rel="stylesheet"> <link href="../assets/css/custom.css" rel="stylesheet"> <div class="container-fluid"> <!-- Page Heading --> <!-- DataTales Example --> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">Employee Lists</h6> </div> <div class="card-body"> <div class="table-responsive"> <input type="button" class="btn btn-facebook" value="Add Employee" data-toggle="modal" data-target="#addEmp"><br><br> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr> <td class="text-center">Employee ID</td> <td class="text-center">Name</td> <td class="text-center">Position</td> <td class="text-center">Schedule</td> <td class="text-center">Member Since</td> <td class="text-center">Tools</td> </tr> </thead> <tbody> <tr> <td class="text-center"></td> <td><NAME></td> <td>CEO</td> <td></td> <td>Member Since</td> <td class="text-center text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#employeeEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; </td> </tr> </tbody> </table> </div> </div> </div> <!-- Modal --> <!------------- ADD EMPLOYEE ----------------> <div class="modal fade" id="addEmp" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title kulay" id="exampleModalLabel">Add Employee</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form method="post" action="<?=base_url('add_employee')?>"> <div class="modal-body mod"> <div class="card"> <!--Card content--> <div class="card-body px-lg-5 pt-0 border"> <br> <div class="row"> <div class="col"> <label for="formGroupExampleInput"></label> <input type="text" class="form-control" id="formGroupExampleInput" placeholder="First name" name="firstname"> </div> <div class="col-6"> <label for="formGroupExampleInput2"></label> <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Last name" name="lastname"> </div> </div> <div class="form-group"> <label for="formGroupExampleInput"></label> <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Address" name="address"> </div> <div class="row"> <div class="col"> <label for="formGroupExampleInput2"></label> <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Birth date" name="birthdate"> </div> <div class="col-6"> <label for="formGroupExampleInput"></label> <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Contact number" name="contact"> </div> </div> <div class="form-group"> <label for="formGroupExampleInput2"></label> <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Gender" name="gender"> </div> <div class="form-group"> <label for="formGroupExampleInput"></label> <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Position" name="position"> </div> <div class="form-group"> <label for="formGroupExampleInput"></label> <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Work schedule" name="schedule"> </div> <div class="form-group"> <label for="formGroupExampleInput2"></label> <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Date hired" name="datehired"> </div> <!-- Form --> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary" name="addEmployee">Submit</button> </div> </div> </div> </div> </form> </div> <!---------------EDIT MODAL--------------------> <div class="modal fade" id="employeeEdit" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title kulay" id="exampleModalLabel">Edit Employee Profile</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form method="post" action="<?=base_url('add_employee')?>"> <div class="modal-body mod"> <div class="card"> <!--Card content--> <div class="card-body px-lg-5 pt-0 border"> <br> <div class="row"> <div class="col"> <label for="formGroupExampleInput"></label> <input type="text" class="form-control" id="formGroupExampleInput" placeholder="<NAME>" name="firstname"> </div> <div class="col-6"> <label for="formGroupExampleInput2"></label> <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="<NAME>" name="lastname"> </div> </div> <div class="form-group"> <label for="formGroupExampleInput"></label> <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Address" name="address"> </div> <div class="row"> <div class="col"> <label for="formGroupExampleInput2"></label> <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Birth date" name="birthdate"> </div> <div class="col-6"> <label for="formGroupExampleInput"></label> <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Contact number" name="contact"> </div> </div> <div class="form-group"> <label for="formGroupExampleInput2"></label> <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Gender" name="gender"> </div> <div class="form-group"> <label for="formGroupExampleInput"></label> <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Position" name="position"> </div> <div class="form-group"> <label for="formGroupExampleInput"></label> <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Work schedule" name="schedule"> </div> <div class="form-group"> <label for="formGroupExampleInput2"></label> <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Date hired" name="datehired"> </div> <!-- Form --> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </form> </div> </div> </div> <!-- END OF EDIT MODAL--> <!---------------DELETE MODAL--------------------> <div class="modal fade" id="employeeDelete" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title kulay" id="exampleModalLabel">Delete Employee</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body mod"> <div> <!--Card content--> <div> <span style="color: black">Are you sure you want to delete this employee?</span> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-primary">Delete</button> </div> </div> </div> </div> <!-- END OF DELETE MODAL--><file_sep>/application/controllers/IController.php <?php /** * Created by PhpStorm. * User: User * Date: 17/02/2020 * Time: 2:55 PM */ interface IController { public function add(); public function view(); public function update(); public function delete(); }<file_sep>/application/config/routes.php <?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------------- | URI ROUTING | ------------------------------------------------------------------------- | This file lets you re-map URI requests to specific controller functions. | | Typically there is a one-to-one relationship between a URL string | and its corresponding controller class/method. The segments in a | URL normally follow this pattern: | | example.com/class/method/id/ | | In some instances, however, you may want to remap this relationship | so that a different class/function is called than the one | corresponding to the URL. | | Please see the user guide for complete details: | | https://codeigniter.com/user_guide/general/routing.html | | ------------------------------------------------------------------------- | RESERVED ROUTES | ------------------------------------------------------------------------- | | There are three reserved routes: | | $route['default_controller'] = 'welcome'; | | This route indicates which controller class should be loaded if the | URI contains no data. In the above example, the "welcome" class | would be loaded. | | $route['404_override'] = 'errors/page_missing'; | | This route will tell the Router which controller/method to use if those | provided in the URL cannot be matched to a valid route. | | $route['translate_uri_dashes'] = FALSE; | | This is not exactly a route, but allows you to automatically route | controller and method names that contain dashes. '-' isn't a valid | class or method name character, so it requires translation. | When you set this option to TRUE, it will replace ALL dashes in the | controller and method URI segments. | | Examples: my-controller/index -> my_controller/index | my-controller/my-method -> my_controller/my_method */ $route['default_controller'] = 'Login'; $route[''] = 'login/index'; $route['login'] = 'login/login'; $route['logout'] = 'login/logout';//not configured yet $route['dashboard'] = 'dashboard/view'; $route['chart-data'] = 'dashboard/chart_data'; $route['dtr'] = 'dtr/view2'; $route['push'] = 'dtr/push'; $route['overtime'] = 'overtime/view'; $route['add-overtime'] = 'overtime/add'; $route['update-overtime'] = 'overtime/update_status'; $route['leave'] = 'leave/view'; $route['add-leave'] = 'leave/add'; $route['delete-leave'] = 'leave/delete'; $route['update-leave'] = 'leave/update'; $route['employee-leave'] = 'leave/employee_view'; $route['update-leave-status'] = 'leave/update_status'; $route['schedule'] = 'schedule/view'; $route['add-schedule'] = 'schedule/add'; $route['update-schedule'] = 'schedule/update'; $route['delete-schedule'] = 'schedule/delete'; $route['payroll'] = 'payroll/view2'; $route['cash-advance'] = 'cash/view'; $route['add-cash-advance'] = 'cash/add'; $route['update-cash-advance'] = 'cash/update'; $route['delete-cash-advance'] = 'cash/delete'; $route['employee'] = 'employee/view'; $route['add-employee'] = 'employee/add'; $route['update-employee'] = 'employee/update'; $route['position'] = 'position/view'; $route['add-position'] = 'position/add'; $route['update-position'] = 'position/update'; $route['delete-position'] = 'position/delete'; $route['calendar'] = 'calendar/view'; $route['calendar2'] = 'calendar2/view'; $route['calendar1'] = 'calendar/AddEvent'; $route['404_override'] = 'errors/show_404'; $route['404'] = 'errors/show_404'; $route['translate_uri_dashes'] = FALSE; <file_sep>/application/models/User_model.php <?php /** * Created by PhpStorm. * User: User * Date: 27/01/2020 * Time: 11:23 AM */ class User_model extends CI_Model { public function __construct() { parent::__construct(); } public function verify_user($user, $pass) { $account = $this->db->select('*') ->from('tbl_employee') ->where('username', $user) ->get() ->result(); if (!empty($account)) { $verified = password_verify($pass, $account[0]->password); if ($verified) { $role = $this->db->select('*,user_role') ->from('tbl_employee as employee') ->join('tbl_user_role as role', 'employee.user_role_id=role.user_role_id') ->where('username', $user) ->get() ->result(); return $role; } return false; } return false; } public function getUsers(){ $users = $this->db->select('*') ->from('tbl_employee as employee') ->join('tbl_loginsheet as loginsheet','employee.employee_id = loginsheet.staff_id') ->where('date between "' . $start_day . '" and "' . $end_day . '"') ->get() ->result(); // SELECT * FROM `tbl_user` as users join tbl_loginsheet as login on users.id=login.staff_id Where users.id= 307 return $users; } }<file_sep>/application/backup/Employee.php <?php /** * Created by PhpStorm. * User: User * Date: 27/01/2020 * Time: 4:32 PM */ class Employee extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper(array('url', 'html', 'form')); $this->load->library('pagination'); $this->load->library('session'); $this->load->database(); $this->load->helper('url'); $this->load->model('Attendance_model'); } public function dtr() { if (!empty($_POST)) { $month = $_POST['month']; $half_month = $_POST['half_month']; $year = $_POST['year']; $user_id = $_POST['user_id']; } else { $month = date('m', strtotime(date('y-m-dd'))); $year = date('y', strtotime(date('y-m-dd'))); $half_month = 'A'; if (date('d', strtotime(date('y-m-dd'))) > 15) { $half_month = 'B'; } $user_id = 0; } $start_day = $year . "-" . $month; $end_day = $start_day; if ($half_month == 'A') { $start_day .= '-01'; $end_day .= -'15'; } else { $start_day .= '-16'; $end_day .= '-' . date('t', strtotime($start_day)); } $days = array(); $month_name = date('F', strtotime($start_day)); $this->load->model('Attendance_model'); $this->load->model('Dbmodel'); $users = $this->dbmodel->getUsers(); $time_data = $this->attendance_model->getAttendance($user_id, $start_day, $end_day); $can_request_ot = $this->dbmodel->canRequestOVertime($_SESSION['user_id']); while (strtotime($start_day) <= strtotime($end_day)) { $day_num = date('d', strtotime($start_day)); $day_name = date('D', strtotime($start_day)); $start_day = date("Y-m-d", strtotime("+1 day", strtotime($start_day))); $days[] = array($day_num, $day_name); } foreach ($time_data as $time) { $time->morning_time = $this->getTimeDiff($time->morning_in_hour, $time->morning_in_minute, $time->morning_out_hour, $time->morning_out_minute); $time->afternoon_time = $this->getTimeDiff($time->afternoon_in_hour, $time->afternoon_in_minute, $time->afternoon_out_hour, $time->afternoon_out_minute); $time->over_time = $this->getTimeDiff($time->over_in_hour, $time->over_in_minute, $time->over_out_hour, $time->over_out_minute); } $data['request_ot'] =$can_request_ot; $data['page_load'] = 'employee/dtr'; $data['days'] = $days; $data['time'] = $time_data; $data['half_month'] = $half_month; $data['month'] = $month_name; $data['year'] = $year; $data['users'] = $users; $data['user_id'] = $user_id; $this->load->view('includes/template', $data); } public function requestOvertime() { if(!empty($_POST)){ $overtime = new stdClass(); $overtime->employee_id = $_SESSION['user_id']; $overtime->date_request = date('Y-m-d'); $overtime->reason = $_POST['reason']; $overtime->request_start_time= '05:00 PM'; $overtime->request_end_time ='10:00 PM'; $overtime->status = 'Pending'; $this->load->model('Dbmodel'); $this->DBModel->addOvertime($overtime); } redirect(base_url('employee/dtr')); } public function leave_requests() { $this->load->model('Dbmodel'); $leaves = $this->DBModel->getLeave($_SESSION['user_id']); $data['leaves'] = $leaves; $data['page_load'] = 'employee/leave_requests'; $this->load->view('includes/template', $data); } public function deleteLeave(){ if (!empty($_POST)) { $this->load->model('Dbmodel'); $this->DBModel->deleteLEave($_POST['leave_id']); } redirect(base_url('employee/leave_requests')); } public function updateLeaveRequest() { if (!empty($_POST)) { $this->load->model('Dbmodel'); $leave = new stdClass(); $leave->type = $_POST['leave_type']; $leave->request_start_time = $_POST['date_from']; $leave->request_duration = $_POST['date_to']; $this->DBModel->updateLeaveRequest($leave,$_POST['leave_id']); } redirect(base_url('employee/leave_requests')); } public function add_leave() { if (!empty($_POST)) { $leave = new stdClass(); $leave->employee_id = $_SESSION['user_id']; $leave->date_request = date('Y-m-d'); $leave->type = $_POST['leave_type']; $leave->request_start_time = $_POST['date_from']; $leave->request_duration = $_POST['date_to']; $leave->status = 'Pending'; $this->load->model('Dbmodel'); $this->DBModel->addLeave($leave); } redirect(base_url('employee/leave_requests')); // $this->leave_requests(); } public function payslip() { $data['page_load'] = 'employee/payslip'; $this->load->view('includes/template', $data); } public function getTimeDiff($start_hr, $start_mn, $end_hr, $end_mn) { if ($start_hr != null && $start_hr != null && $end_hr != null && $end_mn != null) { if ($start_hr == 12) { $start_hr = 1; $end_hr += 1; } $start_date = new DateTime($start_hr . ':' . $start_mn . ':00'); $end_date = new DateTime($end_hr . ':' . $end_mn . ':00'); $interval = $end_date->diff($start_date); $hours = $interval->format('%h'); $minutes = $interval->format('%i'); return round((($hours * 60 + $minutes) / 60), 2); } else { return null; } } }<file_sep>/application/views/admin/calendar2.php <?php /** * Created by PhpStorm. * User: capstonestudent * Date: 2/18/2020 * Time: 9:57 PM */ ?> <div class="container-fluid"> <!-- Page Heading --> <h1 class="h3 mb-3 text-gray-800"><strong>TDZ</strong> <i class="divider"> / </i> <span>Calendar</span></h1> <!-- DataTales Example --> <div class="card shadow mb-4 "style="height:70vh;"> <div class="card-body"> <div class="row " style="height: 100%"> <div class="col-xl-3 "> <div class="card border-left-primary h-100 py-2"> <div class="card-body"> <div class="row no-gutters align-items-center"> <div class="col mr-2"> <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Total Employees</div> <div class="h5 mb-0 font-weight-bold text-gray-800">10</div> </div> <div class="col-auto"> <i class="fas fa-calendar fa-2x text-gray-300"></i> </div> </div> </div> </div> </div> <div class="col-xl-9"> <div class="card border-left-success h-100 py-2"> <div class="card-body"> <div class="row no-gutters align-items-center"> <div class="col-sm-1"> <div class="text-xs font-weight-bold text-success text-uppercase mb-1">< </div> </div> <div class="col-sm-2"> <div class="text-xs font-weight-bold text-success text-uppercase mb-1"> Date </div> </div> <div class="col-sm-2"> <div class="text-xs font-weight-bold text-success text-uppercase mb-1">> </div> </div> </div> <div class="card shadow" style="height:95%;"> <div class="table-responsive"> <table class="table table-bordered" width="100%" cellspacing="0" > <thead> <tr > <th>Sunday</th> <th>Monday</th> <th>Tuesday</th> <th>Wednesday</th> <th>Thursday</th> <th>Friday</th> <th>Saturday</th> </tr> </thead> <tbody> <?php for($i=0;$i<5;$i++):?> <tr style="height: 4rem"> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> <td>6</td> <td>7 </td> </tr> <?php endfor;?> </tbody> </table> </div> </div> </div> </div> </div> </div> </div> </div> </div> <file_sep>/application/backup/Admin.php <?php /** * Created by PhpStorm. * User: User * Date: 27/01/2020 * Time: 4:32 PM */ class Admin extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('pagination', 'session'); $this->load->model("dbmodel"); } public function dashboard() { $data['page_load'] = "admin/dashboard"; $this->load->view('includes/template', $data); } public function dtr() { if (isset($_POST['month'])) { $month = $_POST['month']; $half_month = $_POST['half_month']; $year = $_POST['year']; $user_id = $_POST['user_id']; } else { $month = date('m', strtotime(date('y-m-dd'))); $year = date('y', strtotime(date('y-m-dd'))); $half_month = 'A'; if (date('d', strtotime(date('y-m-dd'))) > 15) { $half_month = 'B'; } $user_id = 0; } $start_day = $year . "-" . $month; $end_day = $start_day; if ($half_month == 'A') { $start_day .= '-01'; $end_day .= -'15'; } else { $start_day .= '-16'; $end_day .= '-' . date('t', strtotime($start_day)); } $days = array(); $month_name = date('F', strtotime($start_day)); $this->load->model('Attendance_model'); $users = $this->attendance_model->getUsers(); $time_data = $this->attendance_model->getAttendance($user_id, $start_day, $end_day); $holidays = $this->dbmodel->getHolidays($start_day, $end_day);//get the holidays for the specific payroll period $hol_day = array(); $hol_name = array(); foreach ($holidays as $hol) { $hol_day[] = substr($hol->date, -2); $hol_name [] = $hol->description; } while (strtotime($start_day) <= strtotime($end_day)) { $day_num = date('d', strtotime($start_day)); $day_name = date('D', strtotime($start_day)); $start_day = date("Y-m-d", strtotime("+1 day", strtotime($start_day))); $days[] = array($day_num, $day_name); } $dtrs = array(); $total_pre = 0; $total_ot = 0; $total_late = 0; foreach ($time_data as $time) { $time->morning_time = $this->getTimeDiff($time->morning_in_hour, $time->morning_in_minute, $time->morning_out_hour, $time->morning_out_minute); $time->afternoon_time = $this->getTimeDiff($time->afternoon_in_hour, $time->afternoon_in_minute, $time->afternoon_out_hour, $time->afternoon_out_minute); $time->over_time = $this->getTimeDiff($time->over_in_hour, $time->over_in_minute, $time->over_out_hour, $time->over_out_minute); $dtr = $time; $dtr->morning_time = $this->getTimeDiff($time->morning_in_hour, $time->morning_in_minute, $time->morning_out_hour, $time->morning_out_minute); $dtr->afternoon_time = $this->getTimeDiff($time->afternoon_in_hour, $time->afternoon_in_minute, $time->afternoon_out_hour, $time->afternoon_out_minute); $dtr->over_time = $this->getTimeDiff($time->over_in_hour, $time->over_in_minute, $time->over_out_hour, $time->over_out_minute); $com_time = $time->morning_time + $time->afternoon_time; $obj = $this->calculate_time($com_time); $dtr->pre_time = $obj->pre; $dtr->ot = $time->over_time + $obj->ot; $dtr->late = $obj->late; $dtrs[] = $dtr; $total_pre += $dtr->pre_time; $total_ot += $dtr->ot; $total_late = $dtr->late; } $data['page_load'] = 'admin/dtr'; $data['hol_day'] = $hol_day; $data['hol_name'] = $hol_name; $data['total_pre'] = $total_pre; $data['total_ot'] = $total_ot; $data['total_late'] = $total_late; $data['dtrs'] = $dtrs; $data['days'] = $days; $data['half_month'] = $half_month; $data['month'] = $month_name; $data['year'] = $year; $data['users'] = $users; $data['user_id'] = $user_id; $this->load->view('includes/template', $data); } public function overtime() { $this->load->model('Dbmodel'); $overtimes = $this->DBModel->getOverTimes(); $users = $this->DBModel->getEmployees(); $data['users'] = $users; $data['overtimes'] = $overtimes; $data['page_load'] = 'admin/overtime'; $this->load->view('includes/template', $data); } public function leave_requests() { $this->load->model('Dbmodel'); $leaves = $this->DBModel->getLeave($_SESSION['user_id']); $data['leaves'] = $leaves; $data['page_load'] = 'admin/leave_requests'; $this->load->view('includes/template', $data); } public function employees_leave_requests() { $this->load->model('Dbmodel'); $leaves = $this->DBModel->getLeaves(); $users = $this->DBModel->getEmployees(); $data['users'] = $users; $data['leaves'] = $leaves; $data['page_load'] = 'admin/employees_leave_requests'; $this->load->view('includes/template', $data); } public function schedule() { $this->load->model("Dbmodel"); $sched = $this->DBModel->get_schedule(); $data['sched'] = $sched; $data['page_load'] = 'admin/schedule'; $this->load->view('includes/template', $data); } public function employee_list() { $users = $this->DBModel->getEmployeeList(); $data['users'] = $users; $data['page_load'] = 'admin/employee_list'; $this->load->view('includes/template', $data); } public function position() { $data['page_load'] = 'admin/position'; $this->load->view('includes/template', $data); } public function payroll() { if (!empty($_POST)) { //getting user inputs $month = $_POST['month']; $half_month = $_POST['half_month']; $year = $_POST['year']; } else { //setting default values; $month = date('m', strtotime(date('y-m-dd'))); $year = date('y', strtotime(date('y-m-dd'))); $half_month = 'A'; if (date('d', strtotime(date('y-m-dd'))) > 15) { $half_month = 'B'; } } //setting the start and end of payroll period to be processed. $start_day = $year . "-" . $month; $end_day = $start_day; if ($half_month == 'A') { $start_day .= '-01'; $end_day .= -'15'; } else { $start_day .= '-16'; $end_day .= '-' . date('t', strtotime($start_day)); } //setting month name for the month dropdown in the view -> to be reconsidered $month_name = date('F', strtotime($start_day)); $users = $this->dbmodel->getUsers();// get all employees that are active $holidays = $this->dbmodel->getHolidays($start_day, $end_day);//get the holidays for the specific payroll period //this code if for checking if the given date is a holiday or not //really needs to be improved.. $hol_day = array(); $hol_type = array(); foreach ($holidays as $hol) { $hol_day[] = substr($hol->date, -2); $hol_type [] = $hol->type; } $payrolls = array(); foreach ($users as $user) { //getting DTR details for the payroll period $result = $this->dbmodel->getUserDTR($user->id, $start_day, $end_day); //creating another start_day and end_day variables to avoid overwriting the payroll period $start = date("Y-m-d", strtotime($start_day)); $end = date("Y-m-d", strtotime($end_day)); if (count($result) > 0) { $payrolls[] = $this->calculate_payroll($user, $result, $start, $end, $hol_day, $hol_type); } else { $payroll = new stdClass();//payroll object $payroll->id = $user->id; $payroll->name = $user->last_name . " " . $user->name; $payroll->monthly_rate = 10068.10;//to get from user data $payroll->daily_rate = round(($payroll->monthly_rate * 12) / 313, 2);//to get from user data // $payrolls[] = $payroll; } } $data['users'] = $users; $data['payrolls'] = $payrolls; $data['half_month'] = $half_month; $data['month'] = $month_name; $data['year'] = $year; $data['page_load'] = 'admin/payroll'; $this->load->view('includes/template', $data); } public function cashAdvance() { $users = $this->DBModel->getEmployees(); $cashAdvances = $this->DBModel->getCashAdvances(); $data['users'] = $users; $data['cashAdvances'] = $cashAdvances; $data['page_load'] = 'admin/cashAdvance'; $this->load->view('includes/template', $data); } public function attendance_report() { $data['page_load'] = 'admin/attendance_report'; $this->load->view('includes/template', $data); } public function payroll_report() { $data['page_load'] = 'admin/payroll_report'; $this->load->view('includes/template', $data); } function getTimeDiff($start_hr, $start_mn, $end_hr, $end_mn) { if ($start_hr != null && $start_hr != null && $end_hr != null && $end_mn != null) { if ($start_hr == 12) { $start_hr = 1; $end_hr += 1; } $start_date = new DateTime($start_hr . ':' . $start_mn . ':00'); $end_date = new DateTime($end_hr . ':' . $end_mn . ':00'); $interval = $end_date->diff($start_date); $hours = $interval->format('%h'); $minutes = $interval->format('%i'); return round((($hours * 60 + $minutes) / 60), 2); } else { return 0.0; } } function calculate_payroll($user, $time_data, $start, $end, $hol_day, $hol_type) { $payroll = new stdClass(); $payroll->id = $user->id; $payroll->name = $user->last_name . " " . $user->name; $payroll->monthly_rate = 12000;//to get from user data $payroll->daily_rate = round(($payroll->monthly_rate * 12) / 313, 2);//to get from user data $payroll->allowance = 0; $payroll->dtr_time = 0; $payroll->nor_ot = 0; $payroll->nor_ot_pay = 0; $payroll->res_sun = 0; $payroll->res_sun_pay = 0; $payroll->res_sun_ot = 0; $payroll->res_sun_ot_pay = 0; $payroll->res_reg_hol = 0; $payroll->res_reg_hol_pay = 0; $payroll->res_reg_hol_ot = 0; $payroll->res_reg_hol_ot_pay = 0; $payroll->res_dob_hol = 0; $payroll->res_dob_hol_pay = 0; $payroll->res_dob_hol_ot = 0; $payroll->res_dob_hol_ot_pay = 0; $payroll->res_spe_hol = 0; $payroll->res_spe_hol_pay = 0; $payroll->res_spe_hol_ot = 0; $payroll->res_spe_hol_ot_pay = 0; $payroll->reg_hol = 0; $payroll->reg_hol_pay = 0; $payroll->reg_hol_ot = 0; $payroll->reg_hol_ot_pay = 0; $payroll->dob_hol = 0; $payroll->dob_hol_pay = 0; $payroll->dob_hol_ot = 0; $payroll->dob_hol_ot_pay = 0; $payroll->spe_hol = 0; $payroll->spe_hol_pay = 0; $payroll->spe_hol_ot = 0; $payroll->spe_hol_ot_pay = 0; $payroll->absent = 0; $payroll->late = 0; $payroll->total_ot = 0; $count = 0; $total_ot = 0; $total_res_ot_pay = 0; $total_hol_ot_pay = 0; $total_res_pay = 0; $total_hol_pay = 0; // echo "<br/>"; while (strtotime($start) <= strtotime($end)) { $a = date('d', strtotime($start)); $b = date('d', strtotime($time_data[$count]->date)); $name = date('D', strtotime($start)); // echo "<br/>"; // echo $a." ".$b; if ($a == $b) { $morning_time = $this->getTimeDiff($time_data[$count]->morning_in_hour, $time_data[$count]->morning_in_minute, $time_data[$count]->morning_out_hour, $time_data[$count]->morning_out_minute); $afternoon_time = $this->getTimeDiff($time_data[$count]->afternoon_in_hour, $time_data[$count]->afternoon_in_minute, $time_data[$count]->afternoon_out_hour, $time_data[$count]->afternoon_out_minute); $over_time = $this->getTimeDiff($time_data[$count]->over_in_hour, $time_data[$count]->over_in_minute, $time_data[$count]->over_out_hour, $time_data[$count]->over_out_minute); $com_time = $morning_time + $afternoon_time; $obj = $this->calculate_time($com_time); $obj->ot += $over_time; $total_ot += $over_time + $obj->ot; $payroll->late += $obj->late; //still need to get the list of holidays in order to proceed if ($name == "Sun") { if (in_array($a, $hol_day)) { $ndx = array_search($a, $hol_day); switch ($hol_type[$ndx]) { case 'Regular': $payroll->res_reg_hol += $obj->pre; $payroll->res_reg_hol_ot += $obj->ot; $payroll->res_reg_hol_pay += ($payroll->daily_rate * (260 / 100)) * ($obj->pre / 8); $payroll->res_reg_hol_ot_pay += (($payroll->daily_rate / 8) * 3.38) * $obj->ot; $total_res_pay += ($payroll->daily_rate * (260 / 100)) * ($obj->pre / 8); $total_res_ot_pay += (($payroll->daily_rate / 8) * 3.38) * $obj->ot; echo "REGULAR"; break; case 'Double': $payroll->res_dob_hol += $obj->pre; $payroll->res_dob_hol_ot += $obj->ot; $payroll->res_dob_hol_pay += ($payroll->daily_rate * (390 / 100)) * ($obj->pre / 8); $payroll->res_dob_hol_ot_pay += (($payroll->daily_rate / 8) * 5.07) * $obj->ot; $total_res_pay += ($payroll->daily_rate * (390 / 100)) * ($obj->pre / 8); $total_res_ot_pay += (($payroll->daily_rate / 8) * 5.07) * $obj->ot; break; case 'Special': $payroll->res_spe_hol += $obj->pre; $payroll->res_spe_hol_ot += $obj->ot; $payroll->res_spe_hol_pay += ($payroll->daily_rate * (150 / 100)) * ($obj->pre / 8); $payroll->res_spe_hol_ot_pay += (($user->daily_rate / 8) * 1.95) * $obj->ot; $total_res_pay += ($payroll->daily_rate * (150 / 100)) * ($obj->pre / 8); $total_res_ot_pay += (($user->daily_rate / 8) * 1.95) * $obj->ot; break; } } else { $payroll->res_sun += $obj->pre; $payroll->res_sun_pay += ($payroll->daily_rate * (130 / 100)) * ($obj->pre / 8); $payroll->res_sun_ot += $obj->ot; $payroll->res_sun_ot_pay += (($payroll->daily_rate / 8) * 1.69) * $obj->ot; $total_res_pay += ($payroll->daily_rate * (130 / 100)) * ($obj->pre / 8); $total_res_ot_pay += (($payroll->daily_rate / 8) * 1.69) * $obj->ot; } } else { if (in_array($a, $hol_day)) { $ndx = array_search($a, $hol_day); switch ($hol_type[$ndx]) { case 'Regular': $payroll->reg_hol += $obj->pre; $payroll->reg_hol_ot += $obj->ot; $payroll->reg_hol_pay += ($payroll->daily_rate * (200 / 100)) * ($obj->pre / 8); $payroll->reg_hol_ot_pay += (($payroll->daily_rate / 8) * 2.6) * $obj->ot; $total_hol_pay += ($payroll->daily_rate * (200 / 100)) * ($obj->pre / 8); $total_hol_ot_pay += (($payroll->daily_rate / 8) * 2.6) * $obj->ot; break; case 'Double': $payroll->dob_hol += $obj->pre; $payroll->dob_hol_ot += $obj->ot; $payroll->dob_hol_pay += ($payroll->daily_rate * (300 / 100)) * ($obj->pre / 8); $payroll->dob_hol_ot_pay += (($payroll->daily_rate / 8) * 3.9) * $obj->ot; $total_hol_pay += ($payroll->daily_rate * (300 / 100)) * ($obj->pre / 8); $total_hol_ot_pay += (($payroll->daily_rate / 8) * 3.9) * $obj->ot; break; case 'Special': $payroll->spe_hol += $obj->pre; $payroll->spe_hol_ot += $obj->ot; $payroll->spe_hol_pay += ($payroll->daily_rate * (130 / 100)) * ($obj->pre / 8); $payroll->spe_hol_ot_pay += (($payroll->daily_rate / 8) * 1.69) * $obj->ot; $total_hol_pay += ($payroll->daily_rate * (130 / 100)) * ($obj->pre / 8); $total_hol_ot_pay += (($payroll->daily_rate / 8) * 1.69) * $obj->ot; break; } } else { $payroll->dtr_time += $obj->pre; $payroll->nor_ot += $obj->ot; $payroll->nor_ot_pay += (($payroll->daily_rate / 8) * 1.25) * $obj->ot; } } if ($count < count($time_data) - 1) { $count++; } } elseif ($name != "Sun") { $payroll->absent++; } $start = date("Y-m-d", strtotime("+1 day", strtotime($start))); } $absent_pay = $payroll->daily_rate * $payroll->absent; $late_pay = ($payroll->daily_rate / 8) * ($payroll->late / 60); $payroll->basic_salary = ($payroll->monthly_rate / 2) - ($absent_pay + $late_pay); $payroll->total_ot = $total_ot; $payroll->gross_pay = $total_res_ot_pay + $total_hol_ot_pay + $total_res_pay + $total_hol_pay + $payroll->nor_ot_pay + $payroll->basic_salary; $payroll->pagibig_con = ($payroll->monthly_rate * .02) / 2; $payroll->philhealth_con = (($payroll->monthly_rate / 2) * (2.75 / 100)) / 2; $payroll->sss_con = 0; $payroll->cash_advance = 0; $payroll->sss_loan = 0; $payroll->pagibib_loan = 0; $payroll->other_deductions = 0; $payroll->total_deductions = $payroll->pagibig_con + $payroll->sss_con + $payroll->philhealth_con + $payroll->cash_advance + $payroll->sss_loan + $payroll->pagibib_loan + $payroll->other_deductions; $payroll->net_pay = $payroll->gross_pay - $payroll->total_deductions; return $payroll; } function calculate_time($time) { $obj = new stdClass(); $obj->late = 0; $obj->ot = 0; if ($time > 8) { $obj->pre = 8; $obj->ot = $time - 8; } else { $obj->pre = $time; $obj->late = 8 - $time; } return $obj; } public function add_leave() { if (!empty($_POST)) { $leave = new stdClass(); $leave->employee_id = $_SESSION['user_id']; $leave->date_request = date('Y-m-d'); $leave->type = $_POST['leave_type']; $leave->request_start_time = $_POST['date_from']; $leave->request_duration = $_POST['date_to']; $leave->status = 'Pending'; $this->load->model('Dbmodel'); $this->DBModel->addLeave($leave); } redirect(base_url('admin/leave_requests')); // $this->leave_requests(); } public function addEmployeeleave() { if (!empty($_POST)) { $leave = new stdClass(); $leave->employee_id = $_POST['user_id']; $leave->date_request = date('Y-m-d'); $leave->type = $_POST['leave_type']; $leave->request_start_time = $_POST['date_from']; $leave->request_duration = $_POST['date_to']; $leave->status = 'Pending'; $this->load->model('Dbmodel'); $this->DBModel->addLeave($leave); } redirect(base_url('admin/employees_leave_requests')); // $this->leave_requests(); } public function updateLeaveStatus() { if (!empty($_POST)) { $this->load->model('Dbmodel'); $this->DBModel->updateLeaveStatus($_POST['leave_id'], $_POST['status']); } redirect(base_url('admin/employees_leave_requests')); } public function updateLeaveRequest() { if (!empty($_POST)) { $this->load->model('Dbmodel'); $leave = new stdClass(); $leave->type = $_POST['leave_type']; $leave->request_start_time = $_POST['date_from']; $leave->request_duration = $_POST['date_to']; $this->DBModel->updateLeaveRequest($leave, $_POST['leave_id']); } redirect(base_url('admin/leave_requests')); } public function deleteLeave() { if (!empty($_POST)) { $this->load->model('Dbmodel'); $this->DBModel->deleteLEave($_POST['leave_id']); } redirect(base_url('admin/leave_requests')); } public function updateOvertimeStatus() { if (!empty($_POST)) { $this->load->model('Dbmodel'); $this->DBModel->updateOvertimeStatus($_POST['overtime_id'], $_POST['status']); echo "hala"; } else { echo "hala"; } redirect(base_url('admin/overtime')); } public function requestOvertime() { if (!empty($_POST)) { $overtime = new stdClass(); $overtime->employee_id = $_SESSION['user_id']; $overtime->date_request = date('Y-m-d'); $overtime->reason = $_POST['reason']; $overtime->request_start_time = '05:00 PM'; $overtime->request_end_time = '10:00 PM'; $overtime->status = 'Pending'; $this->load->model('Dbmodel'); $this->DBModel->addOvertime($overtime); } redirect(base_url('admin/overtime')); } public function add_schedule() { if (!empty($_POST)) { $timein = date('h:m A', strtotime($_POST['time-in'])); $timeout = date('h:m A', strtotime($_POST['time-out'])); date('h:m A', strtotime($timein)); $this->load->model('Dbmodel'); $this->DBModel->schedule_insert($timein, $timeout); } redirect(base_url('admin/schedule')); } public function scheduleUpdate() { $this->load->model('Dbmodel'); if (!empty($_POST)) { $timein = date('h:m A', strtotime($_POST['time-in'])); $timeout = date('h:m A', strtotime($_POST['time-out'])); $sched_id = $_POST['sched-id']; date('h:m A', strtotime($timein)); var_dump($sched_id); $this->load->model('Dbmodel'); $sched = new stdClass(); $sched->time_in = $timein; $sched->time_out = $timeout; $sched->date_modified = date('Y-m-d'); $this->DBModel->update_schedule($sched_id, $sched); } redirect(base_url('admin/schedule')); } public function scheduleDelete() { if (!empty($_POST)) { $this->load->model('Dbmodel'); $id = $_POST['sched']; $this->DBModel->delete_schedule($id); } redirect(base_url('admin/schedule')); } public function calendar() { $page_load = "admin/calendar2"; $data['page_load'] = $page_load; $this->load->view('includes/template', $data); } public function addCashAdvance() { if (!empty($_POST)) { $cash = new stdClass(); $cash->employee_id = $_POST['user_id']; $cash->date_Advance = date('Y-m-d'); $cash->amount = $_POST['amount']; $cash->repay_amount = $_POST['repay_amount']; $cash->purpose = $_POST['purpose']; $cash->date_modified = date('Y-m-d'); $cash->status = "Unpaid"; $cash->balance = $_POST['amount']; $this->load->model('Dbmodel'); $this->DBModel->addCashAdvance($cash); } redirect(base_url('admin/cashAdvance')); } public function updateCashAdvance() { if (!empty($_POST)) { $cash = new stdClass(); $cash->amount = $_POST['amount']; $cash->repay_amount = $_POST['repay_amount']; $this->load->model('Dbmodel'); $this->DBModel->updateCashAdvance($cash, $_POST['cash_id']); } redirect(base_url('admin/cashAdvance')); } public function editEmployee() { redirect(base_url('admin/employee_list')); } }<file_sep>/application/backup/payroll_master/position.php <link href="<?=base_url()?>assets/css/custom.css" rel="stylesheet"> <link href="../assets/css/custom.css" rel="stylesheet"> <div class="container-fluid"> <h1 class="h3 mb-3 text-gray-800"><strong>TDZ</strong> <i class="divider"> / </i> <span>Position</span></h1> <div class="card shadow mb-4"> <div class="card-header py-3"> <input type="button" class="btn btn-facebook" value="Add Position" data-toggle="modal" data-target="#addPosition"> </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable"> <thead> <tr> <td class="text_center">Position</td> <td class="text_center">Wage</td> <td class="text_center">Schedule</td> <td class="text_center">Tools</td> </tr> </thead> <tbody> <tr class="text_center"> <td>Programmer</td> <td>16, 000</td> <td>8:00 AM- 5:00PM</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#positionEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#positionDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr class="text_center"> <td>Programmer</td> <td>16, 000</td> <td>8:00 AM- 5:00PM</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#positionEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#positionDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr class="text_center"> <td>Programmer</td> <td>16, 000</td> <td>8:00 AM- 5:00PM</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#positionEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#positionDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr class="text_center"> <td>Programmer</td> <td>16, 000</td> <td>8:00 AM- 5:00PM</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#positionEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#positionDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr class="text_center"> <td>Programmer</td> <td>16, 000</td> <td>8:00 AM- 5:00PM</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#positionEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#positionDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr class="text_center"> <td>Programmer</td> <td>16, 000</td> <td>8:00 AM- 5:00PM</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#positionEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#positionDelete">&nbsp;&nbsp;Delete</i> </td> </tr> </tbody> </table> </div> </div> </div> <!--Modal for Adding Schedule--> <!-- Modal --> <div class="modal fade" id="addPosition" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Add Position</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action=""> <div class="form-group row"> <label for="posTitle" class="col-sm-5 col-form-label">Position Title</label> <div class="col-sm-5"> <input type="text" class="form-control" id="posTitle"> </div> </div> <div class="form-group row"> <label for="rph" class="col-sm-5 col-form-label">Wage</label> <div class="col-sm-5"> <input type="text" class="form-control" id="rph"> </div> </div> <div class="form-group row"> <label for="sched" class="col-sm-5 col-form-label">Schedule</label> <div class="col-sm-5"> <input type="text" class="form-control" id="sched"> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Add Position</button> </div> </div> </div> </div> <!-- Edit Modal --> <div class="modal fade" id="positionEdit" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Edit Position</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action=""> <div class="form-group row"> <label for="posTitle" class="col-sm-5 col-form-label">Position Title</label> <div class="col-sm-5"> <input type="text" class="form-control" id="posTitle"> </div> </div> <div class="form-group row"> <label for="rph" class="col-sm-5 col-form-label">Wage</label> <div class="col-sm-5"> <input type="text" class="form-control" id="rph"> </div> </div> <div class="form-group row"> <label for="sched" class="col-sm-5 col-form-label">Schedule</label> <div class="col-sm-5"> <input type="text" class="form-control" id="sched"> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save</button> </div> </div> </div> </div> <!-- Modal for delete--> <div class="modal fade" id="positionDelete" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Delete Schedule</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p class="text_center">Are you sure you want to delete this schedule?</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">No</button> <button type="button" class="btn btn-primary">Yes</button> </div> </div> </div> </div> </div> <file_sep>/application/views/includes/modals/add/add_cash_modal.php <?php /** * Created by PhpStorm. * User: capstonestudent * Date: 2/19/2020 * Time: 2:47 AM */?> <div class="modal fade" id="addCashAdvance" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Add Cash Advance</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="add-cash-advance" method="post" id="cash"> <div class="form-group row"> <label for="empName" class="col-sm-4 col-form-label text-right">Employee Name</label> <div class="col-sm-8"> <select name="user_id" id="month" class="input input-sm monthName form-control" style="width: 100%;padding: 5px"> <?php foreach ($users as $user): ?> <option value="<?= $user->employee_id; ?>"><?= strtoupper($user->lastname . " " . $user->firstname); ?></option> <?php endforeach; ?> </select>&nbsp;&nbsp; </div> </div> <div class="form-group row"> <label for="amount" class="col-sm-4 col-form-label text-right">Requested Amount</label> <div class="col-sm-8"> <input type="number" class="form-control" min="0" name="amount" id="amount" required> </div> </div> <div class="form-group row"> <label for="balance" class="col-sm-4 col-form-label text-right">Repayment Amount Every Payroll </label> <div class="col-sm-8"> <input type="number" class="form-control" name="repay_amount" required> </div> </div> <div class="form-group row"> <label for="balance" class="col-sm-4 col-form-label text-right">Purpose</label> <div class="col-sm-8"> <textarea rows="3" class="form-control" name="purpose" form="cash" placeholder="Purpose..." required></textarea> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Add</button> </div> </form> </div> </div> </div> </div> <file_sep>/application/models/Holiday_model.php <?php /** * Created by PhpStorm. * User: User * Date: 05/02/2020 * Time: 9:25 PM */ class Holiday_model extends CI_Model { public function __construct() { parent::__construct(); } public function get_holidays($start_day, $end_day) { $result = $this->db->select('*') ->from('tbl_holiday') ->where('date between "' . $start_day . '" and "' . $end_day . '"') ->get() ->result(); return $result; } }<file_sep>/application/views/includes/scripts.php <?php /** * Created by PhpStorm. * User: <NAME> * Date: 1/15/2020 * Time: 2:59 PM */ ?> <!-- Bootstrap core JavaScript--> <!--<script src="--><?//= base_url(); ?><!--assets/vendor/jquery/jquery.min.js"></script>--> <!--<script src="--><?//= base_url(); ?><!--assets/vendor/jquery/jquery.floatThead.min.js"></script>--> <!--<script src="--><?//= base_url(); ?><!--assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>--> <!--<script src="--><?//= base_url(); ?><!--assets/vendor/jquery-easing/jquery.easing.min.js"></script>--> <!--<script src="--><?//= base_url(); ?><!--assets/js/sb-admin-2.min.js"></script>--> <!--<script src="--><?//= base_url(); ?><!--assets/vendor/datatables/jquery.dataTables.min.js"></script>--> <!--<script src="--><?//= base_url(); ?><!--assets/vendor/datatables/dataTables.bootstrap4.min.js"></script>--> <!--<script src="--><?//= base_url(); ?><!--assets/vendor/chart.js/Chart.min.js"></script>--> <!--<script src="--><?//= base_url(); ?><!--assets/js/demo/datatables-demo.js"></script>--> <!--<!--<script src="-->--><?////= base_url(); ?><!--<!--assets/js/demo/chart-area-demo.js"></script>-->--> <!--<!--<script src="-->--><?////= base_url(); ?><!--<!--assets/js/demo/chart-pie-demo.js"></script>-->--> <!--<!--<script src="-->--><?////= base_url(); ?><!--<!--assets/js/demo/chart-bar-demo.js"></script>-->--> <!--<script src="--><?//= base_url(); ?><!--assets/toastr/toastr.min.js"></script>--> <!--<script src="assets/js/jquery.fixedheadertable.min.js"></script>--> <script type="text/javascript"> $(document).ready(function () { $('[data-toggle="tooltip"]').tooltip(); }); toastr.options = { preventDuplicate: true, positionClass: 'toast-bottom-center', showDuration: 300, hideDuration: 1000, timeOut: 5000, extendedTimeOut: 1000, closeButton: true, progressBar: true, }; </script> <file_sep>/application/libraries/zklib/cron.php <?php /** * Created by PhpStorm. * User: User * Date: 09/03/2020 * Time: 7:04 PM */ include "Crontroller.php"; $cron = new Crontroller(); $cron->connect(); <file_sep>/application/backup/payroll_master/dtr.php <link href="../../../assets/css/custom.css" rel="stylesheet"> <link href="../assets/css/custom.css" rel="stylesheet"> <div class="container-fluid"> <!-- <h1 class="h3 mb-4 text-gray-800">Attendance - TODO ( Mariel) </h1>--> <h1 class="h3 mb-3 text-gray-800"><strong>TDZ</strong> <i class="divider"> / </i> <span>Daily Time Record</span> </h1> <!-- DataTales Example --> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary"><strong>TDZ</strong> <i class="divider"> / </i> <span>Daily Time Record</span> </h6> </div> <div class="card-body"> <div class="sec_head"> <div class="row"> <div class="col-md-6"> <form action="dtr" method="post"> <label for="half_month">Filter: </label>&nbsp;&nbsp;&nbsp; <select name="half_month" id="half_month" class="input input-sm half_month"> <option value="A" <?= ($half_month == 'A' ? 'selected' : ''); ?>>A</option> <option value="B" <?= ($half_month == 'B' ? 'selected' : '') ?>>B</option> </select>&nbsp;&nbsp; <select name="month" id="month" class="input input-sm monthName"> <option value="01" <?= ($month == 'January' ? 'selected' : '') ?>>January</option> <option value="02" <?= ($month == 'February' ? 'selected' : '') ?>>February</option> <option value="03" <?= ($month == 'March' ? 'selected' : '') ?>>March</option> <option value="04" <?= ($month == 'April' ? 'selected' : '') ?>>April</option> <option value="05" <?= ($month == 'May' ? 'selected' : '') ?>>May</option> <option value="06" <?= ($month == 'June' ? 'selected' : '') ?>>June</option> <option value="07" <?= ($month == 'July' ? 'selected' : '') ?>>July</option> <option value="08" <?= ($month == 'August' ? 'selected' : '') ?>>August</option> <option value="09" <?= ($month == 'September' ? 'selected' : '') ?>>September</option> <option value="10" <?= ($month == 'October' ? 'selected' : '') ?>>October</option> <option value="11" <?= ($month == 'November' ? 'selected' : '') ?>>November</option> <option value="12" <?= ($month == 'December' ? 'selected' : '') ?>>December</option> </select>&nbsp;&nbsp; <select name="year" id="year" class="input input-sm year"> <option value="2020" <?= ($year == '2020' ? 'selected' : '') ?>>2020</option> <option value="2019" <?= ($year == '2019' ? 'selected' : '') ?>>2019</option> <option value="2018" <?= ($year == '2018' ? 'selected' : '') ?>>2018</option> <option value="2017" <?= ($year == '2017' ? 'selected' : '') ?>>2017</option> <option value="2016" <?= ($year == '2016' ? 'selected' : '') ?>>2016</option> <option value="2015" <?= ($year == '2015' ? 'selected' : '') ?>>2015</option> <option value="2014" <?= ($year == '2014' ? 'selected' : '') ?>>2014</option> <option value="2013" <?= ($year == '2013' ? 'selected' : '') ?>>2013</option> <option value="2012" <?= ($year == '2012' ? 'selected' : '') ?>>2012</option> </select>&nbsp;&nbsp; <select name="user_id" id="name" class="input input-sm empName"> <?php foreach ($users as $user) { ?> <option value="<?= $user->id ?>" <?=($user->id==$user_id ? 'selected':'')?> ><?= $user->last_name . ' ' . $user->name ?></option> <?php } ?> </select>&nbsp;&nbsp; <button type="submit" class="btn btn-sm btn-primary">GO</button> </form> </div> <span class="date_time"> <span class="time"> <span class="iconn"><i class="fa fa-clock icon">&nbsp;&nbsp;&nbsp;</i>Time: </span> </span> <span class="iconn"><i class="fa fa-calendar icon">&nbsp;&nbsp;&nbsp;</i>Date: </span> </span> </div> </div> <div class="details iconn"> <div class="rh tb_rh text_center"> <span class="show_leave_details">Leave: <span class="text-primary">___</span> <div style="display: none;"> <span class="width-200"></span> </div> </span>&nbsp;&nbsp;&nbsp; <span class="show_absent">Absent: <span class="text-primary">___</span> <div style="display: none;"> <span class="width-200"></span> </div> </span>&nbsp;&nbsp;&nbsp; <span >Over Time: <span class="text-primary">___</span> <div style="display: none"> <span class="width-200"></span> </div> </span>&nbsp;&nbsp;&nbsp; <span>Under Time: <span class="text-primary">___</span> <div style="display: none"> <span class="width-200"></span> </div> </span>&nbsp;&nbsp;&nbsp; <span>Late: <span class="text-primary">___</span> <div style="display: none"> <span class="width-200"></span> </div> </span> </div> </div> <div class="table-responsive"> <table id="attendance" class="table table-sm table-bordered"> <thead> <tr> <th colspan="2" class=" text_center border-left">Half-Month</th> <th colspan="2" class="text_center">Morning</th> <th class="width1"></th> <th colspan="2" class="text_center">Afternoon</th> <th class="width1"></th> <th colspan="2" class="text_center">OverTime</th> <th class="width1"></th> <th colspan="3" class="text_center border-right">Total Time</th> </tr> <tr class=""> <td class="width1 no_hover" colspan="2">Days</td> <td class="width1 no_hover">In</td> <td class="width1 no_hover">Out</td> <td class="width1 no_hover">Time</td> <td class="width1 no_hover">In</td> <td class="width1 no_hover">Out</td> <td class="width1 no_hover">Time</td> <td class="width1 no_hover">In</td> <td class="width1 no_hover">Out</td> <td class="width1 no_hover tc" title="Time Convention" data-toggle='tooltip' data-container='body'>TC </td> <td class="width1 no_hover">Time</td> <td class="width1 no_hover">Pre</td> <td class="width1 no_hover">OT</td> <td class="width1 no_hover">Late</td> </tr> </thead> <tbody> <?php $j = 0;$total_time = 0; $total_ot=0?> <?php $i;for ($i = 0;$i < count($days); $i++): ?> <tr class=" <?=($days[$i][1]=='Sun'? 'sunday':'')?>"> <td width="40"><?= $days[$i][0] ?></td> <td width="40"><?= $days[$i][1] ?></td> <?php if(count($time)==0||$j==-1 || $days[$i][1]=='Sun'):?> <td align="center"> <input value="" style="width: 30px;text-align: center;border: 0">: <input value="" style="width: 30px;text-align: center;border: 0"> </td> <td align="center"> <input value="" style="width: 30px;text-align: center;border: 0">: <input value="" style="width: 30px;text-align: center;border: 0"> </td> <td class="text_center"></td> <td align="center"> <input value="" style="width: 30px;text-align: center;border: 0">: <input value="" style="width: 30px;text-align: center;border: 0"> </td> <td align="center"> <input value="" style="width: 30px;text-align: center;border: 0">: <input value="" style="width: 30px;text-align: center;border: 0"> </td> <td class="text_center"></td> <td align="center"> <input value="" style="width: 30px;text-align: center;border: 0">: <input value="" style="width: 30px;text-align: center;border: 0"> </td> <td align="center"> <input value="" style="width: 30px;text-align: center;border: 0">: <input value="" style="width: 30px;text-align: center;border: 0"> </td> <td class="text_center"></td> <td class="text_center"></td> <td class="text_center"></td> <td class="text_center"></td> <?php elseif ($days[$i][0] == date('d', strtotime($time[$j]->date))) :?> <td align="center"> <input value="<?= ($time[$j]->morning_in_hour ?? ''); ?>" style="width: 30px;text-align: center;border: 0">: <input value="<?= ($time[$j]->morning_in_minute ??''); ?>" style="width: 30px;text-align: center;border: 0"> </td> <td align="center"> <input value="<?= ($time[$j]->morning_out_hour ?? ''); ?>" style="width: 30px;text-align: center;border: 0">: <input value="<?= ($time[$j]->morning_out_minute ?? ''); ?>" style="width: 30px;text-align: center;border: 0"> </td> <td class="text_center"><?=($time[$j]->morning_time??'')?> </td> <td align="center"> <input value="<?= $time[$j]->afternoon_in_hour; ?>" style="width: 30px;text-align: center;border: 0">: <input value="<?= $time[$j]->afternoon_in_minute; ?>" style="width: 30px;text-align: center;border: 0"> </td> <td align="center"> <input value="<?= $time[$j]->afternoon_out_hour; ?>" style="width: 30px;text-align: center;border: 0">: <input value="<?= $time[$j]->afternoon_out_minute; ?>" style="width: 30px;text-align: center;border: 0"> </td> <td class="text_center"><?=($time[$j]->afternoon_time??'')?> </td> <td align="center"> <input value="<?= $time[$j]->over_in_hour; ?>" style="width: 30px;text-align: center;border: 0">: <input value="<?= $time[$j]->over_in_minute; ?>" style="width: 30px;text-align: center;border: 0"> </td> <td align="center"> <input value="<?= $time[$j]->over_out_hour; ?>" style="width: 30px;text-align: center;border: 0">: <input value="<?= $time[$j]->over_out_minute; ?>" style="width: 30px;text-align: center;border: 0"> </td> <td class="text_center"> <td class="text_center"> <?php if($time[$j]->afternoon_time!=null&&$time[$j]->morning_time!=null){}{ $pre = $time[$j]->afternoon_time+$time[$j]->morning_time; if($pre>=8){ echo '8'; $total_time +=8; }else if($pre>0){ echo $pre; $total_time+=$pre; } } ?> </td> <td class="text_center"> <?php if($time[$j]->afternoon_time!=null&&$time[$j]->morning_time!=null){}{ $pre = $time[$j]->afternoon_time+$time[$j]->morning_time; if($pre>=8){ $pre-=8; echo $pre+$time[$j]->over_time; $total_ot +=$pre+$time[$j]->over_time; } } ?> </td> <td class="text_center"> <!-- --><?php // if($time[$j]->afternoon_time!=null&&$time[$j]->morning_time!=null){}{ // $pre = $time[$j]->afternoon_time+$time[$j]->morning_time; // if($pre<8){ // $pre-=8; // echo round(abs($pre)); // } // } // ?> </td> <?php ($j < count($time) - 1 ? $j++ : $j = -1)?> <?php elseif($days[$i][1]!='Sun'):?> <td class="text_center absent" colspan="12">ABSENT</td> <?php endif; endfor;?> </tr> <tr> <td style="text-align: right" colspan="11">Total Time:</td> <td class="text_center"><?=$total_time?></td> <td class="text_center"><?=$total_ot?></td> <td class="text_center"></td> </tr> </tbody> </table> </div> </div> </div> </div><file_sep>/application/views/admin/payroll.php <?php /** * Created by PhpStorm. * User: <NAME> * Date: 1/16/2020 * Time: 10:45 AM */ ?> <style id="compiled-css" type="text/css"> /* CSS overrides for JQuery UI theme */ /* General table formatting */ table { border-collapse: collapse; border-spacing: 0px; } th { border: 1px solid black; text-align: left; padding: 5px; background-color: #5C9CCC; color: #ffffff; } .basic-table td { border: 1px solid black; padding: 5px; white-space: nowrap!important;s } .compact-table td { padding-top: 1px; padding-right: 7px; padding-bottom: 1px; padding-left: 7px; } .row-selectable-table > tbody > tr:hover { background-color: #6CACDC; color: white; cursor: pointer; } #prod-list > tbody > tr:hover { cursor: default; } #wages-table-container { /* Fixed header tables */ max-height: 70vh; overflow-y: scroll; } </style> <div class="container-fluid "> <div class="card shadow mb-4 "> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary">Payroll</h6> </div> <div class="card-body"> <form action="payroll" method="post"> <label for="half_month">Filter: </label>&nbsp;&nbsp;&nbsp; <select name="half_month" id="half_month" class="input input-sm half_month"> <option value="A" <?= ($half_month == 'A' ? 'selected' : ''); ?>>A</option> <option value="B" <?= ($half_month == 'B' ? 'selected' : '') ?>>B</option> </select>&nbsp;&nbsp; <select name="month" id="month" class="input input-sm monthName"> <option value="01" <?= ($month == 'January' ? 'selected' : '') ?>>January</option> <option value="02" <?= ($month == 'February' ? 'selected' : '') ?>>February</option> <option value="03" <?= ($month == 'March' ? 'selected' : '') ?>>March</option> <option value="04" <?= ($month == 'April' ? 'selected' : '') ?>>April</option> <option value="05" <?= ($month == 'May' ? 'selected' : '') ?>>May</option> <option value="06" <?= ($month == 'June' ? 'selected' : '') ?>>June</option> <option value="07" <?= ($month == 'July' ? 'selected' : '') ?>>July</option> <option value="08" <?= ($month == 'August' ? 'selected' : '') ?>>August</option> <option value="09" <?= ($month == 'September' ? 'selected' : '') ?>>September</option> <option value="10" <?= ($month == 'October' ? 'selected' : '') ?>>October</option> <option value="11" <?= ($month == 'November' ? 'selected' : '') ?>>November</option> <option value="12" <?= ($month == 'December' ? 'selected' : '') ?>>December</option> </select>&nbsp;&nbsp; <select name="year" id="year" class="input input-sm year"> <option value="2020" <?= ($year == '2020' ? 'selected' : '') ?>>2020</option> <option value="2019" <?= ($year == '2019' ? 'selected' : '') ?>>2019</option> <option value="2018" <?= ($year == '2018' ? 'selected' : '') ?>>2018</option> <option value="2017" <?= ($year == '2017' ? 'selected' : '') ?>>2017</option> <option value="2016" <?= ($year == '2016' ? 'selected' : '') ?>>2016</option> <option value="2015" <?= ($year == '2015' ? 'selected' : '') ?>>2015</option> <option value="2014" <?= ($year == '2014' ? 'selected' : '') ?>>2014</option> <option value="2013" <?= ($year == '2013' ? 'selected' : '') ?>>2013</option> <option value="2012" <?= ($year == '2012' ? 'selected' : '') ?>>2012</option> </select>&nbsp;&nbsp; <button type="submit" class="btn btn-sm btn-primary">GENERATE</button> </form> </div> <div class="card-body"> <div id="wages-table-container"> <table id="prod-list" style="white-space: nowrap" class="row-selectable-table basic-table compact-table" width="100%"> <div> <thead> <tr style="vertical-align:middle;"> <th rowspan="2" class="align-middle">No.</span></th> <th>Employee</th> <th>Daily</th> <th>Monthly</th> <th>DTR</th> <th># Day(s)</th> <th rowspan="2"class="align-middle">Late(min)</th> <th>Basic </th> <th rowspan="2"class="align-middle">Allowance</th> <th colspan="2"class="align-middle">Normal Day Overtime</th> <th colspan="8"class="align-middle text-center" >Rest Day and Sunday Holiday Overtime</th> <th colspan="4"class="align-middle text-center" >Rest Day and Sunday Holiday</th> <th colspan="6"class="align-middle text-center" >Holiday Overtime</th> <th colspan="3"class="align-middle text-center" >Holiday Rate</th> <th>Total hrs</th> <th>Other</th> <th rowspan="2"class="align-middle">Gross Pay</th> <th>With</th> <th rowspan="2"class="align-middle">Phi</th> <th rowspan="2"class="align-middle">SSS</th> <th rowspan="2"class="align-middle">HDMF</th> <th>Cash</th> <th>SSS</th> <th>PAG-IBIG</th> <th>Other</th> <th>Total</th> <th rowspan="2"class="align-middle">Net Pay</th> <th rowspan="2"class="align-middle">Action</th> </tr> <tr> <th>Name</th> <th>Rate</th> <th>Rate</th> <th>Time</th> <th>Absent</th> <th>Salary</th> <th># of hours</th> <th>OT</th> <th># of hours</th> <th>Sunday OT</th> <th># of hours</th> <th>Regular OT</th> <th># of hours</th> <th>Double OT</th> <th># of hours</th> <th>Special OT</th> <th>Sunday</th> <th>Regular</th> <th>Double</th> <th>Special</th> <th># of hours</th> <th>Regular OT</th> <th># of hours</th> <th>Double OT</th> <th># of hours</th> <th>Special OT</th> <th>Regular</th> <th>Double</th> <th>Special</th> <th>OT</th> <th>Income</th> <th>Tax</th> <th>Advance</th> <th>Loan</th> <th>Loan</th> <th>Deduction</th> <th>Deduction</th> </tr> </thead> </div> <tbody> <?php $i=1;foreach ($payrolls as $payroll){?> <tr> <td><?= $i; ?></td> <td><?= strtoupper($payroll->name); ?></td> <td><?= number_format($payroll->daily_rate, 2); ?></td> <td><?= number_format($payroll->monthly_rate, 2); ?></td> <td><?= number_format($payroll->dtr_time, 2); ?></td> <td><?= ($payroll->absent == 0 ? '' : $payroll->absent); ?></td> <td><?= ($payroll->late == 0 ? '' : number_format($payroll->late*60,2)); ?></td> <td><?= number_format($payroll->basic_salary, 2); ?></td> <td><?= ($payroll->allowance == 0 ? '' : number_format($payroll->allowance,2)); ?></td> <td><?= ($payroll->nor_ot == 0 ? '' : number_format($payroll->nor_ot,2)); ?></td> <td><?= ($payroll->nor_ot_pay == 0 ? '' : number_format($payroll->nor_ot_pay, 2)); ?></td> <td><?= ($payroll->res_sun_ot == 0 ? '' : number_format($payroll->res_sun_ot,2)); ?></td> <td><?= ($payroll->res_sun_ot_pay == 0 ? '' : number_format($payroll->res_sun_ot_pay, 2)); ?></td> <td><?= ($payroll->res_reg_hol_ot == 0 ? '' : number_format($payroll->res_reg_hol_ot,2)); ?></td> <td><?= ($payroll->res_reg_hol_ot_pay == 0 ? '' : number_format($payroll->res_reg_hol_ot_pay, 2)); ?></td> <td><?= ($payroll->res_dob_hol_ot == 0 ? '' : number_format($payroll->res_dob_hol_ot,2)); ?></td> <td><?= ($payroll->res_dob_hol_ot_pay == 0 ? '' : number_format($payroll->res_dob_hol_ot_pay, 2)); ?></td> <td><?= ($payroll->res_spe_hol_ot == 0 ? '' : number_format($payroll->res_spe_hol_ot,2)); ?></td> <td><?= ($payroll->res_spe_hol_ot_pay == 0 ? '' : number_format($payroll->res_spe_hol_ot_pay, 2)); ?></td> <td><?= ($payroll->res_sun_pay == 0 ? '' : number_format($payroll->res_sun_pay, 2)); ?></td> <td><?= ($payroll->res_reg_hol_pay == 0 ? '' : number_format($payroll->res_reg_hol_pay, 2)); ?></td> <td><?= ($payroll->res_dob_hol_pay == 0 ? '' : number_format($payroll->res_dob_hol_pay, 2)); ?></td> <td><?= ($payroll->res_spe_hol_pay == 0 ? '' : number_format($payroll->res_spe_hol_pay, 2)); ?></td> <td><?= ($payroll->reg_hol_ot == 0 ? '' : number_format($payroll->reg_hol_ot,2)); ?></td> <td><?= ($payroll->reg_hol_ot_pay == 0 ? '' : number_format($payroll->reg_hol_ot_pay, 2)); ?></td> <td><?= ($payroll->dob_hol_ot == 0 ? '' : number_format($payroll->sun_hol_ot,2)); ?></td> <td><?= ($payroll->dob_hol_ot_pay == 0 ? '' : number_format($payroll->dob_hol_ot_pay, 2)); ?></td> <td><?= ($payroll->spe_hol_ot == 0 ? '' : number_format($payroll->spe_hol_ot,2)); ?></td> <td><?= ($payroll->spe_hol_ot_pay == 0 ? '' : number_format($payroll->spe_hol_ot_pay, 2)); ?></td> <td><?= ($payroll->reg_hol_pay == 0 ? '' : number_format($payroll->reg_hol_pay, 2)); ?></td> <td><?= ($payroll->dob_hol_pay == 0 ? '' : number_format($payroll->dob_hol_pay, 2)); ?></td> <td><?= ($payroll->spe_hol_pay == 0 ? '' : number_format($payroll->spe_hol_pay, 2)); ?></td> <td><?= ($payroll->total_ot == 0 ? '' : number_format($payroll->total_ot, 2)); ?></td> <td></td> <td><?= ($payroll->gross_pay == 0 ? '' : number_format($payroll->gross_pay, 2)); ?></td> <td></td> <td><?= ($payroll->philhealth_con == 0 ? '' : number_format($payroll->philhealth_con, 2)); ?></td> <td></td> <td><?= ($payroll->pagibig_con == 0 ? '' : number_format($payroll->pagibig_con, 2)); ?></td> <td></td> <td></td> <td></td> <td></td> <td><?= ($payroll->total_deductions == 0 ? '' : number_format($payroll->total_deductions, 2)); ?></td> <td><?= ($payroll->net_pay == 0 ? '' : number_format($payroll->net_pay, 2)); ?></td> <td></td> <?php $i++; }?> </tr> </tbody> </table> </div> </div> </div> </div> <script type="text/javascript"> window.onload = function () { $("#prod-list").floatThead({ scrollContainer: function ($table) { return $('#wages-table-container'); } }); } </script> <file_sep>/application/views/includes/modals/add/add_position_modal.php <?php /** * Created by PhpStorm. * User: capstonestudent * Date: 2/19/2020 * Time: 2:45 AM */?> <div class="modal fade" id="addPosition" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Add Position</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="add-position" method="post"> <div class="form-group row"> <label for="posTitle" class="col-sm-5 col-form-label">Position Title</label> <div class="col-sm-5"> <input type="text" class="form-control" name="position" id="posTitle" required> </div> </div> <div class="form-group row"> <label for="rph" class="col-sm-5 col-form-label">Rate</label> <div class="col-sm-5"> <input type="number" class="form-control" min="1" name="rate" id="rph" required> </div> </div> <div class="form-group row"> <label for="sched" class="col-sm-5 col-form-label">Schedule</label> <div class="col-sm-5"> <select class="form-control" name="schedule_id" data-style="btn-light"> <?php foreach ($schedules as $row){?> <option class="form-control" value=<?=$row->schedule_id?> ><?=$row->time_in." - ".$row->time_out?></option> <?php }?> </select> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Add Position</button> </div> </form> </div> </div> </div> </div> <file_sep>/application/models/Attendance_model.php <?php /** * Created by PhpStorm. * User: User * Date: 23/01/2020 * Time: 9:35 AM */ class Attendance_model extends CI_Model { public function __construct() { parent::__construct(); } public function getTest() { $res = $this->db->select('*') ->from('tbl_loginsheet') ->where('staff_id', '307') ->where("date between '" . "2019-09-01'" . " and " . "'2019-09-15'") ->get(); return $res->result(); } public function getAttendance($user_id,$start_day, $end_day) { $res = $this->db->select('*') ->from('tbl_loginsheet') ->where('staff_id', $user_id) ->where('date between "' . $start_day . '" and "' . $end_day . '"') ->order_by('date','asc') ->get() ->result(); return $res; } public function getAllAttendance($start_day, $end_day) { $result = $this->db->select('*') ->from('tbl_employee as employee') ->join('tbl_loginsheet as loginsheet','employee.employee_id = loginsheet.staff_id') ->where('date between "' . $start_day . '" and "' . $end_day . '"') ->get() ->result(); return $result; } public function getUsers() { $type = array('7','2','16','4'); $result = $this->db->select('*') ->from('tbl_user') ->where_in('account_type',$type) ->where('stillworking',1) ->where('isarchived',0) ->where('last_name IS NOT NULL') ->order_by('last_name','asc') ->get() ->result(); return $result; } public function addEmployee($firstname,$lastname,$address,$birthdate,$contact,$gender,$position,$schedule,$datehired) { $query="insert into add_employee values('','$firstname','$lastname','$address','$birthdate','$contact','$gender','$position','$schedule','$datehired')"; $this->db->query($query); return $query; } // private $event = 'event'; // // function get_event_list() { // $this->db->select("id, title, url, class, UNIX_TIMESTAMP(start_date)*1000 as start, UNIX_TIMESTAMP(end_date)*1000 as end"); // $query = $this->db->get($this->event); // if ($query) { // return $query->result(); // } // return NULL; // } }<file_sep>/application/views/index.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, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>SB Admin 2 - Login</title> <?php include 'includes/css.php'?> </head> <body class="bg-gradient-primary" style="margin-top: 20rem"> <div class="container"> <!-- Outer Row --> <div class="row justify-content-center"> <div class="col-xl-11 col-lg-12 col-md-9"> <div class="card o-hidden border-0 shadow-lg my-5"> <div class="card-body p-0"> <!-- Nested Row within Card Body --> <div class="row"> <div class="col-lg-6 d-none d-lg-block bg-login-image"></div> <div class="col-lg-6"> <div class="p-5"> <div class="text-center"> <h1 class="h4 text-gray-900 mb-4">Welcome Back!</h1> <div id="error_div"></div> </div> <form action="login" method="post" class="user" > <div class="form-group"> <input type="text" class="form-control form-control-user" id="inputUsername" name="username" placeholder="Username" required> </div> <div class="form-group"> <input type="<PASSWORD>" class="form-control form-control-user" id="inputPassword" name="password" placeholder="<PASSWORD>" required> </div> <hr> <button type="submit" class="btn btn-primary btn-user btn-block " >Login</button> </form> </div> </div> </div> </div> </div> </div> </div> </div> <!-- Bootstrap core JavaScript--> <!-- --><?php //include 'includes/scripts.php'?> <script src="<?= base_url(); ?>assets/vendor/jquery/jquery.min.js"></script> <script> error(); function error() { $("#error").appendTo("#error_div").prop('hidden', false); } if ( window.history.replaceState ) { window.history.replaceState( null, null, window.location.href ); } </script> </body> </html> <file_sep>/application/views/admin/test.php <?php /** * Created by PhpStorm. * User: User * Date: 16/03/2020 * Time: 9:51 AM */ var_dump("TEst"); header("Location: http://localhost/ptbcsi/push");<file_sep>/application/libraries/zklib/Crontroller.php <?php /** * Created by PhpStorm. * User: User * Date: 16/03/2020 * Time: 10:02 AM */ class Crontroller { public $host = "localhost"; // MySQL host name eg. localhost public $user = "maricris"; // MySQL user. eg. root ( if your on localserver) public $password = "<PASSWORD>"; // MySQL user password (if password is not set for your root user then keep it empty ) public $database = "maricris_ptbcsi"; // MySQL Database name public $db; public function connect() { // Connect to MySQL Database $db = mysqli_connect($this->host, $this->user, $this->password, $this->database) or die("Could not connect to database"); date_default_timezone_set('Asia/Manila'); //Default Timezone Of Your Country include('ZKLib.php'); $zk = new ZKLib('192.168.127.12'); $ret = $zk->connect(); if ($ret) { $zk->disableDevice(); $zk->setTime(date('Y-m-d H:i:s')); // Synchronize time $users = $zk->getUser(); $attendance = $zk->getAttendance(); if (count($attendance) > 0) { $attendance = array_reverse($attendance, true); sleep(1); foreach ($attendance as $attItem) { $uid = $attItem['uid']; $id = $attItem['id']; $name = (isset($users[$attItem['id']]) ? $users[$attItem['id']]['name'] : $attItem['id']); $state = ZK\Util::getAttState($attItem['state']); $date = date("Y-m-d", strtotime($attItem['timestamp'])); $time = date("H:i:s", strtotime($attItem['timestamp'])); $type = ZK\Util::getAttType($attItem['type']); $query = "INSERT INTO tbl_attendance(uid,id,name,state,date,time,type) VALUES ('$uid', '$id', '$name', '$state','$date','$time','$type')"; if (!$result = mysqli_query($db, $query)) { exit(mysqli_error($db)); }else{ $this->update_dtr($uid, $id, $name, $state, $date, $time, $type, $db); } } $zk->clearAttendance(); } } } function update_dtr($uid, $id, $name, $state, $date, $time, $type, $db) { $query = "SELECT * FROM tbl_time_sheet where employee_id = '" . $id . "' and date ='" . $date . "'"; $dtr = mysqli_query($db, $query)->fetch_assoc(); $am = date('A', strtotime($time)); if (count($dtr) == 0) { $query = "INSERT INTO tbl_time_sheet(employee_id,date) VALUES ('$id', '$date')"; if (!$result = mysqli_query($db, $query)) { exit(mysqli_error($db)); } $query = "SELECT * FROM tbl_time_sheet where employee_id = " . $id . " date =`" . $date . "`"; $dtr = mysqli_query($db, $query)->fetch_assoc(); } $m_i = $dtr['morning_in']; $m_o = $dtr['morning_out']; $m_t = $dtr['morning_time']; $a_i = $dtr['afternoon_in']; $a_o = $dtr['afternoon_out']; $a_t = $dtr['afternoon_time']; $o_i = $dtr['overtime_in']; $o_o = $dtr['overtime_out']; $o_t = $dtr['overtime_time']; if ($am == "AM") { var_dump("AM"); if (empty($dtr['morning_in'])) { var_dump("IN"); $m_i = $time; } elseif (!($dtr['morning_in']) && empty($dtr['morning_out'])) { var_dump("OUT"); $m_o = $time; $a = str_replace(":", ".", $dtr['morning_in']); $a = doubleval($a); $b = str_replace(":", ".", $time); $b = doubleval($b); $m_t = $b - $a; } } else { var_dump("PM"); if (empty($dtr['afternoon_in'])) { var_dump("IN"); $a_i = $time; } elseif (empty($dtr['afternoon_in'])!=true && empty($dtr['afternoon_out'])) { var_dump("OUT"); $a_o = $time; $a = str_replace(":", ".", $dtr['afternoon_in']); $a = doubleval($a); $b = str_replace(":", ".", $time); $b = doubleval($b); $a_t = $b - $a; } } var_dump($dtr); var_dump($m_i); var_dump($m_o); var_dump($m_t); var_dump($a_i); var_dump($a_o); var_dump($a_t); var_dump($o_i); var_dump($o_o); var_dump($o_t); var_dump(empty($dtr['morning_in'])); var_dump(empty($dtr['morning_out'])); var_dump(empty($dtr['afternoon_in'])!=true); var_dump(empty($dtr['afternoon_out'])); $query = "UPDATE tbl_time_sheet SET morning_in='" . $m_i . "', morning_out='" . $m_o. "', morning_time='" . $m_t. "', afternoon_in='" . $a_i. "', afternoon_out='" . $a_o. "', afternoon_time='" . $a_t. "', overtime_in='" . $o_i. "', overtime_out='" . $o_o. "', overtime_time='" . $o_t. "' WHERE time_sheet_id=" . $dtr['time_sheet_id']; if (mysqli_query($db, $query)) { echo "Record updated successfully"; } else { echo "Error updating record: " . mysqli_error($db); } // if (is_null($dtr['morning_in']) && $am === 'AM') { // $time_sheet['morning_in ']= $time; // } elseif (!is_null($dtr['morning_in'])) { // $dtr['morning_out ']= $time; // $a = str_replace(":", ".", $dtr['morning_in']); // $a = doubleval($a); // $b = str_replace(":", ".", $time); // $b = doubleval($b); // $dtr['morning_time ']= $b - $a; // } elseif (is_null($dtr['afternoon_in']) && $am === 'PM') { // $dtr['afternoon_in ']= $time; // } elseif (!is_null($dtr['afternoon_in']) && $am === 'PM' && is_null($dtr['afternoon_out'])) { // $dtr['afternoon_out ']= $time; // $a = str_replace(":", ".", $dtr['afternoon_in']); // $a = doubleval($a); // $b = str_replace(":", ".", $time); // $b = doubleval($b); // $dtr['afternoon_time ']= $b - $a; // } elseif (is_null($dtr['overtime_in']) && $am === 'PM') { // $dtr['overtime_in ']= $time; // } elseif (!is_null($dtr['overtime_in']) && $am === 'PM') { // $dtr['overtime_out ']= $time; // $a = str_replace(":", ".", $dtr['overtime_in']); // $a = doubleval($a); // $b = str_replace(":", ".", $time); // $b = doubleval($b); // $dtr['overtime_time ']= $b - $a; // } // else { // if($am =="AM"){ // if (is_null($dtr->morning_in)) { // $dtr->morning_in = $time; // }else{ // $dtr->morning_out = $time; // } // }else{ // if (is_null($dtr->afternoon_in)) { // $dtr->afternoon_in = $time; // }else{ // $dtr->afternoon_out = $time; // } // } // // } // var_dump($time); // // if () { // // } // // if (!$result = mysqli_query($db, $query)) { // exit(mysqli_error($db)); // } // var_dump($dtr); } }<file_sep>/application/views/admin/dtr2.php <link href="<?= base_url() ?>assets/css/custom.css" rel="stylesheet"> <div class="container-fluid"> <!-- <h1 class="h3 mb-4 text-gray-800">Attendance - TODO ( Mariel) </h1>--> <h1 class="h3 mb-3 text-gray-800"><strong>TDZ</strong> <i class="divider"> / </i> <span>Daily Time Record</span> </h1> <!-- DataTales Example --> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary"><strong>TDZ</strong> <i class="divider"> / </i> <span>Daily Time Record</span> </h6> </div> <div class="card-body"> <div class="sec_head"> <div class="row row-full"> <div class="col-md-7"> <form action="dtr" method="post"> <label for="half_month">Filter: </label>&nbsp;&nbsp;&nbsp; <select name="half_month" id="half_month" class="input input-sm half_month"> <option value="A" <?= ($half_month == 'A' ? 'selected' : ''); ?>>A</option> <option value="B" <?= ($half_month == 'B' ? 'selected' : ''); ?>>B</option> </select>&nbsp;&nbsp; <select name="month" id="month" class="input input-sm monthName "> <option value="01" <?= ($month == 'January' ? 'selected' : ''); ?>>January</option> <option value="02" <?= ($month == 'February' ? 'selected' : ''); ?>>February</option> <option value="03" <?= ($month == 'March' ? 'selected' : ''); ?>>March</option> <option value="04" <?= ($month == 'April' ? 'selected' : ''); ?>>April</option> <option value="05" <?= ($month == 'May' ? 'selected' : ''); ?>>May</option> <option value="06" <?= ($month == 'June' ? 'selected' : ''); ?>>June</option> <option value="07" <?= ($month == 'July' ? 'selected' : ''); ?>>July</option> <option value="08" <?= ($month == 'August' ? 'selected' : ''); ?>>August</option> <option value="09" <?= ($month == 'September' ? 'selected' : ''); ?>>September</option> <option value="10" <?= ($month == 'October' ? 'selected' : ''); ?>>October</option> <option value="11" <?= ($month == 'November' ? 'selected' : ''); ?>>November</option> <option value="12" <?= ($month == 'December' ? 'selected' : ''); ?>>December</option> </select>&nbsp;&nbsp; <select name="year" id="year" class="input input-sm year"> <option value="2020" <?= ($year == '2020' ? 'selected' : ''); ?>>2020</option> <option value="2019" <?= ($year == '2019' ? 'selected' : ''); ?>>2019</option> <option value="2018" <?= ($year == '2018' ? 'selected' : ''); ?>>2018</option> <option value="2017" <?= ($year == '2017' ? 'selected' : ''); ?>>2017</option> <option value="2016" <?= ($year == '2016' ? 'selected' : ''); ?>>2016</option> <option value="2015" <?= ($year == '2015' ? 'selected' : ''); ?>>2015</option> <option value="2014" <?= ($year == '2014' ? 'selected' : ''); ?>>2014</option> <option value="2013" <?= ($year == '2013' ? 'selected' : ''); ?>>2013</option> <option value="2012" <?= ($year == '2012' ? 'selected' : ''); ?>>2012</option> </select>&nbsp;&nbsp; <?php if ($_SESSION['user_type'] != "Employee"): ?> <select name="user_id" id="name" class="input input-sm empName"> <?php foreach ($users as $user): ?> <option value="<?= $user->employee_id; ?>" <?= ($user->employee_id == $user_id ? 'selected' : ''); ?> ><?= $user->lastname . ' ' . $user->firstname; ?></option> <?php endforeach; ?> </select>&nbsp;&nbsp; <?php endif; ?> <button type="submit" class="btn btn-sm btn-primary">GO</button> <?php if ($_SESSION['user_type'] == "Employee"): ?> <input type="text" name="user_id" value="<?= $_SESSION['user_id']; ?>" hidden/> <button type="button" class="btn btn-facebook btn-md center" data-toggle="modal" data-target="#add-overtime" <?= (!$request_ot ? 'disabled' : ''); ?>>Request Overtime </button> <?php endif; ?> </form> </div> <div id="timestamp"> </div> <span class="date_time"> <span class="time"> <span class="iconn"><i class="fa fa-clock icon pr-1"></i>Time: </span><span id="span"></span> </span> <span class="iconn"><i class="fa fa-calendar icon">&nbsp;&nbsp;&nbsp;</i>Date: <?= date('l F d, Y'); ?></span> </span> </div> </div> <div class="details iconn"> <div class="rh tb_rh text_center"> <span class="show_leave_details">Leave: <span class="text-primary">___</span> <div style="display: none;"> <span class="width-200"></span> </div> </span>&nbsp;&nbsp;&nbsp; <span class="show_absent">Absent: <span class="text-primary">___</span> <div style="display: none;"> <span class="width-200"></span> </div> </span>&nbsp;&nbsp;&nbsp; <span>Over Time: <span class="text-primary">___</span> <div style="display: none"> <span class="width-200"></span> </div> </span>&nbsp;&nbsp;&nbsp; <span>Under Time: <span class="text-primary">___</span> <div style="display: none"> <span class="width-200"></span> </div> </span>&nbsp;&nbsp;&nbsp; <span>Late: <span class="text-primary">___</span> <div style="display: none"> <span class="width-200"></span> </div> </span> </div> </div> <div class="table-responsive"> <table id="attendance" class="table table-sm table-bordered "> <thead> <tr> <th colspan="2" class=" text_center border-left " style="white-space: nowrap">Half-Month</th> <th colspan="2" class="text_center">Morning</th> <th class="width1"></th> <th colspan="2" class="text_center">Afternoon</th> <th class="width1"></th> <th colspan="2" class="text_center">OverTime</th> <th class="width1"></th> <th colspan="3" class="text_center border-right">Total Time</th> </tr> <tr class=""> <td class="width1 no_hover" colspan="2">Days</td> <td class="width1 no_hover">In</td> <td class="width1 no_hover">Out</td> <td class="width1 no_hover">Time</td> <td class="width1 no_hover">In</td> <td class="width1 no_hover">Out</td> <td class="width1 no_hover">Time</td> <td class="width1 no_hover">In</td> <td class="width1 no_hover">Out</td> <td class="width1 no_hover">Time</td> <td class="width1 no_hover">Pre</td> <td class="width1 no_hover">OT</td> <td class="width1 no_hover">Late</td> </tr> </thead> <tbody class="dtr_row"> <?php $i; $j = 0; $today = date('Y:m:d'); foreach ($days as $day) { $day_num = date('d', strtotime($day)); $day_name = date('D', strtotime($day)); $hol_name = ''; $class = ''; $is_hol = false; $is_sun = false; foreach ($holidays as $holiday) { if ($holiday->date == $day) { $class = ' holiday '; $is_hol = true; $hol_name = $holiday->description; } } if ($day_name == "Sun") { $class = ' sunday '; $is_sun = true; } ?> <tr class= "<?= $class; ?>"<?= ($is_hol ? ' data-toggle="tooltip" data-placement="top" title="' . $hol_name . '"' : ''); ?>> <td width="40"><?= $day_num; ?></td> <td width="40"><?= $day_name; ?></td> <?php if (count($dtrs)==0|| $j==-1) { ?> <td> <input value="" >: <input value=""> </td> <td> <input value="">: <input value=""> </td> <td></td> <td> <input value="">: <input value=""> </td> <td> <input value="">: <input value=""> </td> <td></td> <td> <input value="">: <input value=""> </td> <td> <input value="">: <input value=""> </td> <td></td> <td></td> <td></td> <td></td> <?php } elseif ($day == $dtrs[$j]->date ){ ?> <td > <input value="<?= ($dtrs[$j]->m_i_h ?? ''); ?>">: <input value="<?= ($dtrs[$j]->m_i_m ??''); ?>"> </td> <td> <input value="<?= ($dtrs[$j]->m_o_h ?? ''); ?>">: <input value="<?= ($dtrs[$j]->m_o_m ?? ''); ?>"> </td> <td><?= ($dtrs[$j]->morning_time==0?'':$dtrs[$j]->morning_time) ?> </td> <td> <input value="<?= ($dtrs[$j]->a_i_h ??'') ; ?>">: <input value="<?= ($dtrs[$j]->a_i_m ??'') ; ?>"> </td> <td> <input value="<?= ($dtrs[$j]->a_o_h ??'') ; ?>">: <input value="<?= ($dtrs[$j]->a_o_m ??'') ; ?>"> </td> <td><?= ($dtrs[$j]->afternoon_time==0?'':$dtrs[$j]->afternoon_time) ; ?> </td> <td> <input value="<?= ($dtrs[$j]->o_i_h ??'') ; ?>">: <input value="<?= ($dtrs[$j]->o_i_m ??'') ; ?>"> </td> <td> <input value="<?= ($dtrs[$j]->o_o_h ??'') ; ?>">: <input value="<?= ($dtrs[$j]->o_o_m ??'') ; ?>"> </td> <td><?= ($dtrs[$j]->overtime_time==0?'':$dtrs[$j]->overtime_time); ?></td> <td><?= $dtrs[$j]->pre_time == 0 ? '' : $dtrs[$j]->pre_time; ?> </td> <td><?= $dtrs[$j]->ot == 0 ? '' : $dtrs[$j]->ot; ?> </td> <td class=<?=doubleval($dtrs[$j]->late)>0 ? 'late':''?>><?= $dtrs[$j]->late == 0 ? '' : $dtrs[$j]->late; ?> </td> <?php ($j < count($dtrs) - 1 ? $j++ : $j = -1); ?> <?php }elseif (!$is_sun && !$is_hol){ ?> <td class="absent" colspan="12">ABSENT</td> <?php }else{ ?> <td colspan="12"></td> <?php } ?> </tr> <?php } ?> <tr> <td style="text-align: right" colspan="11">Total Time:</td> <td><?= $total_pre == 0 ? ' ' : $total_pre; ?></td> <td><?= $total_ot == 0 ? ' ' : $total_ot; ?></td> <td><?= $total_late == 0 ? ' ' : $total_late; ?></td> </tr> </tbody> </table> </div> </div> </div> </div> <?php include getcwd() . '/application/views/includes/modals/add/add_overtime_modal.php'; ?> <script type="text/javascript"> var span = document.getElementById('span'); function time() { var d = new Date(); var s = d.getSeconds(); var m = d.getMinutes(); var h = d.getHours(); span.textContent = h + ":" + m + ":" + s; } setInterval(time, 1000); </script><file_sep>/application/backup/payroll_master/cashAdvance.php <link href="<?=base_url()?>assets/css/schedule.css" rel="stylesheet"> <div class="container-fluid"> <h1 class="h3 mb-3 text-gray-800"><strong>TDZ</strong> <i class="divider"> / </i> <span>Cash Advance</span></h1> <div class="card shadow mb-4"> <div class="card-header py-3"> <input type="button" class="btn btn-facebook" value="New Cash Advance" data-toggle="modal" data-target="#addCashAdvance"> </div> <div class="card-body"> <div class="row"> <div class="table-responsive col-xl-7 col-md-6 mb-6" > <table class="table table-bordered" width="100%" cellspacing="0"> <thead> <tr> <td>Date</td> <td>Employee Name</td> <td>Amount</td> <td>Repayment</td> <td>Balance</td> <td>Status</td> <td>Tools</td> </tr> </thead> <tbody> <?php foreach ($cashAdvances as $cashAdvance):?> <tr> <td><?=$cashAdvance->date_advance;?></td> <td><?=strtoupper($cashAdvance->lastname.' '.$cashAdvance->firstname);?></td> <td><?=$cashAdvance->amount;?></td> <td><?=$cashAdvance->repay_amount;?></td> <td><?=$cashAdvance->balance;?></td> <td><?=$cashAdvance->status;?></td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#cashAdEdit<?=$cashAdvance->cash_advance_id;?>" > &nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#cashAdDelete<?=$cashAdvance->cash_advance_id;?>">&nbsp;&nbsp;Delete</i> </td> <?php endforeach;?> </tr> </tbody> </table> </div> <div class="table-responsive col-xl-5 col-md-6 mb-6" > <div> <h1 class="h3 mb-3 text-gray-800" align="center"> Cash Advance Details</h1> <hr> <h5 class="h6 mb-3 text-gray-800" align="center">Under Construction</h5> </div> <div> <table class="table table-bordered" width="100%" cellspacing="0"> <thead> <tr> <td>Payroll Date Range</td> <td>Payroll #</td> <td>Amount Pay</td> <td>Balance</td> <td>Status</td> </tr> </thead> <tbody> </tbody> </table> </div> </div> </div> </div> </div> <!-- Add Cash Advance Modal--> <div class="modal fade" id="addCashAdvance" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Add Cash Advance</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="addCashAdvance" method="post" id="cash"> <div class="form-group row"> <label for="empName" class="col-sm-4 col-form-label text-right">Employee Name</label> <div class="col-sm-8"> <select name="user_id" id="month" class="input input-sm monthName form-control" style="width: 100%;padding: 5px"> <?php foreach ($users as $user):?> <option value="<?=$user->employee_id;?>" ><?= strtoupper($user->lastname." ".$user->firstname);?></option> <?php endforeach;?> </select>&nbsp;&nbsp; </div> </div> <div class="form-group row"> <label for="amount" class="col-sm-4 col-form-label text-right">Requested Amount</label> <div class="col-sm-8"> <input type="number" class="form-control" min="0"name="amount"id="amount" required> </div> </div> <div class="form-group row"> <label for="balance" class="col-sm-4 col-form-label text-right">Repayment Amount Every Payroll </label> <div class="col-sm-8"> <input type="number" class="form-control" name="repay_amount" required> </div> </div> <div class="form-group row"> <label for="balance" class="col-sm-4 col-form-label text-right" >Purpose</label> <div class="col-sm-8"> <textarea rows="3" class="form-control" name="purpose" form="cash" placeholder="Purpose..." required></textarea> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Add</button> </div> </form> </div> </div> </div> </div> <!--Modal Edit--> <?php foreach ($cashAdvances as $cashAdvance):?> <div class="modal fade" id="cashAdEdit<?=$cashAdvance->cash_advance_id;?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Edit Cash Advance</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action="updateCashAdvance" method="post"> <div class="form-group row"> <label for="empName" class="col-sm-4 col-form-label">Employee Name</label> <div class="col-sm-5"> <input type="text" class="form-control" id="empName" value="<?=strtoupper($cashAdvance->lastname." ".$cashAdvance->firstname);?>" disabled /> <input type="text" name="cash_id" value="<?=$cashAdvance->cash_advance_id?>" hidden/> </div> </div> <div class="form-group row"> <label for="amount" class="col-sm-4 col-form-label">Amount</label> <div class="col-sm-5"> <input type="number" class="form-control" name="amount" value="<?=$cashAdvance->amount;?>"/> </div> </div> <div class="form-group row"> <label for="balance" class="col-sm-4 col-form-label">Repay Amount</label> <div class="col-sm-5"> <input type="number" class="form-control" name="repay_amount" value="<?=$cashAdvance->repay_amount;?>"/> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Save</button> </div> </form> </div> </div> </div> </div> <!-- Modal for delete--> <div class="modal fade" id="cashAdDelete<?=$cashAdvance->cash_advance_id;?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Delete Schedule</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p class="text_center">Are you sure you want to delete this?</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">No</button> <button type="button" class="btn btn-primary">Yes</button> </div> </div> </div> </div> <?php endforeach;?> </div><file_sep>/application/controllers/Overtime.php <?php /** * Created by PhpStorm. * User: User * Date: 05/02/2020 * Time: 5:52 PM */ class Overtime extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper(array('url', 'html', 'form')); $this->load->library('pagination','session'); $this->load->model(array('overtime_model', 'employee_model')); if (!$_SESSION['is_logged_in'] ) { redirect(base_url('')); } } public function view(){ if ($_SESSION['user_type'] == "Employee") { redirect(base_url('404')); } $overtimes = $this->overtime_model->get_all(); $users = $this->employee_model->get_employees(); $data['users'] = $users; $data['overtimes'] = $overtimes; $data['page_load'] = 'admin/overtime'; $data['active'] = "overtime"; $this->load->view('includes/template', $data); } public function add() { if (!empty($_POST)) { $overtime = new stdClass(); $overtime->employee_id = $_POST['user_id']; $overtime->date_request = date('Y-m-d'); $overtime->reason = $_POST['reason']; $overtime->request_start_time = '05:00 PM'; $overtime->request_end_time = '10:00 PM'; $overtime->status = 'Pending'; $this->overtime_model->add($overtime); } if($_SESSION['user_type']=="Employee"): redirect(base_url('dtr')); else: redirect(base_url('overtime')); endif; } public function update_status() { if ($_SESSION['user_type'] == "Employee") { redirect(base_url()); } if (!empty($_POST)) { $this->overtime_model->update_status($_POST['overtime_id'], $_POST['status']); } redirect(base_url('overtime')); } public function update() { // TODO: Implement update() method. } public function delete() { // TODO: Implement delete() method. } }<file_sep>/application/views/admin/calendar.php <?php /** * Created by PhpStorm. * User: Administrator * Date: 2/6/2020 * Time: 6:11 PM */ ?> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/cale.css"> <div class="container container-fluid" style="width: 100%;"> <div class="card shadow"> <div class="card-header"> <div class="row text-center"> <div class="col-4"> <div class="card border-left-warning shadow h-100 py" style="width: 80%;"> <div class="card-body" style="width: 140%; margin-top: -10px; margin-bottom: 5px;"> <div class="calendar-left" style="padding: 0%;"><br> <div class="dot"> <div class="num-date"><?= date('d'); ?></div> </div> <div><?=date('l');?></div> <hr> <div style="margin-top: 50px;"><i class="far fa-calendar-check"></i> My Birthday</div> <input class="text-center btn btn-info" style="width: 50%;font-size: 12px; margin-top: 50%" type="button" data-toggle="modal" data-target="#myModal" value="+ Add Event"/><br/> </div> </div> </div> </div> <div class="col-8"> <div class="card border-left-warning shadow h-100 py-2" style="left: -15%; width: 115%"> <div class="card-body" style="width: 93%"> <div id="calendar" style="color: black; margin-left: 25px; height: 10%; width: 100%;margin-top: -10px;"></div> </div> </div> </div> </div> </div> </div> </div> <div class="modal fade" id="myModal"> <div class="modal-dialog modal-lg" style="width:500px;"> <div class="modal-content"> <div class="modal-header" style="background-color:dodgerblue; color:#F2AA4CFF;"> <h4 class="modal-title">&nbsp;&nbsp;</h4> </div> <div class="modal-body" style="color:#101820; "> <div class="form-group"> <div class='input-group date' style="left: 20px;"> <?php echo form_open(base_url() . 'calendar1'); ?> <i class="fas fa-calendar-alt"></i>&nbsp; <label for="dob">Date of Event</label> <?php $attributes = 'id="dob" placeholder="Date" name="date"'; echo form_input('dob', set_value('dob'), $attributes); ?> <input type="text" class="form-control" name="date" id="exampleInputPassword1" placeholder="Date"><br> <i class="fas fa-marker"></i>&nbsp;<label for="exampleInputPassword1"> Event</label> <input type="text" class="form-control" name="event" id="exampleInputPassword2" placeholder="Add Event"><br> <input type="hidden" name="submitForm"/> </div> </div> <div class="modal-footer"> <button type="submit" name="submitForm" style="background-color:#101820" class="btn btn-success"> Submit </button> <button type="button" class="btn btn-secondary" style="background-color:#101820" data-dismiss="modal"> Close </button> </div> </div> </div> </div> </div> <script type="text/javascript"> var events = <?php echo json_encode($data) ?>; var date = new Date() var d = date.getDate(), m = date.getMonth(), y = date.getFullYear() $('#calendar').fullCalendar({ header: { left: '', center: 'title', right: 'prev,next today' }, buttonText: { today: 'today', month: 'month' }, events: events }) // $(function () { // $("#dob").datepicker(); // }); </script><file_sep>/application/controllers/Position.php <?php class Position extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('pagination', 'session'); $this->load->model(array("position_model",'schedule_model')); if (!$_SESSION['is_logged_in'] ) { redirect(base_url('')); } } public function view() { if ($_SESSION['user_type'] !="Admin") { redirect(base_url('404')); } $positions = $this->position_model->get_all(); $schedules = $this->schedule_model->get_all(); $data['schedules'] = $schedules; $data['positions'] = $positions; $data['page_load'] = 'admin/position'; $data['active'] = 'position'; $this->load->view('includes/template', $data); } public function add() { if(!empty($_POST)) { // var_dump($_POST); $position = new stdClass(); $position->position = $_POST['position']; $position->rate = $_POST['rate']; $position->schedule_id = $_POST['schedule_id']; $position->date_modified = date('Y-m-d'); $this->position_model->add($position); } redirect(base_url('position')); } public function update() { if (!empty($_POST)) { $position = new stdClass(); $position->position_id = $_POST['position_id']; $position->position = $_POST['position']; $position->rate = $_POST['rate']; $position->schedule_id = $_POST['schedule_id']; $position->date_modified = date('Y-m-d'); $this->load->model('position_model'); $this->position_model->update($position, $_POST['position_id']); } redirect(base_url('position')); } public function delete() { if (!empty($_POST)) { $res = $this->position_model->get_references($_POST['position_id']); if (empty($res)) { $this->position_model->delete($_POST['position_id']); echo json_encode(true); } else { } } } } <file_sep>/application/backup/payroll_master/schedule.php <link href="<?=base_url()?>assets/css/schedule.css" rel="stylesheet"> <link href="../assets/css/custom.css" rel="stylesheet"> <div class="container-fluid"> <h1 class="h3 mb-3 text-gray-800"><strong>TDZ</strong> <i class="divider"> / </i> <span>Schedule</span></h1> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary"><strong>TDZ</strong> <i class="divider"> / </i> <span>Schedule</span></h6> </div> <div class="card-body"> <div class="table-responsive"> <input type="button" class="btn btn-facebook" value="Add New Schedule" data-toggle="modal" data-target="#addSched"><br><br> <table class="table table-bordered" id="dataTable"> <thead> <tr> <td class="text_center">Time in</td> <td class="text_center">Time out</td> <td class="text_center">Tools</td> </tr> </thead> <tbody> <tr class="text_center"> <td>7:00 AM</td> <td>6:00 PM</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#scheduleEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#scheduleDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr class="text_center"> <td>8:00 AM</td> <td>5:00 PM</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#scheduleEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#scheduleDelete">&nbsp;&nbsp;Delete</i> </td> </tr> </tbody> </table> </div> </div> </div> <!--Modal for Adding Schedule--> <!-- Modal --> <div class="modal fade" id="addSched" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Add Schedule</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action=""> <div class="form-group row"> <label for="in" class="col-sm-3 col-form-label">Time in</label> <div class="col-sm-5"> <input type="text" class="form-control" id="out"> </div> </div> <div class="form-group row"> <label for="out" class="col-sm-3 col-form-label">Time out</label> <div class="col-sm-5"> <input type="text" class="form-control" id="out"> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Add Schedule</button> </div> </div> </div> </div> <!-- Modal for edit--> <div class="modal fade" id="scheduleEdit" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Edit Schedule</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action=""> <div class="form-group row"> <label for="in" class="col-sm-3 col-form-label">Time in</label> <div class="col-sm-5"> <input type="text" class="form-control" id="out"> </div> </div> <div class="form-group row"> <label for="out" class="col-sm-3 col-form-label">Time out</label> <div class="col-sm-5"> <input type="text" class="form-control" id="out"> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save</button> </div> </div> </div> </div> <!-- Modal for delete--> <div class="modal fade" id="scheduleDelete" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Delete Schedule</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p class="text_center">Are you sure you want to delete this schedule?</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">No</button> <button type="button" class="btn btn-primary">Yes</button> </div> </div> </div> </div> </div> <file_sep>/application/backup/payroll_master/calendar.php <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Collapsible sidebar using Bootstrap 4</title> <!-- <link rel="stylesheet" href="--><?php //echo base_url(); ?><!--assets/css/bootstrap.css">--> <!-- <link rel="stylesheet" href="--><?php //echo base_url(); ?><!--assets/css/bootstrap-responsive.css">--> <!-- <link rel="stylesheet" href="--><?php //echo base_url(); ?><!--assets/css/calendar.min.css">--> <link rel="stylesheet" href="<?php echo base_url(); ?>assets/css/cale.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="css/style.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css"> <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/solid.js" integrity="<KEY>" crossorigin="anonymous"></script> <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js" integrity="<KEY>RaBE01VTOY" crossorigin="anonymous"></script> </head> <body> <div class="container"> <div class="calendar-base"> <div class="year">2017</div> <!-- year --> <div class="triangle-left"></div> <!--triangle --> <div class="triangle-right"></div> <!-- triangle --> <div class="months"> <span class="month-hover">Jan</span> <span class="month-hover">Feb</span> <span class="month-hover">Mar</span> <strong class="month-color">Apr</strong> <span class="month-hover">May</span> <span class="month-hover">Jun</span> <span class="month-hover">July</span> <span class="month-hover">Aug</span> <span class="month-hover">Sep</span> <span class="month-hover">Oct</span> <span class="month-hover">Nov</span> <span class="month-hover">Dec</span> </div><!-- months --> <hr class="month-line" /> <div class="days">SUN MON TUE WED THU FRI SAT</div> <!-- days --> <div class="num-dates"> <div class="first-week"><span class="grey">26 27 28 29 30 31</span> 01</div> <!-- first week --> <div class="second-week">02 03 04 05 06 07 08</div> <!-- week --> <div class="third-week"> 09 10 11 12 13 14 15</div> <!-- week --> <div class="fourth-week"> 16 17 18 19 20 21 22</div> <!-- week --> <div class="fifth-week"> 23 24 25 26 <strong class="white">27</strong> 28 29</div> <!-- week --> <div class="sixth-week"> 30 <span class="grey">01 02 03 04 05 06</span></div> <!-- week --> </div> <!-- num-dates --> <div class="event-indicator"></div> <!-- event-indicator --> <div class="active-day"></div> <!-- active-day --> <div class="event-indicator two"></div> <!-- event-indicator --> </div> <!-- calendar-base --> <div class="calendar-left"> <div class="hamburger"> <div class="burger-line"></div> <!-- burger-line --> <div class="burger-line"></div> <!-- burger-line --> <div class="burger-line"></div> <!-- burger-line --> </div> <!-- hamburger --> <div class="num-date">27</div> <!--num-date --> <div class="day">THURSDAY</div> <!--day --> <div class="current-events">Current Events <br/> <ul> <li>Day 09 Daily CSS Image</li> </ul> <span class="posts">See post events</span></div> <!--current-events --> <div class="create-event">Create an Event</div> <!-- create-event --> <hr class="event-line" /> <div class="add-event"><span class="add">+</span></div> <!-- add-event --> <input type="button" data-toggle="modal" data-target="#myModal" value="Direction"/><br/> <div class="modal fade" id="myModal"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header" style="background-color:#101820; color:#F2AA4CFF;"> <h4 class="modal-title">&nbsp;&nbsp;How?</h4> </div> <div class="modal-body" style="color:#101820"> First, you need to click the OJT button if you want to apply as OJT or Draftsman button if you want to become a Draftsman. After clicking the Draftsman or OJT button, you may start filling up the given text fields and then click the Register button. </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" style="background-color:#101820" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> <!-- calendar-left --> </div> <!-- container --> </body> </html><file_sep>/application/controllers/Dtr.php <?php /** * Created by PhpStorm. * User: User * Date: 05/02/2020 * Time: 4:39 PM */ class Dtr extends CI_Controller { public function __construct() { parent::__construct(); $this->load->helper(array('url', 'html', 'form')); $this->load->library('pagination', 'session'); $this->load->model(array('dtr_model', 'holiday_model', 'employee_model')); if (!$_SESSION['is_logged_in']) { redirect(base_url('')); } include(getcwd() . '/application/libraries/zklib/ZKLib.php'); } public function view() { // $this->add(); if (!empty($_POST)) { $month = $_POST['month']; $half_month = $_POST['half_month']; $year = $_POST['year']; $user_id = $_POST['user_id']; } else { $month = date('m', strtotime(date('y-m-dd'))); $year = date('y', strtotime(date('y-m-dd'))); $half_month = 'A'; if (date('d', strtotime(date('y-m-dd'))) > 15) { $half_month = 'B'; } $user_id = 0; } $start_day = $year . "-" . $month; $end_day = $start_day; if ($half_month == 'A') { $start_day .= '-01'; $end_day .= -'15'; } else { $start_day .= '-16'; $end_day .= '-' . date('t', strtotime($start_day)); } $days = array(); $month_name = date('F', strtotime($start_day)); $users = $this->employee_model->get_employees(); $time_data = $this->dtr_model->get_one($user_id, $start_day, $end_day); $holidays = $this->holiday_model->get_holidays($start_day, $end_day);//get the holidays for the specific payroll period $can_request_ot = $this->dtr_model->can_request_overtime($_SESSION['user_id']); $hol_day = array(); $hol_name = array(); foreach ($holidays as $hol) { $hol_day[] = substr($hol->date, -2); $hol_name [] = $hol->description; } while (strtotime($start_day) <= strtotime($end_day)) { $day_num = date('d', strtotime($start_day)); $day_name = date('D', strtotime($start_day)); $start_day = date("Y-m-d", strtotime("+1 day", strtotime($start_day))); $days[] = array($day_num, $day_name); } $dtrs = array(); $total_pre = 0; $total_ot = 0; $total_late = 0; foreach ($time_data as $time) { $time->morning_time = $this->getTimeDiff($time->morning_in_hour, $time->morning_in_minute, $time->morning_out_hour, $time->morning_out_minute); $time->afternoon_time = $this->getTimeDiff($time->afternoon_in_hour, $time->afternoon_in_minute, $time->afternoon_out_hour, $time->afternoon_out_minute); $time->over_time = $this->getTimeDiff($time->over_in_hour, $time->over_in_minute, $time->over_out_hour, $time->over_out_minute); $dtr = $time; $dtr->morning_time = $this->getTimeDiff($time->morning_in_hour, $time->morning_in_minute, $time->morning_out_hour, $time->morning_out_minute); $dtr->afternoon_time = $this->getTimeDiff($time->afternoon_in_hour, $time->afternoon_in_minute, $time->afternoon_out_hour, $time->afternoon_out_minute); $dtr->over_time = $this->getTimeDiff($time->over_in_hour, $time->over_in_minute, $time->over_out_hour, $time->over_out_minute); $com_time = $time->morning_time + $time->afternoon_time; $obj = $this->calculate_time($com_time); $dtr->pre_time = number_format($obj->pre, 2); var_dump($dtr->pre_time); $dtr->ot = $time->over_time + $obj->ot; $dtr->late = $obj->late; $dtrs[] = $dtr; $total_pre += $dtr->pre_time; $total_ot += $dtr->ot; $total_late = $dtr->late; } $data['active'] = "dtr"; $data['page_load'] = 'admin/dtr2'; $data['request_ot'] = $can_request_ot; $data['hol_day'] = $hol_day; $data['hol_name'] = $hol_name; $data['total_pre'] = number_format($total_pre, 2); $data['total_ot'] = number_format($total_ot, 2); $data['total_late'] = number_format($total_late, 2);; $data['dtrs'] = $dtrs; $data['days'] = $days; $data['half_month'] = $half_month; $data['month'] = $month_name; $data['year'] = $year; $data['users'] = $users; $data['user_id'] = $user_id; $this->load->view('includes/template', $data); } function getTimeDiff($start_hr, $start_mn, $end_hr, $end_mn) { if ($start_hr != null && $start_hr != null && $end_hr != null && $end_mn != null) { if ($start_hr == 12) { $start_hr = 1; $end_hr += 1; } $start_date = new DateTime($start_hr . ':' . $start_mn . ':00'); $end_date = new DateTime($end_hr . ':' . $end_mn . ':00'); $interval = $end_date->diff($start_date); $hours = $interval->format('%h'); $minutes = $interval->format('%i'); return round((($hours * 60 + $minutes) / 60), 2); } else { return 0.0; } } function getTimeDiff2($start, $end) { if ($start != null && $end) { $start_date = new DateTime($start); $end_date = new DateTime($end); $interval = $end_date->diff($start_date); $hours = $interval->format('%h'); $minutes = $interval->format('%i'); return number_format(round((($hours * 60 + $minutes) / 60), 2), 2); } else { return 0.0; } } function calculate_time($com_time, $time) { $obj = new stdClass(); $obj->late = 0; $obj->ot = 0; if ($com_time > 8) { $obj->pre = 8; $obj->ot = $com_time - 8; } else { $obj->pre = $com_time; // $obj->late = 8 - $com_time; } $employee = $this->employee_model->get_one($time->employee_id); $s = str_replace(" ", "", $employee[0]->time_in); $s = str_replace(":", ".", $s); $s = str_split($s, 5); $t = str_replace(":", ".", $time->morning_in); if (doubleval($t) <= doubleval($s[0])) { return $obj; } if (doubleval($t) >= doubleval($s[0])) { $obj->late = (doubleval($t) - doubleval($s[0])); return $obj; } $t = str_replace(":", ".", $time->afternoon_in); if (doubleval($t) > doubleval($s[0])) { $obj->late = (doubleval($t) - doubleval($s[0])); } return $obj; } public function requestOvertime() { if (!empty($_POST)) { $overtime = new stdClass(); $overtime->employee_id = $_SESSION['user_id']; $overtime->date_request = date('Y-m-d'); $overtime->reason = $_POST['reason']; $overtime->request_start_time = '05:00 PM'; $overtime->request_end_time = '10:00 PM'; $overtime->status = 'Pending'; $this->load->model('Dbmodel'); $this->DBModel->addOvertime($overtime); } redirect(base_url('admin/overtime')); } public function view2() { // $this->push(); // echo "<pre>"; if (!empty($_POST)) { $month = $_POST['month']; $half_month = $_POST['half_month']; $year = $_POST['year']; $user_id = $_POST['user_id']; } else { $month = date('m'); $year = date('Y'); $half_month = 'A'; if (date('d') > 15) { $half_month = 'B'; } $user_id = 0; } $start_day = $year . "-" . $month; $end_day = $start_day; if ($half_month == 'A') { $start_day .= '-01'; $end_day .= -'15'; } else { $start_day .= '-16'; $end_day .= '-' . date('t', strtotime($start_day)); } $days = array(); $month_name = date('F', strtotime($start_day)); $employees = $this->employee_model->get_employees(); if ($user_id == 0) { $user_id = $employees[0]->employee_id; } $time_data = $this->dtr_model->get_one2($user_id, $start_day, $end_day); $holidays = $this->holiday_model->get_holidays($start_day, $end_day);//get the holidays for the specific payroll period $can_request_ot = $this->dtr_model->can_request_overtime($_SESSION['user_id']); while (strtotime($start_day) <= strtotime($end_day)) { $days[] = $start_day; $start_day = date("Y-m-d", strtotime("+1 day", strtotime($start_day))); } $dtrs = array(); $total_pre = 0; $total_ot = 0; $total_late = 0; // echo "<pre>"; // var_dump($time_data); foreach ($time_data as $time) { $time->morning_time = $this->getTimeDiff2($time->morning_in, $time->morning_out); $time->afternoon_time = $this->getTimeDiff2($time->afternoon_in, $time->afternoon_out); $time->overtime_time = $this->getTimeDiff2($time->overtime_in, $time->overtime_out); if (strlen($time->morning_in) > 0) { $arr = str_replace(":", "", $time->morning_in); $arr = str_split($arr, 2); $time->m_i_h = $arr[0]; $time->m_i_m = $arr[1]; } if (strlen($time->morning_out) > 0) { $arr = str_replace(":", "", $time->morning_out); $arr = str_split($arr, 2); $time->m_o_h = $arr[0]; $time->m_o_m = $arr[1]; } if (strlen($time->afternoon_in) > 0) { $arr = str_replace(":", "", $time->afternoon_in); $arr = str_split($arr, 2); $time->a_i_h = $arr[0]; $time->a_i_m = $arr[1]; } if (strlen($time->afternoon_out > 0)) { $arr = str_replace(":", "", $time->afternoon_out); $arr = str_split($arr, 2); $time->a_o_h = $arr[0]; $time->a_o_m = $arr[1]; } if (strlen($time->overtime_in) > 0) { $arr = str_replace(":", "", $time->overtime_in); $arr = str_split($arr, 2); $time->o_i_h = $arr[0]; $time->o_i_m = $arr[1]; } if (strlen($time->overtime_out) > 0) { $arr = str_replace(":", "", $time->overtime_out); $arr = str_split($arr, 2); $time->o_o_h = $arr[0]; $time->o_o_m = $arr[1]; } $com_time = $time->morning_time + $time->afternoon_time; $obj = $this->calculate_time($com_time, $time); $time->pre_time = number_format($obj->pre, 2); $time->ot = number_format($time->overtime_time + $obj->ot, 2); $time->late = number_format($obj->late, 2); // echo "<pre>"; // var_dump($time); // echo "</pre>"; $dtrs[] = $time; $total_pre += $time->pre_time; $total_ot += $time->ot; $total_late += $time->late; } $data['active'] = "dtr"; $data['page_load'] = 'admin/dtr2'; $data['request_ot'] = $can_request_ot; $data['holidays'] = $holidays; $data['total_pre'] = number_format($total_pre, 2); $data['total_ot'] = number_format($total_ot, 2); $data['total_late'] = number_format($total_late, 2);; $data['dtrs'] = $dtrs; $data['days'] = $days; $data['half_month'] = $half_month; $data['month'] = $month_name; $data['year'] = $year; $data['users'] = $employees; $data['user_id'] = $user_id; $this->load->view('includes/template', $data); } public function add() { // date_default_timezone_set('Asia/Manila'); //Default Timezone Of Your Country; // include(getcwd() . '/application/libraries/zklib/ZKLib.php'); // $ret = $zk->connect(); // if ($ret) { // $this->sort_attendance($zk->getAttendance()); // } // $zk->disconnect(); // $this->view(); } public function update() { // TODO: Implement update() method. } public function delete() { // TODO: Implement delete() method. } public function sort_attendance($attendances) { // echo "<pre>"; foreach ($attendances as $attendance) { $date = date("Y-m-d", strtotime($attendance['timestamp'])); $time = date("H:i", strtotime($attendance['timestamp'])); $hour = date("H", strtotime($attendance['timestamp'])); $am = date("A", strtotime($attendance['timestamp'])); $result = $this->dtr_model->get_employee_time($attendance['id'], $date); if (empty($result)) { $time_sheet = new stdClass(); $time_sheet->employee_id = $attendance['id']; $time_sheet->date = $date; $this->dtr_model->add($time_sheet); $result = $this->dtr_model->get_employee_time($attendance['id'], $date); } $time_sheet = $result[0]; if (is_null($time_sheet->morning_in) && $am === 'AM') { $time_sheet->morning_in = $time; } elseif (!is_null($time_sheet->morning_in)) { $time_sheet->morning_out = $time; $a = str_replace(":", ".", $time_sheet->morning_in); $a = doubleval($a); $b = str_replace(":", ".", $time); $b = doubleval($b); $time_sheet->morning_time = $b - $a; } elseif (is_null($time_sheet->afternoon_in) && $am === 'PM') { $time_sheet->afternoon_in = $time; } elseif (!is_null($time_sheet->afternoon_in) && $am === 'PM' && is_null($time_sheet->afternoon_out)) { $time_sheet->afternoon_out = $time; $a = str_replace(":", ".", $time_sheet->afternoon_in); $a = doubleval($a); $b = str_replace(":", ".", $time); $b = doubleval($b); $time_sheet->afternoon_time = $b - $a; } elseif (is_null($time_sheet->overtime_in) && $am === 'PM') { $time_sheet->overtime_in = $time; } elseif (!is_null($time_sheet->overtime_in) && $am === 'PM') { $time_sheet->overtime_out = $time; $a = str_replace(":", ".", $time_sheet->overtime_in); $a = doubleval($a); $b = str_replace(":", ".", $time); $b = doubleval($b); $time_sheet->overtime_time = $b - $a; } $this->dtr_model->update($time_sheet, $time_sheet->time_sheet_id); } } public function push() { redirect(base_url('dashboard')); // $zk = new ZKLib('172.16.17.32'); // $ret = $zk->connect(); // if ($ret) { // $users = $zk->getUser(); // $att = $zk->getAttendance(); // if (count($att) > 0) { //// foreach ($att as $a){ //// echo json_encode($_POST['name']); //// $z =(isset($users[$a['id']]) ? $users[$a['id']]['name'] : $a['id']); // $attend = new stdClass(); // $attend->uid=1; // $attend->id='1'; // $attend->name='1'; // $attend->state='1'; // $attend->date='1'; // $attend->time='1'; // $attend->type='1'; // $this->dtr_model->add_attendance($attend); //// } // $zk->clearAttendance(); // echo json_encode("Test"); // } // } // $zk->disconnect(); // //// echo json_encode($_POST['name']); } }<file_sep>/application/controllers/crontroller.php <?php /** * Created by PhpStorm. * User: User * Date: 13/03/2020 * Time: 4:57 PM */ class crontroller { public function __construct() { $this->load->helper(array('url', 'html', 'form')); $this->load->library('pagination', 'session'); $this->load->model(array('dtr_model', 'holiday_model', 'employee_model')); include(getcwd() . '/application/libraries/zklib/ZKLib.php'); } public function push(){ echo ("TEST"); $zk = new ZKLib('172.16.17.32'); if ($zk->connect()) { $zk->disableDevice(); $attendances = $zk->getAttendance(); if (count($attendances) > 0) { $attendances = array_reverse($attendances, true); $users = $zk->getUser(); sleep(1); foreach ($attendances as $item) { $attendance = new stdClass(); $attendance->uid = $item['uid']; $attendance->id = $item['id']; $attendance->name = $users[$item['id']]['name']; $attendance->state = ZK\Util::getAttState($item['state']); $attendance->date = date("d-m-Y", strtotime($item['timestamp'])); $attendance->time = date("H:i:s", strtotime($item['timestamp'])); $attendance->type = ZK\Util::getAttType($item['type']); $this->dtr_model->add_attendance($attendance); } $zk->clearAttendance(); } $zk->enableDevice(); $zk->disconnect(); } } }<file_sep>/application/models/Position_model.php <?php /** * Created by PhpStorm. * User: capstonestudent * Date: 2/6/2020 * Time: 8:39 PM */ class Position_Model extends CI_Model { public function __construct() { parent::__construct(); } public function get_all() { $query = $this->db->query("select * from tbl_position as position join tbl_schedule as schedule on position.schedule_id = schedule.schedule_id"); return $query->result(); } public function add($position) { $this->db->insert('tbl_position', $position); } public function update( $position,$id) { $this->db->where('position_id', $id); $this->db->update('tbl_position', $position); } public function delete($id) { $this->db->where('position_id', $id); $this->db->delete('tbl_position'); } public function get_references($position_id) { $result = $this->db->select('*') ->from('tbl_position as position') ->join('tbl_employee as employee', 'position.position_id = employee.position_id') ->where('position.position_id', $position_id) ->get() ->result(); return $result; } }<file_sep>/application/models/IModel.php <?php /** * Created by PhpStorm. * User: User * Date: 17/02/2020 * Time: 3:01 PM */ interface IModel { public function add($data); public function get_one(); public function get_all(); public function update(); public function delete(); }<file_sep>/application/backup/employee/dtr.php <link href="../../../assets/css/custom.css" rel="stylesheet"> <link href="../assets/css/custom.css" rel="stylesheet"> <div class="container-fluid"> <!-- <h1 class="h3 mb-4 text-gray-800">Attendance - TODO ( Mariel) </h1>--> <h1 class="h3 mb-3 text-gray-800"><strong>TDZ</strong> <i class="divider"> / </i> <span>Daily Time Record</span> </h1> <!-- DataTales Example --> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary"><strong>TDZ</strong> <i class="divider"> / </i> <span>Daily Time Record</span> </h6> </div> <div class="card-body"> <div class="sec_head"> <div class="row"> <div class="col-md-6"> <form action="dtr" method="post"> <label for="half_month">Filter: </label>&nbsp;&nbsp;&nbsp; <select name="half_month" id="half_month" class="input input-sm half_month"> <option value="A" <?= ($half_month == 'A' ? 'selected' : ''); ?>>A</option> <option value="B" <?= ($half_month == 'B' ? 'selected' : '') ?>>B</option> </select>&nbsp;&nbsp; <select name="month" id="month" class="input input-sm monthName"> <option value="01" <?= ($month == 'January' ? 'selected' : '') ?>>January</option> <option value="02" <?= ($month == 'February' ? 'selected' : '') ?>>February</option> <option value="03" <?= ($month == 'March' ? 'selected' : '') ?>>March</option> <option value="04" <?= ($month == 'April' ? 'selected' : '') ?>>April</option> <option value="05" <?= ($month == 'May' ? 'selected' : '') ?>>May</option> <option value="06" <?= ($month == 'June' ? 'selected' : '') ?>>June</option> <option value="07" <?= ($month == 'July' ? 'selected' : '') ?>>July</option> <option value="08" <?= ($month == 'August' ? 'selected' : '') ?>>August</option> <option value="09" <?= ($month == 'September' ? 'selected' : '') ?>>September</option> <option value="10" <?= ($month == 'October' ? 'selected' : '') ?>>October</option> <option value="11" <?= ($month == 'November' ? 'selected' : '') ?>>November</option> <option value="12" <?= ($month == 'December' ? 'selected' : '') ?>>December</option> </select>&nbsp;&nbsp; <select name="year" id="year" class="input input-sm year"> <option value="2020" <?= ($year == '2020' ? 'selected' : '') ?>>2020</option> <option value="2019" <?= ($year == '2019' ? 'selected' : '') ?>>2019</option> <option value="2018" <?= ($year == '2018' ? 'selected' : '') ?>>2018</option> <option value="2017" <?= ($year == '2017' ? 'selected' : '') ?>>2017</option> <option value="2016" <?= ($year == '2016' ? 'selected' : '') ?>>2016</option> <option value="2015" <?= ($year == '2015' ? 'selected' : '') ?>>2015</option> <option value="2014" <?= ($year == '2014' ? 'selected' : '') ?>>2014</option> <option value="2013" <?= ($year == '2013' ? 'selected' : '') ?>>2013</option> <option value="2012" <?= ($year == '2012' ? 'selected' : '') ?>>2012</option> </select>&nbsp;&nbsp; <input name="user_id" value="<?=$_SESSION['user_id'];?>" hidden/> <button type="submit" class="btn btn-sm btn-primary">GO</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <button type="button" class="btn btn-facebook btn-md center" data-toggle="modal" data-target="#overtimeRequest" <?=(!$request_ot? 'disabled':'');?>>Request Overtime</button> </form> </div> <span class="date_time"> <span class="time"> <span class="iconn"><i class="fa fa-clock icon">&nbsp;&nbsp;&nbsp;</i>Time: </span> </span> <span class="iconn"><i class="fa fa-calendar icon">&nbsp;&nbsp;&nbsp;</i>Date: <?=date('l F d, Y')?> </span> </span> </div> </div> <div class="details iconn"> <div class="rh tb_rh text_center"> <span class="show_leave_details">Leave: <span class="text-primary">___</span> <div style="display: none;"> <span class="width-200"></span> </div> </span>&nbsp;&nbsp;&nbsp; <span class="show_absent">Absent: <span class="text-primary">___</span> <div style="display: none;"> <span class="width-200"></span> </div> </span>&nbsp;&nbsp;&nbsp; <span >Over Time: <span class="text-primary">___</span> <div style="display: none"> <span class="width-200"></span> </div> </span>&nbsp;&nbsp;&nbsp; <span>Under Time: <span class="text-primary">___</span> <div style="display: none"> <span class="width-200"></span> </div> </span>&nbsp;&nbsp;&nbsp; <span>Late: <span class="text-primary">___</span> <div style="display: none"> <span class="width-200"></span> </div> </span> </div> </div> <div class="table-responsive"> <table id="attendance" class="table table-sm table-bordered"> <thead> <tr> <th colspan="2" class=" text_center border-left">Half-Month</th> <th colspan="2" class="text_center">Morning</th> <th class="width1"></th> <th colspan="2" class="text_center">Afternoon</th> <th class="width1"></th> <th colspan="2" class="text_center">OverTime</th> <th class="width1"></th> <th colspan="3" class="text_center border-right">Total Time</th> </tr> <tr class=""> <td class="width1 no_hover" colspan="2">Days</td> <td class="width1 no_hover">In</td> <td class="width1 no_hover">Out</td> <td class="width1 no_hover">Time</td> <td class="width1 no_hover">In</td> <td class="width1 no_hover">Out</td> <td class="width1 no_hover">Time</td> <td class="width1 no_hover">In</td> <td class="width1 no_hover">Out</td> <td class="width1 no_hover tc" title="Time Convention" data-toggle='tooltip' data-container='body'>TC </td> <td class="width1 no_hover">Time</td> <td class="width1 no_hover">Pre</td> <td class="width1 no_hover">OT</td> <td class="width1 no_hover">Late</td> </tr> </thead> <tbody> <?php $j = 0;$total_time = 0; $total_ot=0?> <?php $i;for ($i = 0;$i < count($days); $i++): ?> <tr class=" <?=($days[$i][1]=='Sun'? 'sunday':'')?>"> <td width="40"><?= $days[$i][0] ?></td> <td width="40"><?= $days[$i][1] ?></td> <?php if(count($time)==0||$j==-1 || $days[$i][1]=='Sun'):?> <td align="center"> <input value="" style="width: 30px;text-align: center;border: 0">: <input value="" style="width: 30px;text-align: center;border: 0"> </td> <td align="center"> <input value="" style="width: 30px;text-align: center;border: 0">: <input value="" style="width: 30px;text-align: center;border: 0"> </td> <td class="text_center"></td> <td align="center"> <input value="" style="width: 30px;text-align: center;border: 0">: <input value="" style="width: 30px;text-align: center;border: 0"> </td> <td align="center"> <input value="" style="width: 30px;text-align: center;border: 0">: <input value="" style="width: 30px;text-align: center;border: 0"> </td> <td class="text_center"></td> <td align="center"> <input value="" style="width: 30px;text-align: center;border: 0">: <input value="" style="width: 30px;text-align: center;border: 0"> </td> <td align="center"> <input value="" style="width: 30px;text-align: center;border: 0">: <input value="" style="width: 30px;text-align: center;border: 0"> </td> <td class="text_center"></td> <td class="text_center"></td> <td class="text_center"></td> <td class="text_center"></td> <?php elseif ($days[$i][0] == date('d', strtotime($time[$j]->date))) :?> <td align="center"> <input value="<?= ($time[$j]->morning_in_hour ?? ''); ?>" style="width: 30px;text-align: center;border: 0">: <input value="<?= ($time[$j]->morning_in_minute ??''); ?>" style="width: 30px;text-align: center;border: 0"> </td> <td align="center"> <input value="<?= ($time[$j]->morning_out_hour ?? ''); ?>" style="width: 30px;text-align: center;border: 0">: <input value="<?= ($time[$j]->morning_out_minute ?? ''); ?>" style="width: 30px;text-align: center;border: 0"> </td> <td class="text_center"><?=($time[$j]->morning_time??'')?> </td> <td align="center"> <input value="<?= $time[$j]->afternoon_in_hour; ?>" style="width: 30px;text-align: center;border: 0">: <input value="<?= $time[$j]->afternoon_in_minute; ?>" style="width: 30px;text-align: center;border: 0"> </td> <td align="center"> <input value="<?= $time[$j]->afternoon_out_hour; ?>" style="width: 30px;text-align: center;border: 0">: <input value="<?= $time[$j]->afternoon_out_minute; ?>" style="width: 30px;text-align: center;border: 0"> </td> <td class="text_center"><?=($time[$j]->afternoon_time??'')?> </td> <td align="center"> <input value="<?= $time[$j]->over_in_hour; ?>" style="width: 30px;text-align: center;border: 0">: <input value="<?= $time[$j]->over_in_minute; ?>" style="width: 30px;text-align: center;border: 0"> </td> <td align="center"> <input value="<?= $time[$j]->over_out_hour; ?>" style="width: 30px;text-align: center;border: 0">: <input value="<?= $time[$j]->over_out_minute; ?>" style="width: 30px;text-align: center;border: 0"> </td> <td class="text_center"> <td class="text_center"> <?php if($time[$j]->afternoon_time!=null&&$time[$j]->morning_time!=null){}{ $pre = $time[$j]->afternoon_time+$time[$j]->morning_time; if($pre>=8){ echo '8'; $total_time +=8; }else if($pre>0){ echo $pre; $total_time+=$pre; } } ?> </td> <td class="text_center"> <?php if($time[$j]->afternoon_time!=null&&$time[$j]->morning_time!=null){}{ $pre = $time[$j]->afternoon_time+$time[$j]->morning_time; if($pre>=8){ $pre-=8; echo $pre+$time[$j]->over_time; $total_ot +=$pre+$time[$j]->over_time; } } ?> </td> <td class="text_center"> <!-- --><?php // if($time[$j]->afternoon_time!=null&&$time[$j]->morning_time!=null){}{ // $pre = $time[$j]->afternoon_time+$time[$j]->morning_time; // if($pre<8){ // $pre-=8; // echo round(abs($pre)); // } // } // ?> </td> <?php ($j < count($time) - 1 ? $j++ : $j = -1)?> <?php elseif($days[$i][1]!='Sun'):?> <td class="text_center absent" colspan="12">ABSENT</td> <?php endif; endfor;?> </tr> <tr> <td style="text-align: right" colspan="11">Total Time:</td> <td class="text_center"><?=$total_time?></td> <td class="text_center"><?=$total_ot?></td> <td class="text_center"></td> </tr> </tbody> </table> </div> </div> </div> </div> <!--REQUEST OVERTIME--> <div class="modal fade" id="overtimeRequest" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title kulay" id="exampleModalLabel">Request Overtime</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body mod"> <div class="card"> <!--Card content--> <div class="card-body px-lg-5 pt-0 border"> <br> <form method="post" action="requestOvertime"> <div class="form-group"> <label for="formGroupExampleInput">Reason</label> <input type="text" class="form-control" id="formGroupExampleInput" name="reason" placeholder="Please state your reason" required/> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Submit</button> </div> </form> <!-- Form --> </div> </div> </div> </div> </div> </div><file_sep>/application/backup/employee/home.php <div class="container-fluid"> <section class="banner-section hidden-xs"> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <div class="item active"> <img src="<?=base_url()?>assets/img/slide1.png" alt="slide1"> <div class="carousel-caption"> <h1>Aflex HOMES </h1> <p>We offer an affordable option for new home buyers New Zealand wide.</p> <a class="get_bg_btn" href="contact.html">GET IN TOUCH</a> </div> </div> </div> </div> </section> <!-- .banner-section--> </div> <br> <br> <br> <!--================Why Chose Us Area =================--> <div class="container"> <div class="row"> <div class="col-md-6"> <div class="why_us"> <h2>WHY CHOOSE US?</h2> <p>Here at Aflex Homes we have spent years developing and perfecting the home planning and construction processes. This means you can trust us to deliver high quality homes and customer service. We are with you through the entire journey, you will quickly discover that we get just as excited about your new home, as you do.</p> </div> </div> <div class="col-md-6"> <img src="<?=base_url()?>assets/img/about.jpg" alt="about" width="550" height="350"> </div> </div> </div> <!--================End Why Chose Us Area =================--> <br> <br> <br> <div class="container"> <div class="row"> <div class="service-section"> <div class="col-md-12"> <!-- Nav tabs --> <ul class="tablist" role="tablist"> <li>Some of our Products</li> <li role="presentation" class="active"><a href="#transport" aria-controls="transport" role="tab" data-toggle="tab">Transportable</a></li> <li role="presentation"><a href="#kitset" aria-controls="kitset" role="tab" data-toggle="tab">Kitset</a></li> </ul> </div> <div class="tab-content"> <div role="tabpanel" class="tab-pane active" id="transport"> <div class="col-md-6 col-xs-12 col-sm-6"> <div class="service-item"> <div class="service-thumb"> <img src="<?=base_url()?>assets/img/service/Transport/stafford.jpg" alt=""> </div> <div class="service-description"> <a href="water-heater.html"> <h3>STAFFORD</h3> </a> <p>Affordable family living. Three bedroom, one bathroom home, with separate laundry.</p> </div> </div> </div> <div class="col-md-6 col-xs-12 col-sm-6"> <div class="service-item"> <div class="service-thumb"> <img src="<?=base_url()?>assets/img/service/Transport/esplanade.jpg" alt=""> </div> <div class="service-description"> <a href="bathroom.html"> <h3>ESPLANADE</h3> </a> <p>Surprisingly Spacious. Two bedroom, one bathroom home. The ideal Low cost living solution.</p> </div> </div> </div> <div class="col-md-6"> <a href="services">see all Transportable Homes</a> </div> </div> <div role="tabpanel" class="tab-pane fade" id="kitset"> <div class="col-md-6 col-xs-12 col-sm-6"> <div class="service-item"> <div class="service-thumb"> <img src="<?=base_url()?>assets/img/service/Transport/wakefield.jpg" alt=""> </div> <div class="service-description"> <a href="#"> <h3>WAKEFIELD</h3> </a> <p>3 bedroom family home, with large open plan living area and great-indoor outdoor flow.</p> </div> </div> </div> <div class="col-md-6 col-xs-12 col-sm-6"> <div class="service-item"> <div class="service-thumb"> <img src="<?=base_url()?>assets/img/service/Transport/adderley.jpg" alt=""> </div> <div class="service-description"> <a href="#"> <h3>ADDERLEY</h3> </a> <p>Ultra-modern 3 bedroom home with ensuite and sheltered outdoor entrance.</p> </div> </div> </div> <div class="col-md-12"> <a href="services">see all Kitset Homes</a> </div> </div> </div> </div> <!-- .service-section--> </div> <!-- .row--> </div> <!-- .container--> <div class="container"> <div class="service-activity"> <div class="row"> <div class="col-md-12"> <div class="activity-head"> <h2>Why you can rely with 100% confidence ON <span>Aflex HOMES</span></h2> </div> </div> </div> <div class="row"> <div class="activity-list-items"> <div class="col-md-4 col-xs-12 col-sm-4"> <div class="activity-list"> <div class="activity-icon"> <i class="fa fa-book"></i> </div> <div class="activity-details"> <h4>Honesty</h4> <p>we operate with honesty, integrity and in complete transparency. So that we serve 10,000+ clients.</p> </div> </div> </div> <div class="col-md-4 col-xs-12 col-sm-4"> <div class="activity-list"> <div class="activity-icon"> <i class="fa fa-clock-o"></i> </div> <div class="activity-details"> <h4>Non-stop service</h4> <p>We operate 24/7/365. You will be hard-pressed to to find in a plumber.</p> </div> </div> </div> <div class="col-md-4 col-xs-12 col-sm-4"> <div class="activity-list"> <div class="activity-icon"> <i class="fa fa-trophy"></i> </div> <div class="activity-details"> <h4>Awards</h4> <p>This is why we earned the Angie’s List Super Service Award 4 times in the last 4 years.</p> </div> </div> </div> </div> <!-- .activity-list-items--> </div> </div> <!-- .service-activity--> </div> <!-- .container--> <div class="quote-section"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="quote"> <h2>Let's wow you!</h2> <p>Ready to take it a step further? Let’s start talking about your Transportable or Kitset Home Need. We can help you.</p> <a class="get_bg_btn" href="contact.html">REQUEST A QUOTE</a> </div> <!--quote--> </div> </div> <!-- .row--> </div> <!-- .container--> </div> <!-- .quote-section--> <?php $this->load->view('includes/works-carousel');?> <!-- .our-clients-carousel--> </div> </div> <!-- .row --> </div> <!--================Address Area =================--> <section class="address_area"> <div class="container"> <div class="row address_inner"> <div class="col-md-4"> <div class="media"> <div class="media-left"> <img src="<?=base_url()?>assets/img/icon/place-icon.png" alt=""> </div> <div class="media-body"> <h4>Office Address :</h4> <h5>Auckland,New Zealand</h5> </div> </div> </div> <div class="col-md-4"> <div class="media"> <div class="media-left"> <img src="<?=base_url()?>assets/img/icon/phone-icon.png" alt=""> </div> <div class="media-body"> <h5>(027) 714-7739</h5> </div> </div> </div> <div class="col-md-4"> <div class="media"> <div class="media-left"> <img src="<?=base_url()?>assets/img/icon/inbox-icon.png" alt=""> </div> <div class="media-body"> <h5><EMAIL></h5> </div> </div> </div> </div> </div> </section> <!--================End Address Area =================--> <file_sep>/application/models/Dtr_model.php <?php /** * Created by PhpStorm. * User: User * Date: 05/02/2020 * Time: 9:25 PM */ class Dtr_model extends CI_Model { public function __construct() { parent::__construct(); } public function get_one($user_id, $start_day, $end_day) { $res = $this->db->select('*') ->from('tbl_loginsheet') ->where('staff_id', $user_id) ->where('date between "' . $start_day . '" and "' . $end_day . '"') ->order_by('date', 'asc') ->get() ->result(); return $res; } public function get_one2($user_id, $start_day, $end_day) { $res = $this->db->select('*') ->from('tbl_time_sheet') ->where('employee_id', $user_id) ->where('date between "' . $start_day . '" and "' . $end_day . '"') ->order_by('date', 'asc') ->get() ->result(); return $res; } public function get_all($start_day, $end_day) { $result = $this->db->select('*') ->from('tbl_employee as employee') ->join('tbl_loginsheet as loginsheet', 'employee.employee_id = loginsheet.staff_id') ->where('date between "' . $start_day . '" and "' . $end_day . '"') ->get() ->result(); return $result; } public function get_all2($start_day, $end_day) { $result = $this->db->select('*') ->from('tbl_employee as employee') ->join('tbl_time_sheet as loginsheet', 'employee.employee_id = loginsheet.employee_id') ->where('date between "' . $start_day . '" and "' . $end_day . '"') ->get() ->result(); return $result; } public function can_request_overtime($user_id) { $result = $this->db->select('*') ->from('tbl_overtime_request') ->where('employee_id', $user_id) ->where('date_request', date('Y-m-d')) ->get() ->result(); if (count($result) > 0) { return false; } else { return true; } } public function get_employee_time($employee_id, $date) { $result = $this->db->select('*') ->from('tbl_time_sheet') ->where('employee_id', $employee_id) ->where('date', $date) ->get() ->result(); return $result; } public function add($time_sheet) { $this->db->insert('tbl_time_sheet', $time_sheet); } public function update($time_sheet, $id) { $this->db->where('time_sheet_id', $id); $this->db->update('tbl_time_sheet', $time_sheet); } public function get_absent($id, $date = null) { if (is_null($date)) { $date = date('Y-m-d'); } } public function add_attendance($attedance) { $this->db->insert('tbl_attendance', $attedance); } public function get_today($user_id, $start_day) { $res = $this->db->select('*') ->from('tbl_time_sheet') ->where('employee_id', $user_id) ->where('date', $start_day) ->get() ->result(); return $res; } }<file_sep>/application/controllers/Login.php <?php /** * Created by PhpStorm. * UserModel: UserModel * Date: 27/01/2020 * Time: 10:15 AM */ class Login extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model("login_model"); $this->load->library('pagination', 'session'); } public function index() { if ($this->session->userdata('is_logged_in')) { if ($_SESSION['user_type'] == "Admin") { redirect(base_url('dashboard')); } else { redirect(base_url('dtr')); } } else { $this->load->view('index'); } } public function login() { if (!empty($_POST)) { $user = $_POST['username']; $pass = $_POST['<PASSWORD>']; $this->verify_login($user, $pass); } else { $this->index(); } } function verify_login($user, $pass) { $employee = $this->login_model->validate($user, $pass); if ($employee != false) { $data = array( 'username' => $employee[0]->username, 'name' => strtoupper($employee[0]->lastname . ' ' . $employee[0]->firstname), 'user_type' => $employee[0]->user_role, 'user_id' => $employee[0]->employee_id, 'is_logged_in' => true ); $this->session->set_userdata($data); switch ($employee[0]->user_role) { case 'Admin' : redirect(base_url('dashboard')); break; case 'Employee' : case 'Payroll Master' : redirect(base_url('dtr')); break; } } else { $error_credentials = "<h6 id='error' style='color: rgba(255,0,0,0.7)' hidden>Incorrect username or password, Please try gain!</h6>"; echo $error_credentials; $this->index(); } } public function logout() { if ($_POST['logout']=="true") { $this->session->unset_userdata('username'); $this->session->unset_userdata('user_id'); $this->session->unset_userdata('user_type'); $this->session->unset_userdata('is_logged_in'); $this->session->sess_destroy(); } return redirect(base_url()); } public function validate_credentials() { $this->load->library('form_validation'); $this->form_validation->set_rules('username', 'Username:', 'required|trim|xss_clean|callback_validation'); $this->form_validation->set_rules('password', 'Password:', 'required|trim'); $this->load->model('Login_model'); $query = $this->login_model->validate(); if ($query) // if the user's credentials validated... { if ($this->form_validation->run()) { redirect('pricing'); } } else // incorrect username or password { $this->index(); } } public function validate() { $credentials = [ 'username' => $_POST['username'], 'password' => $_POST['<PASSWORD>'] ]; foreach ($credentials as $key => $value) { define(strtoupper($key), $value); } $query = $this->db->get_where('users', array('username' => USERNAME)); $row = $query->row(); if ($query->num_rows() == 1) { if (isset($row)) { //Using hashed password - (PASSWORD_BCRYPT method) - from database $hash = $row->password; $verify = password_verify(PASSWORD, $hash); $data = array( 'username' => $row->username, 'user_type' => $row->user_type, 'is_logged_in' => true ); $this->session->set_userdata($data); if ($verify) { return true; } } } } public function add() { // TODO: Implement add() method. } public function view() { // TODO: Implement view() method. } public function update() { // TODO: Implement update() method. } public function delete() { // TODO: Implement delete() method. } }<file_sep>/application/controllers/Dashboard.php <?php /** * Created by PhpStorm. * User: User * Date: 05/02/2020 * Time: 9:13 PM */ class Dashboard extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('pagination', 'session'); $this->load->model(array("dtr_model", 'employee_model', 'dashboard_model', 'holiday_model')); if (!$_SESSION['is_logged_in']) { redirect(base_url('')); } if ($_SESSION['user_type'] != "Admin") { redirect(base_url('404')); } } public function view() { $employees = $this->employee_model->get_employees(); $lates = $this->late_today(); $data['lates'] = $lates; $data['page_load'] = "admin/dashboard"; $data['active'] = "dashboard"; $data['employees'] = $employees; $this->load->view('includes/template', $data); } public function chart_data() { $lat = $this->late_by_month(); $data = array(); $data[] = $lat['lates']; $data[] = $lat['ontime']; $data[] = $lat['absences']; echo json_encode($data); } public function add() { // TODO: Implement add() method. } public function update() { // TODO: Implement update() method. } public function delete() { // TODO: Implement delete() method. } public function late_today() { $start_day = date('Y-m-d'); $end_day = date('Y-m-d'); $employees = $this->employee_model->get_employees(); $late = 0; $holidays = $this->holiday_model->get_holidays($start_day, $end_day);//get the holidays for the specific payroll period foreach ($employees as $em) { $time_data = $this->dtr_model->get_today($em->employee_id, $start_day); if (count($time_data) > 0) { $s = str_replace(" ", "", $em->time_in); $s = str_replace(":", ".", $s); $s = str_split($s, 5); // time_in mornig $t = str_replace(":", ".", $time_data[0]->morning_in); //time in //schedule if (doubleval($t) >= doubleval($s[0])) { $late_diff = (doubleval($t) - doubleval($s[0])); if ($late_diff >= .15) { $late++; } } // time_in afternoon else { $t = str_replace(":", ".", $time_data[0]->afternoon_in); if (doubleval($t) >= doubleval($s[0])) { $late_diff = (doubleval($t)) - (doubleval($s[0])); if ($late_diff >= .15) { $late++; } } } } } return $late; } public function late_by_month() { $lat = array(); $abs = array(); $ont = array(); for ($i = 1; $i <= 3; $i++) { $year = date('Y'); $month = date('m', strtotime($year . '-' . $i . '-01')); $start_day = $year . "-" . $month . '-01'; $end_day = $year . '-' . $month . '-' . date('t', strtotime($start_day)); $employees = $this->employee_model->get_employees(); $holidays = $this->holiday_model->get_holidays($start_day, $end_day); $late = 0; $absences = 0; $ontime = 0; $days = intval(date('t', strtotime($start_day))); foreach ($employees as $employee) { $time_data = $this->dtr_model->get_one2($employee->employee_id, $start_day, $end_day); // var_dump($start_day . ' ' . $end_day); // var_dump($time_data); $ndx = 0; if (count($time_data) > 0) { for ($j = 1; $j <= $days; $j++) { $day = date('Y-m-d', strtotime($year . '-' . $month . '-' . $j)); $day_name = date('l', strtotime($day)); if ($day == $time_data[$ndx]->date) { $s = str_replace(" ", "", $employee->time_in); $s = str_replace(":", ".", $s); $s = str_split($s, 5); // time_in mornig $t = str_replace(":", ".", $time_data[$ndx]->morning_in); $aft = str_replace(":", ".", $time_data[$ndx]->afternoon_in); //time in //schedule if (doubleval($t) >= doubleval($s[0])) { $late_diff = (doubleval($t) - doubleval($s[0])); if ($late_diff >= .15) { $late++; } } // time_in afternoon elseif (doubleval($aft) >= doubleval($s[0])) { $late_diff_aft = (doubleval($aft)) - (doubleval($s[0])); if ($late_diff_aft >= .15) { $late++; } } else { $ontime++; } if ($ndx < count($time_data) - 1) { $ndx++; } //!= sunday && not equal holidays } elseif ($day_name != "Sunday") { $absences++; } } } } $abs[] = $absences; $lat[] = $late; $ont[] = $ontime; } $data['lates'] = $lat; $data['absences'] = $abs; $data['ontime'] = $ont; return $data; } public function push() { redirect(base_url('dashboard')); } }<file_sep>/application/views/includes/css.php <?php /** * Created by PhpStorm. * UserModel: UserModel * Date: 27/01/2020 * Time: 9:23 AM */?> <link href="assets/vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href="assets/css/defaultTheme.css" rel="stylesheet"> <link href="assets/css/sb-admin-2.min.css" rel="stylesheet"> <link href="assets/vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet"> <link href="../assets/vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href="../assets/css/defaultTheme.css" rel="stylesheet"> <link href="../assets/css/sb-admin-2.min.css" rel="stylesheet"> <link href="../assets/vendor/datatables/dataTables.bootstrap4.min.css" rel="stylesheet"> <file_sep>/application/views/includes/footer.php <?php /** * Created by PhpStorm. * User: <NAME> * Date: 1/15/2020 * Time: 3:12 PM */ ?> </div> <footer class="sticky-footer bg-white"> <div class="container my-auto"> <div class="copyright text-center my-auto"> <span>Copyright &copy; Team Premium <?= date('Y'); ?></span> </div> </div> </footer> </div> </div> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <?php include 'modals/logout_modal.php' ?> <?php include 'scripts.php' ?> <script>//SEARCH BAR FOR JOBS if (window.history.replaceState) { window.history.replaceState(null, null, window.location.href); } $('#search_text_reports').on('input', function () { var searchTerm = $(this).val().toUpperCase(); $('.search').each(function () { var jobs = $(this).data('search-term').toUpperCase(); if (jobs.indexOf(searchTerm) > -1) { $(this).show(); } else { $(this).hide(); } }); }); if (window.history.replaceState) { window.history.replaceState(null, null, window.location.href); } // $(document).ready(function () { // try{ // $('#dataTable').DataTable(); // }catch (Exception e){} // }); // var span = document.getElementById('span'); // // function time() { // var d = new Date(); // var s = d.getSeconds(); // var m = d.getMinutes(); // var h = d.getHours(); // span.textContent = h + ":" + m + ":" + s; // } // // setInterval(time, 1000); </script> </body> </html> <file_sep>/application/controllers/Calendar2.php <?php /** * Created by PhpStorm. * User: capstonestudent * Date: 2/18/2020 * Time: 9:59 PM */ class Calendar2 extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('pagination', 'session'); $this->load->model(array("event_model", "holiday_model")); if (!$_SESSION['is_logged_in']) { redirect(base_url('')); } } public function view() { $data['page_load'] = "admin/calendar2"; $data['active'] = "dashboard"; $this->load->view('includes/template', $data); } public function add() { } public function update() { } public function delete() { } }<file_sep>/application/views/admin/overtime.php <link href="<?=base_url()?>assets/css/custom.css" rel="stylesheet"> <div class="container-fluid"> <!-- <h1 class="h3 mb-4 text-gray-800">Attendance - TODO ( Mariel) </h1>--> <!-- DataTales --> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary"><strong>TDZ</strong> <i class="divider"> / </i> <span>Overtime</span></h6> </div> <div class="card-body"> <input type="button" class="btn btn-facebook" value="Add New Overtime" data-toggle="modal" data-target="#add-overtime"><br><br> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" style="max-height: 50vh;overflow: auto" width="100%" cellspacing="0"> <thead> <tr class="fonts"> <th>Date</th> <th>EMPLOYEE ID</th> <th>EMPLOYEE NAME</th> <th>From</th> <th>To</th> <th>Reason</th> <th>Status</th> <th class="text_center">TOOLS</th> </tr> </thead> <tbody> <?php foreach ($overtimes as $overtime):?> <tr> <td><?=$overtime->date_request;?></td> <td><?=$overtime->employee_id;?></td> <td><?=strtoupper($overtime->lastname." ".$overtime->firstname);?></td> <td><?=$overtime->request_start_time;?></td> <td><?=$overtime->request_end_time;?></td> <td><?=$overtime->reason;?></td> <td><?=$overtime->status;?></td> <td class="text_center display-flex"> <i class="btn btn-info fa fa-edit iconaccept" <?=($overtime->status=='Pending' ? 'data-toggle="modal" ':'style=" cursor: not-allowed;"');?> data-target="#overtimeAccept<?=$overtime->overtime_request_id?>" >Accept</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete"<?=($overtime->status=='Pending' ? 'data-toggle="modal" ':'style=" cursor: not-allowed;"');?> data-target="#overtimeReject<?=$overtime->overtime_request_id?>">&nbsp;&nbsp;Reject</i> </td> <?php endforeach;?> </tr> </tbody> </table> </div> </div> </div> <?php include getcwd().'/application/views/includes/modals/add/add_overtime_modal.php';?> <!-- Edit Modal--> <div class="modal fade" id="overtimeEdit" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Add Overtime</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form action=""> <div class="form-group row"> <label for="date" class="col-sm-4 col-form-label">Date</label> <div class="col-sm-5"> <input type="text" class="form-control" id="date"> </div> </div> <div class="form-group row"> <label for="empID" class="col-sm-4 col-form-label">Employee ID</label> <div class="col-sm-5"> <input type="text" class="form-control" id="empID"> </div> </div> <div class="form-group row"> <label for="empName" class="col-sm-4 col-form-label">Employee Name</label> <div class="col-sm-5"> <input type="text" class="form-control" id="empName"> </div> </div> <div class="form-group row"> <label for="datefrm" class="col-sm-4 col-form-label">Date From</label> <div class="col-sm-5"> <input type="text" class="form-control" id="datefrm"> </div> </div> <div class="form-group row"> <label for="dateto" class="col-sm-4 col-form-label">Date To</label> <div class="col-sm-5"> <input type="text" class="form-control" id="dateto"> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save</button> </div> </div> </div> </div> <?php foreach ($overtimes as $overtime):?> <div class="modal fade" id="overtimeAccept<?=$overtime->overtime_request_id?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <form action="update-overtime" method="post"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Delete Schedule</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p class="text_center">Are you sure you want to accept this?</p> </div> <input type="text" value=<?=$overtime->overtime_request_id?> name="overtime_id" hidden> <input type="text" value="Accepted" name="status" hidden> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">No</button> <button type="submit" class="btn btn-primary">Yes</button> </div> </form> </div> </div> </div> <?php endforeach;?> <!-- Modal for delete--> <?php foreach ($overtimes as $overtime):?> <div class="modal fade" id="overtimeReject<?=$overtime->overtime_request_id?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <form action="update-overtime" method="post"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Delete Schedule</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p class="text_center">Are you sure you want to reject this?</p> </div> <input type="text" value=<?=$overtime->overtime_request_id?> name="overtime_id" hidden> <input type="text" value="Rejected" name="status" hidden> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">No</button> <button type="submit" class="btn btn-primary">Yes</button> </div> </form> </div> </div> </div> <?php endforeach;?> </div><file_sep>/application/views/includes/template.php <?php /** * Created by PhpStorm. * User: <NAME> * Date: 1/15/2020 * Time: 4:23 PM */?> <?php $this->load->view('includes/header')?> <?php $this->load->view($page_load)?> <?php $this->load->view('includes/footer')?><file_sep>/application/backup/employee/employees_leave_requests.php <?php /** * Created by PhpStorm. * User: capstonestudent * Date: 1/15/2020 * Time: 9:23 PM */ ?> <link href="../../../assets/css/custom.css" rel="stylesheet"> <div class="container-fluid"> <!-- Page Heading --> <h1 class="h3 mb-3 text-gray-800"><strong>TDZ</strong> <i class="divider"> / </i> <span>Leave Requests</span></h1> <!-- DataTales Example --> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary"><a href="leave_requests"><span>My Leave Requests</span></a></h6> </div> <br> <div>&nbsp;&nbsp;&nbsp;&nbsp; <button type="button" class="btn btn-facebook btn-md" data-toggle="modal" data-target="#leaveRequest">Add Leave Request</button>&nbsp; <span class="date_time_leave_employee"> <span class="time"> <span class="iconn"><i class="fa fa-clock icon">&nbsp;&nbsp;&nbsp;</i>Time: </span> </span> <span class="iconn"><i class="fa fa-calendar icon">&nbsp;&nbsp;&nbsp;</i>Date: </span> </span> </div> <div class="card-body"> <div class="table-responsive"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr class="fonts"> <th>EMPLOYEE ID</th> <th>EMPLOYEE NAME</th> <th>DATE REQUESTED</th> <th>DATE FROM</th> <th>DATE TO</th> <th>TYPE</th> <th>STATUS</th> <th class="text_center">TOOLS</th> </tr> </thead> <tbody> <tr> <td class="text_center">1107</td> <td><NAME>y</td> <td>January 18, 2020</td> <td>January 29, 2020</td> <td>February 14, 2020</td> <td>Sick Leave</td> <td>Pending</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#leaveRequestEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#leaveRequestDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr> <td class="text_center">1340</td> <td><NAME></td> <td>December 12, 2019</td> <td>December 15, 2019</td> <td>December 30, 2019</td> <td>Maternity Leave</td> <td>Approved</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#leaveRequestEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#leaveRequestDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr> <td class="text_center">3102</td> <td><NAME></td> <td>April 11, 2019</td> <td>April 30, 2019</td> <td>May 5, 2019</td> <td>Fraternity Leave</td> <td>Approved</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#leaveRequestEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#leaveRequestDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr> <td class="text_center">1352</td> <td>Kerrang</td> <td>March 9, 2019</td> <td>March 20, 2019</td> <td>March 28, 2019</td> <td>Sick Leave</td> <td>Approved</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#leaveRequestEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#leaveRequestDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr> <td class="text_center">8674</td> <td>Tipzy</td> <td>December 12, 2019</td> <td>December 15, 2019</td> <td>December 30, 2019</td> <td>Maternity Leave</td> <td>Approved</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#leaveRequestEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#leaveRequestDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr> <td class="text_center">2428</td> <td>Nadnad</td> <td>April 11, 2019</td> <td>April 30, 2019</td> <td>May 5, 2019</td> <td>Fraternity Leave</td> <td>Approved</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#leaveRequestEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#leaveRequestDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr> <td class="text_center">3838</td> <td>Kwangkeng</td> <td>March 9, 2019</td> <td>March 20, 2019</td> <td>March 28, 2019</td> <td>Sick Leave</td> <td>Approved</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#leaveRequestEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#leaveRequestDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr> <td class="text_center">8762</td> <td>Chingkoy</td> <td>December 12, 2019</td> <td>December 15, 2019</td> <td>December 30, 2019</td> <td>Maternity Leave</td> <td>Approved</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#leaveRequestEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#leaveRequestDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr> <td class="text_center">3543</td> <td>Elicka</td> <td>April 11, 2019</td> <td>April 30, 2019</td> <td>May 5, 2019</td> <td>Fraternity Leave</td> <td>Approved</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#leaveRequestEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#leaveRequestDelete">&nbsp;&nbsp;Delete</i> </td> <tr> <td class="text_center">5439</td> <td><NAME></td> <td>January 18, 2020</td> <td>January 29, 2020</td> <td>February 14, 2020</td> <td>Sick Leave</td> <td>Pending</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#leaveRequestEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#leaveRequestDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr> <td class="text_center">5843</td> <td><NAME></td> <td>December 12, 2019</td> <td>December 15, 2019</td> <td>December 30, 2019</td> <td>Maternity Leave</td> <td>Approved</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#leaveRequestEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#leaveRequestDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr> <td class="text_center">2113</td> <td><NAME></td> <td>April 11, 2019</td> <td>April 30, 2019</td> <td>May 5, 2019</td> <td>Fraternity Leave</td> <td>Approved</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#leaveRequestEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#leaveRequestDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr> <td class="text_center">1123</td> <td><NAME></td> <td>March 9, 2019</td> <td>March 20, 2019</td> <td>March 28, 2019</td> <td>Sick Leave</td> <td>Approved</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#leaveRequestEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#leaveRequestDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr> <td class="text_center">6843</td> <td>Opora Mix</td> <td>December 12, 2019</td> <td>December 15, 2019</td> <td>December 30, 2019</td> <td>Maternity Leave</td> <td>Approved</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#leaveRequestEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#leaveRequestDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr> <td class="text_center">7231</td> <td><NAME></td> <td>April 11, 2019</td> <td>April 30, 2019</td> <td>May 5, 2019</td> <td>Fraternity Leave</td> <td>Approved</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#leaveRequestEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#leaveRequestDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr> <td class="text_center">5425</td> <td>Pringles</td> <td>March 9, 2019</td> <td>March 20, 2019</td> <td>March 28, 2019</td> <td>Sick Leave</td> <td>Approved</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#leaveRequestEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#leaveRequestDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr> <td class="text_center">4525</td> <td>Piattos</td> <td>December 12, 2019</td> <td>December 15, 2019</td> <td>December 30, 2019</td> <td>Maternity Leave</td> <td>Approved</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#leaveRequestEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#leaveRequestDelete">&nbsp;&nbsp;Delete</i> </td> </tr> <tr> <td class="text_center">9864</td> <td>Nova</td> <td>April 11, 2019</td> <td>April 30, 2019</td> <td>May 5, 2019</td> <td>Fraternity Leave</td> <td>Approved</td> <td class="text_center"> <i class="btn btn-info fa fa-edit iconedit" data-toggle="modal" data-target="#leaveRequestEdit">&nbsp;&nbsp;Edit</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" data-toggle="modal" data-target="#leaveRequestDelete">&nbsp;&nbsp;Delete</i> </td> </tr> </tbody> </table> </div> </div> </div> </div> <!---------------LEAVE REQUEST MODAL--------------------> <div class="modal fade" id="leaveRequest" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title kulay" id="exampleModalLabel">Request Leave</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body mod"> <div class="card"> <!--Card content--> <div class="card-body px-lg-5 pt-0 border"> <br> <form method="post" action=""> <div class="form-group"> <label for="formGroupExampleInput">Employee Name</label> <input type="text" class="form-control" id="formGroupExampleInput" placeholder="<NAME>"> </div> <div class="form-group"> <label for="formGroupExampleInput2">Date Requested</label> <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="mm / dd / yy"> </div> <div> <div class="form-group"> <label for="formGroupExampleInput">Date from</label> <input type="text" class="form-control" id="formGroupExampleInput" placeholder="mm / dd / yy"> </div> <div class="form-group"> <label for="formGroupExampleInput2">Date to</label> <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="mm / dd / yy"> </div> </div> <div class="form-group"> <label for="formGroupExampleInput">Type of Leave</label> <input type="text" class="form-control" id="formGroupExampleInput" placeholder="dropdown ni"> </div> </form> <!-- Form --> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Submit</button> </div> </div> </div> </div> <!-- END OF LEAVE REQUEST MODAL--> <!---------------EDIT MODAL--------------------> <div class="modal fade" id="leaveRequestEdit" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title kulay" id="exampleModalLabel">Edit Leave Request</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body mod"> <div class="card"> <!--Card content--> <div class="card-body px-lg-5 pt-0 border"> <br> <form method="post" action=""> <div class="form-group"> <label for="formGroupExampleInput">Employee Name</label> <input type="text" class="form-control" id="formGroupExampleInput" placeholder="<NAME>"> </div> <div class="form-group"> <label for="formGroupExampleInput2">Date Requested</label> <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="mm / dd / yy"> </div> <div> <div class="form-group"> <label for="formGroupExampleInput">Date from</label> <input type="text" class="form-control" id="formGroupExampleInput" placeholder="mm / dd / yy"> </div> <div class="form-group"> <label for="formGroupExampleInput2">Date to</label> <input type="text" class="form-control" id="formGroupExampleInput2" placeholder="mm / dd / yy"> </div> </div> <div class="form-group"> <label for="formGroupExampleInput">Type of Leave</label> <input type="text" class="form-control" id="formGroupExampleInput" placeholder="dropdown ni"> </div> </form> <!-- Form --> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> <!-- END OF EDIT MODAL--> <!---------------DELETE MODAL--------------------> <div class="modal fade" id="leaveRequestDelete" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title kulay" id="exampleModalLabel">Delete Leave Request</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body mod"> <div> <!--Card content--> <div> <span style="color: black">Are you sure you want to delete this request?</span> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-primary">Delete</button> </div> </div> </div> </div> <!-- END OF DELETE MODAL--><file_sep>/application/views/admin/employees_leave.php <?php /** * Created by PhpStorm. * User: capstonestudent * Date: 1/15/2020 * Time: 9:23 PM */ ?> <link href="<?=base_url()?>assets/css/custom.css" rel="stylesheet"> <div class="container-fluid"> <!-- Page Heading --> <h1 class="h3 mb-3 text-gray-800"><strong>TDZ</strong> <i class="divider"> / </i> <span>Leave Requests</span></h1> <!-- DataTales Example --> <div class="card shadow mb-4"> <div class="card-header py-3"> <h6 class="m-0 font-weight-bold text-primary"><a href="leave"><span>My Leave Requests</span></a></h6> </div> <br> <div>&nbsp;&nbsp;&nbsp;&nbsp; <button type="button" class="btn btn-facebook btn-md" data-toggle="modal" data-target="#leaveRequest">Add Leave Request</button>&nbsp; </div> <div class="card-body"> <div class="table-responsive" style="overflow:auto; max-height: 50vh"> <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0"> <thead> <tr class="fonts"> <th>EMPLOYEE ID</th> <th>EMPLOYEE NAME</th> <th>DATE REQUESTED</th> <th>DATE FROM</th> <th>DATE TO</th> <th>TYPE</th> <th>STATUS</th> <th class="text_center">TOOLS</th> </tr> </thead> <tbody> <?php foreach ($leaves as $leave):?> <tr> <td><?=$leave->employee_id;?></td> <td><?=strtoupper($leave->lastname." ".$leave->firstname);?></td> <td><?=$leave->date_request;?></td> <td><?=$leave->request_start_time;?></td> <td><?=$leave->request_duration;?></td> <td><?=$leave->type;?></td> <td><?=$leave->status;?></td> <td class="text_center display-flex"> <i class="btn btn-info fa fa-edit iconaccept"<?=($leave->status=='Pending' ? 'data-toggle="modal" ':'style=" cursor: not-allowed;"');?> data-target="#leaveRequestAccept<?=$leave->leave_request_id?>" >Accept</i>&nbsp;&nbsp;&nbsp; <i class="btn btn-danger fa fa-trash-alt icondelete" <?=($leave->status=='Pending' ? 'data-toggle="modal" ':'style=" cursor: not-allowed; "');?> data-target="#leaveRequestReject<?=$leave->leave_request_id?>">&nbsp;&nbsp;Reject</i> </td> <?php endforeach;?> </tr> </tbody> </table> </div> </div> </div> </div> <!--add--> <?php include getcwd().'/application/views/includes/modals/add/add_leave_modal.php';?> <!--accept--> <?php foreach ($leaves as $leave):?> <div class="modal fade" id="leaveRequestAccept<?=$leave->leave_request_id;?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title kulay" id="exampleModalLabel">Request Leave</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body mod"> <div class="card"> <!--Card content--> <div class="card-body px-lg-5 pt-0 border"> <br> <form method="post" action="update-leave-status"> <div class="form-group"> <h5 for="formGroupExampleInput">Confirm accept leave request.</h5> <input name ="leave_id" value=<?=$leave->leave_request_id;?> hidden type="text"/> <input name ="status" value="Accepted" hidden type="text"/> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Accept</button> </div> </form> <!-- Form --> </div> </div> </div> </div> </div> </div> <?php endforeach;?> <!--edit--> <div class="modal fade" id="leaveRequestEdit" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title kulay" id="exampleModalLabel">Edit Leave Request</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body mod"> <div class="card"> <!--Card content--> <div class="card-body px-lg-5 pt-0 border"> <br> <form method="post" action=""> <div class="form-group"> <label for="formGroupExampleInput">Employee Name</label> <input type="text" class="form-control" placeholder="<NAME>"> </div> <div class="form-group"> <label for="formGroupExampleInput2">Date Requested</label> <input type="text" class="form-control" placeholder="mm / dd / yy"> </div> <div> <div class="form-group"> <label for="formGroupExampleInput">Date from</label> <input type="text" class="form-control" placeholder="mm / dd / yy"> </div> <div class="form-group"> <label for="formGroupExampleInput2">Date to</label> <input type="text" class="form-control" placeholder="mm / dd / yy"> </div> </div> <div class="form-group"> <label for="formGroupExampleInput">Type of Leave</label> <input type="text" class="form-control" placeholder="dropdown ni"> </div> </form> <!-- Form --> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> <!--reject--> <?php foreach ($leaves as $leave):?> <div class="modal fade" id="leaveRequestReject<?=$leave->leave_request_id?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title kulay" id="exampleModalLabel">Request Leave</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body mod"> <div class="card"> <!--Card content--> <div class="card-body px-lg-5 pt-0 border"> <br> <form method="post" action="update-leave-status"> <div class="form-group"> <h5 for="formGroupExampleInput">Confirm reject leave request.</h5> <input name ="leave_id" value=<?=$leave->leave_request_id?> hidden type="text"/> <input name ="status" value="Rejected" hidden type="text"/> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Reject</button> </div> </form> <!-- Form --> </div> </div> </div> </div> </div> </div> <?php endforeach;?>
ab331a5983b36ed2af2f8fbbd7b8a94ce96e223e
[ "PHP" ]
70
PHP
johnebarita/ptbcsi
284561592df6f6679ab5df461817b10df1a24a7e
983723dd2b1656eb61999354d327348ee8c67f43
refs/heads/master
<file_sep>package co.adrianblan.fastbrush; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.os.Bundle; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.Spannable; import android.text.SpannableString; import android.text.style.ImageSpan; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; public class Main2Activity extends AppCompatActivity { private MyGLSurfaceView mMyGLSurfaceView; private Button mClearButton; private Button mSaveButton; private Button mBitmapButton; private File mPhoto; private Bitmap mBitmap; private EditText mEText; private ImageView mImageView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); mMyGLSurfaceView = (MyGLSurfaceView) findViewById(R.id.signature_pad); mClearButton = (Button) findViewById(R.id.clear); mSaveButton = (Button) findViewById(R.id.save); mBitmapButton = (Button) findViewById(R.id.bitmap); mEText = (EditText) findViewById(R.id.modify_edit_text_view); mClearButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mMyGLSurfaceView.clearScreen(); } }); mImageView = (ImageView) findViewById(R.id.iamgeview); mSaveButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Bitmap signatureBitmap = mMyGLSurfaceView.getRenderer().getBitmap(); // mImageView.setVisibility(View.VISIBLE); // mImageView.setImageBitmap(signatureBitmap); boolean b = addJpgSignatureToGallery(signatureBitmap); if (b){ saveBitmap(mPhoto); mMyGLSurfaceView.clearScreen(); } // mMyGLSurfaceView.saveImage(); // File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/FastBrush"); //Creates app specific folder // path.mkdirs(); // File imageFile = new File(path, "shiming" + ".png"); // Imagename.png // saveBitmap(imageFile); } }); } private static String full_name = ""; private static final String LAST_NAME = "img_"; private int first_name = 1; public void saveBitmap(File path) { mBitmap = null; try { FileInputStream fis = new FileInputStream(path); Bitmap bitmap = BitmapFactory.decodeStream(fis); mBitmap = BitmapUtils.resizeImage(bitmap, 150, 150); } catch (FileNotFoundException e) { e.printStackTrace(); } if (mBitmap != null) { //根据Bitmap对象创建ImageSpan对象 ImageSpan imageSpan = new ImageSpan(this, mBitmap); //创建一个SpannableString对象,以便插入用ImageSpan对象封装的图像 full_name = LAST_NAME + first_name; String s = "[" + full_name + "]"; first_name++; SpannableString spannableString = new SpannableString(s); // 用ImageSpan对象替换face spannableString.setSpan(imageSpan, 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); //将选择的图片追加到EditText中光标所在位置 int index = mEText.getSelectionStart(); //获取光标所在位置 Editable edit_text = mEText.getEditableText(); if (index < 0 || index >= edit_text.length()) { edit_text.append(spannableString); } else { edit_text.insert(index, spannableString); } } } public boolean addJpgSignatureToGallery(Bitmap signature) { boolean result = false; try { mPhoto = new File(getAlbumStorageDir("SignaturePad"), String.format("Signature_%d.jpg", System.currentTimeMillis())); saveBitmapToJPG(signature, mPhoto); result = true; } catch (IOException e) { e.printStackTrace(); } return result; } public void saveBitmapToJPG(Bitmap bitmap, File photo) throws IOException { Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(newBitmap); canvas.drawColor(Color.WHITE); canvas.drawBitmap(bitmap, 0, 0, null); OutputStream stream = new FileOutputStream(photo); //图片的质量 newBitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream); stream.close(); } public File getAlbumStorageDir(String albumName) { // Get the directory for the user's public pictures directory. File file = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), albumName); if (!file.mkdirs()) { Log.e("SignaturePad", "Directory not created"); } return file; } @Override protected void onPause() { super.onPause(); mMyGLSurfaceView.onPause(); } @Override protected void onResume() { super.onResume(); mMyGLSurfaceView.onResume(); } }
ddde4966a01d188772acfc12c7bca0612b84ed66
[ "Java" ]
1
Java
Shimingli/FastBrush
d5a1f4acc22a2d4a5826d2f67d7c5fe681d4aec3
c7cb069d247151637a6d313a1da5582dc6a10665
refs/heads/master
<repo_name>Irwing-Herrera/spring<file_sep>/src/main/java/com/examplee/demoo/repositories/TaskRepository.java package com.examplee.demoo.repositories; import com.examplee.demoo.models.Task; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface TaskRepository extends JpaRepository<Task, Long> { }
da8b322655ba8dce73271d7509904e1053ecf17d
[ "Java" ]
1
Java
Irwing-Herrera/spring
12287a687fdbc257925e04aeb67fc3961c1c33cf
445c9552ad681f856fb424d12f5e59d3fc1dab82
refs/heads/master
<repo_name>stelaseldano/weather<file_sep>/app/upstream.js export function fetchForecast(url) { return fetch(url) .then(response => { return response.json() }) .then(response => { if (response.cod === 200) { return { name: response.name, temp: Math.round(response.main.temp).toString() + '°', max: Math.round(response.main.temp_max).toString() + '°', min: Math.round(response.main.temp_min).toString() + '°', image: setImage(response.weather[0].description), description: response.weather[0].description, country: response.sys.country, cod: response.cod } } else { return { cod: response.cod, message: response.message } } }) .catch(err => { console.err(err) }) } function setImage(description) { if (description.includes('rain') || description.includes('thunderstorm') || description.includes('drizzle')) { return "~/images/rain.png" } else if (description.includes('broken') && description.includes('clouds') || description.includes('few clouds')) { return "~/images/suncloud.png" } else if (description.includes('clouds')) { return "~/images/cloud.png" } else if (description.includes('snow') || description.includes('sleet') || description.includes('mist') || description.includes('drizzle') || description.includes('haze')) { return "~/images/suncloud.png" } else if (description.includes('clear')) { return "~/images/sun.png" } return '' }<file_sep>/app/app.js import Vue from 'nativescript-vue' import { TNSFontIcon, fonticon } from 'nativescript-fonticon' import Main from './components/Main' TNSFontIcon.paths = { 'fa': 'fonts/font-awesome.css', } TNSFontIcon.loadCss() Vue.filter('fonticon', fonticon) new Vue({ template: ` <Frame> <Main /> </Frame>`, components: { Main } }).$start() <file_sep>/app/fetch.js import { fetchForecast } from './upstream' import Forecast from './components/Forecast' export const fetch = { data() { return { locationError: false, locErrorMessage: '' } }, methods: { getData(url) { fetchForecast(url) .then(data => { if (data.cod === 200) { this.$navigateTo(Forecast, { transition: { name: 'fade' }, props: { response: data } }) } else { this.locationError = true, this.locErrorMessage = data.message + ' 😢' } }) .catch(err => { this.locationError = true, this.locErrorMessage = 'unsupported symbol 😢' }) } } }<file_sep>/README.md # Weather A simple weather app for android and ios made using [NativeScript](https://docs.nativescript.org/) and [VueJS](https://vuejs.org/) ## Where to find it Coming soon ## Development Please make sure you have Node.js and NativeScript installed If not, you can find these [instructions](https://docs.nativescript.org/start/quick-setup/) helpful * install the dependencies * `npm install` * add platforms * `tns platform add android` * `tns platform add ios` * run the app in the emulator * `tns run android --bundle` * `tns run ios --bunble` * build * `tns build android --bundle --env.uglify` * `tns build ios --bundle --env.uglify` ## License [Apache License](http://www.apache.org/licenses/)
e0fe2e9715cbbcd8810499d762a9b262e922f9c2
[ "JavaScript", "Markdown" ]
4
JavaScript
stelaseldano/weather
77ea5e3321f3bccb2805b185f01d6369bd2cc95f
e07a4f3d7a2afe0088a88e61ca6ce8623cb9c737
refs/heads/master
<repo_name>miguel-misstipsi/Wpf<file_sep>/Converter/MainWindow.xaml.cs 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 Converter { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public List<Usuario> Usuarios { get; set; } public MainWindow() { InitializeComponent(); Usuarios = new List<Usuario> { new Usuario{ Nombre = "Fernando", Edad = 29 }, new Usuario{ Nombre = "Miguel", Edad = 40 }, new Usuario{ Nombre = "Jaimito", Edad = 14 }, new Usuario{ Nombre = "Raymond", Edad = 37 } }; listaUsuarios.ItemsSource = Usuarios; } } public class Usuario { public string Nombre { get; set; } public int Edad { get; set; } } } <file_sep>/DataTemplate/MainWindow.xaml.cs 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 DataTemplate { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); var listGrupos = new List<Grupo>{ new Grupo{ Nombre = "Grupo 1", Descripcion = "Este es el primer grupo", Prioridad = "Prioridad alta" }, new Grupo{ Nombre = "Grupo 2", Descripcion = "Son unos paquetes", Prioridad = "Prioridad baja" } }; taskList.ItemsSource = listGrupos; } } } <file_sep>/README.md # Wpf Repsitory de ejemplos del evento Tajamar <file_sep>/DataTemplate/Grupo.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataTemplate { public class Grupo { public string Nombre {get; set;} public string Descripcion {get; set;} public string Prioridad { get; set; } } }
62b59ec8d119b377d05d7dbd13e52ae65c7826b7
[ "Markdown", "C#" ]
4
C#
miguel-misstipsi/Wpf
8a6a492839685c846eb05130c7c1901968e9c234
a787ceaeb1cdef6ccd177f2a6565aac88983f5a2
refs/heads/main
<file_sep># health-management-program- its gives complete analysis of your's day to day time table with date and time for your better health <file_sep>try: import datetime def gettime(): return datetime.datetime.now() def look (k): z=1 while(z!=0): if k==1: c= int(input("enter 1 for excerise or 2 for food")) if c==1: value= input("write here ") with open ("ayush.txt food","a") as f: f.write(str([str(gettime())]) + ":" + value + "\n") print("write successfully") elif c==2: value= input("write here ") with open ("ayush.txt excerise","a") as f: f.write(str([str(gettime())]) + ":" + value + "\n") print("write successfully") elif k==2: c= int(input("enter 1 for excerise or 2 for food")) if c==1: value= input("write here ") with open ("piyush.txt food","a") as f: f.write(str([str(gettime())]) + ":" + value + "\n") print("write successfully") elif c==2: value= input("write here ") with open ("piyush.txt excerise","a") as f: f.write(str([str(gettime())]) + ":" + value + "\n") print("write successfully") elif k==3: c= int(input("enter 1 for excerise or 2 for food")) if c==1: value= input("write here ") with open ("ashish.txt food","a") as f: f.write(str([str(gettime())]) + ":"+ value + "\n") print("write successfully") if c==2: value= input("write here ") with open ("ashish.txt excerise","a") as f: f.write(str([str(gettime())]) +":" + value + "\n") print("write successfully") else: print("please enter valid input") k=input("u write some more say 1 for yes or n for 0") # continue def reterive(k): if k==1: c= int(input("enter 1for food and 2 for excerise ")) if c==1: with open ("ayush.txt food ") as f: for i in f: print( i, end=" ") elif c==2: with open ("ayush.text excerise") as f: for i in f: print(i , end="") elif k==2: c= int(input("enter 1for food and 2 for excerise ")) if c==1: with open ("piyush.txt food ") as f: for i in f: print( i, end=" ") elif c==2: with open ("piyush.txt food ") as f: for i in f: print(i, end="") elif k==3: c= int(input("enter 1for food and 2 for excerise ")) if c==1: with open ("ashish.txt food ") as f: for i in f: print(i, end="") elif c==2: with open ("ashish.txt excerise ") as f: for i in f: print(i, end="") else: print("please enter valid input ") print( "HEALTH MANAGEMENT SYSTEM FOR COVID 19" ) a=int(input("press 1 for look and 2 for retrieve ")) if a==1: b=int(input("press 1 for ayush ,2 for piyush ,3 for ashish")) look(b) else: b=int(input("press 1 for ayush ,2 for piyush ,3 for ashish")) reterive(b) except Exception as e: print(e)
741aeea273119a31a3bcd616c8c6d19d9060edbe
[ "Markdown", "Python" ]
2
Markdown
ayushranjan2806/health-management-program-
0d50bbd50ce3b3bfa5cb25ee83cc2b2017060e72
d4db01be94da074ef799d591dc983e30551cd120
refs/heads/main
<repo_name>SafonovDanil/SPPO-lab1-model-view-controller<file_sep>/main.cpp #include <QCoreApplication> #include <QString> #include <QList> #include <iostream> #include "companiesregister.h" #include "companytype_1.h" #include "companytype_2.h" #include "companytype_3.h" void printCompaniesInfoByType(ICompany::COMPANY_TYPE companyType) { CompaniesRegister& companiesRegister = CompaniesRegister::instance(); std::cout << "Info about TYPE" << companyType+1 << " companies:\n"; ICompany * company = nullptr; for(int i = 0, size = companiesRegister.getRegisterSize(); i < size; i++) { company = companiesRegister.getCompany(i); if(company->getCompanyType() == companyType) { std::cout << "company name: " << company->getCompanyName().toStdString() << std::endl; QList<QString> owners = company->getOwnersList(); std::cout << "owners list: "; while(!owners.isEmpty()) { std::cout << owners.front().toStdString() << ", "; owners.pop_front(); } std::cout << std::endl << "income: " << company->getIncome() << std::endl; std::cout << "tax: " << company->getTax() << std::endl; std::cout << "area: " << company->getArea() << std::endl; std::cout << "number of employees: " << company->getNumberOfEmployees() << std::endl; std::cout << std::endl << std::endl; } } } void printCompaniesInfoByOwner(QString owner) { CompaniesRegister& companiesRegister = CompaniesRegister::instance(); ICompany* company = nullptr; int size = companiesRegister.getRegisterSize(); std::cout << owner.toStdString() << " owns: "; for(int i = 0; i < size; i++) { company = companiesRegister.getCompany(i); if(company->getOwnersList().contains(owner)) { std::cout << company->getCompanyName().toStdString() << ", "; } } std::cout << "." <<std::endl; } void printAverageValuesForAllTypes() { CompaniesRegister& companiesRegister = CompaniesRegister::instance(); ICompany* company = nullptr; int size = companiesRegister.getRegisterSize(); int companiesCount[3] = {0, 0, 0}; double incomeCount[3] = {0, 0, 0}; double areaCount[3] = {0, 0, 0}; double taxCount[3] = {0, 0, 0}; double numberOfEmployeesCount[3] = {0, 0, 0}; for(int i = 0; i < size; i++) { company = companiesRegister.getCompany(i); companiesCount[company->getCompanyType()]++; incomeCount[company->getCompanyType()] += company->getIncome(); areaCount[company->getCompanyType()] += company->getArea(); taxCount[company->getCompanyType()] += company->getTax(); numberOfEmployeesCount[company->getCompanyType()] += company->getNumberOfEmployees(); } std::cout << "average values for companies of COMPANY_TYPE_1 :" << std::endl; std::cout << "income: " << incomeCount[ICompany::COMPANY_TYPE_1]/companiesCount[ICompany::COMPANY_TYPE_1] << std::endl; std::cout << "tax: " << taxCount[ICompany::COMPANY_TYPE_1]/companiesCount[ICompany::COMPANY_TYPE_1] << std::endl; std::cout << "area: " << areaCount[ICompany::COMPANY_TYPE_1]/companiesCount[ICompany::COMPANY_TYPE_1] << std::endl; std::cout << "employees: " << numberOfEmployeesCount[ICompany::COMPANY_TYPE_1]/companiesCount[ICompany::COMPANY_TYPE_1] << std::endl; std::cout << std::endl << std::endl; std::cout << "average values for companies of COMPANY_TYPE_2 :" << std::endl; std::cout << "income: " << incomeCount[ICompany::COMPANY_TYPE_2]/companiesCount[ICompany::COMPANY_TYPE_2] << std::endl; std::cout << "tax: " << taxCount[ICompany::COMPANY_TYPE_2]/companiesCount[ICompany::COMPANY_TYPE_2] << std::endl; std::cout << "area: " << areaCount[ICompany::COMPANY_TYPE_2]/companiesCount[ICompany::COMPANY_TYPE_2] << std::endl; std::cout << "employees: " << numberOfEmployeesCount[ICompany::COMPANY_TYPE_2]/companiesCount[ICompany::COMPANY_TYPE_2] << std::endl; std::cout << std::endl << std::endl; std::cout << "average values for companies of COMPANY_TYPE_3 :" << std::endl; std::cout << "income: " << incomeCount[ICompany::COMPANY_TYPE_3]/companiesCount[ICompany::COMPANY_TYPE_3] << std::endl; std::cout << "tax: " << taxCount[ICompany::COMPANY_TYPE_3]/companiesCount[ICompany::COMPANY_TYPE_3] << std::endl; std::cout << "area: " << areaCount[ICompany::COMPANY_TYPE_3]/companiesCount[ICompany::COMPANY_TYPE_3] << std::endl; std::cout << "employees: " << numberOfEmployeesCount[ICompany::COMPANY_TYPE_3]/companiesCount[ICompany::COMPANY_TYPE_3] << std::endl; std::cout << std::endl << std::endl; } int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); try { CompaniesRegister& companiesRegister = CompaniesRegister::instance(); QList<QString> ownersOfCompany1; QList<QString> ownersOfCompany2; QList<QString> ownersOfCompany3; QList<QString> ownersOfCompany4; ownersOfCompany1.push_back(QString("owner 1,2")); ownersOfCompany1.push_back(QString("owner 1")); ownersOfCompany2.push_back(QString("owner 2,3")); ownersOfCompany2.push_back(QString("owner 1,2")); ownersOfCompany3.push_back(QString("owner 2,3")); ownersOfCompany3.push_back(QString("owner 3")); ownersOfCompany3.push_back(QString("owner 3,4")); ownersOfCompany4.push_back(QString("owner 3,4")); ownersOfCompany4.push_back(QString("owner 4")); companiesRegister.addCompany(new CompanyType_1(QString("company1_type1"),ownersOfCompany1,100,20,3)); companiesRegister.addCompany(new CompanyType_2(QString("company2_type2"),ownersOfCompany2,1100,100,20)); companiesRegister.addCompany(new CompanyType_3(QString("company3_type3"),ownersOfCompany3,10000,150,30)); companiesRegister.addCompany(new CompanyType_1(QString("company4_type4"),ownersOfCompany4,5000,25,4)); printCompaniesInfoByType(ICompany::COMPANY_TYPE_1); std::cout << std::endl; printCompaniesInfoByType(ICompany::COMPANY_TYPE_2); std::cout << std::endl; printCompaniesInfoByType(ICompany::COMPANY_TYPE_3); std::cout << std::endl; printCompaniesInfoByOwner("owner 1,2"); std::cout << std::endl; printCompaniesInfoByOwner("owner 3,4"); std::cout << std::endl; printAverageValuesForAllTypes(); } catch (QString errorMessage) { std::cout << errorMessage.toStdString() << std::endl; } return a.exec(); } <file_sep>/companytype_1.h #ifndef CompanyType_1_H #define CompanyType_1_H #include "abstractcompany.h" class CompanyType_1: public AbstractCompany { public: CompanyType_1(); CompanyType_1(const QString& companyName, QList<QString> &ownersList, double income, double area, int employeesNumber); double getTax() override; COMPANY_TYPE getCompanyType() override; ~CompanyType_1() = default; }; #endif // COMPANYTYPE_1_H <file_sep>/abstractcompany.cpp #include "abstractcompany.h" AbstractCompany::AbstractCompany(){} AbstractCompany::AbstractCompany(const QString& companyName, QList<QString>& ownersList, double income, double area, int numberOfEmployees) { if(!companyName.isEmpty()) companyName_ = companyName; else throw QString("empty company name"); if(!ownersList.isEmpty()) ownersList_ = ownersList; else throw QString("empty owners list"); income_ = income; if(area>=0) area_ = area; else throw QString("negative area"); if(numberOfEmployees>=0) numberOfEmployees_ = numberOfEmployees; else throw QString("negative number of employees"); } void AbstractCompany::setCompanyName(QString companyName) { if(!companyName.isEmpty()) companyName_ = companyName; else throw QString("empty company name"); } void AbstractCompany::setOwnersList(QList<QString>& ownersList) { if(!ownersList.isEmpty()) ownersList_ = ownersList; else throw QString("empty owners list"); } void AbstractCompany::setIncome(double income) { income_ = income; } void AbstractCompany::setArea(double area) { if(area>=0) area_ = area; else throw QString("negative area"); } void AbstractCompany::setNumberOfEmployees(int numberOfEmployees) { if(numberOfEmployees>=0) numberOfEmployees_ = numberOfEmployees; else throw QString("negative number of employees"); } QString AbstractCompany::getCompanyName() { return companyName_; } QList<QString> AbstractCompany::getOwnersList() { return ownersList_; } double AbstractCompany::getIncome() { return income_; } double AbstractCompany::getArea() { return area_; } int AbstractCompany::getNumberOfEmployees() { return numberOfEmployees_; } <file_sep>/ICompany.h #ifndef ICOMPANY_H #define ICOMPANY_H #include <QString> #include <QList> class ICompany { public: enum COMPANY_TYPE { COMPANY_TYPE_1, COMPANY_TYPE_2, COMPANY_TYPE_3 }; ICompany() = default; virtual void setCompanyName(QString companyName) = 0; virtual void setOwnersList(QList<QString>& ownersList) = 0; virtual void setIncome(double income) = 0; virtual void setArea(double area) = 0; virtual void setNumberOfEmployees(int n) = 0; virtual QString getCompanyName() = 0; virtual QList<QString> getOwnersList() = 0; virtual double getIncome() = 0; virtual double getArea() = 0; virtual int getNumberOfEmployees() = 0; virtual COMPANY_TYPE getCompanyType() = 0; virtual double getTax() = 0; }; #endif // ICOMPANY_H <file_sep>/companytype_2.h #ifndef CompanyType_2_H #define CompanyType_2_H #include "abstractcompany.h" class CompanyType_2: public AbstractCompany { public: CompanyType_2(); CompanyType_2(const QString& companyName, QList<QString> &ownersList, double income, double area, int employeesNumber); double getTax() override; COMPANY_TYPE getCompanyType() override; ~CompanyType_2() = default; }; #endif // COMPANYTYPE_2_H <file_sep>/companytype_3.cpp #include "companytype_3.h" CompanyType_3::CompanyType_3() { } CompanyType_3::CompanyType_3(const QString& companyName, QList<QString>& ownersList, double income, double area, int numberOfEmployees):AbstractCompany(companyName, ownersList, income, area, numberOfEmployees) { } double CompanyType_3::getTax() { return(income_*area_/1000); } CompanyType_3::COMPANY_TYPE CompanyType_3::getCompanyType() { return COMPANY_TYPE_3; } <file_sep>/companiesregister.cpp #include "companiesregister.h" CompaniesRegister& CompaniesRegister:: instance() { static CompaniesRegister companiesRegister; return companiesRegister; } void CompaniesRegister::addCompany(AbstractCompany* company) { if(!register_.contains(company)) register_.push_back(company); } bool CompaniesRegister::removeCompany(AbstractCompany* company) { return(register_.removeOne(company)); } int CompaniesRegister::getRegisterSize() { return(register_.size()); } AbstractCompany* CompaniesRegister::getCompany(int i) { return register_[i]; } CompaniesRegister::~CompaniesRegister() { qDeleteAll(register_); register_.clear(); } <file_sep>/companiesregister.h #ifndef COMPANIESREGISTER_H #define COMPANIESREGISTER_H #include <QList> #include "abstractcompany.h" class CompaniesRegister { public: static CompaniesRegister& instance(); void addCompany(AbstractCompany* company); bool removeCompany(AbstractCompany* company); int getRegisterSize(); AbstractCompany* getCompany(int i); ~CompaniesRegister(); private: CompaniesRegister() = default; CompaniesRegister(const CompaniesRegister &companiesRegister) = delete; CompaniesRegister& operator = (const CompaniesRegister &companiesRegister) = delete; QList<AbstractCompany*> register_; }; #endif // COMPANIESREGISTER_H <file_sep>/companytype_2.cpp #include "companytype_2.h" CompanyType_2::CompanyType_2() { } CompanyType_2::CompanyType_2(const QString& companyName, QList<QString>& ownersList, double income, double area, int numberOfEmployees):AbstractCompany(companyName, ownersList, income, area, numberOfEmployees) { } double CompanyType_2::getTax() { return (income_*numberOfEmployees_*2*area_ /100000); } CompanyType_2::COMPANY_TYPE CompanyType_2::getCompanyType() { return COMPANY_TYPE_2; } <file_sep>/abstractcompany.h #ifndef ABSTRACTCOMPANY_H #define ABSTRACTCOMPANY_H #include "ICompany.h" #include <QString> class AbstractCompany:public ICompany { public: AbstractCompany(); AbstractCompany(const QString& companyName, QList<QString>& ownersList, double income, double area, int numberOfEmployees); virtual void setCompanyName(QString companyName); virtual void setOwnersList(QList<QString> &ownersList); virtual void setIncome(double income); virtual void setArea(double area); virtual void setNumberOfEmployees(int numberOfEmployees); virtual QString getCompanyName(); virtual QList<QString> getOwnersList(); virtual double getIncome(); virtual double getArea(); virtual int getNumberOfEmployees(); virtual COMPANY_TYPE getCompanyType() = 0; virtual double getTax() = 0; virtual ~AbstractCompany() = default; protected: QString companyName_; QList<QString> ownersList_; double income_; double area_; int numberOfEmployees_; }; #endif // ABSTRACTCOMPANY_H <file_sep>/companytype_1.cpp #include "companytype_1.h" CompanyType_1::CompanyType_1() { } CompanyType_1::CompanyType_1(const QString& companyName, QList<QString>& ownersList, double income, double area, int numberOfEmployees):AbstractCompany(companyName, ownersList, income, area, numberOfEmployees) { } double CompanyType_1::getTax() { return( income_*numberOfEmployees_*2/1000); } CompanyType_1::COMPANY_TYPE CompanyType_1::getCompanyType() { return COMPANY_TYPE_1; } <file_sep>/companytype_3.h #ifndef CompanyType_3_H #define CompanyType_3_H #include "abstractcompany.h" class CompanyType_3: public AbstractCompany { public: CompanyType_3(); CompanyType_3(const QString& companyName, QList<QString> &ownersList, double income, double area, int employeesNumber); double getTax() override; COMPANY_TYPE getCompanyType() override; ~CompanyType_3() = default; }; #endif // COMPANYTYPE_3_H
d12fbc5071a95089fb71b76a6cc264854c67ccf7
[ "C++" ]
12
C++
SafonovDanil/SPPO-lab1-model-view-controller
38712498ed084f26b6fe1603dd3d28ac6d2bfda7
b3500515d1552bb22623563c2029154c9d1008b7
refs/heads/master
<file_sep>#!/bin/bash #initial commands apt-get clean && apt-get update && apt-get upgrade -y && apt-get dist-upgrade -y rm /var/www/index.html mkdir /var/www/rawr #basic installs apt-get install python-setuptools easy_install pip pip install selenium apt-get install unrar unace rar unrar p7zip zip unzip p7zip-full p7zip-rar file-roller -y #Big gitlist # # mkdir /opt/gitlist/ # cd /opt/gitlist # git clone https://github.com/macubergeek/gitlist.git # cd gitlist # chmod +x gitlist.sh # ./gitlist.sh #msfconsole.rc # echo "spool /mylog.log" >> /msfconsole.rc echo "set consolelogging true" >> /msfconsole.rc echo "set loglevel 5" >> /msfconsole.rc echo "set sessionlogging true" >> /msfconsole.rc echo "set timestampoutput true" >> /msfconsole.rc echo 'setg prompt "%cya%T%grn S:%S%blu J:%J "' >> /msfconsole.rc #sipvicious cd /opt git clone https://github.com/sandrogauci/sipvicious.git #Empire cd /opt git clone https://github.com/PowerShellEmpire/Empire.git #run setup manually. #Snarf # apt-get install nodejs cd /opt git clone https://github.com/purpleteam/snarf.git #Veil-Evasion setup # cd /opt git clone https://github.com/Veil-Framework/Veil.git git clone https://github.com/Veil-Framework/PowerTools.git cd /opt/Veil/Veil-Evasion/setup ./setup.sh cd /opt/Veil/Veil-Catapult ./setup.sh #Responder Setup rm -r /usr/share/responder rm /usr/bin/responder cd /opt git clone https://github.com/SpiderLabs/Responder.git cd Responder cp -r * /usr/bin #Impacket Setup cd /opt git clone https://github.com/CoreSecurity/impacket.git cd impacket python setup.py install cp /opt/impacket/examples/smbrelayx.py /usr/bin chmod 755 /usr/bin/smbrelayx.py cp /opt/impacket/examples/goldenPac.py /usr/bin chmod 755 /usr/bin/goldenPac.py #payload autogeneration # cd /opt git clone https://github.com/trustedsec/unicorn.git echo '#!/bin/bash' >> /payload_gen.sh echo "ADDY=$(ifconfig eth0 | awk '/inet addr/{print $2}' | awk -F':' '{print $2}')" >> /payload_gen.sh echo 'cd /root/payload_temp' >> /payload_gen.sh echo 'python /opt/Veil-Evasion/Veil-Evasion.py -p python/meterpreter/rev_tcp -c compile_to_exe=Y use_pyherion=Y LHOST=$ADDY LPORT=443 --overwrite' >> /payload_gen.sh echo 'sleep 1' >> /payload_gen.sh echo 'mv -f /root/veil-output/compiled/payload.exe /var/www/FreshPayload.exe' >> /payload_gen.sh cd ~/Desktop wget http://www.rarlab.com/rar/wrar520.exe wine wrar520.exe rm wrar520.exe #msf resource scripts # echo "use multi/handler" >> /bounce echo "jobs -K" >> /bounce echo "set payload windows/meterpreter/reverse_tcp" >> /bounce echo "set exitonsession false" >> /bounce echo "set lport 443" >> /bounce echo "set enablestageencoding true" >> /bounce echo "set autorunscript migrate -f" >> /bounce echo "set LHOST 0.0.0.0" >> /bounce echo "exploit -j -z" >> /bounce echo "use multi/handler" >> /bouncessl echo "jobs -K" >> /bouncessl echo "set payload windows/meterpreter/reverse_https" >> /bouncessl echo "set exitonsession false" >> /bouncessl echo "set lhost 0.0.0.0" >> /bouncessl echo "set lport 443" >> /bouncessl echo "set enablestageencoding true" >> /bouncessl echo "set autorunscript migrate -f" >> /bouncessl echo "exploit -j -z" >> /bouncessl #foofus OWA enum scripts # mkdir -p /opt/foofus cd /opt/foofus wget http://www.foofus.net/jmk/tools/owa/OWALogonBrute.pl wget http://www.foofus.net/jmk/tools/owa/OWA55EnumUsersURL.pl wget http://www.foofus.net/jmk/tools/owa/OWALightFindUsers.pl wget http://www.foofus.net/jmk/tools/owa/OWAFindUsers.pl wget http://www.foofus.net/jmk/tools/owa/OWAFindUsersOld.pl #Praeda install # cd /opt git clone https://github.com/percx/Praeda.git git clone https://github.com/MooseDojo/praedasploit.git cd praedasploit mkdir -p /usr/share/metasploit-framework/modules/auxiliary/praedasploit cp * /usr/share/metasploit-framework/modules/auxiliary/praedasploit #CG's gold_digger script {http://carnal0wnage.attackresearch.com/2015/02/my-golddigger-script.html} # mkdir -p /opt/carnal0wnage cd /opt/carnal0wnage git clone https://github.com/carnal0wnage/Metasploit-Code.git cp /opt/carnal0wnage/Metasploit-Code/modules/post/windows/gather/gold_digger.rb /usr/share/metasploit-framework/modules/post/windows/gather #Shell_Shocker Setup cd /opt git clone https://github.com/mubix/shellshocker-pocs.git #RAWR Setup cd /opt git clone https://bitbucket.org/al14s/rawr.git cd rawr ./install.sh #PowerSploit Setup cd /opt git clone https://github.com/mattifestation/PowerSploit.git #PowerTools Setup cd /opt git clone https://github.com/Veil-Framework/PowerTools.git cp /opt/PowerTools/PowerUp/PowerUp.ps1 /var/www cp /opt/PowerTools/PowerView/powerview.ps1 /var/www #Pykek Setup cd /opt git clone https://github.com/bidord/pykek.git #<NAME>'s asdi scripts # cd /opt git clone https://github.com/darkoperator/Meterpreter-Scripts.git carlos-perez-meterpreter cd carlos-perez-meterpreter mkdir -p ~/.msf4/modules/post/windows/gather cp post/windows/gather/* ~/.msf4/modules/post/windows/gather/ #netripper # cd /opt git clone https://github.com/NytroRST/NetRipper.git cd NetRipper cp netripper.rb /usr/share/metasploit-framework/modules/post/windows/gather/netripper.rb mkdir /usr/share/metasploit-framework/modules/post/windows/gather/netripper g++ -Wall netripper.cpp -o netripper cp netripper /usr/share/metasploit-framework/modules/post/windows/gather/netripper/netripper cd ../Release cp DLL.dll /usr/share/metasploit-framework/modules/post/windows/gather/netripper/DLL.dll #autoconnect MSF db update-rc.d postgresql enable update-rc.d metasploit enable #setup samba mkdir /srv/kali chmod 777 /srv/kali echo "[kali]" >> /etc/samba/smb.conf echo " comment = Kali share" >> /etc/samba/smb.conf echo " path = /srv/kali" >> /etc/samba/smb.conf echo " browseable = yes" >> /etc/samba/smb.conf echo " public = yes" >> /etc/samba/smb.conf echo " writable = yes" >> /etc/samba/smb.conf echo " guest ok = yes" >> /etc/samba/smb.conf #cleanup # updatedb apt-get clean && apt-get update && apt-get upgrade -y && apt-get dist-upgrade -y echo echo "[!] You must run the setup on Empire manually at /opt/Empire"<file_sep>#!/bin/bash #by bluescreenofjeff IFS=$'\n' USERLISTFILE='/root/Desktop/users.txt' PASSVAR='<PASSWORD>' OUTFILELOCAL='mass_user_add_local.rc' OUTBATLOCAL='mass_user_add_local.bat' OUTFILEDOMAIN='mass_user_add_domain.rc' OUTBATDOMAIN='mass_user_add_domain.bat' #BAT Output - local for CURRUSER in `cat $USERLISTFILE` do echo net user $CURRUSER /add /active:yes\ >> $OUTBATLOCAL echo net user $CURRUSER $PASSVAR >> $OUTBATLOCAL echo net localgroup administrators $CURRUSER /add >> $OUTBATLOCAL done #BAT to RC - local echo 'use auxiliary/admin/smb/psexec_command' >> $OUTFILELOCAL for EACH in `cat $OUTBATLOCAL` do echo set command \" $EACH \" >> $OUTFILELOCAL echo run >> $OUTFILELOCAL done #BAT Output - domain for CURRUSER in `cat $USERLISTFILE` do echo net user $CURRUSER /add /active:yes /domain >> $OUTBATDOMAIN echo net user $CURRUSER $PASSVAR /domain >> $OUTBATDOMAIN echo net localgroup administrators $CURRUSER /add /domain >> $OUTBATDOMAIN echo net group "Enterprise Admins" $CURRUSER /add /domain >> $OUTBATDOMAIN echo net group "Enterprise Admins" $CURRUSER /add /domain >> $OUTBATDOMAIN done #BAT to RC - domain echo 'use auxiliary/admin/smb/psexec_command' >> $OUTFILEDOMAIN for EACH in `cat $OUTBATDOMAIN` do echo set command \" $EACH \" >> $OUTFILEDOMAIN echo run >> $OUTFILEDOMAIN done <file_sep># CCDC-Scripts This repo hosts any scripts I find useful for Red Teaming at a CCDC event. ## kali_setup.sh A script to setup a Kali VM for testing. ## mass_user_add_generator.sh Generate a Metasploit resource script to mass add users locally and to the domain. ## OpsPlan2016.txt A sample Operations Plan some friends and I made. Has copy/paste commands and functions to limit Googling during the competition. ## website-defacement A defacement site I used one year. *For Aggressor scripts designed for use at CCDC, check out my [CCDC Scripts](https://github.com/bluscreenofjeff/AggressorScripts) repo.* # Thanks [<NAME>](https://twitter.com/armitagehacker)
1ce562c1911d0f5213d3cdd67cb231b14a6d4048
[ "Markdown", "Shell" ]
3
Shell
bluscreenofjeff/CCDC-Scripts
7a59e9629288bcdb4ff00bc2403dda052d076b8e
8ac51bd98a6021353c0054df6b7c35a96ec526a4
refs/heads/master
<file_sep>// Copyright 2019 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package terminfo import ( "bytes" "testing" "time" ) // This terminfo entry is a stripped down version from // xterm-256color, but I've added some of my own entries. var testTerminfo = &Terminfo{ Name: "simulation_test", Columns: 80, Lines: 24, Colors: 256, Bell: "\a", Blink: "\x1b2ms$<20>something", Reverse: "\x1b[7m", SetFg: "\x1b[%?%p1%{8}%<%t3%p1%d%e%p1%{16}%<%t9%p1%{8}%-%d%e38;5;%p1%d%;m", SetBg: "\x1b[%?%p1%{8}%<%t4%p1%d%e%p1%{16}%<%t10%p1%{8}%-%d%e48;5;%p1%d%;m", AltChars: "``aaffggiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz{{||}}~~", Mouse: "\x1b[M", MouseMode: "%?%p1%{1}%=%t%'h'%Pa%e%'l'%Pa%;\x1b[?1000%ga%c\x1b[?1002%ga%c\x1b[?1006%ga%c", SetCursor: "\x1b[%i%p1%d;%p2%dH", PadChar: "\x00", } func TestTerminfoExpansion(t *testing.T) { ti := testTerminfo // Tests %i and basic parameter strings too if ti.TGoto(7, 9) != "\x1b[10;8H" { t.Error("TGoto expansion failed") } // This tests some conditionals if ti.TParm("A[%p1%2.2X]B", 47) != "A[2F]B" { t.Error("TParm conditionals failed") } // Color tests. if ti.TParm(ti.SetFg, 7) != "\x1b[37m" { t.Error("SetFg(7) failed") } if ti.TParm(ti.SetFg, 15) != "\x1b[97m" { t.Error("SetFg(15) failed") } if ti.TParm(ti.SetFg, 200) != "\x1b[38;5;200m" { t.Error("SetFg(200) failed") } if ti.TParm(ti.MouseMode, 1) != "\x1b[?1000h\x1b[?1002h\x1b[?1006h" { t.Error("Enable mouse mode failed") } if ti.TParm(ti.MouseMode, 0) != "\x1b[?1000l\x1b[?1002l\x1b[?1006l" { t.Error("Disable mouse mode failed") } } func TestTerminfoDelay(t *testing.T) { ti := testTerminfo buf := bytes.NewBuffer(nil) now := time.Now() ti.TPuts(buf, ti.Blink) then := time.Now() s := string(buf.Bytes()) if s != "\x1b2mssomething" { t.Errorf("Terminfo delay failed: %s", s) } if then.Sub(now) < time.Millisecond*20 { t.Error("Too short delay") } if then.Sub(now) > time.Millisecond*50 { t.Error("Too late delay") } } func BenchmarkSetFgBg(b *testing.B) { ti := testTerminfo for i := 0; i < b.N; i++ { ti.TParm(ti.SetFg, 100, 200) ti.TParm(ti.SetBg, 100, 200) } } <file_sep>// Copyright 2016 The TCell Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tcell import "time" // EventPaste represents a bracketed paste event. type EventPaste struct { t time.Time text string esc string } // When returns the time when this Event was created, which should closely // match the time when the paste was made. func (e *EventPaste) When() time.Time { return e.t } // Text returns the text that was pasted func (e *EventPaste) Text() string { return e.text } func (e *EventPaste) EscSeq() string { return e.esc } // NewEventPaste creates a new paste event from the given text func NewEventPaste(text string, esc string) *EventPaste { return &EventPaste{ t: time.Now(), text: text, esc: esc, } } <file_sep>package tcell import "time" // EventRaw is an event where tcell was not able to // parse the escape sequence, so the escape sequence is // sent directly to the application type EventRaw struct { t time.Time esc string // The escape code } // When returns the time when this EventMouse was created. func (ev *EventRaw) When() time.Time { return ev.t } func (ev *EventRaw) EscSeq() string { return ev.esc } func NewEventRaw(code string) *EventRaw { return &EventRaw{ t: time.Now(), esc: code, } } <file_sep>module github.com/zyedidia/tcell/v2 require ( github.com/gdamore/encoding v1.0.0 github.com/lucasb-eyer/go-colorful v1.0.3 github.com/mattn/go-runewidth v0.0.7 github.com/xo/terminfo v0.0.0-20200218205459-454e5b68f9e8 github.com/zyedidia/poller v1.0.1 golang.org/x/sys v0.0.0-20190626150813-e07cf5db2756 golang.org/x/text v0.3.0 ) go 1.13
d6fbbe93c6e341a5f530102d38b0b00691cdd5f3
[ "Go Module", "Go" ]
4
Go
zyedidia/tcell
061c5b2c7260dcacb069c2165a11eb393fb963b5
12ba8ce3fe2fc620a479b1a3852234995ef23d19
refs/heads/master
<repo_name>teddygod/TextAreaLimitation<file_sep>/TextAreaLimitation.ts interface ITextAreaLimitationOption { popOverPosition?: string; onInvalid?(state: string): void; onInvalidLineLength?(lineNumber: number, lineText: string): void; onInvalidLines?(lineCount: string): void; onKeyDownCanceled?(): void; usePopOver?: boolean; lang?: string; maxLines: number; maxCharPerLines: number; } class TextAreaLimitation { isInError: boolean; formGroup: JQuery; textArea: HTMLTextAreaElement; constructor(public Element: JQuery, public param?: ITextAreaLimitationOption) { if (Element.length > 1) { Element.each((index, element) => { var d = new TextAreaLimitation($(element)); }); } else { this.textArea = <HTMLTextAreaElement>this.Element[0]; var parrent = Element.parent(); if (parrent.hasClass('form-group') == false) { Element.wrap("<div class='form-group'></div>"); } if (Element.hasClass('form-control') == false) Element.addClass('form-control'); this.formGroup = Element.closest('.form-group'); this.setDefaultValues(); this.registerEvents(); } } registerEvents() { var KeyUpCancelText: string = null; this.Element.keydown((e) => { if (e.ctrlKey) return; if (e.keyCode === 46 || e.keyCode === 37 || e.keyCode === 38 || e.keyCode === 39 || e.keyCode === 40 || e.keyCode === 16 || e.keyCode === 17 || e.keyCode === 18) // ARROWS and others non caractrers keys return; if (e.keyCode === 8) //backspace return; var lines = this.getInfo(); var linesValidation = this.validateLinesLenght(lines, false, e.keyCode); var valide = true; if (!linesValidation) valide = false; if (e.keyCode !== 13) { var valideText = this.validateText(false, lines); if (!valideText) valide = false; } if (!valide) { KeyUpCancelText = this.Element.val(); setTimeout(() => { //run this in a timeout to prevent wait to long before returning the false. //here if we wait to long, the keydown is not canceled. this.Element.trigger("cs.TextAreaLimitation.KeyDownCanceled", ["valid"]); if (this.param.onKeyDownCanceled != null && $.isFunction(this.param.onKeyDownCanceled)) this.param.onKeyDownCanceled.call(this.Element); }, 100); e.preventDefault(); e.returnValue = false; //alert('KeyDown cancelled'); return false; } }); this.Element.keyup((e) => { //A hack for mobile. Some mobile dont take the cancel on keyDown if (KeyUpCancelText != null && this.Element.val() != KeyUpCancelText) this.Element.val(KeyUpCancelText); KeyUpCancelText = null; }); this.Element.change(() => { var lines = this.getInfo(); var linesValidation = this.validateLinesLenght(lines, true); if (!linesValidation) { this.displayLinesExceedError(lines.length); return; } var text = this.validateText(true, lines); if (text && linesValidation) if (this.isInError) { this.Element.trigger("cs.TextAreaLimitation.Invalid", ["valid"]); if (this.param.onInvalid != null && $.isFunction(this.param.onInvalid)) this.param.onInvalid.call(this.Element, "valid"); this.Element.removeClass("cs-invalid"); this.isInError = false; this.formGroup.removeClass('has-error'); this.Element.popover('hide'); } }); } setDefaultValues() { if (this.param == null) this.param = { lang: 'en', maxCharPerLines: null, maxLines: null, popOverPosition: 'top' }; else { if (this.param.lang == null) this.param.lang = 'en'; if (this.param.popOverPosition == null) this.param.popOverPosition = 'top'; } if (this.hasData('maxlines')) this.param.maxLines = parseInt(this.Element.data('maxlines')); if (this.hasData('maxcharperlines')) this.param.maxCharPerLines = parseInt(this.Element.data('maxcharperlines')); if (this.hasData('popoverposition')) this.param.popOverPosition = this.Element.data('popoverposition'); if (this.hasData('lang')) this.param.lang = this.Element.data('lang'); if (this.hasData('usepopover')) this.param.usePopOver = ("" + this.Element.data('usepopover')).toLowerCase() == "true"; } hasData(Data) { if (typeof this.Element.data(Data) !== 'undefined') return true; return false; } getLineNumber(): number { return this.textArea.value.substr(0, this.textArea.selectionStart).split("\n").length; } validateText(isFromChange: boolean, info: Array<string>): boolean { if (this.param.maxCharPerLines == null) return true; var l = 0; var currentLine = this.getLineNumber() - 1; for (var i = 0; i < info.length; i++) { l = info[i].length; if (!isFromChange && l + 1 > this.param.maxCharPerLines && currentLine == i) { //alert("max text reach"); return false; } if ((isFromChange && l > this.param.maxCharPerLines)) { //alert("max text reach"); this.isInError = true; this.formGroup.addClass('has-error'); this.Element.addClass("cs-invalid"); this.displayErrorLenghtMessage(i, info[i]); return false; } } return true; }; validateLinesLenght(lines: Array<string>, isFromChange: boolean, keypress?: number): boolean { if (this.param.maxLines == null) return true; if ((lines.length > this.param.maxLines) || (keypress != null && keypress === 13 && lines.length + 1 > this.param.maxLines)) { if (isFromChange) { this.isInError = true; this.formGroup.addClass('has-error'); this.Element.addClass("cs-invalid"); this.displayLinesExceedError(lines.length); } return false; } return true; }; getInfo(): Array<string> { var val = this.Element.val(); var lines: Array<string> = val.split('\n'); return lines; }; displayErrorLenghtMessage(lineNumber: number, lineText: string) { if (this.param.usePopOver) { var errorMessage = ""; if (this.param.lang == "fr") { errorMessage = "Chaque ligne ne doit pas dépasser " + this.param.maxCharPerLines + " caractères par ligne.<br />La ligne " + (lineNumber + 1) + " dépasse ce maximum. Elle a " + lineText.length + " caractères.<br / ><blockquote><p>" + lineText + "</p><footer>" + (this.param.maxCharPerLines - lineText.length) + " caractères de trop.</foorter></blockquote>" } else { errorMessage = "Each line must not exceed " + this.param.maxCharPerLines + " characters per line.<br /> Line " + (lineNumber + 1) + " exceeds this maximum.It has " + lineText.length + " characters.<br / ><blockquote><p>" + lineText + "</p><footer>It exceed this limit by " + (this.param.maxCharPerLines - lineText.length) + ".</foorter></blockquote>"; } this.Element.popover('destroy'); setTimeout(() => { this.Element.popover({ html: true, content: errorMessage, placement: this.param.popOverPosition, trigger: 'manual' }); this.Element.popover('show'); }, 300); } this.Element.trigger("cs.TextAreaLimitation.Invalid", ["invalid"]); this.Element.trigger("cs.TextAreaLimitation.InvalidLineLength", [lineNumber, lineText]); if (this.param.onInvalid != null && $.isFunction(this.param.onInvalid)) this.param.onInvalid.call(this.Element, "invalid"); if (this.param.onInvalidLineLength != null && $.isFunction(this.param.onInvalidLineLength)) this.param.onInvalidLineLength.call(this.Element, lineNumber, lineText); }; displayLinesExceedError(lineCount: number) { if (this.param.usePopOver) { var errorMessage = ""; if (this.param.lang == "fr") { errorMessage = "Vous devez entrer un maximum de " + this.param.maxLines + " lignes.<br />Votre texte contient " + lineCount.toString() + " lignes."; } else { errorMessage = "You must enter a maximum of " + this.param.maxLines + " lines. Your text contains " + lineCount.toString() + " lines."; } this.Element.popover('destroy'); setTimeout(() => { this.Element.popover({ html: true, content: errorMessage, placement: this.param.popOverPosition, trigger: 'manual' }); this.Element.popover('show'); }, 300); } this.Element.trigger("cs.TextAreaLimitation.Invalid", ["invalid"]); this.Element.trigger("cs.TextAreaLimitation.InvalidLines", [lineCount]); if (this.param.onInvalid != null && $.isFunction(this.param.onInvalid)) this.param.onInvalid.call(this.Element, "invalid"); if (this.param.onInvalidLines != null && $.isFunction(this.param.onInvalidLines)) this.param.onInvalidLines.call(this.Element, lineCount); }; } <file_sep>/README.md # TextAreaLimitation Provide helper to limit text input in Html TextArea. This helper allow to limit text lenght per line and the total number of line. It cancel user input if the current line exceed the maximum and popup validation error(as a popover) if the user paste text. ## [JsFidler](http://jsfiddle.net/werddomain/6eaa6bfu/) ## Dependencies - [jQuery](https://github.com/jquery/jquery) (1.6+) - [Bootstrap 3](https://github.com/twbs/bootstrap) (For error display) ## Usage ``` <textarea class="TextAreaLimitation" data-maxlines="5" data-charperline="10"></textarea> <script src="/Scripts/TextAreaLimitation.js"></script> <script> $(function () { var element = $('.TextAreaLimitation'); var t = new TextAreaLimitation(element, {lang: 'fr'}); //French var t2 = new TextAreaLimitation(element); //English element.on('cs.TextAreaLimitation', function(state){ if (state == 'valid') { //state pass from invalid to valid } if state == 'invalid') { //state of textArea is invalid } }); t.maxLines = 10; //You can change rules without re-initialise it. }); </script> ``` ## Property property can be acceded by the object returned by the instance: ``` var t = new TextAreaLimitation(element); t.propertyName = 'myValue'; ``` |Property |Type |Default Value |Description | |:----|----|----|----:| |param |ITextAreaLimitationOption | null| Caraters per lines.<br/> If null, the rule do not aply.| |isInError |boolean | null| Get if the current state is in error.| |formGroup |JQuery | n/a| Get the form-group container.| |textArea |HTMLTextAreaElement | n/a| Get the current textArea element.| ## Parameters (ITextAreaLimitationOption) Parameters can be changed after initialize ``` var t = new TextAreaLimitation(element,{lang: 'fr'}); t.param.lang = 'en'; ``` ### TypeScript definition ``` interface ITextAreaLimitationOption { popOverPosition?: string; onInvalid?(state: string): void; onInvalidLineLength?(lineNumber: number, lineText: string): void; onInvalidLines?(lineCount: string): void; usePopOver?: boolean; lang?: string; maxLines: number; maxCharPerLines: number; } ``` ### List of parameters |Name |Data |Type |Default Value |Description | |:----|----|----|----|----:| |maxLines |data-maxlines |number | null| Max Lines.<br/>If null, the rule do not aply.| |maxCharPerLines |data-maxcharperlines |number | null| Caraters per lines.<br/> If null, the rule do not aply.| |popOverPosition | data-popoverposition | string | 'top'| The [bootstrap popover](http://getbootstrap.com/javascript/#popovers-options) placement parameter.| |lang | data-lang |string | 'en'| Set the lang for the display message.| |usePopOver | data-usepopover |boolean | true| If false, the popOver will not be displayed on validation error| |onInvalid | n/a |function | null| On validation Error <br/> [info](#invalid)| |onInvalidLineLength | n/a |function | null| On validation Error in a line length<br/> [info](#invalidlinelength)| |onInvalidLines | n/a |function | null| On validation Error in total lines<br/> [info](#invalidlines)| |onKeyDownCanceled | n/a |function | null| When we cancel the keyDown event<br/> [info](#keydowncanceled)| ## Events All event set the ```this``` to the current TextArea ### Invalid Throw when validation state change.<br/> Parameters: - state: string ('valid' or 'invalid') <b>in param:</b> ``` { onInvalid: function(state){ if (state == 'valid') { //state pass from invalid to valid } if (state == 'invalid') { //state of textArea is invalid } } } ``` <br/><b>JQuery event:</b><br/> ``` element.on('cs.TextAreaLimitation.Invalid', function(event, state){ }; ``` ### InvalidLineLength Throw when a line exceed the maximum text length.<br/> Parameters: - lineNumber : number (the line number of the failed text length [0 based]) - lineText : string (the text) <b>in param:</b> ``` { onInvalidLineLength: function(lineNumber, lineText){ } } ``` <b>JQuery event:</b><br/> ``` element.on('cs.TextAreaLimitation.InvalidLineLength', function(event, lineNumber, lineText){ }; ``` ### InvalidLines Throw when the total line exceed the maximum alowed.<br/> Parameters: - lineCount: number (current line count) <b>in param:</b> ``` { onInvalidLines: function(lineCount){ } } ``` <b>JQuery event:</b> ``` element.on('cs.TextAreaLimitation.InvalidLines', function(event, lineCount){ }; ``` ### KeyDownCanceled Throw when we cancel the keydown. Can be maximum line lenght or maximum lines reach.<br/> Parameters: - NONE <b>in param:</b> ``` { onKeyDownCanceled: function(){ } } ``` <b>JQuery event:</b> ``` element.on('cs.TextAreaLimitation.KeyDownCanceled', function(event){ }; ``` ## Note If textarea is not in a form-group container, it will be added. ``` <textarea class="TextAreaLimitation" data-maxlines="5" data-charperline="10"></textarea> ``` will be replaced by: ``` <div class='form-group'> <textarea class="TextAreaLimitation form-control" data-maxlines="5" data-charperline="10"></textarea> </div> ``` ## Validation When the text inside the text area is invalid: - The textarea will have the `cs-invalid` class. - The textarea will throw the `cs.TextAreaLimitation` event. - The form-group container will have the `has-error` class. ## license This code is free to use, under the MIT license
f8ff4f3221669016bb61f333a0625950ae2248f0
[ "Markdown", "TypeScript" ]
2
TypeScript
teddygod/TextAreaLimitation
3725a248f39db379902f778f403e0b4aadd9834e
ad777c6dbd430deb80d8487d42ec70fcd2c94b41
refs/heads/master
<file_sep>const hbs = require('express-handlebars'); const express_handlebars_sections = require('express-handlebars-sections'); var handlebars = hbs.create({ extname: '.hbs', helpers: { section: express_handlebars_sections(), getFlashMessage: (arg, options) => { return getMessages().arg && options(this); }, ifEquals: (arg1, arg2, options) => { return (arg1 === arg2) ? options.fn(this) : ''; }, ifNotEquals: (arg1, arg2, options) => { return (arg1 !== arg2) ? options.fn(this) : ''; }, greaterThen: (arg1, arg2, options) => { return (arg1 > arg2) ? options.fn(this) : ''; }, lessThen: (arg1, arg2, options) => { return (arg1 < arg2) ? options.fn(this) : ''; }, greaterThenOREqual: (arg1, arg2, options) => { return (arg1 >= arg2) ? options.fn(this) : ''; }, lessThenOREqual: (arg1, arg2, options) => { return (arg1 <= arg2) ? options.fn(this) : ''; } } }); module.exports = handlebars;<file_sep>const AbstractRequest = require('../../plugins/Requests/AbstractRequest'); class TestRequest extends AbstractRequest { constructor(fieldName = '') { super(); this.fieldName = fieldName; this.message = `${this.fieldName} field is required`; } validate() { return true; } } module.exports = TestRequest;<file_sep>const app = require('express'); const router = app.Router(); const Home = require('../app/controllers/HomeController'); const adminRouter = require('./admin'); router.get('/', Home.index); // # Add admin route router.use('/admin', adminRouter); module.exports = router;<file_sep>/** * Node JS custom render helper * Receive flash and make them output * * @type {{nodeRender: nodeRender}} */ const RenderHelper = module.exports = { /** * Render method * @param view * @param req * @param res * @param data */ nodeRender: (view, req, res, data) => { if(req.session.flash) { // # info msg if(req.session.flash.info){ res.locals.info = req.session.flash.info; } // # error msg if(req.session.flash.error_msg){ res.locals.error_msg = req.session.flash.error_msg; } // # success msg if(req.session.flash.success_msg){ res.locals.success_msg = req.session.flash.success_msg; } } res.render(view, data); } }<file_sep># node-admin NodeJS / Express Admin Panel with CRUD generator Features : 1. Admin dashboard 2. Authentication 3. MVC folder structure 4. Template engine (Handlebars) 5. Mongo DB <file_sep>const registerURL = '/admin/register'; const { nodeRender } = require('../../helpers/RenderHelper'); const { registerValidation } = require('../../requests/RegistrationRequest'); const Requests = require('../../../plugins/Requests/Requests'); const TestRequest = require('../../requests/TestRequest'); /** * Register Controller */ const RegisterController = module.exports = { /** * Register * @param req * @param res */ register : (req, res) => { let validation = new Requests(req, [ {name: new TestRequest()}, {roll: 'required'} ]).validate(); if( validation.valid() === false ) { console.log(validation.errors); } // nodeRender('auth/register', req, res, {layout: 'login-register-layout'}); }, /** * Registration * @param req * @param res */ store: (req, res) => { registerValidation(req, res) .then(validate => { console.log('here....'); }) .catch(error =>{ req.flash('error_msg', error); res.redirect(registerURL); }); } };<file_sep>const app = require('express'); const adminRouter = app.Router(); const AuthController = require('../app/controllers/auth/AuthController'); const RegisterController = require('../app/controllers/auth/RegisterController'); /** * Admin Routes * @prefix /admin */ adminRouter.get('/', (req, res) => { res.send('welcome to admin home page'); }); adminRouter.get('/register', RegisterController.register); adminRouter.post('/register', RegisterController.store); module.exports = adminRouter;<file_sep>class AbstractRequest { constructor() { this.fieldName = ''; this.message = ''; if (this.constructor === AbstractRequest) { throw new TypeError('Abstract class "RequestExtended" cannot be instantiated directly.'); } } /** * Validate request * * @return boolean */ validate() {} } module.exports = AbstractRequest;<file_sep>const AbstractRequest = require('./AbstractRequest'); /** * Request class * Validate user requests * * @return mixed */ class Requests { constructor (req, rules) { this.requests = req; this.rules = rules; this.errors = []; } /** * Validate by rules * * @returns {Requests} */ validate() { this.expectedParametersShouldPassed(); this.iterateRules(); return this; } /** * Iterate rules * * @return null */ iterateRules() { this.rules.forEach(rule => { if(this.getRuleFieldName(rule)){ // # if extended new rule class rule[this.ruleField] instanceof AbstractRequest && this.makeInstance(rule[this.ruleField]); // # is this field required this.isRequired(rule[this.ruleField]); } }); } /** * Create new instance * * @param instance */ makeInstance(instance) { if(instance.validate() === false) { this.errors.push(instance.message); } } /** * Get validation status * * @returns {boolean} */ valid() { return !this.errors.length; } /** * Get rule field * @param rule * @returns {string} */ getRuleFieldName(rule) { this.ruleField = Object.keys(rule)[0]; return this.ruleField; } /** * Check required * * @param rule */ isRequired(rule) { if(rule === 'required'){ if( !this.requests.query[this.ruleField] ) { this.errors.push(`${this.ruleField} is required.`); } } } /** * Make sure expected valid * parameter has been passed * @return mixed */ expectedParametersShouldPassed() { if(!this.requests){ throw new Error('Please provide the request as first parameter'); } if(!this.rules){ throw new Error('Please provide rules as second parameter'); } if( !Array.isArray(this.rules) || (this.rules.length === 0) ){ throw new Error('Rules must be an array with at least one rule'); } } } module.exports = Requests;<file_sep>const express = require('express'); const flash = require('express-flash-messages'); const config = express(); // # body parser bodyParserConf = require('./body-parser'); // # session sessionConfig = require('./session'); config.use(bodyParserConf); config.use(sessionConfig); // # flash config.use(flash()); module.exports = config;<file_sep>const session = require('express-session'); // # Environment require('dotenv').config(); const sessionConfig = session({ name: 'node-admin', resave: false, saveUninitialized: false, secret: process.env.SESSION_SECRET, cookie: { maxAge: 1000 * 60 * 60 * 2, // 2 hours sameSite: true, // secure: true } }); module.exports = sessionConfig;<file_sep>/** * Home Controller * @type {{index: index}} */ const HomeController = module.exports = { /** * Index * @param req * @param res */ index : (req, res) => { res.render('home'); } };<file_sep>const express = require('express'); const app = express(); // # todo this port comes from .env file const port = 3000; // # config const config = require('./config/index'); app.use(config) // # handlebars hbsConf = require('./config/handlebars'); app.engine('hbs', hbsConf.engine); app.set('view engine', 'hbs'); // # static assets path app.use(express.static('public')); // # routers const routers = require('./routes'); app.use(routers); // # listen app.listen(port, () => console.log(`Node Admin is running on ${port} port`));
2601a324440f42f1f70131c5cef4e03c365cf29f
[ "JavaScript", "Markdown" ]
13
JavaScript
sagormax/node-admin
cbe592f8a82ce55984f420636a2dfc57add3007f
25d92020c8d2342c87a5252caab9fea7744f9ee7
refs/heads/master
<file_sep>let config = { iceServers: [ {urls: 'stun:stun.l.google.com:19302' }] }; const pc = new RTCPeerConnection(config); console.log(pc) function isSafari() { return browser() === 'safari'; } function browser() { const ua = window.navigator.userAgent.toLocaleLowerCase(); if (ua.indexOf('edge') !== -1) { return 'edge'; } else if (ua.indexOf('chrome') !== -1 && ua.indexOf('edge') === -1) { return 'chrome'; } else if (ua.indexOf('safari') !== -1 && ua.indexOf('chrome') === -1) { return 'safari'; } else if (ua.indexOf('opera') !== -1) { return 'opera'; } else if (ua.indexOf('firefox') !== -1) { return 'firefox'; } return; } let log = msg => { document.getElementById('div').innerHTML += msg + '<br>' } pc.ontrack = function (event) { console.log("ontrack") var el = document.createElement(event.track.kind) el.srcObject = event.streams[0] el.muted = true el.autoplay = true el.controls = true el.width = 600 document.getElementById('remoteVideos').appendChild(el) } pc.oniceconnectionstatechange = e => log(pc.iceConnectionState) pc.onicecandidate = event => { console.log("onicecandidate") if (event.candidate === null) { document.getElementById('localSessionDescription').value = btoa(pc.localDescription.sdp) var suuid = $('#suuid').val(); $.post("/recive", { suuid: suuid,data:btoa(pc.localDescription.sdp)} ,function(data){ document.getElementById('remoteSessionDescription').value = data window.startSession() }); } } pc.createOffer({offerToReceiveVideo: true, offerToReceiveAudio: false}).then(d => pc.setLocalDescription(d)).catch(log) window.startSession = () => { let sd = document.getElementById('remoteSessionDescription').value if (sd === '') { return alert('Session Description must not be empty') } try { pc.setRemoteDescription(new RTCSessionDescription({type: 'answer', sdp: atob(sd)})) } catch (e) { alert(e) } } $(document).ready(function() { var suuid = $('#suuid').val(); $('#'+suuid).addClass('active'); }); <file_sep>module mod go 1.13 require ( github.com/deepch/vdk v0.0.0-20191130205321-087a2b4c2d63 github.com/gin-gonic/gin v1.5.0 github.com/pion/webrtc/v2 v2.1.18 ) <file_sep># RTSPtoWebRTC RTSP Stream to WebBrowser over WebRTC based on Pion full native! not use ffmpeg or gstreamer if you need RTSPtoWSMP4f use https://github.com/deepch/RTSPtoWSMP4f ## Team Deepch - https://github.com/deepch streaming developer Dmitry - https://github.com/vdalex25 web developer ![RTSPtoWebRTC image](doc/demo4.png) ## Installation 1. ```bash go get github.com/deepch/RTSPtoWebRTC ``` 2. ```bash cd src/github.com/deepch/RTSPtoWebRTC ``` 3. ```bash go run *.go ``` 4. ```bash open web browser http://127.0.0.1:8083 work google chrome ``` ## Configuration ### Edit file config.json format: ```bash { "server": { "http_port": ":8083" }, "streams": { "demo1": { "url": "rtsp://172.16.17.32/rtplive/470011e600ef003a004ee33696235daa" }, "demo2": { "url": "rtsp://172.16.17.32/rtplive/470011e600ef003a004ee33696235daa" }, "demo3": { "url": "rtsp://172.16.17.32/rtplive/470011e600ef003a004ee33696235daa" } } } ``` ## Limitations Video Codecs Supported: H264 Audio Codecs Supported: none <file_sep>package main import ( "encoding/base64" "fmt" "log" "math/rand" "net/http" "sort" "time" "github.com/deepch/vdk/codec/h264parser" "github.com/gin-gonic/gin" "github.com/pion/webrtc/v2" "github.com/pion/webrtc/v2/pkg/media" ) func serveHTTP() { router := gin.Default() router.LoadHTMLGlob("web/templates/*") router.GET("/", func(c *gin.Context) { fi, all := Config.list() sort.Strings(all) c.HTML(http.StatusOK, "index.tmpl", gin.H{ "port": Config.Server.HTTPPort, "suuid": fi, "suuidMap": all, "version": time.Now().String(), }) }) router.GET("/player/:suuid", func(c *gin.Context) { _, all := Config.list() sort.Strings(all) c.HTML(http.StatusOK, "index.tmpl", gin.H{ "port": Config.Server.HTTPPort, "suuid": c.Param("suuid"), "suuidMap": all, "version": time.Now().String(), }) }) router.POST("/recive", reciver) router.StaticFS("/static", http.Dir("web/static")) err := router.Run(Config.Server.HTTPPort) if err != nil { log.Fatalln(err) } } func reciver(c *gin.Context) { c.Header("Access-Control-Allow-Origin", "*") data := c.PostForm("data") suuid := c.PostForm("suuid") log.Println("Request", suuid) if Config.ext(suuid) { codecs := Config.coGe(suuid) if codecs == nil { log.Println("No Codec Info") return } //sps, pps := []byte{}, []byte{} sps := codecs[0].(h264parser.CodecData).SPS() pps := codecs[0].(h264parser.CodecData).PPS() //log.Fatalln(ch, codecs) sd, err := base64.StdEncoding.DecodeString(data) if err != nil { log.Println(err) return } log.Println(string(sd)) // webrtc.RegisterDefaultCodecs() //peerConnection, err := webrtc.New(webrtc.RTCConfiguration{ //var m webrtc.MediaEngine peerConnection, err := webrtc.NewPeerConnection(webrtc.Configuration{ ICEServers: []webrtc.ICEServer{ { URLs: []string{"stun:stun.l.google.com:19302"}, }, }, }) if err != nil { panic(err) } videoTrack, err := peerConnection.NewTrack(webrtc.DefaultPayloadTypeH264, rand.Uint32(), "video", suuid+"_video") if err != nil { log.Println(err) return } _, err = peerConnection.AddTrack(videoTrack) if err != nil { log.Println(err) return } offer := webrtc.SessionDescription{ Type: webrtc.SDPTypeOffer, SDP: string(sd), } if err := peerConnection.SetRemoteDescription(offer); err != nil { log.Println(err) return } answer, err := peerConnection.CreateAnswer(nil) if err != nil { log.Println(err) return } c.Writer.Write([]byte(base64.StdEncoding.EncodeToString([]byte(answer.SDP)))) go func() { control := make(chan bool, 10) conected := make(chan bool, 10) defer peerConnection.Close() peerConnection.OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) { fmt.Printf("Connection State has changed %s \n", connectionState.String()) if connectionState != webrtc.ICEConnectionStateConnected { log.Println("Client Close Exit") control <- true return } if connectionState == webrtc.ICEConnectionStateConnected { conected <- true } }) <-conected cuuid, ch := Config.clAd(suuid) defer Config.clDe(suuid, cuuid) var pre uint32 var start bool for { select { case <-control: return case pck := <-ch: if pck.IsKeyFrame { start = true } if !start { continue } if pck.IsKeyFrame { pck.Data = append([]byte("\000\000\001"+string(sps)+"\000\000\001"+string(pps)+"\000\000\001"), pck.Data[4:]...) } else { pck.Data = pck.Data[4:] } var ts uint32 if pre != 0 { ts = uint32(timeToTs(pck.Time)) - pre } err := videoTrack.WriteSample(media.Sample{Data: pck.Data, Samples: uint32(ts)}) pre = uint32(timeToTs(pck.Time)) if err != nil { return } } } }() return } } func timeToTs(tm time.Duration) int64 { return int64(tm * time.Duration(90000) / time.Second) }
cafc78b6dc38303ff7ed6c84db168be54885d13d
[ "JavaScript", "Go Module", "Go", "Markdown" ]
4
JavaScript
rancococ/RTSPtoWebRTC
62924e939965f20f39e3302328512b2ff25eabd8
3a198aa36486fb9c4b7d74e04c7bd417b2515c21
refs/heads/main
<repo_name>r-f-g/prometheus-bind-exporter-operator<file_sep>/src/charm.py #!/usr/bin/env python3 # Copyright 2021 Unicorn # See LICENSE file for licensing details. # # Learn more at: https://juju.is/docs/sdk """Prometheus-bind-exporter as charm the service. """ import logging import subprocess from ops.charm import CharmBase from ops.framework import StoredState from ops.main import main from ops.model import ActiveStatus, MaintenanceStatus logger = logging.getLogger(__name__) DEFAULT_LISTEN_PORT = 9119 DEFAULT_STATS_GROUPS = "server,view,tasks" class PrometheusBindExporterOperatorCharm(CharmBase): """Charm the service.""" _stored = StoredState() def __init__(self, *args): super().__init__(*args) self.framework.observe(self.on.install, self._on_install) self.framework.observe(self.on.config_changed, self._on_config_changed) self._stored.set_default(listen_port=DEFAULT_LISTEN_PORT, stats_groups=DEFAULT_STATS_GROUPS,) self.unit.status = ActiveStatus("Unit is ready") def _on_install(self, _): """Installation hook that installs prometheus-bind-exporter daemon.""" self.unit.status = MaintenanceStatus("Installing prometheus-bind-exporter") snap_file = self.model.resources.fetch("prometheus-bind-exporter") subprocess.check_call(["snap", "install", "--dangerous", snap_file]) self._manage_prometheus_bind_exporter_service() self.unit.status = ActiveStatus("Unit is ready") def _on_config_changed(self, _): """Config change hook.""" self.unit.status = MaintenanceStatus("prometheus-bind-exporter configuration") self._stored.listen_port = self.config.get("exporter-listen-port") self._stored.stats_groups = self.config.get("exporter-stats-groups") self._manage_prometheus_bind_exporter_service() self.unit.status = ActiveStatus("Unit is ready") def _manage_prometheus_bind_exporter_service(self): """Manage the prometheus-bind-exporter service.""" logger.debug("prometheus-bind-exporter configuration in progress") private_address = self.model.get_binding("designate-bind").network.bind_address subprocess.check_call([ "snap", "set", "prometheus-bind-exporter", f"web.listen-address={private_address or ''}:{self._stored.listen_port}", f"web.stats-groups={self._stored.stats_groups}" ]) logger.info("prometheus-bind-exporter has been reconfigured") if __name__ == "__main__": main(PrometheusBindExporterOperatorCharm) <file_sep>/tests/unit/test_charm.py # Copyright 2021 Unicorn # See LICENSE file for licensing details. # # Learn more about testing at: https://juju.is/docs/sdk/testing import unittest from unittest import mock import charm from ops.testing import Harness from build.venv.ops.model import ActiveStatus class TestInitCharm(unittest.TestCase): def test_init(self): """Test initialization of charm.""" harness = Harness(charm.PrometheusBindExporterOperatorCharm) harness.begin() self.assertNotEqual(harness.charm.unit.status, ActiveStatus("Unit is ready")) class TestCharm(unittest.TestCase): def setUp(self): self.harness = Harness(charm.PrometheusBindExporterOperatorCharm) self.addCleanup(self.harness.cleanup) self.harness.begin() @mock.patch.object(charm, "subprocess") def test_on_install(self, mock_subprocess): """Test install hook.""" with mock.patch.object(self.harness.model.resources, "fetch") as mock_fetch: mock_fetch.return_value = "test" self.harness.charm.on.install.emit() mock_fetch.assert_called_once_with("prometheus-bind-exporter") mock_subprocess.check_call.assert_called_once_with(["snap", "install", "--dangerous", "test"]) self.assertNotEqual(self.harness.charm.unit.status, ActiveStatus("Unit is ready"))
c791203a85b33e6cd411a4efd0c47ca6a891b265
[ "Python" ]
2
Python
r-f-g/prometheus-bind-exporter-operator
bea01787d4185e9a15dec59261f0da072662b108
e1bf35d4667bad21a12407bcb6b823c83f15bbf7
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JcService { public class Rdata { public int code { get; set; } public string msg { get; set; } public List<long> data { get; set; } public List<string> urlList { get; set; } } } <file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading; using System.Threading.Tasks; namespace JcService { public partial class aJcService : ServiceBase { System.Timers.Timer timer1; //计时器 int iHour = 00; int iMinute = 00; int iSecond = 05;//每天00.00.05 执行 public aJcService() { InitializeComponent(); } protected override void OnStart(string[] args) { timer1 = new System.Timers.Timer(); timer1.Interval = 1000; //设置计时器事件间隔执行时间 timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed); timer1.Enabled = true; } protected override void OnStop() { this.timer1.Enabled = false; EventLog.WriteEntry("OnStop", "任务结束"); } private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { try { int intHour = e.SignalTime.Hour; int intMinute = e.SignalTime.Minute; int intSecond = e.SignalTime.Second; // 设置 每天 00:00:05开始执行程序 if (intHour == iHour && intMinute == iMinute && intSecond == iSecond) { List<string> urlList = new List<string>(); string resoultData = HttpUtil.HttpGet2("http://www.caoam.cn/JcService/GetMonitorUrl"); Rdata myData = JsonConvert.DeserializeObject<Rdata>(resoultData); if (myData.msg == "操作成功") { urlList.AddRange(myData.urlList); } foreach (var ur in urlList) { List<long> jzItemList = new List<long>(); resoultData = HttpUtil.HttpGet2($"{ur}JcService/GetMonitorJzItem"); myData = JsonConvert.DeserializeObject<Rdata>(resoultData); if (myData.msg == "操作成功") { foreach (var item in myData.data) { jzItemList.Add(Convert.ToInt64(item)); } } foreach (var item in jzItemList) { string url = "https://trade-acs.m.taobao.com/gw/mtop.taobao.detail.getdetail/6.0/?data=itemNumId%22%3A%22{0}%22&callback=__jp5"; string result = HttpUtil.HttpGet2(string.Format(url, item)); var newdata = new { jzitem = item, result = result }; string data = Newtonsoft.Json.JsonConvert.SerializeObject(newdata); resoultData = HttpUtil.PostData($"{ur}JcService/MonitorJzItemChanges", data); myData = JsonConvert.DeserializeObject<Rdata>(resoultData); if (myData.msg == "操作成功") { WriteLogs(0, $"{item}"); } else { WriteLogs(1, $"竞品{item}-{myData.msg}"); } Thread.Sleep(3000); } } WriteLogs(0, "全部竞品"); } } catch (Exception ex) { WriteLogs(1, $"我异常了:{ex.Message}"); } //// 设置 每个小时的30分钟开始执行 //if (intMinute == iMinute && intSecond == iSecond) //{ // Console.WriteLine("每个小时的30分钟开始执行一次!"); // write("每个小时的30分钟开始执行一次!\n"); //} // 设置 每天 00:00:00开始执行程序 //if (intHour == iHour && intMinute == iMinute && intSecond == iSecond) //{ // string resoultData = HttpUtil.HttpGet2("http://www.bk.caoam.cn/JCApiCore/GetJDKeyWordDetial"); // dynamic myData = JsonConvert.DeserializeObject<dynamic>(resoultData); // if (myData.msg == "操作成功") // { // WriteLogs(0); // } // else // { // WriteLogs(1); // } //} } public static void WriteLogs(int type, string error) { string path = AppDomain.CurrentDomain.BaseDirectory; if (!string.IsNullOrEmpty(path)) { path = AppDomain.CurrentDomain.BaseDirectory + "ServiceLog"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path = path + "\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt"; string delPath = AppDomain.CurrentDomain.BaseDirectory + "ServiceLog" + "\\" + DateTime.Now.AddDays(-5).ToString("yyyyMMdd") + ".txt";//只保留五天的 if (!File.Exists(path)) { FileStream fs = File.Create(path); fs.Close(); if (File.Exists(delPath)) { File.Delete(delPath); } } if (File.Exists(path)) { StreamWriter sw = new StreamWriter(path, true, System.Text.Encoding.Default); if (type == 0) { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " >>> 竞品" + error + ":执行成功"); sw.WriteLine("-----------------华丽的分割线-----------------------"); sw.Close(); } else { sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " >>> " + "执行失败:" + error); sw.WriteLine("-----------------华丽的分割线-----------------------"); sw.Close(); } } } } } }
5649599b4c168562e3dd83a9d99ac95c58dc0c35
[ "C#" ]
2
C#
1350783396/jcService
0c43caa086d55a9e696b18f5c5a2874c92f67bea
86b604cc4419086029f117fecd1a51903bca36eb
refs/heads/master
<file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { AngularFirestore ,AngularFirestoreDocument} from '@angular/fire/firestore'; import {UserService} from '../user.service'; import {firestore} from 'firebase/app'; import { ToastController } from '@ionic/angular'; @Component({ selector: 'app-post', templateUrl: './post.page.html', styleUrls: ['./post.page.scss'], }) export class PostPage implements OnInit { postID:string post kalpDurum:string="heart-empty" postRefence:AngularFirestoreDocument sub efekt:string='' constructor(private route:ActivatedRoute, private afStore:AngularFirestore, public toastController: ToastController, private user:UserService) { } ngOnInit() { this.postID=this.route.snapshot.paramMap.get('id') // this.post=this.afStore.doc(`posts/${this.postID}`).valueChanges() this.postRefence=this.afStore.doc(`posts/${this.postID}`) this.sub=this.postRefence.valueChanges().subscribe(val=>{ this.post=val this.kalpDurum=val.begeniler.includes(this.user.getUID())?'heart':'heart-empty' this.efekt=val.efekt }) } ngOnDestroy(){ this.sub.unsubscribe() } toogleKalp(){ // this.kalpDurum=this.kalpDurum=="heart" ? "heart-empty":"heart" if(this.kalpDurum=='heart-empty'){ this.favori() this.postRefence.update({ begeniler:firestore.FieldValue.arrayUnion(this.user.getUID()) }) }else{ this.unfavori() this.postRefence.update({ begeniler:firestore.FieldValue.arrayRemove(this.user.getUID()) }) } } async favori() { const toast = await this.toastController.create({ message: 'Şikayetiniz favorilere eklenmiştir!', duration: 4000 }); toast.present(); } async unfavori() { const toast = await this.toastController.create({ message: 'Şikayetiniz favorilerden kaldırılmıştır!', duration: 4000 }); toast.present(); } } <file_sep>import { Component, OnInit, ViewChild } from '@angular/core'; import { AngularFirestoreDocument, AngularFirestore } from '@angular/fire/firestore'; import { UserService } from '../user.service'; import { Http } from '@angular/http'; import { AlertController } from '@ionic/angular'; import { Router } from '@angular/router'; //import { Geolocation } from '@ionic-native/geolocation/ngx'; @Component({ selector: 'app-bilgi-duzenle', templateUrl: './bilgi-duzenle.page.html', styleUrls: ['./bilgi-duzenle.page.scss'], }) export class BilgiDuzenlePage implements OnInit { @ViewChild('filebtn') fileBtn:{ nativeElement:HTMLInputElement } bilgiKullanici:AngularFirestoreDocument sub kullanici:string profilFoto:string // enlem: any; // boylam: any; busy:boolean=false eskiParola:string yeniParola:string constructor(private afStore:AngularFirestore, private user:UserService, private http:Http, private alert:AlertController, private router:Router) { this.bilgiKullanici=afStore.doc(`users/${user.getUID()}`) this.sub=this.bilgiKullanici.valueChanges().subscribe(event=>{ this.kullanici=event.username this.profilFoto=event.profilFoto }) } ngOnInit() { } ngOnDestroy(){ this.sub.unsubscribe() } bilgiFotoSec(){ this.fileBtn.nativeElement.click() } bilgiFotoGuncelle(event){ const files=event.target.files const data=new FormData() data.append('file',files[0]) data.append('UPLOADCARE_STORE','1') data.append('UPLOADCARE_PUB_KEY','e8d70db5e2bdfc77e9e5') this.http.post('https://upload.uploadcare.com/base/',data).subscribe(event=>{ const uuid=event.json().file this.bilgiKullanici.update({ profilFoto:uuid }) }) } // doRefresh(yenile) { // console.log('Yenileme başlatıldı'); //setTimeout(() => { //console.log('Yenileme bitti'); // yenile.target.complete(); // }, 2000);} async MesajGoster(baslik:string,icerik:string){ const mesaj=await this.alert.create({ header:baslik, message:icerik, buttons:['Tamam'] }) return mesaj.present() } async bilgileriGuncelle(){ this.busy=true if(!this.eskiParola){ this.busy=false return this.MesajGoster("Hata","Parola Alanı Boş Geçilemez") } try { this.busy=false await this.user.reAuth(this.user.getUsername(),this.eskiParola) } catch (error) { this.busy=false return this.MesajGoster("Hata","Yanlış Parola") } if(this.yeniParola){ this.busy=false await this.user.updatePassword(this.yeniParola) } if(this.kullanici!==this.user.getUsername()){ await this.user.updateUsername(this.kullanici) this.bilgiKullanici.update({ username:this.kullanici }) } this.eskiParola="" this.yeniParola="" this.busy=false this.MesajGoster("Başarılı","Şikayet Bilgileriniz Güncellendi") this.router.navigate(['/tabs/feed']) } // async getMyLocation() { // this.geolocation.getCurrentPosition().then(pos =>{ // this.enlem=pos.coords.latitude; // this.boylam=pos.coords.longitude; //}).catch(eror=>console.log(eror)); //} }<file_sep>import { Component, OnInit } from '@angular/core'; import { aciklamalar } from '../pipe/data/aciklamalar-list'; import { Aciklamalar } from '../pipe/models/aciklamalar'; @Component({ selector: 'app-aciklamalar', templateUrl: './aciklamalar.page.html', styleUrls: ['./aciklamalar.page.scss'], }) export class AciklamalarPage implements OnInit { tumAciklamalar: Aciklamalar[]; constructor() { } ngOnInit() { this.tumAciklamalar = aciklamalar; } } <file_sep>import { Pipe, PipeTransform } from '@angular/core'; import { Aciklamalar } from '../models/aciklamalar'; @Pipe({ name: 'filter' //Pipe name olarak bu kullanılacak. }) export class FilterPipe implements PipeTransform {transform(aciklamalar: Aciklamalar[], searchText?: string): Aciklamalar[] { if (!searchText) { return aciklamalar; } else { return aciklamalar.filter(function (item: any) { for (let property in item) { if (item[property] === null) { continue; } if (item[property].toString().toLowerCase().includes(searchText)) { return true; } } return false; }); } } }<file_sep>export class Aciklamalar{ icerik : string; baslik : string; }<file_sep>import { Aciklamalar } from '../models/aciklamalar'; export const aciklamalar: Aciklamalar[] = [{ "icerik": "En üst kısmında başlangıç bölümüdür dilekçe yazılacak kurum ismi girilir. Tamamı yazılır ya da baş harfleri büyük yazılır. İl adı kurumun adının bitiminde sağ altta yazılır ya da ilk başa hitap edilirken yazılır. ", "baslik": "Dilekçe" },{ "icerik": "2020 yılı için belirlenen Abone Bağlantı Bedeli 200 m2'a kadar 656,7 TL + %18 KDV = 774,91 TL + Damga Vergisi 200 m2'den sonraki her 100 m2 için 570,5 TL + %18 KDV = 673,19 TL + Damga Vergisi ilave olarak alınacaktır.", "baslik": "Doğalgaz" }, { "icerik": " Geçmişte sadece muhtarlıklardan alınan ikametgah belgesini, günümüzde Nüfus Müdürlükleri ve e-Devlet yoluyla da almak mümkün. Müdürlüklerden nüfus cüzdanınızla alabileceğiniz ikametgah belgesini, e-Devlet uygulaması ile sıra beklemeden ve zaman kaybı yaşamadan edinebilirsiniz.", "baslik": "İkametgah" }, { "icerik": "Karayollarının yapım, bakım ve onarımı ile emniyetle işlemesi için gerekli olan garaj ve atölyeleri, makine ve malzeme ambarları ile depolarını, servis ve akaryakıt tesislerini, laboratuvarlarını, deneme istasyonlarını, dinlenme yerlerini, bakım ve trafik emniyetini sağlamaya yönelik bina ve lojmanları, alıcı-verici telsiz istasyonları ile gerekli haberleşme şebekelerini, Genel Müdürlüğün görevlerini daha verimli şekilde yerine getirmesine yönelik eğitim tesisleri ile sosyal tesisleri ve diğer bütün yan tesisleri hazırlayacağı ve hazırlatacağı plan ve projelere göre yapmak, yaptırmak, donatmak, işletmek veya işlettirmek, bakım ve onarımını yapmak veya yaptırmak, kiralamak.", "baslik": "Karayolları" }]<file_sep>import { SqlserviceService, Dev } from '../../sqlservice.service'; import { Component, OnInit } from '@angular/core'; import { Observable } from 'rxjs'; import {Router} from '@angular/router'; @Component({ selector: 'app-kurum', templateUrl: './kurum.page.html', styleUrls: ['./kurum.page.scss'], }) export class KurumPage implements OnInit { kurumlar: Dev[] = []; aranan: any; notes: Observable<any[]>; public searchKurum: string = ""; kurum = {}; note = {}; selectedView = 'krmlr'; constructor(private db: SqlserviceService,public router:Router) { } ngOnInit() { this.db.getDurum().subscribe(rdy => { if (rdy) { this.db.getKurumlr().subscribe(devs => { this.kurumlar = devs; this.aranan = this.kurumlar; }) this.notes = this.db.getNotlar(); } }); } setFilteredKurum() { this.kurumlar = this.aranan; if (this.searchKurum.length > 0) { this.kurumlar = this.filterItems(this.searchKurum); } } filterItems(searchKurum) { return this.kurumlar.filter(kurumlar => { if (searchKurum === '') return return kurumlar.name.toLowerCase().indexOf(searchKurum.toLowerCase()) > -1; }); } async acAna(){ this.router.navigate(['/tabs/sikayetlerim/']) } addKurum() { let skills = this.kurum['skills'].split(','); skills = skills.map(skill => skill.trim()); this.db.addKurum(this.kurum['name'], skills, this.kurum['img']) .then(_ => { this.kurum = {}; }); } addNote() { this.db.addNote(this.note['name'], this.note['creator']) .then(_ => { this.note = {}; }); } } <file_sep> ## Şikayet Var-İonic Tabanlı Mobil Uygulaması Şikayetlerim Modülü <img src="https://raw.githubusercontent.com/2019-BLM441/app-180201130/master/logo.png" width="100" height="100" /> <img src="https://raw.githubusercontent.com/2019-BLM441/module-180201130/master/assets/img/logo-html5.png" width="30" height="30" /> -- <img src="https://raw.githubusercontent.com/2019-BLM441/module-180201130/master/assets/img/logo-angular.png" width="30" height="30" /> -- <img src="https://raw.githubusercontent.com/2019-BLM441/module-180201130/master/assets/img/logo-ionic.png" width="30" height="30" /> -- <img src="https://raw.githubusercontent.com/2019-BLM441/module-180201130/master/assets/img/logo-nodejs.png" width="30" height="30" /> -- <img src="https://raw.githubusercontent.com/2019-BLM441/module-180201130/master/assets/img/logo-javascript.png" width="30" height="30" /> # ### Modül Sahibi | İsim Soyisim | Numara | Email | | ------ | ------ | ------ | | <NAME> | 180201130 | <EMAIL> | # **Şikayet Var!** uygulaması belediyeler gibi küçük nüfuslu yerleşim yerlerine özel kullanıcıların çevrelerindeki herhangi bir olumsuz durum yada şikayetlerini herkese açık bir şekilde paylaşıp ileti atabildiği bir ionic tabanlı mobil uygulamadır.Uygulama aynı zamanda bulut tabanlı ve local tabanlı veritabanı içerir. **Açıklama** Bu uygulama <abbr title="Mobil uygulamalar için HTML5 bazında hazırlanmış açık kaynak bir yazılım iskeleti">IONIC</abbr> tabanlı açık kaynak bir mobil projedir. Kocaeli Üniversitesi Bilgisayar Mühendisliği 4. sınıf mobil programlama dersi için geliştirilmektedir. Modül şikayetlerim sayfasıyla başlar.Şikayet oluşturabilir, düzenleyebilirsiniz ayrıca çekilen fotoğrafa efekt verebilirsiniz.Kişisel listenizde resmi kurumların bilgileri tutabilir yada kurumlara ait notlar alabilirsiniz bunlar üzeründe düzenlemeler yapabilirsiniz.Yardımcı menüde merak ettiğiniz resmi işlemler ile ilgili bilgi alabilirsiniz(örn:İkametgah,Doğalgaz vs...). Geliştiriciyi ara butonu ile telefondan direk arama yapabilirsiniz.Bilgi düzenle kısmından bilgilerinizi düzenlebilirsiniz.Atılan tüm şikayetleri listeleyebilirsiniz.Şikayetlerinizi görebilir yada kaydedebilirsiniz.Uygulama sadece firebase'e bağlı değildir. Derste işlenen http modülünüde aktif şekilde kullanabilmek için uploadcore web sitesi üzerinden httpModül kullanılarak fotoğraf ekleme ve işlemleri yapılmıştır.Bu işlem için uploadcore web servisi oluşturulmuştur.Assets klasörü içinde apk dosyası mevcuttur. # ![](https://img.shields.io/static/v1?label=Version&message=1.0&color=<COLOR>) ![](https://img.shields.io/static/v1?label=ionic&message=4.0&color=<COLOR>) ![](https://img.shields.io/github/license/2019-BLM441/module-180201130) ![](https://img.shields.io/twitter/url?url=https%3A%2F%2Fgithub.com%2F2019-BLM441%2Fmodule-180201130) ## ŞİKAYETLERİM MODÜLÜ #### ->Bu modül [Şikayet Var](https://github.com/2019-BLM441/app-180201130) uygulamasının bir modülüdür.Uygulamanın Şikayetlerim bölümü bu modül sayesinde çalışmaktadır. ##### Şikayetlerim Modülünün Sunduğu Özellikler + Şikayetlerim Bölümü * Kullanıcı şikayetlerini görme * Kullanıcı şikayetlerini kaydetme + Tüm Şikayetler Bölümü * Şikayetleri Listeleyebilirsiniz. + Kişisel Liste Bölümü * Resmi Kurum bilgisi kaydetme,silme,güncelleme(Local işlemler,sqlite) * Kuruma ait not alma(Güncelleme,silme,ekleme)(Local işlemler,sqlite) + Yardımcı Menü Bölümü * Merak ettiğiniz resmi işlerle ilgili bilgiler edinebilirsiniz.(Pipe) + Yeni Şikayet Oluşturma Bölümü * Yeni şikayet upload etme(httpModülü+firebase) * Şikayet içeriğini düzenleme açıklama ekleme, fotoğrafa efekt ekleme(httpModülü) + Service Dosyası * Firebase için servis dosyası içermektedir. * Sqlite için servis dosyası içermektedir. + Yükleme Component * Tüm sayfaların başlangıcında yükleme simgesi fonksiyonu + Bilgi Düzenle Bölümü + Kendi fotoğrafını düzenleme + Kullanıcı adı düzenleme + Şifre Yenileme ##### Native kısım için geliştirici numarasını arama servisleri kullanılmıştır. Gerekli kütüphaneler aşağıda belitilmiştir. ### Kurulum Şikayet Var [Node.js](https://nodejs.org/) v4+ ihtiyaç duyar. Konsol ekranını açın ```sh $ npm install -g ionic $ npm install @angular/cli $ cd sikayetvar $ ionic serve ``` Gerekli kütüphaneler ```sh $ @ionic-native/call-number/ngx $ ionic cordova plugin add cordova-sqlite-storage $ ionic cordova plugin add cordova-plugin-firebase $ ionic cordova plugin add cordova-plugin-advanced-http ``` ## Ekran Görüntüleri <img src="https://github.com/2019-BLM441/module-180201130/blob/master/assets/ekranimg/7.png" width="280" height="480" /><img src="https://github.com/2019-BLM441/module-180201130/blob/master/assets/ekranimg/1.png" width="280" height="480" /><img src="https://github.com/2019-BLM441/module-180201130/blob/master/assets/ekranimg/2.png" width="280" height="480" /> <img src="https://github.com/2019-BLM441/module-180201130/blob/master/assets/ekranimg/4.png" width="280" height="480" /><img src="https://github.com/2019-BLM441/module-180201130/blob/master/assets/ekranimg/5.png" width="280" height="480" /><img src="https://github.com/2019-BLM441/module-180201130/blob/master/assets/ekranimg/6.png" width="280" height="480" /><img src="https://github.com/2019-BLM441/module-180201130/blob/master/assets/ekranimg/3.png" width="280" height="480" /> <img src="https://github.com/2019-BLM441/module-180201130/blob/master/assets/ekranimg/32.png" width="280" height="480" /> <file_sep>import { Component, OnInit } from '@angular/core'; import {AngularFirestore, AngularFirestoreDocument} from '@angular/fire/firestore'; import {UserService} from './user.service'; import { Router } from '@angular/router'; import { ToastController } from '@ionic/angular'; import { CallNumber } from '@ionic-native/call-number/ngx'; @Component({ selector: 'app-sikayetlerim', templateUrl: './sikayetlerim.page.html', styleUrls: ['./sikayetlerim.page.scss'], }) export class SikayetlerimPage implements OnInit { sikayetKullanici:AngularFirestoreDocument sub posts kullanici:string benimFotom:string userPosts constructor(public afStore:AngularFirestore, public service:UserService, public toastController: ToastController, private callNumber: CallNumber, public router:Router) { this.sikayetKullanici=this.afStore.doc(`users/${this.service.getUID()}`) this.sub=this.sikayetKullanici.valueChanges().subscribe(event=>{ this.posts=event.posts this.kullanici=event.username this.benimFotom=event.benimFotom }) } doRefresh(event) { console.log('Başlatıldı'); setTimeout(() => { console.log('Yenilendi'); event.target.complete(); }, 2000); } ngOnInit() { if (!navigator.onLine) { this.netKontrol(); } } ngOnDestroy(){ this.sub.unsubscribe() } async netKontrol() { const toast = await this.toastController.create({ message: 'İnternetiniz bağlantınızda sorun var!', duration: 4000 }); toast.present(); } async ac(){ this.router.navigate(['tabs/sikayetlerim/uploader']) } posttaGit(postID:string){ this.router.navigate(['/tabs/sikayetlerim/post/'+postID.split('/')[0]]) } async tumSikayet(){ this.router.navigate(['/tabs/sikayetlerim/sikayetler']) } async ara(){ this.callNumber.callNumber("0555000000", true) .then(res => console.log('Arama Başarılı!', res)) .catch(err => console.log('Arama Hatası!', err)); } } <file_sep>export interface KurumList { kurumid : string kurumName : string }
7fe2575c002e336fd2457ad5838e1d29183c8b0d
[ "Markdown", "TypeScript" ]
10
TypeScript
2019-BLM441/module-180201130
c19809c52bdaee7bde252edb8d732375930c2061
d36836258c9f67e24dc1b27bc56a6069be1128e6
refs/heads/master
<file_sep>import * as types from "../constants/index"; // toggle status export const actionToggleStatus = () => { return { type: types.TOGGLE_STATUS }; }; //change sort export const actionChangeSort = (sort) => { return { type: types.CHANGE_SORT, sort }; }; <file_sep>import { createStore } from "redux"; import { actionToggleStatus, actionChangeSort } from "./actions/index"; import reducer from "./reducers/index"; const store = createStore(reducer); // Default console.log("DEFAULT", store.getState()); // toggle status store.dispatch(actionToggleStatus()); console.log("TOGGLE_STATUS", store.getState()); //change sort store.dispatch(actionChangeSort({ by: "name", value: -1 })); console.log("CHANGE_SORT", store.getState()); <file_sep>import * as types from "../constants/index"; let intialState = false; const statusReducer = (state = intialState, action) => { if (action.type === types.TOGGLE_STATUS) { return !state; } return state; }; export default statusReducer; <file_sep>import statusReducer from "./statusReducer"; import sortReducer from "./sortReducer"; import { combineReducers } from "redux"; const reducer = combineReducers({ status: statusReducer, sort: sortReducer }); export default reducer; <file_sep># demo-redux-reactjs Created with CodeSandbox <file_sep>import * as types from "../constants/index"; let intialState = { by: "name", value: 1 // 1: A-Z ; -1 : Z-A }; const sortReducer = (state = intialState, action) => { if (action.type === types.CHANGE_SORT) { return { by: action.sort.by, value: action.sort.value }; } return state; }; export default sortReducer;
689b71ff5391291dbe763e76c2d7b5cc7b95a245
[ "JavaScript", "Markdown" ]
6
JavaScript
diennguyen2002/demo-redux-reactjs
6fe2bfa4ec694224e9edbf20398ccfd2fd6b578c
a2c074c0caaaeddea2e1f2399b5e28fd8acdfd73
refs/heads/master
<file_sep>// Variável inimigo que recebe posição x e y, além de uma variável de // velocidade para o seu movimento automático. var Enemy = function(x, y, vel) { this.x = x; this.y = y; this.vel = vel; this.sprite = 'images/enemy-bug.png'; }; // Faz o update da posição do inimigo Enemy.prototype.update = function(dt) { // Multiplica-se a velocidade atual por dt e atribua à coordenada x // para manter a velocidade estável em qualquer computador this.x += this.vel * dt; // Verifica se o inimigo ultrapassou o tamanho do canvas e o retorna // para o início do canvas. Também modifica a velocidade do inimigo, // afim de que seu movimento seja aleátorio e diferente do movimento // anterior. if (this.x > 505){ this.x = -50; this.vel = 100 + Math.floor(Math.random() * 200); } // Função de Colisão - Verifica se a diferença entre posição do player // e a posição do inimigo é menor ou maior que o tamanho de seus sprites, // retornando o player à posição inicial. if((this.x - player.x) <= 71 && (this.y - player.y) <= 80 & (this.x - player.x) > -71 && (this.y - player.y) > -80) { setTimeout(() => { player.x = 202; player.y = 400; }, 50); } }; // Renderização do sprite do inimigo Enemy.prototype.render = function() { // Recebe imagem e posição x e y para renderizar ctx.drawImage(Resources.get(this.sprite), this.x, this.y); }; // Variável player recebe apenas a posição x e y, já que o controle de movimento // fica nas mãos do jogador var Player = function(x, y){ this.x = x; this.y = y; this.sprite = 'images/char-cat-girl.png'; }; // Faz o update da posição do jogador Player.prototype.update = function(){ // Os 3 primeiros if a seguir verificam se a posição do jogador em x ou y // pode ultrapassar o canvas. Se sim, impede o jogador de se movimentar além. if (this.x > 402){ this.x = 402; } if (this.x < 2){ this.x = 2; } if (this.y > 400){ this.y = 400; } // Verifica se o jogador chegou à água. Se sim, retorna o jogador para a posição // inicial de forma mais devagar utilizando o setTimeout. if (this.y < 0){ setTimeout(() => { this.x = 202; this.y = 400; }, 50); } }; // Renderização do sprite do jogador Player.prototype.render = function(){ // Recebe imagem e posição x e y para renderizar ctx.drawImage(Resources.get(this.sprite), this.x, this.y); }; // Função de movimento do jogador - Recebe as teclas pressionadas e adiciona coordenadas // diferentes à x e y. Player.prototype.handleInput = function(key){ // Movimentação para a esquerda if(key == 'left' && this.x > 0){ this.x -= 100; } // Movimentação para a direita if(key == 'right' && this.x < 408){ this.x += 100; } // Movimentação para cima if (key == 'up' && this.y > 0) { this.y -= 85; } // Movimentação para baixo if (key == 'down' && this.y < 408){ this.y += 85; } }; // Instanciação do jogador, passando as coordenadas x e y var player = new Player(202, 400); // Instanciação do inimigo var allEnemies = []; // Array de posições y dos 3 inimigos var bugLocation = [228, 145, 62]; // Adiciona instâncias no array dos inimigos bugLocation.forEach(function (y){ var enemy = new Enemy(0, y, 300); allEnemies.push(enemy); }); // Leitor de teclas pressionadas document.addEventListener('keyup', function(e) { var allowedKeys = { 37: 'left', 38: 'up', 39: 'right', 40: 'down' }; player.handleInput(allowedKeys[e.keyCode]); }); <file_sep># Udacity Web Front-End Nanodegree: Frogger Clone 1º Projeto do Nanodegree Web Front-End. O projeto consiste em recriar um jogo no mesmo estilo do game Frogger. ## Como configurar para jogar 1. Clone o repositório em seu desktop ou baixe o zip. 2. Abra a página `index.html` e é só jogar! ## Como jogar **Objetivo**: Atravessar o caminho e chegar ao rio sem ser tocado pelos insetos. **Movimentos**: Use as teclas direcionais para movimentar o seu avatar. ========================= Students should use this [rubric](https://www.udacity.com/course/viewer#!/c-ud015/l-3072058665/m-3072588797) for self-checking their submission.
28c4d1934b357827cf20a250df31c6edba409aa7
[ "JavaScript", "Markdown" ]
2
JavaScript
JessyFehnle/Frogger
4e50d188d3b307e3e96a05f800004d1e2431584b
25548892c59f282dadf088a64fdea1a3106ebd5e
refs/heads/master
<file_sep># Copyright 2020 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utilities for keras models.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import tempfile import tensorflow as tf from tensorflow_examples.lite.model_maker.core import compat def set_batch_size(model, batch_size): """Sets batch size for the model.""" for model_input in model.inputs: new_shape = [batch_size] + model_input.shape[1:] model_input.set_shape(new_shape) def _create_temp_dir(convert_from_saved_model): if convert_from_saved_model: return tempfile.TemporaryDirectory() else: return DummyContextManager() class DummyContextManager(object): def __enter__(self): pass def __exit__(self, *args): pass def export_tflite(model, tflite_filepath, quantization_config=None, gen_dataset_fn=None, convert_from_saved_model_tf2=False): """Converts the retrained model to tflite format and saves it. Args: model: model to be converted to tflite. tflite_filepath: File path to save tflite model. quantization_config: Configuration for post-training quantization. gen_dataset_fn: Function to generate tf.data.dataset from `representative_data`. Used only when `representative_data` in `quantization_config` is setted. convert_from_saved_model_tf2: Convert to TFLite from saved_model in TF 2.x. """ if tflite_filepath is None: raise ValueError( "TFLite filepath couldn't be None when exporting to tflite.") if compat.get_tf_behavior() == 1: lite = tf.compat.v1.lite else: lite = tf.lite convert_from_saved_model = ( compat.get_tf_behavior() == 1 or convert_from_saved_model_tf2) with _create_temp_dir(convert_from_saved_model) as temp_dir_name: if temp_dir_name: save_path = os.path.join(temp_dir_name, 'saved_model') model.save(save_path, include_optimizer=False, save_format='tf') converter = lite.TFLiteConverter.from_saved_model(save_path) else: converter = lite.TFLiteConverter.from_keras_model(model) if quantization_config: converter = quantization_config.get_converter_with_quantization( converter, gen_dataset_fn) tflite_model = converter.convert() with tf.io.gfile.GFile(tflite_filepath, 'wb') as f: f.write(tflite_model) <file_sep># Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the 'License'); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an 'AS IS' BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import numpy as np import tensorflow as tf from tensorflow_examples.lite.model_maker.core import test_util from tensorflow_examples.lite.model_maker.core.task import configs from tensorflow_examples.lite.model_maker.core.task import model_util def _get_quantization_config_list(input_dim, num_classes, max_input_value): # Configuration for dynamic range quantization. config1 = configs.QuantizationConfig.create_dynamic_range_quantization() representative_data = test_util.get_dataloader( data_size=1, input_shape=[input_dim], num_classes=num_classes, max_input_value=max_input_value) # Configuration for full integer quantization with float fallback. config2 = configs.QuantizationConfig.create_full_integer_quantization( representative_data=representative_data, quantization_steps=1) # Configuration for full integer quantization with integer only. config3 = configs.QuantizationConfig.create_full_integer_quantization( representative_data=representative_data, quantization_steps=1, is_integer_only=True) # Configuration for full integer quantization with float fallback. config4 = configs.QuantizationConfig.create_float16_quantization() return [config1, config2, config3, config4] def _mock_gen_dataset(data, batch_size=1, is_training=False): # pylint: disable=unused-argument ds = data.dataset ds = ds.batch(batch_size) return ds class ModelUtilTest(tf.test.TestCase): @test_util.test_in_tf_1and2 def test_export_tflite(self): input_dim = 4 model = test_util.build_model(input_shape=[input_dim], num_classes=2) tflite_file = os.path.join(self.get_temp_dir(), 'model.tflite') model_util.export_tflite(model, tflite_file) self._test_tflite(model, tflite_file, input_dim) @test_util.test_in_tf_1and2 def test_export_tflite_quantized(self): input_dim = 4 num_classes = 2 max_input_value = 5 model = test_util.build_model([input_dim], num_classes) tflite_file = os.path.join(self.get_temp_dir(), 'model_quantized.tflite') for config in _get_quantization_config_list(input_dim, num_classes, max_input_value): model_util.export_tflite(model, tflite_file, config, _mock_gen_dataset) self._test_tflite( model, tflite_file, input_dim, max_input_value, atol=1e-01) def _test_tflite(self, keras_model, tflite_model_file, input_dim, max_input_value=1000, atol=1e-04): with tf.io.gfile.GFile(tflite_model_file, 'rb') as f: tflite_model = f.read() np.random.seed(0) random_input = np.random.uniform( low=0, high=max_input_value, size=(1, input_dim)).astype(np.float32) # Gets output from keras model. keras_output = keras_model.predict(random_input) # Gets output from tflite model. interpreter = tf.lite.Interpreter(model_content=tflite_model) interpreter.allocate_tensors() input_details = interpreter.get_input_details()[0] if input_details['dtype'] != np.float32: # Quantize the input scale, zero_point = input_details['quantization'] random_input = random_input / scale + zero_point random_input = random_input.astype(input_details['dtype']) interpreter.set_tensor(input_details['index'], random_input) interpreter.invoke() output_details = interpreter.get_output_details()[0] lite_output = interpreter.get_tensor(output_details['index']) if output_details['dtype'] != np.float32: # Dequantize the output scale, zero_point = output_details['quantization'] lite_output = lite_output.astype(np.float32) lite_output = (lite_output - zero_point) * scale self.assertTrue(np.allclose(lite_output, keras_output, atol=atol)) if __name__ == '__main__': tf.test.main()
17bf434079f9d5f0b39cdbdda3ed411c6457323a
[ "Python" ]
2
Python
Jamesweng/examples
39c65d5c453747bc0602e2f7a29aa100f9ca0a58
7c7d566d223ae163fb6462681796eda4735381fb
refs/heads/master
<repo_name>markiplagat/php<file_sep>/hello.php <?php echo "Hello php <br/>"; $string='Hello php <br/>'; echo $string; ?><file_sep>/array.php <!DOCTYPE html> <html lang="en"> <head> <title></title> </head> <body> <?php $friends=array("mark","kip","rutto","dp"); setcookie("test","PHP-Hypertext-Preprocessor",time()+60,"/location",1); ?> </body> </html><file_sep>/getmax.php <?php function getMax($num1,$num2,$num3){ if($num1>=$num2 && $num1>=$num3){ return $num1;} elseif($num2>=$num1 && $num2>=$num3){ return $num2;} else { return $num3; } } echo getMax(23,45,65); ?><file_sep>/input.php <!DOCTYPE html> <html> <head> </head> <title> </title> <body> <?php ?> <form action="input.php" method="get"> Name:<br> <input type="text" name="username"> <br> Num1:<br><input type="number" name="num1"><br> Num2:<br><input type="number" name="num2"><br> Age:<br> <input type="number" name="age"> <br><input type="submit"> </form> <br> Your name is <?php echo $_GET["username"]?> <br> Your age is <?php echo $_GET["age"] ?> ANSWER: <?php echo$_GET["num1"]+$_GET["num2"]?> <br> <form action="input.php" method="post"> PASSWORD: <br><input type= "password" name="password"> <br> <Input type ="submit"> </form> <br> Your password is <?php echo $_POST["password"]?> </body> </html> <file_sep>/function.php <?php function mark($name){ echo "Hello $name"; } mark("Kip"); ?><file_sep>/mine.php <?php ?> <form action="mine.php" method ="post"> Num1:<input type="number" step="0.0001" name="num1"> <br>OP:<input type="text" name="operator"><br> Num2:<input type="number"step="0.0001" name="num2"><br> <input type="submit"> </form> <?php $num1=$_POST["num1"]; $op=$_POST["operator"]; $num2=$_POST["num2"]; if($op=="+"){ echo $num1+$num2; } elseif($op=="-"){ echo $num1-$num2; } elseif($op=="/"){ echo $num1/$num2; } elseif($op=="*"){ echo $num1*$num2; } else { echo "invalid operator"; } ?> <file_sep>/ifstatements.php <?php $d=date("D"); if ($d=="Fri") echo "Have a nice weekend"; else echo "Oops you have a tight schedule"; ?><file_sep>/checkboxes.php <?php ?> <form action="checkboxes.php" method="post"> Apples: <input type="checkbox" name="fruits[]" value="apples"><br> Oranges: <input type="checkbox" name="fruits[]" value="oranges"><br> Pears: <input type="checkbox" name="fruits[]" value="pears"><br> Student: <input type="text"name="student"> <input type="submit"> </form> <?php $grades=array("jim"=>"A","tom"=>"B"); echo $grades[$_POST["student"]]; $fruits= $_POST["fruits"]; ?><file_sep>/operations.php <?php $x='5'; $y='4'; $z=$x+$y; echo "$z <br/>"; $z=$y*$y-5; echo "$z <br/>"; $string='Php is wonderful and great'; $string=$string ." ". "Kip loves it"; echo $string; ?>
1df60858de088f1714d0e93e9ae906e2867c2450
[ "PHP" ]
9
PHP
markiplagat/php
4bbecf3fe50a9a92dd4a2d4074f30d073241cbc7
7f254f1042dcf910f6da09aa4d73b398a626c82a
refs/heads/master
<file_sep>// The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below import * as vscode from 'vscode'; import Messages from './messages'; // this method is called when your extension is activated // your extension is activated the very first time the command is executed export function activate(context: vscode.ExtensionContext) { // Use the console to output diagnostic information (console.log) and errors (console.error) // This line of code will only be executed once when your extension is activated // The command has been defined in the package.json file // Now provide the implementation of the command with registerCommand // The commandId parameter must match the command field in package.json let disposable = vscode.commands.registerCommand('extension.caress-generator', () => { // Display a message box to the user // const quickpicks = [new vscode.QuickInputButtons()] const quickPick = vscode.window.createQuickPick(); quickPick.items = getQuickPicks(); quickPick.show(); quickPick.onDidChangeSelection(() => { const selectedItem = quickPick.selectedItems; if (selectedItem && selectedItem[0] && selectedItem[0].description) { vscode.window.showInputBox({ prompt: 'Enter the name you want for the new ' + selectedItem[0].description.toLowerCase() + ' above - ', placeHolder: 'Give the new ' + selectedItem[0].description.toLowerCase() + ' a name...', }).then((name) => { if (name && selectedItem[0].description) { const terminal = getTerminal(); // terminal.sendText('@ECHO OFF'); terminal.sendText(getTerminalCommand(selectedItem[0].description, name, selectedItem[0].detail)); vscode.window.showInformationMessage(Messages.getMessage(selectedItem[0].description)); // terminal.sendText('@echo on'); } else { vscode.window.showErrorMessage('No name entered.'); } }); } }); }); context.subscriptions.push(disposable); function getTerminal() { let terminal = vscode.window.activeTerminal; if (!terminal) { terminal = vscode.window.createTerminal(); } terminal.show(); return terminal; } function getTerminalCommand(type?: string, name?: string, path?: string): string { let command = ''; if (type && name && path) { if (type.toLowerCase() !== 'entity') { command = 'ionic generate ' + type.toLowerCase(); command += ' '; command += path; command += name; } else { command = generateEntity(name, path); } } return command; } } function generateEntity(name: string, path: string): string { let command = "(echo '// This class was generated by mijnCaress-generator"; command += '\n'; command += "export default class " + capitalize(name) + " {"; command += '\n\n'; command += " constructor() {"; command += '\n'; command += " }"; command += '\n\n'; command += "}"; command += '\n'; command += "') > src/" + path + name + ".ts"; return command; } function getQuickPicks(): Array<GeneratorType> { let list = []; const pageItem: GeneratorType = { 'description': 'Page', 'detail': 'pages/', 'label': 'Generate a page' }; const serviceItem: GeneratorType = { 'description': 'Service', 'detail': 'services/', 'label': 'Generate a service' }; const moduleItem: GeneratorType = { 'description': 'Module', 'detail': 'modules/', 'label': 'Generate a module' }; const sharedModuleItem: GeneratorType = { 'description': 'Shared module', 'detail': 'sharedModules/', 'label': 'Generate a shared module' }; const entityItem: GeneratorType = { 'description': 'Entity', 'detail': 'entities/', 'label': 'Generate an entity' }; list.push(pageItem); list.push(serviceItem); list.push(moduleItem); list.push(sharedModuleItem); list.push(entityItem); return list; } class GeneratorType { label: string = ''; description: string = ''; detail: string = ''; } const capitalize = (s: string) => { if (typeof s !== 'string') { return ''; } return s.charAt(0).toUpperCase() + s.slice(1); }; // this method is called when your extension is deactivated export function deactivate() { } <file_sep># mijncaress Generator Deze generator maakt het makkelijk om op een juiste manier een bestand voor mijncaress te genereren ## Opties Open de plugin met CTRL+SHIFT+P en typ ```bash mijncaress generator ``` ```bash * page -> genereert een pagina in src/pages/ * service -> genereert een service in src/services/ * module -> genereert een module in src/modules/ * shared module -> genereert een gedeelde module in src/sharedModules/ * entity -> genereert een entity die niet uit anubis komt naar src/entities/ ``` ## Contributing Medewerkers van PRHC kunnen toegang tot de source code aanvragen bij <NAME> Carlo <file_sep>export default class Messages { static getMessage(type: string) { const position = Math.floor(Math.random() * this.messages.length); return this.messages[position].replace('{}', type.toLowerCase()); } static messages = [ 'Awesome! Je hebt een {} gegenereerd! Veel plezier samen!', 'Niemand kan een {} genereren als jij...', 'Alsjeblieft! Een nieuwe {} - je bent echt een genereerbeer', 'Genereren kan je leren. Als je valt kan je je bezeren. Alsjeblieft; hier de {} waar je om vroeg.', 'Rozen zijn rood, violen zijn blauw. Ik ben awesome, deze {} genereer ik voor jou.', 'E = MC({})' ]; }
901d20e7ce94b8ae76a266591ae6f11b4326d55b
[ "Markdown", "TypeScript" ]
3
TypeScript
jeremybosscha/mijncaress-generator
f5d0a45f2af95efad586f249412fd98d05ec5bde
1f95713bb9605d3b9c43e10a91debf6c78139ce5
refs/heads/master
<repo_name>sandy-1998/aguafacturacion<file_sep>/view/paginawebView.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>FCPC CAPREMCI</title> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <meta content="" name="keywords"> <meta content="" name="description"> <!-- Favicons --> <link href="view/img/favicon.png" rel="icon"> <link href="view/img/apple-touch-icon.png" rel="apple-touch-icon"> <!-- Google Fonts --> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,700,700i|Montserrat:300,400,500,700" rel="stylesheet"> <!-- Bootstrap CSS File --> <link href="view/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Libraries CSS Files --> <link href="view/lib/font-awesome/css/font-awesome.min.css" rel="stylesheet"> <link href="view/lib/animate/animate.min.css" rel="stylesheet"> <link href="view/lib/ionicons/css/ionicons.min.css" rel="stylesheet"> <link href="view/lib/owlcarousel/assets/owl.carousel.min.css" rel="stylesheet"> <link href="view/lib/lightbox/css/lightbox.min.css" rel="stylesheet"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <!-- Main Stylesheet File --> <link href="view/css/style.css" rel="stylesheet"> <!-- ======================================================= Theme Name: BizPage Theme URL: https://bootstrapmade.com/bizpage-bootstrap-business-template/ Author: BootstrapMade.com License: https://bootstrapmade.com/license/ ======================================================= --> <script type="text/javascript"> $(document).ready( function (){ $("#mostrarmodal").modal("show"); }); </script> </head> <body> <?php $data =""; $i=0; if (!empty($resultSet)) { $data="["; foreach($resultSet as $res) { $data.="'"; $data.=$res->nombre_preguntas_encuestas_participes."',"; } $data.="]"; $pre_1_r1="["; $pre_1_r2="["; $pre_1_r3="["; foreach($resultSet as $res) { $i++; if($i==1){ $pre_1_r1.="'"; $pre_1_r1.=$res->bueno_pregunta_1."',"; $pre_1_r2.="'"; $pre_1_r2.=$res->intermedio_1."',"; $pre_1_r3.="'"; $pre_1_r3.=$res->malo_1."',"; } elseif ($i==2){ $pre_1_r1.="'"; $pre_1_r1.=$res->si_2."',"; $pre_1_r2.="'"; $pre_1_r2.=$res->algo_2."',"; $pre_1_r3.="'"; $pre_1_r3.=$res->nada_2."',"; } elseif ($i==3){ $pre_1_r2.="'"; $pre_1_r2.=$res->la_informacion_3."',"; $pre_1_r3.="'"; $pre_1_r3.=$res->los_colores_3."',"; $pre_1_r1.="'"; $pre_1_r1.=$res->nada_3."',"; } elseif ($i==4){ $pre_1_r1.="'"; $pre_1_r1.=$res->r10_4."',"; $pre_1_r2.="'"; $pre_1_r2.=$res->r9_4."',"; $pre_1_r3.="'"; $pre_1_r3.=$res->r8_4."',"; } elseif ($i==5){ $pre_1_r1.="'"; $pre_1_r1.=$res->si_5."',"; $pre_1_r2.="'"; $pre_1_r2.=$res->intermedio_5."',"; $pre_1_r3.="'"; $pre_1_r3.=$res->no_5."',"; } elseif ($i==6){ $pre_1_r1.="'"; $pre_1_r1.=$res->si_6."',"; $pre_1_r2.="'"; $pre_1_r2.=$res->no_6."',"; $pre_1_r3.="'"; $pre_1_r3.='0'."',"; } elseif ($i==7){ $pre_1_r1.="'"; $pre_1_r1.=$res->si_7."',"; $pre_1_r2.="'"; $pre_1_r2.=$res->no_7."',"; $pre_1_r3.="'"; $pre_1_r3.='0'."',"; } elseif ($i==8){ $pre_1_r1.="'"; $pre_1_r1.=$res->si_8."',"; $pre_1_r2.="'"; $pre_1_r2.=$res->intermedio_8."',"; $pre_1_r3.="'"; $pre_1_r3.=$res->no_8."',"; } } $pre_1_r1.="]"; $pre_1_r2.="]"; $pre_1_r3.="]"; // echo ($data1); }else{ } ?> <!--========================== Header ============================--> <header id="header"> <div class="container-fluid"> <div id="logo" class="pull-left"> <!-- Uncomment below if you prefer to use an image logo --> <a href="#intro"><img src="view/img/logo.png" width="160" height="37" alt="" title="" /></a> </div> <nav id="nav-menu-container"> <ul class="nav-menu"> <li class="menu-active"><a href="#intro">Inicio</a></li> <li><a href="#about">El Fondo</a></li> <li><a href="index.php?controller=Usuarios&action=Loguear">Servicios en Linea</a></li> <li><a href="#services">Prestaciones</a></li> <li><a href="#testimonials">Servicios Financieros</a></li> <li><a href="#service">Educación Financiera</a></li> <li><a href="#contact">Contáctanos</a></li> </ul> </nav><!-- #nav-menu-container --> </div> </header><!-- #header --> <!--========================== Intro Section ============================--> <section id="intro"> <div class="intro-container"> <div id="introCarousel" class="carousel slide carousel-fade" data-ride="carousel"> <ol class="carousel-indicators"></ol> <div class="carousel-inner" role="listbox"> <div class="carousel-item active"> <div class="carousel-background"><img src="view/img/intro-carousel/1.jpg" alt=""></div> <div class="carousel-container"> <div class="carousel-content"> <h2>Bienvenido a CAPREMCI</h2> <h3>Tú ahorro presente , tú bienestar del mañana</h3> <p>Afíliate ya.</p> <a href="#about" class="btn-get-started scrollto">Ver Más</a> </div> </div> </div> <div class="carousel-item"> <div class="carousel-background"><img src="view/img/intro-carousel/2.jpg" alt=""></div> <div class="carousel-container"> <div class="carousel-content"> <h2>Bienvenido a CAPREMCI</h2> <h3>Tú ahorro presente , tú bienestar del mañana</h3> <p>Afiliate ya.</p> <a href="#about" class="btn-get-started scrollto">Ver Más</a> </div> </div> </div> <div class="carousel-item"> <div class="carousel-background"><img src="view/img/intro-carousel/3.jpg" alt=""></div> <div class="carousel-container"> <div class="carousel-content"> <h2>Bienvenido a CAPREMCI</h2> <h3>Tú ahorro presente , tú bienestar del mañana</h3> <p>Afiliate ya.</p> <a href="#about" class="btn-get-started scrollto">Ver Más</a> </div> </div> </div> <div class="carousel-item"> <div class="carousel-background"><img src="view/img/intro-carousel/4.jpg" alt=""></div> <div class="carousel-container"> <div class="carousel-content"> <h2>Bienvenido a CAPREMCI</h2> <h3>Tú ahorro presente , tú bienestar del mañana</h3> <p>Afiliate ya.</p> <a href="#about" class="btn-get-started scrollto">Ver Más</a> </div> </div> </div> <div class="carousel-item"> <div class="carousel-background"><img src="view/img/intro-carousel/5.jpg" alt=""></div> <div class="carousel-container"> <div class="carousel-content"> <h2>Bienvenido a CAPREMCI</h2> <h3>Tú ahorro presente , tú bienestar del mañana</h3> <p>Afiliate ya.</p> <a href="#about" class="btn-get-started scrollto">Ver Más</a> </div> </div> </div> </div> <a class="carousel-control-prev" href="#introCarousel" role="button" data-slide="prev"> <span class="carousel-control-prev-icon ion-chevron-left" aria-hidden="true"></span> <span class="sr-only">Anterior</span> </a> <a class="carousel-control-next" href="#introCarousel" role="button" data-slide="next"> <span class="carousel-control-next-icon ion-chevron-right" aria-hidden="true"></span> <span class="sr-only">Siguiente</span> </a> </div> </div> </section><!-- #intro --> <div class="modal fade" id="mostrarmodal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true"> <div class="modal-dialog modal-md"> <div class="modal-content"> <div class="modal-header"> <h4>Contáctanos a los números.</h4> </div> <div class="modal-body"> <strong>Quito:</strong> 02-2236931 <i class="ion-ios-telephone-outline"></i><BR> <strong>Guayaquil:</strong> 04-2564900 <i class="ion-ios-telephone-outline"></i> </div> <div class="modal-footer"> <a href="#" data-dismiss="modal" class="btn btn-danger">Cerrar</a> </div> </div> </div> </div> <main id="main"> <!--========================== About Us Section ============================--> <section id="about"> <div class="container"> <header class="section-header"> <h3>Bienvenidos a CAPREMCI</h3> <p align="justify"></p> </header> <div class="row about-cols"> <div class="col-md-3 wow fadeInUp"> <div class="about-col"> <div class="img"> <img src="view/img/about-mission.jpg" alt="" class="img-fluid"> <div class="icon"><i class="ion-ios-speedometer-outline"></i></div> </div> <h2 class="title"><a href="#">Misión</a></h2> <p align="justify"> Al 2017 Consolidamos nuestra operación como Fondo previsional llegando a más partícipes para satisfacer sus necesidades con procesos controlados, utilizando canales de comunicación apropiados al sistema; y manteniendo niveles óptimos de rentabilidad y en constante crecimiento como entidad a nivel nacional.</p> </div> </div> <div class="col-md-3 wow fadeInUp" data-wow-delay="0.1s"> <div class="about-col"> <div class="img"> <img src="view/img/about-plan.jpg" alt="" class="img-fluid"> <div class="icon"><i class="ion-ios-eye-outline"></i></div> </div> <h2 class="title"><a href="#">Visión</a></h2> <p align="justify"> Somos un Fondo Previsional orientado a asegurar el futuro de sus partícipes, prestando servicios complementarios para satisfacer sus necesidades; con infraestructura tecnológica – operativa de vanguardia y talento humano competitivo.</p> </div> </div> <div class="col-md-3 wow fadeInUp" data-wow-delay="0.2s"> <div class="about-col"> <div class="img"> <img src="view/img/about-vision.jpg" alt="" class="img-fluid"> <div class="icon"><i class="ion-ios-list-outline"></i></div> </div> <h2 class="title"><a href="#">Administración</a></h2> <p align="justify"> Se comunica a todos ustedes, que el 22 de septiembre de 2017 mediante oficio No. BIESS-OF-GGEN-1520-2017, el Banco del Instituto Ecuatoriano de Seguridad Social BIESS, designa a la Señora Ingeniera STEPHANY ALEJANDRA ZURITA CEDEÑO, como Representante Legal del Fondo Complementario Previsional Cerrado de Cesantía de Servidores y Trabajadores Públicos de Fuerzas Armadas.</p> </div> </div> <div class="col-md-3 wow fadeInUp" data-wow-delay="0.2s"> <div class="about-col"> <div class="img"> <img src="view/img/about15.jpg" alt="" class="img-fluid"> <div class="icon"><i class="ion-closed-captioning"></i></div> </div> <h2 class="title"><a href="#">Valores Corporativos</a></h2> <p align="justify"> Ofrecer planes de cesantía de largo plazo, a través del ahorro previsional con una transparente, eficiente y honesta política de inversión de los recursos, tendiente a la entrega ágil y oportuna de una Cesantía acorde a las expectativas del partícipe. El Fondo ofrece créditos quirografarios con tasas y plazos mejores que las del mercado.</p> </div> </div> </div> </div> </section><!-- #about --> <!--========================== Call To Action Section ============================--> <section id="call-to-action" class="wow fadeIn"> <div class="container text-center"> <h3>Servicios en Linea</h3> <p> Contamos con la mayor tecnología para tu mayor comodidad.</p> <p> Nos encontramos en una transformación actualmente para acceder a los apoyos y beneficios en Capremci encontraras que los sistemas se encuentran en plataformas diferentes, solicitamos ubiques en trámite que deseas realizar y elijas la opción adecuada.</p> <a class="cta-btn" href="index.php?controller=Usuarios&action=Loguear" >Ingresar</a> </div> </section><!-- #call-to-action --> <?php if (!empty($resultSet)) { $int=0?> <br><br> <div class="panel panel-info" style="text-align: center;"> <h4><strong>GRÁFICA ENCUESTAS GENERADAS</strong></h4> <!-- <h4><strong>GRÁFICA DE LAS <?php if($total>0){echo $total;}?> ENCUESTAS GENERADAS</strong></h4> --> <div class="col-lg-12 col-md-12 col-xs-12" style="text-align: center;" data-wow-duration="1.4s"> Bueno <span style="margin-left:35px; background: #6b9dfa; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;">=</span> Intermedio <span style="margin-left:12px; background: #52BE80; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;">=</span> Malo <span style="margin-left:45px; background: #F7DC6F; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;">=</span> <!-- <section style="overflow-y:auto; text-align: center; margin-left: 100px;"> <table style='text-align: center; margin-top:10px; width: 90%;' class='tablesorter table table-striped table-bordered dt-responsive nowrap'> <tr> <th style='text-align: center; font-size: 11px;'>Respuestas Preg. 1</th> <th style='text-align: center; font-size: 11px;'>Respuestas Preg. 2</th> <th style='text-align: center; font-size: 11px;'>Respuestas Preg. 3</th> <th style='text-align: center; font-size: 11px;'>Respuestas Preg. 4</th> <th style='text-align: center; font-size: 11px;'>Respuestas Preg. 5</th> <th style='text-align: center; font-size: 11px;'>Respuestas Preg. 6</th> <th style='text-align: center; font-size: 11px;'>Respuestas Preg. 7</th> <th style='text-align: center; font-size: 11px;'>Respuestas Preg. 8</th> </tr> <tr style="text-align: justify; font-size: 11px;"> <?php foreach ($resultSet as $res){ $int++; if($int==1){ ?> <td> Bueno =<span style="margin-left:35px; background: #6b9dfa; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->bueno_pregunta_1;?></span><br> Intermedio =<span style="margin-left:12px; background: #52BE80; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->intermedio_1;?></span><br> Malo =<span style="margin-left:45px; background: #F7DC6F; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->malo_1;?></span> </td> <?php } elseif($int==2){ ?> <td> Si =<span style="margin-left:31px; background: #6b9dfa; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->si_2;?></span><br> Algo =<span style="margin-left:17px; background: #52BE80; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->algo_2;?></span><br> Nada =<span style="margin-left:12px; background: #F7DC6F; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->nada_2;?></span> </td> <?php } elseif($int==3){ ?> <td> Los Colores =<span style="margin-left:31px; background: #6b9dfa; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->los_colores_3;?></span><br> La Información =<span style="margin-left:15px; background: #52BE80; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->la_informacion_3;?></span><br> Nada =<span style="margin-left:70px; background: #F7DC6F; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->nada_3;?></span><br> Las Imágenes =<span style="margin-left:20px; background: #F1CBC3; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->las_imagenes_3;?></span> </td> <?php } elseif($int==4){ ?> <td> 10 =<span style="margin-left:3px; background: #6b9dfa; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->r10_4;?></span> 9 =<span style="margin-left:10px; background: #52BE80; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->r9_4;?></span> 8 =<span style="margin-left:10px; background: #F7DC6F; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->r8_4;?></span><br> 7 =<span style="margin-left:10px; background: #F1CBC3; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->r7_4;?></span> 6 =<span style="margin-left:10px; background: #F1CBC3; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->r6_4;?></span> 5 =<span style="margin-left:10px; background: #F1CBC3; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->r5_4;?></span><br> 4 =<span style="margin-left:10px; background: #F1CBC3; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->r4_4;?></span> 3 =<span style="margin-left:10px; background: #F1CBC3; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->r3_4;?></span> 2 =<span style="margin-left:10px; background: #F1CBC3; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->r2_4;?></span><br> 1 =<span style="margin-left:10px; background: #F1CBC3; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->r1_4;?></span> </td> <?php } elseif($int==5){ ?> <td> Si =<span style="margin-left:60px; background: #6b9dfa; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->si_5;?></span><br> Intermedio =<span style="margin-left:10px; background: #52BE80; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->intermedio_5;?></span><br> No =<span style="margin-left:55px; background: #F7DC6F; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->no_5;?></span> </td> <?php } elseif($int==6){ ?> <td> Si =<span style="margin-left:16px; background: #6b9dfa; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->si_6;?></span><br> No =<span style="margin-left:12px; background: #52BE80; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->no_6;?></span><br> </td> <?php } elseif($int==7){ ?> <td> Si =<span style="margin-left:16px; background: #6b9dfa; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->si_7;?></span><br> No =<span style="margin-left:12px; background: #52BE80; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->no_7;?></span><br> </td> <?php } elseif($int==8){ ?> <td> Si =<span style="margin-left:60px; background: #6b9dfa; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->si_8;?></span><br> Intermedio =<span style="margin-left:10px; background: #52BE80; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->intermedio_8;?></span><br> No =<span style="margin-left:55px; background: #F7DC6F; border-radius: 0.8em; -moz-border-radius: 0.8em; -webkit-border-radius: 0.8em; color: #ffffff; display: inline-block; font-weight: bold; line-height: 1.6em; text-align: center; width: 1.6em;"><?php echo $res->no_8;?></span> </td> <?php } }?> </tr> </table> </section> --> </div> <section style="height:130px; overflow-y:scroll;"> <div id="canvas-holder"> <canvas id="chart-area" width="250" height="92"></canvas> </div> </section> </div> <?php }?> <!--========================== Services Section ============================--> <section id="services"> <div class="container"> <header class="section-header wow fadeInUp"> <h3>Prestaciones</h3> </header> <div class="row"> <div class="col-lg-6 col-md-6 box wow bounceInUp" data-wow-duration="1.4s"> <div class="icon"><i class="ion-ios-analytics-outline"></i></div> <h4 class="title"><a href="view/CesantiaView.php">Cesantía</a></h4> <p class="description" align="justify">Es el valor que se paga al afiliado que queda cesante y que está conformado por su cuenta individual. La cuenta Individual está integrado por: aporte y rendimiento personal; aporte y rendimiento patronal en el caso que existieren. Pare efectos del presente reglamento la cesantía opera con las siguientes condiciones:</br></br> Haber cesado en sus funciones laborales, definitivamente, en Entidades de Fuerzas Armadas.</br></br> Fallecimiento.</br></br> En caso de fallecimiento del afiliado sin haber dejado testamento legalmente valido, la cesantía corresponderá a sus derechohabientes en el orden establecido en el Código Civil respecto de la sucesión intestada.</br> </br> <a href="view/CesantiaView.php">Leer Más</a> </p> </div> <div class="col-lg-6 col-md-6 box wow bounceInUp" data-wow-duration="1.4s"> <div class="icon"><i class="ion-ios-bookmarks-outline"></i></div> <h4 class="title"><a href="view/DesafiliacionesView.php">Desafiliaciones</a></h4> <p class="description" align="justify">A partir de Agosto del 2013 de acuerdo al Art. 18 de la Norma 504, emitida por la Superintendencia de Bancos y Seguros los partícipes que opten por la desafiliación voluntaria podrán únicamente retirar el 50% de los aportes personales más sus rendimientos siempre y cuando este valor cubra la totalidad de los créditos que mantenga en el Fondo, caso contrario deberá realizar el deposito correspondiente para cubrir el saldo a favor del Fondo.</br></br> El 50% restante de los aportes personales y aportes patronales más rendimientos quedará registrada en una cuenta por pagar generando rendimientos hasta que el ex – partícipe quede efectivamente cesante la entidad patronal para la cual labora.</br></br> </br> <a href="view/DesafiliacionesView.php">Leer Más</a> </p> </div> </div> </div> </section><!-- #services --> <!--========================== Clients Section ============================--> <section id="testimonials" class="section-bg wow fadeInUp"> <div class="container"> <header class="section-header"> <h3>Servicios Financieros</h3> </header> <div class="owl-carousel testimonials-carousel"> <div class="testimonial-item"> <img src="img/blog1.jpg" class="testimonial-img" alt=""> <h3>CRÉDITO ORDINARIO</h3> <h4>Información</h4> <p> <img alt=""> <p align="center"> Se concede el crédito hasta el 100% de la Cuenta Individual.</br> • La cuota mensual no podrá exceder del 50% del sueldo líquido del solicitante.</br> • Tasa de interés: 9% anual fija sobre saldos.</br> • Plazo: 7 años.</br> • El afiliado debe tener un mínimo 3 aportaciones seguidas.</br> • El Crédito cuenta con Seguro de Desgravamen para el deudor.</br></br> <a href="view/CreditoOrdinarioView.php">Leer Más</a> </p> <img class="quote-sign-right" alt=""> </p> </div> <div class="testimonial-item"> <img src="view/img/blog2.jpg" class="testimonial-img" alt=""> <h3>CRÉDITO HIPOTECARIO</h3> <h4>Información</h4> <p> <img alt=""> <p align="center"> Se concede el crédito hasta el 80% del Avalúo (valor de realización) y hasta por un monto máximo de US$ 80,000.00.</br> • La cuota mensual no podrá exceder del 40% del sueldo líquido de la sociedad conyugal.</br> • Tasa de interés: 8.8% anual fija sobre saldos.</br> • Plazo hasta 25 años, siempre que la edad más plazo no supere los 75 años.</br> • El bien no podrá tener más de 15 años de antigüedad.</br></br> <a href="view/CreditoHipotecarioView.php">Leer Más</a> </p> <img alt=""> </p> </div> <div class="testimonial-item"> <img src="view/img/blog3.jpg" class="testimonial-img" alt=""> <h3>CRÉDITO EMERGENTE</h3> <h4>Información</h4> <p> <img alt=""> <p align="center"> Montos desde $100.00 hasta $5,000.00.</br> • Plazo desde 3 meses hasta 48 meses.</br> • Plazos convenientes: desde 3 hasta 48 meses para cancelar tu crédito.</br> • El desembolso esta efectivizado hasta en 48 horas desde la firma del pagaré.</br> • Realiza con total libertad pre-pagos totales o parciales, sin ninguna penalidad o costo.</br></br> <a href="view/CreditoEmergenteView.php">Leer Más</a> </p> <img alt=""> </p> </div> </div> </div> </section><!-- #testimonials --> <!--========================== Services Section ============================--> <section id="service"> <div class="container"> <header class="section-header wow fadeInUp"> <br><br> <h3>Educación Financiera</h3> <p>Saber mas sobre nuestras finanzas nos permite alcanzar más fácilmente nuestras metas.</p> </header> <div class="row"> <div class="col-lg-4 col-md-6 box wow bounceInUp" data-wow-duration="1.4s"> <h4 class="title"><a href="javascript:void(0);">• Establece Metas Claras.</a></h4> <p class="description" align="justify">Toma en cuenta el estado real de tus ingresos para que sepas lo que se encuentra al alcance de tus posibilidades.</p> </div> <div class="col-lg-4 col-md-6 box wow bounceInUp" data-wow-duration="1.4s"> <h4 class="title"><a href="javascript:void(0);">• Construye un Fondo para Emergencias.</a></h4> <p class="description" align="justify">Con tus ahorros podras cubrir situaciones imprevistas que no esten dentro de tu presupuesto mensual o diario.</p> </div> <div class="col-lg-4 col-md-6 box wow bounceInUp" data-wow-duration="1.4s"> <h4 class="title"><a href="javascript:void(0);">• Planifica tus Gastos.</a></h4> <p class="description" align="justify">Aprende a identificar lo que es realmente importante, de esta manera gastarás lo estrictamente necesario.</p> </div> <div class="col-lg-4 col-md-6 box wow bounceInUp" data-wow-delay="0.1s" data-wow-duration="1.4s"> <h4 class="title"><a href="javascript:void(0);">• Invierte mejor tu Dinero.</a></h4> <p class="description" align="justify">Establece inversiones que generen ganancias en un futuro cercano qeu sean de provecho para ti y tú familia.</p> </div> <div class="col-lg-4 col-md-6 box wow bounceInUp" data-wow-delay="0.1s" data-wow-duration="1.4s"> <h4 class="title"><a href="javascript:void(0);">• Ahorra para una Cesantía Cómoda.</a></h4> <p class="description" align="justify">Piensa en tu futuro, ahorra para que puedas disfrutar con tu familia el fruto de tu trabajo.</p> </div> <div class="col-lg-4 col-md-6 box wow bounceInUp" data-wow-delay="0.1s" data-wow-duration="1.4s"> <img src="view/img/Educación-financiera.jpg" alt=""> </div> </div> </div> </section><!-- #services --> <!--========================== Clients Section ============================--> <section id="clients" class="wow fadeInUp"> <div class="container"> <header class="section-header"> <h3><NAME></h3> </header> <div class="owl-carousel clients-carousel"> <img src="view/img/clients/client-10.png" alt=""> <img src="view/img/clients/client-11.png" alt=""> <img src="view/img/clients/client-13.png" alt=""> <img src="view/img/clients/client-14.png" alt=""> <img src="view/img/clients/client-16.png" alt=""> <img src="view/img/clients/client-17.png" alt=""> </div> </div> </section><!-- #clients --> <!--========================== Contact Section ============================--> <section id="contact" class="section-bg wow fadeInUp"> <div class="container"> <div class="section-header"> <h3>Contáctanos</h3> <p>Cada vez mas cerca de ti.</p> </div> <div class="row contact-info"> <div class="col-md-4"> <div class="contact-address"> <i class="ion-ios-location-outline"></i> <h3>Dirección</h3> <address>Quito: Baquerizo Moreno E-978 y Leonidas Plaza <br>Guayaquil: Edificio Torres de la Merced, calle Córdova 810 y V. <NAME>, piso 4 oficina 12</address> </div> </div> <div class="col-md-4"> <div class="contact-phone"> <i class="ion-ios-telephone-outline"></i> <h3>Teléfono</h3> <p><a href="tel:+155895548855">Quito: 02-2236931 <br>Guayaquil: 04-2564900</a></p> </div> </div> <div class="col-md-4"> <div class="contact-email"> <i class="ion-ios-email-outline"></i> <h3>Email</h3> <p><a href="<EMAIL>"><EMAIL></a></p> </div> </div> <div class="row"> <div class="col-lg-12"> <form id="contactForm" name="sentMessage" novalidate> </br> </br> </form> </div> </div> </div> <div class="row"> <div class="col-md-6"> <div class="form-group"> <input class="form-control" id="name" type="text" placeholder="Tu Nombre *" required data-validation-required-message="Por favor ingrese su nombre."> <p class="help-block text-danger"></p> </div> <div class="form-group"> <input class="form-control" id="email" type="email" placeholder="Tu Correo *" required data-validation-required-message="Por favor ingrese su correo."> <p class="help-block text-danger"></p> </div> <div class="form-group"> <input class="form-control" id="phone" type="tel" placeholder="Tu Telefono *" required data-validation-required-message="Por favor ingrese su telefono."> <p class="help-block text-danger"></p> </div> </div> <div class="col-md-6"> <div class="form-group"> <textarea class="form-control" id="message" placeholder="Tu mensaje *" required data-validation-required-message="Por favor ingrese su mensaje."></textarea> <p class="help-block text-danger"></p> </div> </div> <div class="clearfix"></div> <div class="col-lg-12 text-center"> <div id="success"></div> <button id="sendMessageButton" class="btn btn-primary btn-xl text-uppercase" type="submit">Enviar Mensaje</button> </div> </div> </div> </section><!-- #contact --> </main> <!--========================== Footer ============================--> <footer id="footer"> <div class="footer-top"> <div class="container"> <div class="row"> <div class="col-lg-4 col-md-6 footer-info"> <h3>Capremci</h3> <p align="justify">El objetivo social es establecer y conceder a sus afiliados, los beneficios de Cesantía y Crédito con los aportes recibidos de sus partícipes conjuntamente con los rendimientos generados en los términos que establece su Estatuto, los reglamentos, normas y políticas que se emitieren.</p> </div> <div class="col-lg-4 col-md-6 footer-links"> <h4>Formularios</h4> <ul> <li><i class="ion-ios-arrow-right"></i> <a href="documentos/ordinario papeles.pdf">Solicitud de Crédito Ordinario</a></li> <li><i class="ion-ios-arrow-right"></i> <a href="documentos/PAPELES EMERGENTE.pdf">Solicitud de Crédito Emergente</a></li> <li><i class="ion-ios-arrow-right"></i> <a href="documentos/SOLICITUD DE CRÉDITO HIPOTECARIO.pdf">Solicitud de Crédito Hipotecario</a></li> <li><i class="ion-ios-arrow-right"></i> <a href="documentos/SOLICITUD DE PRESTACIONES.pdf">Solicitud de Prestaciones</a></li> </ul> </div> <div class="col-lg-4 col-md-6 footer-contact"> <h4>Contáctanos</h4> <p> <NAME> <br> E-978 y Leonidas Plaza <br> Quito <br> <strong>Teléfono:</strong> Quito: 02-2236931<BR>Guayaquil: 04-2564900<br> <strong>Correo:</strong> <EMAIL><br> </p> <div class="social-links"> <a href="#" class="twitter"><i class="fa fa-twitter"></i></a> <a href="#" class="facebook"><i class="fa fa-facebook"></i></a> <a href="#" class="instagram"><i class="fa fa-instagram"></i></a> <a href="#" class="google-plus"><i class="fa fa-google-plus"></i></a> <a href="#" class="linkedin"><i class="fa fa-linkedin"></i></a> </div> </div> </div> </div> </div> <div class="container"> <div class="copyright"> &copy; <strong>Capremci</strong>. Todos los derechos reservados </div> <div class="credits"> <!-- All the links in the footer should remain intact. You can delete the links only if you purchased the pro version. Licensing information: https://bootstrapmade.com/license/ Purchase the pro version with working PHP/AJAX contact form: https://bootstrapmade.com/buy/?theme=BizPage --> Diseñado por<a href="www.capremci.com.ec"> Capremci</a> </div> </div> </footer><!-- #footer --> <a href="#" class="back-to-top"><i class="fa fa-chevron-up"></i></a> <!-- Contact form JavaScript --> <script src="view/js/jqBootstrapValidation.js"></script> <script src="view/js/contact_me.js"></script> <!-- Custom scripts for this template --> <script src="view/js/agency.min.js"></script> <!-- JavaScript Libraries --> <script src="view/lib/jquery/jquery.min.js"></script> <script src="view/lib/jquery/jquery-migrate.min.js"></script> <script src="view/lib/bootstrap/js/bootstrap.bundle.min.js"></script> <script src="view/lib/easing/easing.min.js"></script> <script src="view/lib/superfish/hoverIntent.js"></script> <script src="view/lib/superfish/superfish.min.js"></script> <script src="view/lib/wow/wow.min.js"></script> <script src="view/lib/waypoints/waypoints.min.js"></script> <script src="view/lib/counterup/counterup.min.js"></script> <script src="view/lib/owlcarousel/owl.carousel.min.js"></script> <script src="view/lib/isotope/isotope.pkgd.min.js"></script> <script src="view/lib/lightbox/js/lightbox.min.js"></script> <script src="view/lib/touchSwipe/jquery.touchSwipe.min.js"></script> <!-- Contact Form JavaScript File --> <script src="view/contactform/contactform.js"></script> <!-- Template Main Javascript File --> <script src="view/js/main.js"></script> <!-- codigo de las funciones --> <script src="view/js/Chart.js"></script> <script> var barChartData = { labels : <?php echo $data;?>, datasets : [ { fillColor : "#6b9dfa", strokeColor : "#ffffff", highlightFill: "#1864f2", highlightStroke: "#ffffff", data : <?php echo $pre_1_r1;?> }, { fillColor : "#52BE80", strokeColor : "#ffffff", highlightFill: "#27AE60", highlightStroke: "#ffffff", data : <?php echo $pre_1_r2;?> }, { fillColor : "#F7DC6F", strokeColor : "#ffffff", highlightFill: "#F4D03F", highlightStroke: "#ffffff", data : <?php echo $pre_1_r3;?> } ] } var ctx3 = document.getElementById("chart-area").getContext("2d"); window.myPie = new Chart(ctx3).Bar(barChartData, {responsive:true}); </script> </body> </html>
e55f03ce043abf834e9539eb68297b8dab8a05e0
[ "PHP" ]
1
PHP
sandy-1998/aguafacturacion
086817b7c1d2f07177c80ddd3db16059096aad14
e2b94238f7196f06963be384eb4e4810745c6b8f
refs/heads/master
<repo_name>bdnorris/MixTapes<file_sep>/js/app.js // http://codesamplez.com/programming/control-html5-audio-with-jquery var numberOfTracks = ($('.player').length); console.log(numberOfTracks); // Adds first and last classes automatically $('.player').first().addClass('first'); $('.player').last().addClass('last'); // Makes the next track play after end, or start over on the first track if it's the last track. $('.player').on('ended', function() { if ($(this).hasClass('last')) { $('.first').trigger('play'); } else { $('.player').next().trigger('play'); } }); /* $('.play').toggle(function() { $(".player").trigger('play'); }); $('.pause').click(function() { $(".player").trigger('pause'); }); */ function stopAudio(){ //pause playing $(".player").trigger('pause'); //set play time to 0 $(".player").prop("currentTime",0); } function volumeUp(){ var volume = $(".player").prop("volume")+0.2; if(volume >1){ volume = 1; } $(".player").prop("volume",volume); } function volumeDown(){ var volume = $(".audioDemo").prop("volume")-0.2; if(volume <0){ volume = 0; } $(".player").prop("volume",volume); } function toggleMuteAudio(){ $(".player").prop("muted",!$(".player").prop("muted")); }
312321ebb6bc8c44a9514c8417475a45657f5877
[ "JavaScript" ]
1
JavaScript
bdnorris/MixTapes
794df26ce8a337373c47966647ae0c9914c10a25
c48519702a6792e962ec47b1339f921b1732b3ed
refs/heads/master
<file_sep>// // main.c // Turkey // // Created by <NAME> on 2014-08-12. // Copyright (c) 2014 blakestiller. All rights reserved. // #include <stdio.h> int main(int argc, const char * argv[]) { float weight = 14.2; printf("The turkey weighs %f. \n", weight); float cookingTime; cookingTime = 15.0 + 15.0 * weight; // insert code here... printf("Cook it for %f hours. \n", cookingTime / 60); return 0; } <file_sep>// // main.c // Numbers // // Created by <NAME> on 2014-08-13. // Copyright (c) 2014 blakestiller. All rights reserved. // #include <stdio.h> int main(int argc, const char * argv[]) { // insert code here... double y = 12345.6789; printf("y is %.2f\n", y); printf("Y iS %.2e\n", y); return 0; } <file_sep>// // main.c // Coolness // // Created by <NAME> on 2014-08-13. // Copyright (c) 2014 blakestiller. All rights reserved. // #include <stdio.h> int main(int argc, const char * argv[]) { int i = 0; while (i < 12 ){ printf("%d. Aaron is Cool!\n", i ); i++; } return 0; }
ecb481f30fb0d1c059e8137d5bc66d39d8ef1090
[ "C" ]
3
C
bstiller1/iOS
94d488c37f38488b4b3102dd4d2d1902cc7f5413
49da1de3a6b857431d7f3f3371f5f64021540488
refs/heads/master
<repo_name>sagarpednekar/alpha_blog<file_sep>/README.md # News Map Blog Portal #### News Map is a open source blog portal with Tranding Blogs in many categories such as technology,food , books etc ### Functionality: ##### User can Sign in and Add there own blog in many categories ##### User can able to read any blog news without sign in ##### User can modify their own Articles ##### Effective Sign in & sign out Functionality<file_sep>/app/controllers/welcome_controller.rb class WelcomeController < ApplicationController def home redirect_to articles_path if loged_in? @disable_nav = true end def landing_page end end
cc36adff93df965072c81de63b7e84254cbf1865
[ "Markdown", "Ruby" ]
2
Markdown
sagarpednekar/alpha_blog
ca1456f558998be64dc78227b0b2b695f2d68943
5d3a7166254207344fba49e12cdf78755dcf900b
refs/heads/master
<file_sep>import { default as curry } from 'ramda/src/curry' import deepEqual from 'fast-deep-equal' import { Just, Nothing, Left, Right } from './constants' import { pipe } from './pipe' export const pure = x => ({ value: x, tag: Just, }) export const just = pure export const of = pure export const nothing = () => ({ tag: Nothing }) export const fromNullable = x => x == null ? nothing() : just(x) export const chain = curry((f, x) => { switch (x.tag) { case Just: return f(x.value) case Nothing: return x } }) export const flatMap = chain export const bind = chain export const map = curry((f, x) => { switch (x.tag) { case Just: return just(f(x.value)) case Nothing: return x } }) export const lift2 = curry((f, a, b) => { switch (f.tag) { case Just: return pipe(curry, pure, ap(a), ap(b))(f.value) case Nothing: return f } }) export const lift3 = curry((f, a, b, c) => { switch (f.tag) { case Just: return pipe(curry, pure, ap(a), ap(b), ap(c))(f.value) case Nothing: return f } }) export const map2 = curry((f, a, b) => lift2(pure(f), a, b)) export const map3 = curry((f, a, b, c) => lift3(pure(f), a, b, c)) export const map4 = (f, a, b, c, d) => pipe( curry, pure, ap(a), ap(b), ap(c), ap(d) )(f) export const map5 = (f, a, b, c, d, e) => pipe( curry, pure, ap(a), ap(b), ap(c), ap(d), ap(e) )(f) export const fold = curry((n, j, x) => { switch (x.tag) { case Just: return j(x.value) case Nothing: return n() } }) export const ap = curry((x, f) => isJust(f) ? map(f.value, x) : nothing()) export const get = x => { switch (x.tag) { case Just: return x.value case Nothing: throw new TypeError(`Cannot extract the value of a ${x.tag}`) } } export const getOrElse = curry((f, x) => { switch (x.tag) { case Just: return x.value case Nothing: return f() } }) export const isJust = x => x.tag === Just export const isNothing = x => x.tag === Nothing export const equals = (x, y) => { if (isNothing(x) && isNothing(y)) { return true } else if (isJust(x) && isJust(y)) { return x === y || deepEqual(x, y) } else { return false } } export const fromEither = either => { switch (either.tag) { case Left: return nothing() case Right: return just(either.value) } } export const toEither = curry((err, x) => { switch (x.tag) { case Just: return right(either.value) case Nothing: return typeof err === 'function' ? left(err()) : left(err) } }) <file_sep>// @flow import test from 'tape' import { flip } from '../src' const x = 'x' const y = 'y' const z = 'z' test('flip reverse first and second arguments', t => { const concatString = (x, y) => x.concat(y) const flipped = flip(concatString) t.deepEqual(flipped(x, y), 'yx') t.end() }) test('flip passes other arguments', t => { const concatThreeStrings = (x, y, z) => x + y + z const flipped = flip(concatThreeStrings) t.deepEqual(flipped(x, y, z), 'yxz') t.end() }) <file_sep>// @flow import test from 'tape' import { io, pipe } from '../src' const queryDatabase = x => 0 // eslint-disable-line no-unused-vars const effect = () => queryDatabase('id') const tostr = x => x.toString() test('io - from creates IO instance', t => { const output = io.from(effect) t.deepEqual(output, { tag: 'IO', effect }) t.end() }) test('io - of creates IO instance', t => { const value = 0 const output = pipe( io.of, io.run )(value) t.deepEqual(output, value) t.end() }) test('io - IO is a functor', t => { const output = pipe( io.from, io.map(tostr), io.run )(effect) t.deepEqual(output, '0') t.end() }) test('io - IO is applicative', t => { const output = pipe( io.from, io.ap(io.of(tostr)), io.run )(effect) t.deepEqual(output, '0') t.end() }) test('io - chain IO', t => { const output = pipe( io.from, io.chain(x => io.from(() => tostr(x))), io.run )(effect) t.deepEqual(output, '0') t.end() }) test('io - run IO', t => { const output = pipe( io.from, io.run )(effect) t.deepEqual(output, effect()) t.end() }) <file_sep>// @flow import test from 'tape' import { either, pipe } from '../src' const x = 5 const y = 10 const z = 100 const a = 1 const b = 3 const err = 'err' const double = x => x * 2 const triple = x => x * 3 const add = (a, b) => a + b const add3 = (a, b, c) => add(a, b) + c const add4 = (a, b, c, d) => add3(a, b, c) + d const add5 = (a, b, c, d, e) => add4(a, b, c, d) + e test('pure', t => { const output = either.pure(x) const expected = { tag: 'Right', value: x } t.deepEqual(output, expected) t.end() }) test('right constructor', t => { const output = either.right(x) const expected = { tag: 'Right', value: x } t.deepEqual(output, expected) t.end() }) test('either of', t => { const output = either.of(x) t.deepEqual(output, either.right(x)) t.end() }) test('left constructor', t => { const output = either.left(x) const expected = { tag: 'Left', value: x } t.deepEqual(output, expected) t.end() }) test('map right value', t => { const output = pipe( either.of, either.map(double) )(x) const expected = pipe( double, either.right )(x) t.deepEqual(output, expected) t.end() }) test('map left value', t => { const output = pipe( either.left, either.mapLeft(double) )(x) const expected = pipe( double, either.left )(x) t.deepEqual(output, expected) t.end() }) test('bimap left value', t => { const output = pipe( either.left, either.bimap(double, () => null) )(x) const expected = pipe( double, either.left )(x) t.deepEqual(output, expected) t.end() }) test('bimap right value', t => { const output = pipe( either.of, either.bimap(() => null, double) )(x) const expected = pipe( double, either.right )(x) t.deepEqual(output, expected) t.end() }) test('either - lift2 right', t => { const output = either.lift2(either.of(add), either.of(x), either.of(y)) const expected = either.of(add(x, y)) t.deepEqual(output, expected) t.end() }) test('either - lift2 left', t => { const output = either.lift2(either.left(err), either.of(x), either.left(y)) t.deepEqual(output, either.left(err)) t.end() }) test('either - lift2 left first arg', t => { const output = either.lift2(either.of(add), either.left(err), either.of(y)) t.deepEqual(output, either.left(err)) t.end() }) test('either - lift2 nothing second arg', t => { const output = either.lift2(either.of(add), either.of(x), either.left(err)) t.deepEqual(output, either.left(err)) t.end() }) test('either - lift3 right', t => { const output = either.lift3(either.of(add3), either.of(x), either.of(y), either.of(z)) const expected = either.right(add3(x, y, z)) t.deepEqual(output, expected) t.end() }) test('either - lift3 left', t => { const output = either.lift3(either.left(err), either.of(x), either.of(y), either.of(z)) t.deepEqual(output, either.left(err)) t.end() }) test('either - lift3 left first arg', t => { const output = either.lift3(either.of(add3), either.left(err), either.of(x), either.of(y)) t.deepEqual(output, either.left(err)) t.end() }) test('either - lift3 left second arg', t => { const output = either.lift3(either.of(add3), either.of(x), either.left(err), either.of(y)) t.deepEqual(output, either.left(err)) t.end() }) test('either - lift3 left third arg', t => { const output = either.lift3(either.of(add3), either.of(x), either.of(y), either.left(err)) t.deepEqual(output, either.left(err)) t.end() }) test('either - map2 right', t => { const output = either.map2(add, either.of(x), either.of(y)) t.deepEqual(output, either.of(add(x, y))) t.end() }) test('either - map2 left', t => { const output = either.map2(add, either.of(x), either.left(err)) t.deepEqual(output, either.left(err)) t.end() }) test('either - map3 right', t => { const output = either.map3(add3, either.of(x), either.of(y), either.of(z)) t.deepEqual(output, either.of(add3(x, y, z))) t.end() }) test('either - map3 left', t => { const output = either.map3(add3, either.of(x), either.left(err), either.of(y)) t.deepEqual(output, either.left(err)) t.end() }) test('either - map4 just', t => { const output = either.map4(add4, either.of(x), either.of(y), either.of(z), either.of(a)) t.deepEqual(output, either.of(add4(x, y, z, a))) t.end() }) test('either - map4 left', t => { const output = either.map4(double, either.of(x), either.left(err), either.of(y), either.of(z)) t.deepEqual(output, either.left(err)) t.end() }) test('either - map5 right', t => { const output = either.map5(add5, either.of(x), either.of(y), either.of(z), either.of(a), either.of(b)) const expected = either.of(add5(x, y, z, a, b)) t.deepEqual(output, expected) t.end() }) test('either - map5 left first arg', t => { const output = either.map5(add5, either.left(err), either.of(x), either.of(y), either.of(z), either.of(a)) t.deepEqual(output, either.left(err)) t.end() }) test('either - map5 left second arg', t => { const output = either.map5(add5, either.of(x), either.left(err), either.of(y), either.of(z), either.of(a)) t.deepEqual(output, either.left(err)) t.end() }) test('either - map5 left third arg', t => { const output = either.map5(add5, either.of(x), either.of(y), either.left(err), either.of(z), either.of(a)) t.deepEqual(output, either.left(err)) t.end() }) test('either - map5 left fourth arg', t => { const output = either.map5(add5, either.of(x), either.of(y), either.of(z), either.left(err), either.of(a)) t.deepEqual(output, either.left(err)) t.end() }) test('either - map5 left fifth arg', t => { const output = either.map5(add5, either.of(x), either.of(y), either.of(z), either.of(a), either.left(err)) t.deepEqual(output, either.left(err)) t.end() }) test('either chain', t => { const output = pipe( either.of, either.chain(x => either.of(double(x))) )(x) const expected = pipe( double, either.right )(x) t.deepEqual(output, expected) t.end() }) test('either flatMap', t => { const output = pipe( either.of, either.flatMap(x => either.of(double(x))) )(x) const expected = pipe( double, either.right )(x) t.deepEqual(output, expected) t.end() }) test('either bind', t => { const output = pipe( either.of, either.bind(x => either.of(double(x))) )(x) const expected = pipe( double, either.right )(x) t.deepEqual(output, expected) t.end() }) test('either ap', t => { const wrappedDouble = either.of(double) const output = either.ap(either.of(x), wrappedDouble) const expected = pipe( double, either.right )(x) t.deepEqual(output, expected) t.end() }) test('fold left value', t => { const output = pipe( either.left, either.fold(double, triple) )(x) t.deepEqual(output, double(x)) t.end() }) test('fold right value', t => { const output = pipe( either.of, either.fold(double, triple) )(x) t.deepEqual(output, triple(x)) t.end() }) test('either is left ?', t => { const output = pipe( either.left, either.isLeft )(x) t.deepEqual(output, true) t.end() }) test('either is right ?', t => { const output = pipe( either.of, either.isRight )(x) t.deepEqual(output, true) t.end() }) test('left are not equals when they does not hold the same values', t => { t.deepEqual( either.equals(either.left(5), either.left(6)), false ) t.end() }) test('right are not equals when they does not hold the same values', t => { t.deepEqual( either.equals(either.right(5), either.right(6)), false ) t.end() }) test('left are equals by reference', t => { const x = either.left(5) t.deepEqual(either.equals(x, x), true) t.end() }) test('right are equals by reference', t => { const x = either.right(5) t.deepEqual(either.equals(x, x), true) t.end() }) test('left are equals by deep equality', t => { const x = either.left(5) const y = either.left(5) t.deepEqual(either.equals(x, y), true) t.end() }) test('right are equals by deep equality', t => { const x = either.right(5) const y = either.right(5) t.deepEqual(either.equals(x, y), true) t.end() }) test('left and right are not equals', t => { const x = either.left(5) const y = either.right(5) t.deepEqual(either.equals(x, y), false) t.end() }) test('get right', t => { const output = pipe( either.of, either.get )(x) t.deepEqual(output, x) t.end() }) test('get left', t => { const fn = pipe( either.left, either.get ) t.throws(fn) t.end() }) test('getOrElse left', t => { const output = pipe( either.left, either.map(double), either.getOrElse(triple) )(x) t.deepEqual(output, triple(x)) t.end() }) test('getOrElse right', t => { const output = pipe( either.right, either.map(double), either.getOrElse(triple) )(x) t.deepEqual(output, double(x)) t.end() }) <file_sep>import { default as curry } from 'ramda/src/curry' import deepEqual from 'fast-deep-equal' import { just, nothing } from './maybe' import { Just, Nothing, Left, Right, Success, Failure, NotAsked, Loading } from './constants' import { pipe } from './pipe' export const pure = x => ({ value: x, tag: Success }) export const success = pure export const of = success export const failure = err => ({ value: err, tag: Failure }) export const notAsked = () => ({ tag: NotAsked }) export const loading = () => ({ tag: Loading }) export const fromNullable = x => x == null ? notAsked() : success(x) export const fold = curry((cases, rd) => { switch (rd.tag) { case Success: return cases.Success(rd.value) case Failure: return cases.Failure(rd.value) case NotAsked: return cases.NotAsked() case Loading: return cases.Loading() } }) export const map = curry((f, x) => { switch (x.tag) { case Success: return success(f(x.value)) case Failure: return x case NotAsked: return x case Loading: return x } }) export const mapLeft = curry((f, rd) => { switch (rd.tag) { case Success: return rd case Failure: return failure(f(rd.value)) case NotAsked: return rd case Loading: return rd } }) export const chain = curry((f, rd) => { switch (rd.tag) { case Success: return f(rd.value) case Failure: return rd case NotAsked: return rd case Loading: return rd } }) export const ap = curry((rd, rdf) => { switch (rdf.tag) { case Success: return map(rdf.value, rd) case Failure: return rdf case NotAsked: return rdf case Loading: return rdf } }) export const lift2 = curry((f, rd1, rd2) => { switch (f.tag) { case Success: return pipe(curry, pure, ap(rd1), ap(rd2))(f.value) default: return f } }) export const lift3 = curry((f, rd1, rd2, rd3) => { switch (f.tag) { case Success: return pipe(curry, pure, ap(rd1), ap(rd2), ap(rd3))(f.value) default: return f } }) export const map2 = curry((f, a, b) => lift2(pure(f), a, b)) export const map3 = curry((f, a, b, c) => lift3(pure(f), a, b, c)) export const map4 = (f, rd1, rd2, rd3, rd4) => pipe( curry, pure, ap(rd1), ap(rd2), ap(rd3), ap(rd4) )(f) export const map5 = (f, rd1, rd2, rd3, rd4, rd5) => pipe( curry, pure, ap(rd1), ap(rd2), ap(rd3), ap(rd4), ap(rd5) )(f) export const flatMap = chain export const bind = chain export const get = rd => { switch (rd.tag) { case Success: return rd.value default: throw new Error(`Cannot extract the value of a ${rd.tag}`) } } export const getOrElse = curry((x, rd) => { switch (rd.tag) { case Success: return rd.value default: return x() } }) export const isSuccess = ({ tag }) => tag === Success export const isFailure = ({ tag }) => tag === Failure export const isLoading = ({ tag }) => tag === Loading export const isNotAsked = ({ tag }) => tag === NotAsked export const equals = (x, y) => x === y || deepEqual(x, y) export const toMaybe = rd => { switch (rd.tag) { case Success: return just(rd.value) case Failure: return nothing() case NotAsked: return nothing() case Loading: return nothing() } } export const fromMaybe = maybe => { switch (maybe.tag) { case Just: return success(maybe.value) case Nothing: return notAsked() } } export const toEither = (rd, fallback) => { switch (rd.tag) { case Success: return right(rd.value) case Failure: return left(rd.value) case NotAsked: return left(fallback()) case Loading: return left(fallback()) } } export const fromEither = (either) => { switch (either.tag) { case Left: return failure(either.value) case Right: return success(either.value) } } <file_sep>// @flow import test from 'tape' import { maybe, pipe } from '../src' const a = 1 const b = 3 const x = 5 const y = 10 const z = 100 const zero = () => 0 const double = x => x * 2 const triple = x => x * 3 const add = (a, b) => a + b const add3 = (a, b, c) => add(a, b) + c const add4 = (a, b, c, d) => add3(a, b, c) + d const add5 = (a, b, c, d, e) => add4(a, b, c, d) + e test('pure', t => { const output = maybe.pure(x) const expected = { tag: 'Just', value: x } t.deepEqual(output, expected) t.end() }) test('just constructor', t => { const output = maybe.just(x) const expected = { tag: 'Just', value: x } t.deepEqual(output, expected) t.end() }) test('nothing constructor', t => { const output = maybe.nothing() const expected = { tag: 'Nothing' } t.deepEqual(output, expected) t.end() }) test('maybe of', t => { const output = maybe.of(x) t.deepEqual(output, maybe.just(x)) t.end() }) test('maybe from nullable', t => { const just = maybe.fromNullable(x) t.deepEqual(just, maybe.just(x)) const nothing = maybe.fromNullable(null) t.deepEqual(nothing, maybe.nothing()) t.end() }) test('maybe map', t => { const output = pipe( maybe.of, maybe.map(double) )(x) const expected = pipe( double, maybe.just )(x) t.deepEqual(output, expected) t.end() }) test('maybe - lift2 just', t => { const output = maybe.lift2(maybe.of(add), maybe.of(x), maybe.of(y)) const expected = maybe.just(add(x, y)) t.deepEqual(output, expected) t.end() }) test('maybe - lift2 nothing', t => { const output = maybe.lift2(maybe.nothing(), maybe.of(x), maybe.of(y)) t.deepEqual(output, maybe.nothing()) t.end() }) test('maybe - lift2 nothing first arg', t => { const output = maybe.lift2(maybe.of(add), maybe.nothing(), maybe.of(y)) t.deepEqual(output, maybe.nothing()) t.end() }) test('maybe - lift2 nothing second arg', t => { const output = maybe.lift2(maybe.of(add), maybe.of(x), maybe.nothing()) t.deepEqual(output, maybe.nothing()) t.end() }) test('maybe - lift3 just', t => { const output = maybe.lift3(maybe.of(add3), maybe.of(x), maybe.of(y), maybe.of(z)) const expected = maybe.just(add3(x, y, z)) t.deepEqual(output, expected) t.end() }) test('maybe - lift3 nothing', t => { const output = maybe.lift3(maybe.nothing(), maybe.of(x), maybe.of(y), maybe.of(z)) t.deepEqual(output, maybe.nothing()) t.end() }) test('maybe - lift3 nothing first arg', t => { const output = maybe.lift3(maybe.of(add3), maybe.nothing(), maybe.of(x), maybe.of(y)) t.deepEqual(output, maybe.nothing()) t.end() }) test('maybe - lift3 nothing second arg', t => { const output = maybe.lift3(maybe.of(add3), maybe.of(x), maybe.nothing(), maybe.of(y)) t.deepEqual(output, maybe.nothing()) t.end() }) test('maybe - lift3 nothing third arg', t => { const output = maybe.lift3(maybe.of(add3), maybe.of(x), maybe.of(y), maybe.nothing()) t.deepEqual(output, maybe.nothing()) t.end() }) test('maybe - map2 with just', t => { const output = maybe.map2(add, maybe.of(x), maybe.of(y)) t.deepEqual(output, maybe.just(add(x, y))) t.end() }) test('maybe - map2 with nothing', t => { const output = maybe.map2(add, maybe.of(x), maybe.nothing()) t.deepEqual(output, maybe.nothing()) t.end() }) test('maybe - map3 with just', t => { const z = 100 const output = maybe.map3(add3, maybe.of(x), maybe.of(y), maybe.of(z)) t.deepEqual(output, maybe.just(add3(x, y, z))) t.end() }) test('maybe - map3 with nothing', t => { const output = maybe.map3(add3, maybe.of(x), maybe.nothing(), maybe.of(y)) t.deepEqual(output, maybe.nothing()) t.end() }) test('maybe - map4 with just', t => { const output = maybe.map4(add4, maybe.of(x), maybe.of(y), maybe.of(z), maybe.of(a)) t.deepEqual(output, maybe.just(add4(x, y, z, a))) t.end() }) test('maybe - map4 with nothing', t => { const output = maybe.map4(double, maybe.of(x), maybe.nothing(), maybe.of(y), maybe.of(z)) t.deepEqual(output, maybe.nothing()) t.end() }) test('maybe - map5 just', t => { const output = maybe.map5(add5, maybe.of(x), maybe.of(y), maybe.of(z), maybe.of(a), maybe.of(b)) const expected = maybe.just(add5(x, y, z, a, b)) t.deepEqual(output, expected) t.end() }) test('maybe - map5 nothing first arg', t => { const output = maybe.map5(add5, maybe.nothing(), maybe.of(x), maybe.of(y), maybe.of(z), maybe.of(a)) t.deepEqual(output, maybe.nothing()) t.end() }) test('maybe - map5 nothing second arg', t => { const output = maybe.map5(add5, maybe.of(x), maybe.nothing(), maybe.of(y), maybe.of(z), maybe.of(a)) t.deepEqual(output, maybe.nothing()) t.end() }) test('maybe - map5 nothing third arg', t => { const output = maybe.map5(add5, maybe.of(x), maybe.of(y), maybe.nothing(), maybe.of(z), maybe.of(a)) t.deepEqual(output, maybe.nothing()) t.end() }) test('maybe - map5 nothing fourth arg', t => { const output = maybe.map5(add5, maybe.of(x), maybe.of(y), maybe.of(z), maybe.nothing(), maybe.of(a)) t.deepEqual(output, maybe.nothing()) t.end() }) test('maybe - map5 nothing fifth arg', t => { const output = maybe.map5(add5, maybe.of(x), maybe.of(y), maybe.of(z), maybe.of(a), maybe.nothing()) t.deepEqual(output, maybe.nothing()) t.end() }) test('maybe chain', t => { const output = pipe( maybe.of, maybe.chain(x => maybe.of(double(x))) )(x) const expected = pipe( double, maybe.just )(x) t.deepEqual(output, expected) t.end() }) test('maybe flatMap', t => { const output = pipe( maybe.of, maybe.flatMap(x => maybe.of(double(x))) )(x) const expected = pipe( double, maybe.just )(x) t.deepEqual(output, expected) t.end() }) test('maybe bind', t => { const output = pipe( maybe.of, maybe.bind(x => maybe.of(double(x))) )(x) const expected = pipe( double, maybe.just )(x) t.deepEqual(output, expected) t.end() }) test('maybe ap', t => { const wrappedDouble = maybe.of(double) const output = maybe.ap(maybe.of(x), wrappedDouble) const expected = pipe( double, maybe.just )(x) t.deepEqual(output, expected) t.end() }) test('maybe ap with nothing', t => { const wrappedDouble = maybe.of(double) const nothing = maybe.nothing() const output = maybe.ap(wrappedDouble, nothing) t.deepEqual(output, maybe.nothing()) t.end() }) test('maybe fold', t => { const nothing = maybe.nothing() const output = maybe.fold(zero, triple, nothing) t.deepEqual(output, zero()) t.end() }) test('maybe is nothing ?', t => { const nothing = maybe.nothing() const output = maybe.isNothing(nothing) t.deepEqual(output, true) t.end() }) test('maybe is just ?', t => { const output = pipe( maybe.of, maybe.isJust )(x) t.deepEqual(output, true) t.end() }) test('nothing equals nothing', t => { t.deepEqual( maybe.equals(maybe.nothing(), maybe.nothing()), true ) t.end() }) test('just are not equals when they does not hold the same values', t => { t.deepEqual( maybe.equals(maybe.just(5), maybe.just(6)), false ) t.end() }) test('just are equals by reference', t => { const x = maybe.just(5) t.deepEqual(maybe.equals(x, x), true) t.end() }) test('just are equals by deep equality', t => { const x = maybe.just(5) const y = maybe.just(5) t.deepEqual(maybe.equals(x, y), true) t.end() }) test('nothing and just are not equals', t => { const x = maybe.just(5) const y = maybe.nothing() t.deepEqual(maybe.equals(x, y), false) t.end() }) test('get just', t => { const output = pipe( maybe.of, maybe.get )(x) t.deepEqual(output, x) t.end() }) test('get nothing', t => { const nothing = maybe.nothing() t.throws(() => maybe.get(nothing)) t.end() }) test('getOrElse nothing', t => { const nothing = maybe.nothing() const output = pipe( maybe.map(double), maybe.getOrElse(zero) )(nothing) t.deepEqual(output, zero()) t.end() }) test('getOrElse right', t => { const output = pipe( maybe.just, maybe.map(double), maybe.getOrElse(zero) )(x) t.deepEqual(output, double(x)) t.end() }) <file_sep>import { default as curry } from 'ramda/src/curry' import { IO } from './constants' export const from = effect => ({ tag: IO, effect }) export const of = x => ({ tag: IO, effect: () => x }) export const map = curry((f, x) => from(() => f(x.effect()))) export const ap = curry((f, x) => from(() => run(f)(run(x)))) export const chain = curry((f, x) => f(x.effect())) export const run = x => x.effect() <file_sep>import { default as curry } from 'ramda/src/curry' export const tap = curry((f, x) => { f() return x }) <file_sep>// @flow import test from 'tape' import { remoteData, maybe, pipe, either } from '../src' const x = 5 const zero = () => 0 const one = () => 1 const double = x => x * 2 const triple = x => x * 3 test('pure', t => { const expected = { tag: 'Success', value: x } t.deepEqual(remoteData.pure(x), expected) t.end() }) test('success constructor', t => { t.deepEqual(remoteData.success(x), remoteData.pure(x)) t.end() }) test('remote data of', t => { t.deepEqual(remoteData.of(x), remoteData.pure(x)) t.end() }) test('failure constructor', t => { const expected = { tag: 'Failure', value: x } t.deepEqual(remoteData.failure(x), expected) t.end() }) test('notAsked constructor', t => { t.deepEqual(remoteData.notAsked(), { tag: 'NotAsked' }) t.end() }) test('loading constructor', t => { t.deepEqual(remoteData.loading(), { tag: 'Loading' }) t.end() }) test('map success', t => { const output = pipe( remoteData.of, remoteData.map(double) )(x) const expected = pipe( double, remoteData.success )(x) t.deepEqual(output, expected) t.end() }) test('map failure', t => { const output = pipe( remoteData.failure, remoteData.mapLeft(double) )(x) const expected = pipe( double, remoteData.failure )(x) t.deepEqual(output, expected) t.end() }) test('remote data chain', t => { const output = pipe( remoteData.of, remoteData.chain(x => remoteData.of(double(x))) )(x) const expected = pipe( double, remoteData.success )(x) t.deepEqual(output, expected) t.end() }) test('remote data flatMap', t => { const output = pipe( remoteData.of, remoteData.flatMap(x => remoteData.of(double(x))) )(x) const expected = pipe( double, remoteData.success )(x) t.deepEqual(output, expected) t.end() }) test('remote data bind', t => { const output = pipe( remoteData.of, remoteData.bind(x => remoteData.of(double(x))) )(x) const expected = pipe( double, remoteData.success )(x) t.deepEqual(output, expected) t.end() }) test('remote data ap', t => { const output = pipe( remoteData.of, remoteData.ap(remoteData.of(x)) )(double) const expected = pipe( double, remoteData.success )(x) t.deepEqual(output, expected) t.end() }) test('remote data lift2 success', t => { const str = 'test' const rd1 = remoteData.of(x) const rd2 = remoteData.of(str) const f = (a, b) => `${a} ${b}` const output = remoteData.lift2(remoteData.of(f), rd1, rd2) const expected = remoteData.success(f(x, str)) t.deepEqual(output, expected) t.end() }) test('remote data lift2 loading', t => { const str = 'test' const rd1 = remoteData.of(x) const rd2 = remoteData.of(str) const f = remoteData.loading() const output = remoteData.lift2(f, rd1, rd2) t.deepEqual(output, f) t.end() }) test('remote data lift2 notAsked', t => { const str = 'test' const rd1 = remoteData.of(x) const rd2 = remoteData.of(str) const f = remoteData.notAsked() const output = remoteData.lift2(f, rd1, rd2) t.deepEqual(output, f) t.end() }) test('remote data lift2 failure', t => { const str = 'test' const rd1 = remoteData.of(x) const rd2 = remoteData.of(str) const f = remoteData.failure('err') const output = remoteData.lift2(f, rd1, rd2) t.deepEqual(output, f) t.end() }) test('remote data lift2 with loading first value', t => { const str = 'test' const rd1 = remoteData.loading() const rd2 = remoteData.of(str) const f = (a, b) => `${a} ${b}` const output = remoteData.lift2(remoteData.of(f), rd1, rd2) t.deepEqual(output, rd1) t.end() }) test('remote data lift2 with notAsked first value', t => { const str = 'test' const rd1 = remoteData.notAsked() const rd2 = remoteData.of(str) const f = (a, b) => `${a} ${b}` const output = remoteData.lift2(remoteData.of(f), rd1, rd2) t.deepEqual(output, rd1) t.end() }) test('remote data lift2 with failure first value', t => { const str = 'test' const rd1 = remoteData.failure('err') const rd2 = remoteData.of(str) const f = (a, b) => `${a} ${b}` const output = remoteData.lift2(remoteData.of(f), rd1, rd2) t.deepEqual(output, rd1) t.end() }) test('remote data lift2 loading second value', t => { const str = 'test' const rd1 = remoteData.of(str) const rd2 = remoteData.loading() const f = (a, b) => `${a} ${b}` const output = remoteData.lift2(remoteData.of(f), rd1, rd2) t.deepEqual(output, rd2) t.end() }) test('remote data lift2 notAsked first value', t => { const str = 'test' const rd1 = remoteData.of(str) const rd2 = remoteData.notAsked() const f = (a, b) => `${a} ${b}` const output = remoteData.lift2(remoteData.of(f), rd1, rd2) t.deepEqual(output, rd2) t.end() }) test('remote data lift2 with failure first value', t => { const str = 'test' const rd1 = remoteData.of(str) const rd2 = remoteData.failure('err') const f = (a, b) => `${a} ${b}` const output = remoteData.lift2(remoteData.of(f), rd1, rd2) t.deepEqual(output, rd2) t.end() }) test('remote data lift3 success', t => { const str = 'test' const rd1 = remoteData.of(x) const rd2 = remoteData.of(str) const rd3 = remoteData.of(x) const f = (a, b, c) => `${a} ${b} ${c}` const output = remoteData.lift3(remoteData.of(f), rd1, rd2, rd3) const expected = remoteData.success(f(x, str, x)) t.deepEqual(output, expected) t.end() }) test('remote data lift3 loading', t => { const str = 'test' const rd1 = remoteData.of(x) const rd2 = remoteData.of(str) const rd3 = remoteData.of(x) const f = remoteData.loading() const output = remoteData.lift3(f, rd1, rd2, rd3) const expected = remoteData.loading() t.deepEqual(output, expected) t.end() }) test('remote data lift3 with loading first value', t => { const str = 'test' const rd1 = remoteData.loading() const rd2 = remoteData.of(str) const rd3 = remoteData.of(x) const f = (a, b, c) => `${a} ${b} ${c}` const output = remoteData.lift3(remoteData.of(f), rd1, rd2, rd3) t.deepEqual(output, rd1) t.end() }) test('remote data lift3 with notAsked first value', t => { const str = 'test' const rd1 = remoteData.notAsked() const rd2 = remoteData.of(str) const rd3 = remoteData.of(x) const f = (a, b, c) => `${a} ${b} ${c}` const output = remoteData.lift3(remoteData.of(f), rd1, rd2, rd3) t.deepEqual(output, rd1) t.end() }) test('remote data lift3 with failure first value', t => { const str = 'test' const rd1 = remoteData.failure('err') const rd2 = remoteData.of(str) const rd3 = remoteData.of(x) const f = (a, b, c) => `${a} ${b} ${c}` const output = remoteData.lift3(remoteData.of(f), rd1, rd2, rd3) t.deepEqual(output, rd1) t.end() }) test('remote data lift3 second value loading', t => { const str = 'test' const rd1 = remoteData.of(str) const rd2 = remoteData.loading() const rd3 = remoteData.of(x) const f = (a, b, c) => `${a} ${b} ${c}` const output = remoteData.lift3(remoteData.of(f), rd1, rd2, rd3) t.deepEqual(output, rd2) t.end() }) test('remote data lift3 with notAsked second value', t => { const str = 'test' const rd1 = remoteData.of(str) const rd2 = remoteData.notAsked() const rd3 = remoteData.of(x) const f = (a, b, c) => `${a} ${b} ${c}` const output = remoteData.lift3(remoteData.of(f), rd1, rd2, rd3) t.deepEqual(output, rd2) t.end() }) test('remote data lift3 with failure second value', t => { const str = 'test' const rd1 = remoteData.of(str) const rd2 = remoteData.failure('err') const rd3 = remoteData.of(x) const f = (a, b, c) => `${a} ${b} ${c}` const output = remoteData.lift3(remoteData.of(f), rd1, rd2, rd3) t.deepEqual(output, rd2) t.end() }) test('remote data lift3 third value loading', t => { const str = 'test' const rd1 = remoteData.of(str) const rd2 = remoteData.of(x) const rd3 = remoteData.loading() const f = (a, b, c) => `${a} ${b} ${c}` const output = remoteData.lift3(remoteData.of(f), rd1, rd2, rd3) t.deepEqual(output, rd3) t.end() }) test('remote data lift3 with notAsked third value', t => { const str = 'test' const rd1 = remoteData.of(str) const rd2 = remoteData.of(x) const rd3 = remoteData.notAsked() const f = (a, b, c) => `${a} ${b} ${c}` const output = remoteData.lift3(remoteData.of(f), rd1, rd2, rd3) t.deepEqual(output, rd3) t.end() }) test('remote data lift3 with failure third value', t => { const str = 'test' const rd1 = remoteData.of(str) const rd2 = remoteData.of(x) const rd3 = remoteData.failure('err') const f = (a, b, c) => `${a} ${b} ${c}` const output = remoteData.lift3(remoteData.of(f), rd1, rd2, rd3) t.deepEqual(output, rd3) t.end() }) test('remote data map2 success', t => { const str = 'test' const rd1 = remoteData.of(x) const rd2 = remoteData.of(str) const f = (a, b) => `${a} ${b}` const output = remoteData.map2(f, rd1, rd2) const expected = remoteData.success(f(x, str)) t.deepEqual(output, expected) t.end() }) test('remote data map2 loading', t => { const rd1 = remoteData.of(x) const rd2 = remoteData.loading() const f = (a, b) => `${a} ${b}` const output = remoteData.map2(f, rd1, rd2) t.deepEqual(output, rd2) t.end() }) test('remote data map2 notAsked', t => { const rd1 = remoteData.of(x) const rd2 = remoteData.notAsked() const f = (a, b) => `${a} ${b}` const output = remoteData.map2(f, rd1, rd2) t.deepEqual(output, rd2) t.end() }) test('remote data map2 failure', t => { const rd1 = remoteData.of(x) const rd2 = remoteData.failure(x) const f = (a, b) => `${a} ${b}` const output = remoteData.map2(f, rd1, rd2) const expected = remoteData.failure(x) t.deepEqual(output, expected) t.end() }) test('remote data map3 success', t => { const str = 'test' const rd1 = remoteData.of(x) const rd2 = remoteData.of(x + 1) const rd3 = remoteData.of(str) const f = (a, b, c) => `${a} ${b} ${c}` const output = remoteData.map3(f, rd1, rd2, rd3) const expected = remoteData.success(f(x, x + 1, str)) t.deepEqual(output, expected) t.end() }) test('remote data map3 failure', t => { const rd1 = remoteData.of(x) const rd2 = remoteData.of(x) const rd3 = remoteData.failure(x) const output = remoteData.map3(double, rd3, rd1, rd2) t.deepEqual(output, rd3) t.end() }) test('remote data map3 notAsked', t => { const rd1 = remoteData.of(x) const rd2 = remoteData.notAsked() const rd3 = remoteData.of(x) const output = remoteData.map3(double, rd1, rd2, rd3) t.deepEqual(output, rd2) t.end() }) test('remote data map3 loading', t => { const rd1 = remoteData.of(x) const rd2 = remoteData.loading() const rd3 = remoteData.of(x) const output = remoteData.map3(double, rd1, rd2, rd3) t.deepEqual(output, rd2) t.end() }) test('remote data map4 success', t => { const str = 'test' const rd1 = remoteData.of(x) const rd2 = remoteData.of(x + 1) const rd3 = remoteData.of(x) const rd4 = remoteData.of(str) const f = (a, b, c, d) => `${a} ${b} ${c} ${d}` const output = remoteData.map4(f, rd1, rd2, rd3, rd4) const expected = remoteData.success(f(x, x + 1, x, str)) t.deepEqual(output, expected) t.end() }) test('remote data map4 failure', t => { const rd1 = remoteData.of(x) const rd2 = remoteData.of(x) const rd3 = remoteData.failure(x) const rd4 = remoteData.of(x) const output = remoteData.map4(double, rd3, rd1, rd2, rd4) t.deepEqual(output, rd3) t.end() }) test('remote data map4 notAsked', t => { const rd1 = remoteData.of(x) const rd2 = remoteData.notAsked() const rd3 = remoteData.of(x) const rd4 = remoteData.of(x) const output = remoteData.map4(double, rd1, rd2, rd3, rd4) t.deepEqual(output, rd2) t.end() }) test('remote data map4 loading', t => { const rd1 = remoteData.of(x) const rd2 = remoteData.loading() const rd3 = remoteData.of(x) const rd4 = remoteData.of(x) const output = remoteData.map4(double, rd1, rd2, rd3, rd4) t.deepEqual(output, rd2) t.end() }) test('remote data map5 success', t => { const str = 'test' const rd1 = remoteData.of(x) const rd2 = remoteData.of(x + 1) const rd3 = remoteData.of(x) const rd4 = remoteData.of(x) const rd5 = remoteData.of(str) const f = (a, b, c, d, e) => `${a} ${b} ${c} ${d} ${e}` const output = remoteData.map5(f, rd1, rd2, rd3, rd4, rd5) const expected = remoteData.success(f(x, x + 1, x, x, str)) t.deepEqual(output, expected) t.end() }) test('remote data map5 failure', t => { const rd1 = remoteData.of(x) const rd2 = remoteData.of(x) const rd3 = remoteData.failure(x) const rd4 = remoteData.of(x) const rd5 = remoteData.of(x) const output = remoteData.map5(double, rd3, rd1, rd2, rd4, rd5) t.deepEqual(output, rd3) t.end() }) test('remote data map5 notAsked', t => { const rd1 = remoteData.of(x) const rd2 = remoteData.notAsked() const rd3 = remoteData.of(x) const rd4 = remoteData.of(x) const rd5 = remoteData.of(x) const output = remoteData.map5(double, rd1, rd2, rd3, rd4, rd5) t.deepEqual(output, rd2) t.end() }) test('remote data map5 loading', t => { const rd1 = remoteData.of(x) const rd2 = remoteData.loading() const rd3 = remoteData.of(x) const rd4 = remoteData.of(x) const rd5 = remoteData.of(x) const output = remoteData.map5(double, rd1, rd2, rd3, rd4, rd5) t.deepEqual(output, rd2) t.end() }) test('fold success', t => { const output = pipe( remoteData.success, remoteData.fold({ Success: double, Failure: triple, NotAsked: zero, Loading: one }) )(x) t.deepEqual(output, double(x)) t.end() }) test('fold failure', t => { const output = pipe( remoteData.failure, remoteData.fold({ Success: triple, Failure: double, NotAsked: zero, Loading: one }) )(x) t.deepEqual(output, double(x)) t.end() }) test('fold not asked', t => { const notAsked = remoteData.notAsked() const output = remoteData.fold({ Success: triple, Failure: double, NotAsked: zero, Loading: one }, notAsked) t.deepEqual(output, zero()) t.end() }) test('fold loading', t => { const loading = remoteData.loading() const output = remoteData.fold({ Success: triple, Failure: double, NotAsked: zero, Loading: one }, loading) t.deepEqual(output, one()) t.end() }) test('remote data is success ?', t => { const output = pipe( remoteData.success, remoteData.isSuccess )(x) t.isEqual(output, true) t.end() }) test('remote data is failure ?', t => { const output = pipe( remoteData.failure, remoteData.isFailure )(x) t.isEqual(output, true) t.end() }) test('remote data is not asked ?', t => { const notAsked = remoteData.notAsked() t.isEqual(remoteData.isNotAsked(notAsked), true) t.end() }) test('remote data is loading ?', t => { const loading = remoteData.loading() t.isEqual(remoteData.isLoading(loading), true) t.end() }) test('success are not equals when they does not hold the same values', t => { t.isEqual( remoteData.equals(remoteData.success(5), remoteData.success(6)), false ) t.end() }) test('failure are not equals when they does not hold the same values', t => { t.isEqual( remoteData.equals(remoteData.failure(5), remoteData.failure(6)), false ) t.end() }) test('success are equals by reference', t => { const x = remoteData.success(5) t.isEqual(remoteData.equals(x, x), true) t.end() }) test('failure are equals by reference', t => { const x = remoteData.failure(5) t.isEqual(remoteData.equals(x, x), true) t.end() }) test('success are equals by deep equality', t => { const x = remoteData.success(5) const y = remoteData.success(5) t.isEqual(remoteData.equals(x, y), true) t.end() }) test('failure are equals by deep equality', t => { const x = remoteData.failure(5) const y = remoteData.failure(5) t.isEqual(remoteData.equals(x, y), true) t.end() }) test('success and failure are not equals', t => { const x = remoteData.success(5) const y = remoteData.failure(5) t.isEqual(remoteData.equals(x, y), false) t.end() }) test('get success', t => { const output = pipe( remoteData.of, remoteData.get )(x) t.deepEqual(output, x) t.end() }) test('get failure', t => { const fn = pipe( remoteData.failure, remoteData.get ) t.throws(fn) t.end() }) test('get not asked', t => { t.throws(() => remoteData.get(remoteData.notAsked())) t.end() }) test('get loading', t => { t.throws(() => remoteData.get(remoteData.loading())) t.end() }) test('getOrElse success', t => { const output = pipe( remoteData.success, remoteData.map(double), remoteData.getOrElse(zero) )(x) t.deepEqual(output, double(x)) t.end() }) test('getOrElse failure', t => { const output = pipe( remoteData.failure, remoteData.map(double), remoteData.getOrElse(zero) )(x) t.deepEqual(output, zero()) t.end() }) test('getOrElse loading', t => { const loading = remoteData.loading() const output = pipe( remoteData.map(double), remoteData.getOrElse(zero) )(loading) t.deepEqual(output, zero()) t.end() }) test('getOrElse not asked', t => { const notAsked = remoteData.notAsked() const output = pipe( remoteData.map(double), remoteData.getOrElse(zero) )(notAsked) t.deepEqual(output, zero()) t.end() }) test('remote data from maybe nothing', t => { const nothing = maybe.nothing() t.deepEqual(remoteData.fromMaybe(nothing), remoteData.notAsked()) t.end() }) test('remote data from maybe just', t => { const output = pipe( maybe.just, remoteData.fromMaybe )(x) t.deepEqual(output, remoteData.success(x)) t.end() }) test('remote data from either right', t => { const output = pipe( either.right, remoteData.fromEither )(x) t.deepEqual(output, remoteData.success(x)) t.end() }) test('remote data from either left', t => { const output = pipe( either.left, remoteData.fromEither )(x) t.deepEqual(output, remoteData.failure(x)) t.end() }) test('remote data success to maybe', t => { const output = pipe( remoteData.success, remoteData.toMaybe )(x) t.deepEqual(output, maybe.just(x)) t.end() }) test('remote data failure to maybe', t => { const output = pipe( remoteData.failure, remoteData.toMaybe )(x) t.deepEqual(output, maybe.nothing()) t.end() }) test('remote data not asked to maybe', t => { const notAsked = remoteData.notAsked() const output = remoteData.toMaybe(notAsked) t.deepEqual(output, maybe.nothing()) t.end() }) test('remote data loading to maybe', t => { const loading = remoteData.loading() const output = remoteData.toMaybe(loading) t.deepEqual(output, maybe.nothing()) t.end() }) <file_sep>export const pipe = (...funs) => { return x => funs.reduce((acc, f) => f(acc), x) } <file_sep>// @flow import test from 'tape' import { compose } from '../src' const x = 0 const substract = x => y => y - x const decrement = substract(1) test('compose 1', t => { const y = compose(decrement)(x) t.equal(y, -1) t.end() }) test('compose 2', t => { const y = compose( decrement, decrement )(x) t.equal(y, -2) t.end() }) test('compose 3', t => { const y = compose( decrement, decrement, decrement )(x) t.equal(y, -3) t.end() }) test('compose 4', t => { const y = compose( decrement, decrement, decrement, decrement )(x) t.equal(y, -4) t.end() }) test('compose 5', t => { const y = compose( decrement, decrement, decrement, decrement, decrement )(x) t.equal(y, -5) t.end() }) test('compose 6', t => { const y = compose( decrement, decrement, decrement, decrement, decrement, decrement )(x) t.equal(y, -6) t.end() }) test('compose 7', t => { const y = compose( decrement, decrement, decrement, decrement, decrement, decrement, decrement )(x) t.equal(y, -7) t.end() }) test('compose 8', t => { const y = compose( decrement, decrement, decrement, decrement, decrement, decrement, decrement, decrement )(x) t.equal(y, -8) t.end() }) test('compose 9', t => { const y = compose( decrement, decrement, decrement, decrement, decrement, decrement, decrement, decrement, decrement )(x) t.equal(y, -9) t.end() }) test('compose 10', t => { const y = compose( decrement, decrement, decrement, decrement, decrement, decrement, decrement, decrement, decrement, decrement )(x) t.equal(y, -10) t.end() }) <file_sep># FP-FLOW [![Build Status](https://travis-ci.com/seb-bizeul/fp-flow.svg?branch=master)](https://travis-ci.com/seb-bizeul/fp-flow) ### Install npm i -S @sbizeul/fp-flow or yarn add @sbizeul/fp-flow ### Build yarn build ### Test yarn test ### Documentation * [API Reference](https://github.com/seb-bizeul/fp-flow/wiki) <file_sep>export const flip = f => (x, y, ...rest) => f(y, x, ...rest) <file_sep>// @flow import * as either from './either' import * as maybe from './maybe' import * as remoteData from './remote-data' import * as io from './io' import * as ordering from './ordering' import { pipe } from './pipe' import { compose } from './compose' import { tap } from './tap' import { flip } from './flip' export { either, maybe, remoteData, io, pipe, compose, tap, ordering, flip } <file_sep>export const Left = 'Left' export const Right = 'Right' export const Just = 'Just' export const Nothing = 'Nothing' export const Success = 'Success' export const Failure = 'Failure' export const NotAsked = 'NotAsked' export const Loading = 'Loading' export const IO = 'IO' export const GT = 'GT' export const LT = 'LT' export const EQ = 'EQ' <file_sep>// @flow import test from 'tape' import { pipe } from '../src' const x = 0 const add = x => y => x + y const increment = add(1) test('pipe 1', t => { const y = pipe(increment)(x) t.equal(y, 1) t.end() }) test('pipe 2', t => { const y = pipe( increment, increment )(x) t.equal(y, 2) t.end() }) test('pipe 3', t => { const y = pipe( increment, increment, increment )(x) t.equal(y, 3) t.end() }) test('pipe 4', t => { const y = pipe( increment, increment, increment, increment )(x) t.equal(y, 4) t.end() }) test('pipe 5', t => { const y = pipe( increment, increment, increment, increment, increment )(x) t.equal(y, 5) t.end() }) test('pipe 6', t => { const y = pipe( increment, increment, increment, increment, increment, increment )(x) t.equal(y, 6) t.end() }) test('pipe 7', t => { const y = pipe( increment, increment, increment, increment, increment, increment, increment )(x) t.equal(y, 7) t.end() }) test('pipe 8', t => { const y = pipe( increment, increment, increment, increment, increment, increment, increment, increment )(x) t.equal(y, 8) t.end() }) test('pipe 9', t => { const y = pipe( increment, increment, increment, increment, increment, increment, increment, increment, increment )(x) t.equal(y, 9) t.end() }) test('pipe 10', t => { const y = pipe( increment, increment, increment, increment, increment, increment, increment, increment, increment, increment )(x) t.equal(y, 10) t.end() }) <file_sep>export const compose = (...funs) => { return x => funs.reduceRight((acc, f) => f(acc), x) } <file_sep>import { default as curry } from 'ramda/src/curry' import { GT, LT, EQ } from './constants' export const compare = curry((x, y) => { if (x > y) return GT else if (x < y) return LT else return EQ }) export { GT, LT, EQ }
2d623dda58a334463be2f57a609e2e5e2e0d9095
[ "JavaScript", "Markdown" ]
18
JavaScript
seb-bizeul/fp-flow
0048c24b4b6fa094ab60b2d4c2c91fac535529e5
2559b6e58db6def800a601595c0bf9e383b00618
refs/heads/master
<file_sep>namespace _03.PlaidTowel { using System; class PlaidTowel { private static void Main(string[] args) { int size = int.Parse(Console.ReadLine()); char bg = char.Parse(Console.ReadLine()); char fg = char.Parse(Console.ReadLine()); string topBottomPart = new string(bg, size) + fg + new string(bg, size * 2 - 1) + fg + new string(bg, size); string middlePart = fg + new string(bg, size * 2 - 1) + fg + new string(bg, size * 2 - 1) + fg; Console.WriteLine(topBottomPart); BuildDown(size, bg, fg); Console.WriteLine(middlePart); BuildUp(size, bg, fg); Console.WriteLine(topBottomPart); BuildDown(size, bg, fg); Console.WriteLine(middlePart); BuildUp(size, bg, fg); Console.WriteLine(topBottomPart); } private static void BuildDown(int size, char bg, char fg) { int leftRight = size - 1; int middle = size * 2 - 3; int sub = 1; for (int i = 1; i < size; i++) { Console.WriteLine(new string(bg, leftRight) + fg + new string(bg, sub) + fg + new string(bg, middle) + fg + new string(bg, sub) + fg + new string(bg, leftRight)); leftRight--; middle -= 2; sub += 2; } } private static void BuildUp(int size, char bg, char fg) { int leftRight = 1; int middle = 1; int sub = size * 2 - 3; for (int i = 1; i < size; i++) { Console.WriteLine(new string(bg, leftRight) + fg + new string(bg, sub) + fg + new string(bg, middle) + fg + new string(bg, sub) + fg + new string(bg, leftRight)); leftRight++; middle += 2; sub -= 2; } } } } <file_sep>namespace _04.FirefightingOrganization { using System; class FirefightingOrganization { static void Main(string[] args) { int fireFighters = int.Parse(Console.ReadLine()); int savedKids = 0; int savedAdults = 0; int savedSeniors = 0; string building; while (!(building = Console.ReadLine()).Equals("rain")) { char[] people = building.Replace("A", "L").ToCharArray(); Array.Sort(people); for (int i = 0; i < Math.Min(people.Length, fireFighters); i++) { switch (people[i]) { case 'K': savedKids++; break; case 'L': savedAdults++; break; case 'S': savedSeniors++; break; } } } Console.WriteLine($"Kids: {savedKids}\nAdults: {savedAdults}\nSeniors: {savedSeniors}"); } } } <file_sep>namespace _01.TheBetterMusicProducer { using System; class TheBetterMusicProducer { static void Main(string[] args) { int europeAlbums = int.Parse(Console.ReadLine()); decimal euro = decimal.Parse(Console.ReadLine()); int northAmericaAlbums = int.Parse(Console.ReadLine()); decimal dollars = decimal.Parse(Console.ReadLine()); int southAmericaAlbums = int.Parse(Console.ReadLine()); decimal pesos = decimal.Parse(Console.ReadLine()); int numOfConcerts = int.Parse(Console.ReadLine()); decimal incomePerConcert = decimal.Parse(Console.ReadLine()); decimal albumsIncome = CalculateIncomeFromAlbums(europeAlbums, euro, northAmericaAlbums, dollars, southAmericaAlbums, pesos); decimal concertsIncome = CalculateIncomeFromConcerts(numOfConcerts, incomePerConcert); if (albumsIncome > concertsIncome) { Console.WriteLine($"Let's record some songs! They'll bring us {albumsIncome:F2}lv."); } else { Console.WriteLine($"On the road again! We'll see the world and earn {concertsIncome:F2}lv."); } } private static decimal CalculateIncomeFromConcerts(int numOfConcerts, decimal incomePerConcert) { incomePerConcert = incomePerConcert * numOfConcerts * 1.94M; if (incomePerConcert > 100000) { incomePerConcert *= .85M; } return incomePerConcert; } private static decimal CalculateIncomeFromAlbums(int europeAlbums, decimal euro, int northAmericaAlbums, decimal dollars, int southAmericaAlbums, decimal pesos) { decimal totalIncome = europeAlbums * euro * 1.94M; totalIncome += northAmericaAlbums * dollars * 1.72M; totalIncome += southAmericaAlbums * pesos / 332.74M; totalIncome *= .65M; totalIncome *= .8M; return totalIncome; } } } <file_sep>namespace _02.GrandTheftExamo { using System; class GrandTheftExamo { private const int MaxSlapped = 5; static void Main(string[] args) { long slappedThieves = 0; long escapedThieves = 0; long beersDrunk = 0; int attempts = int.Parse(Console.ReadLine()); for (int i = 0; i < attempts; i++) { int thieves = int.Parse(Console.ReadLine()); beersDrunk += int.Parse(Console.ReadLine()); int result = thieves - MaxSlapped; if (result > 0) { escapedThieves += result; slappedThieves += MaxSlapped; continue; } slappedThieves += thieves; } Console.WriteLine($"{slappedThieves} thieves slapped."); Console.WriteLine($"{escapedThieves} thieves escaped."); Console.WriteLine($"{beersDrunk / 6} packs, {beersDrunk % 6} bottles."); } } } <file_sep>namespace _05.BohemchoTheBadGhost { using System; using System.Linq; class BohemchoTheBadGhost { static void Main(string[] args) { int lightsOn = 0; long score = 0; string command; while (!(command = Console.ReadLine()).Equals("Stop, God damn it")) { long floorState = long.Parse(command); int[] apartaments = Console.ReadLine() .Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToArray(); foreach (int ap in apartaments) { floorState ^= 1L << ap; } for (int i = 0; i < 32; i++) { if (((floorState >> i) & 1L) == 1) { lightsOn++; } } score += floorState; } Console.WriteLine($"Bohemcho left {lightsOn} lights on and his score is {score }"); } } }
85ed1a58f624b396c7e6e7a94938d3b376237d87
[ "C#" ]
5
C#
vdonchev/ProgrammingBasicsExam-18October2015
51ff5a6ca315a73c4d0de8820177ab118cb11313
db159c9b16e1a21765312154a037777a227ed60d
refs/heads/master
<file_sep>package co.com.diccionario.negocio.cacheable.iface; import java.util.List; import co.com.diccionario.dto.SinonimosDTO; public interface SinonimosCachableIface { public List<SinonimosDTO> obtenerTodasLasPalabras(); } <file_sep>package co.com.diccionario.mongodb.repository.iface; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import co.com.diccionario.document.Palabras; import co.com.diccionario.document.Sinonimos; public interface SinonimosRepository extends MongoRepository<Sinonimos, String> { public List<Sinonimos> findByPaisOrigenAndPaisDestinoAndDepartamentoOrigenAndDepartamentoDestinoAndTerminoAndCategoria( String paisOrigen, String paisDestino, String departamentoOrigen, String departamentoDestino, String termino, String categoria); public List<Sinonimos> findByPaisOrigenAndPaisDestinoAndTerminoAndCategoria(String paisOrigen, String paisDestino, String termino, String categoria); public List<Sinonimos> findByPaisOrigenAndPaisDestinoAndTermino(String paisOrigen, String paisDestino, String termino); public List<Sinonimos> findByPaisOrigenAndPaisDestinoAndCategoria(String paisOrigen, String paisDestino, String categoria); public List<Sinonimos> findByPaisOrigenAndPaisDestino(String paisOrigen, String paisDestino); public List<Sinonimos> findByPaisOrigen(String paisOrigen); public List<Sinonimos> findByPaisOrigenAndPaisDestinoAndTerminoAndSinonimosIn(String paisOrigen, String paisDestino, String termino, Palabras palabraSinonimo); } <file_sep>package co.com.diccionario.mongodb.repository.iface; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import co.com.diccionario.document.Ciudad; public interface CiudadesRepository extends MongoRepository<Ciudad, Integer> { public List<Ciudad> findByDepartamento(int departamento); public List<Ciudad> findByDepartamentoAndNombreIgnoreCase(int departamento, String nombre); } <file_sep>package co.com.diccionario.client.catalogos; import java.util.List; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.client.HttpClientErrorException; import org.springframework.web.client.RestTemplate; import co.com.diccionario.dto.ParametrosRegistroTermino; import co.com.diccionario.dto.ParamsBusquedaPalabraDTO; import co.com.diccionario.dto.SinonimosDTO; import co.com.diccionario.utils.ParamsBundle; public class GestionarPalabrasServiceClient { private static GestionarPalabrasServiceClient INSTANCE; private static String HOST_END_POINT; private static final String HOST = "host_end_point"; private static final String PALABRAS = "palabras"; private static final String BUSQUEDA = "busqueda"; private static final String SINONIMO = "sinonimo"; private static final String ORACION = "oracion"; private static final String CALIFICACION = "calificacion"; private GestionarPalabrasServiceClient() { // TODO Auto-generated constructor stub } public static GestionarPalabrasServiceClient getInstance() throws Exception { if (INSTANCE == null) { INSTANCE = new GestionarPalabrasServiceClient(); ParamsBundle.getInstance().getEtiquetasParamsClient(ParamsBundle.SERVICE_CLIENT_DICCIONARIO); HOST_END_POINT = ParamsBundle.getInstance().getMapParamsServiceClientPatios().get(HOST); } return INSTANCE; } public List<SinonimosDTO> obtenerSinonimos(ParamsBusquedaPalabraDTO paramsBusqueda) throws Exception { RestTemplate restTemplate = new RestTemplate(); String uri = HOST_END_POINT + PALABRAS + "/" + BUSQUEDA; try { HttpEntity<ParamsBusquedaPalabraDTO> httpEntity = new HttpEntity<ParamsBusquedaPalabraDTO>(paramsBusqueda); ResponseEntity<List<SinonimosDTO>> response = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, new ParameterizedTypeReference<List<SinonimosDTO>>() { }); List<SinonimosDTO> listSinonimos = response.getBody(); return listSinonimos; } catch (HttpClientErrorException e) { if (e.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) { throw new Exception(e.getResponseBodyAsString() + " " + e.getMessage()); } if (e.getStatusCode().equals(HttpStatus.NOT_FOUND)) { return null; } } return null; } public List<SinonimosDTO> getSinonimoCategoriaPalabra(ParamsBusquedaPalabraDTO paramsBusqueda) throws Exception { RestTemplate restTemplate = new RestTemplate(); String uri = HOST_END_POINT + PALABRAS + "/" + BUSQUEDA + "/validarSinonimoPalabra"; try { HttpEntity<ParamsBusquedaPalabraDTO> httpEntity = new HttpEntity<ParamsBusquedaPalabraDTO>(paramsBusqueda); ResponseEntity<List<SinonimosDTO>> response = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, new ParameterizedTypeReference<List<SinonimosDTO>>() { }); List<SinonimosDTO> listSinonimos = response.getBody(); return listSinonimos; } catch (HttpClientErrorException e) { if (e.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) { throw new Exception(e.getResponseBodyAsString() + " " + e.getMessage()); } if (e.getStatusCode().equals(HttpStatus.NOT_FOUND)) { return null; } } return null; } public SinonimosDTO agregarNuevoSinonimo(SinonimosDTO sinonimosDTO) throws Exception { RestTemplate restTemplate = new RestTemplate(); String uri = HOST_END_POINT + PALABRAS + "/sinonimo"; try { HttpEntity<SinonimosDTO> httpEntity = new HttpEntity<>(sinonimosDTO); ResponseEntity<SinonimosDTO> response = restTemplate.exchange(uri, HttpMethod.PUT, httpEntity, new ParameterizedTypeReference<SinonimosDTO>() { }); return response.getBody(); } catch (HttpClientErrorException e) { throw new Exception(e.getResponseBodyAsString() + " " + e.getMessage()); } } public List<SinonimosDTO> obtenerSinonimosCategoriaPalabra(ParamsBusquedaPalabraDTO paramsBusqueda) throws Exception { RestTemplate restTemplate = new RestTemplate(); String uri = HOST_END_POINT + PALABRAS + "/" + BUSQUEDA + "/categoriaTermino"; try { HttpEntity<ParamsBusquedaPalabraDTO> httpEntity = new HttpEntity<ParamsBusquedaPalabraDTO>(paramsBusqueda); ResponseEntity<List<SinonimosDTO>> response = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, new ParameterizedTypeReference<List<SinonimosDTO>>() { }); List<SinonimosDTO> listSinonimos = response.getBody(); return listSinonimos; } catch (HttpClientErrorException e) { if (e.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) { throw new Exception(e.getResponseBodyAsString() + " " + e.getMessage()); } if (e.getStatusCode().equals(HttpStatus.NOT_FOUND)) { return null; } } return null; } public List<SinonimosDTO> obtenerSinonimosPalabra(ParamsBusquedaPalabraDTO paramsBusqueda) throws Exception { RestTemplate restTemplate = new RestTemplate(); String uri = HOST_END_POINT + PALABRAS + "/" + BUSQUEDA + "/termino"; try { HttpEntity<ParamsBusquedaPalabraDTO> httpEntity = new HttpEntity<ParamsBusquedaPalabraDTO>(paramsBusqueda); ResponseEntity<List<SinonimosDTO>> response = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, new ParameterizedTypeReference<List<SinonimosDTO>>() { }); List<SinonimosDTO> listSinonimos = response.getBody(); return listSinonimos; } catch (HttpClientErrorException e) { if (e.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) { throw new Exception(e.getResponseBodyAsString() + " " + e.getMessage()); } if (e.getStatusCode().equals(HttpStatus.NOT_FOUND)) { return null; } } return null; } public boolean crearNuevoTermino(ParametrosRegistroTermino params) throws Exception { RestTemplate restTemplate = new RestTemplate(); String uri = HOST_END_POINT + PALABRAS + "/sinonimo"; try { ResponseEntity<HttpStatus> response = restTemplate.postForEntity(uri, params, HttpStatus.class); HttpStatus httpStatus = response.getBody(); if (httpStatus.equals(HttpStatus.OK)) { return true; } return false; } catch (HttpClientErrorException e) { throw new Exception(e.getResponseBodyAsString() + " " + e.getMessage()); } } public SinonimosDTO actualizarCalificacionSinonimos(SinonimosDTO sinonimosDTO) throws Exception { RestTemplate restTemplate = new RestTemplate(); String uri = HOST_END_POINT + PALABRAS + "/" + SINONIMO + "/" + CALIFICACION; try { HttpEntity<SinonimosDTO> httpEntity = new HttpEntity<>(sinonimosDTO); ResponseEntity<SinonimosDTO> response = restTemplate.exchange(uri, HttpMethod.PUT, httpEntity, new ParameterizedTypeReference<SinonimosDTO>() { }); return response.getBody(); } catch (HttpClientErrorException e) { throw new Exception(e.getResponseBodyAsString() + " " + e.getMessage()); } } public SinonimosDTO actualizarCalificacionOraciones(SinonimosDTO sinonimosDTO) throws Exception { RestTemplate restTemplate = new RestTemplate(); String uri = HOST_END_POINT + PALABRAS + "/" + SINONIMO + "/" + ORACION + "/" + CALIFICACION; try { HttpEntity<SinonimosDTO> httpEntity = new HttpEntity<>(sinonimosDTO); ResponseEntity<SinonimosDTO> response = restTemplate.exchange(uri, HttpMethod.PUT, httpEntity, new ParameterizedTypeReference<SinonimosDTO>() { }); return response.getBody(); } catch (HttpClientErrorException e) { throw new Exception(e.getResponseBodyAsString() + " " + e.getMessage()); } } public SinonimosDTO actualizarOraciones(SinonimosDTO sinonimosDTO) throws Exception { RestTemplate restTemplate = new RestTemplate(); String uri = HOST_END_POINT + PALABRAS + "/" + SINONIMO + "/" + ORACION; try { HttpEntity<SinonimosDTO> httpEntity = new HttpEntity<>(sinonimosDTO); ResponseEntity<SinonimosDTO> response = restTemplate.exchange(uri, HttpMethod.POST, httpEntity, new ParameterizedTypeReference<SinonimosDTO>() { }); return response.getBody(); } catch (HttpClientErrorException e) { throw new Exception(e.getResponseBodyAsString() + " " + e.getMessage()); } } } <file_sep>package co.com.diccionario.mongodb.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.FindAndModifyOptions; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Component; import co.com.diccionario.document.CountersImagenes; import co.com.diccionario.mongodb.iface.CounterImagenesIface; @Component public class CounterImagenesImpl implements CounterImagenesIface { @Autowired MongoTemplate mongoTemplate; @Override public long getNextSequenceId(String key) { Query query = new Query(Criteria.where("_id").is(key)); Update update = new Update(); update.inc("seq", 1); FindAndModifyOptions options = new FindAndModifyOptions(); options.returnNew(true); CountersImagenes seqId = mongoTemplate.findAndModify(query, update, options, CountersImagenes.class); return seqId.getSeq(); } } <file_sep>package co.com.diccionario.rest.exception; public class CommonException extends Exception { /** * */ private static final long serialVersionUID = 1L; private String msgError; public CommonException() { super(); } public CommonException(String msgError) { super(msgError); this.msgError = msgError; } /** * @return the msgError */ public String getMsgError() { return msgError; } /** * @param msgError * the msgError to set */ public void setMsgError(String msgError) { this.msgError = msgError; } } <file_sep>package co.com.diccionario.mongodb.iface; import co.com.diccionario.document.Ciudad; public interface CiudadIface { Ciudad findLastId(); } <file_sep>package co.com.diccionario.mongodb.iface; import java.util.List; import co.com.diccionario.document.Palabras; import co.com.diccionario.document.Sinonimos; public interface SinonimosIface { public List<Sinonimos> findByPaisOrigenAndPaisDestinoAndTerminoAndSinonimosIn(String paisOrigen, String paisDestino, String termino, Palabras palabraSinonimo); } <file_sep>package co.com.diccionario.mongodb.iface; import co.com.diccionario.document.Paises; public interface PaisesIface { Paises findLastId(); } <file_sep>package co.com.diccionario.negocio.iface; import co.com.diccionario.dto.ParametrosRegistroTermino; import co.com.diccionario.dto.SinonimosDTO; public interface GestionarRegistroPalabrasIface { public SinonimosDTO actualizarSinonimos(SinonimosDTO sinonimosDTO); public SinonimosDTO actualizarCalificacionSinonimos(SinonimosDTO sinonimosDTO); public SinonimosDTO actualizarCalificacionOraciones(SinonimosDTO sinonimosDTO); public void registrarSinonimosPalabrasCompleta(ParametrosRegistroTermino params); public SinonimosDTO actualizarOraciones(SinonimosDTO sinonimosDTO); } <file_sep>package co.com.diccionario.document; public class RutaImagenes { private String rutaImagen; private boolean aprobada; /** * @return the rutaImagen */ public String getRutaImagen() { return rutaImagen; } /** * @param rutaImagen the rutaImagen to set */ public void setRutaImagen(String rutaImagen) { this.rutaImagen = rutaImagen; } /** * @return the aprobada */ public boolean isAprobada() { return aprobada; } /** * @param aprobada the aprobada to set */ public void setAprobada(boolean aprobada) { this.aprobada = aprobada; } } <file_sep>package co.com.diccionario.negocio.cacheable.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import co.com.diccionario.document.Paises; import co.com.diccionario.dto.PaisesDTO; import co.com.diccionario.mapper.PaisesMapper; import co.com.diccionario.mongodb.repository.iface.PaisesRepository; import co.com.diccionario.negocio.cacheable.iface.PaisesCaheableIface; @Service public class PaisesCacheableImpl implements PaisesCaheableIface { @Autowired PaisesRepository paisesRepository; @Override @Cacheable("paises") public List<PaisesDTO> obtenerPaises() { List<Paises> listPaises = paisesRepository.findAll(); if (listPaises != null && !listPaises.isEmpty()) { List<PaisesDTO> listPaisesDTO = PaisesMapper.INSTANCE.paisesToPaisesDTOs(listPaises); return listPaisesDTO; } return null; } } <file_sep>package co.com.diccionario.negocio.impl; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Service; import co.com.diccionario.document.Categoria; import co.com.diccionario.dto.CategoriaDTO; import co.com.diccionario.mapper.CategoriaMapper; import co.com.diccionario.mongodb.iface.CategoriaIface; import co.com.diccionario.mongodb.repository.iface.CategoriaRepository; import co.com.diccionario.negocio.cacheable.iface.CategoriasCacheableIface; import co.com.diccionario.negocio.iface.GestionarBusquedaCategoriaIface; import co.com.diccionario.utilidades.LevenshteinDistance; @Service public class GestionarBusquedaCategoriaImpl implements GestionarBusquedaCategoriaIface { @Autowired CategoriaRepository categoriaRepository; @Autowired CategoriaIface categoriaIface; @Autowired CategoriasCacheableIface categoriasCacheableIface; @Autowired Environment env; @Override public List<CategoriaDTO> obtenerCategorias(String nombre) { List<Categoria> listCategoria = categoriaRepository.findByNombreIgnoreCase(nombre); List<CategoriaDTO> listCatDto; if (listCategoria != null && !listCategoria.isEmpty()) { listCatDto = CategoriaMapper.INSTANCE.categoriasToCategoriaDTOs(listCategoria); return listCatDto; } return null; } @Override public List<CategoriaDTO> obtenerCategoriasAproximado(String nombre) { List<Categoria> listCategoria = categoriaIface.findByNombreLike(nombre); List<CategoriaDTO> listCatDto = new ArrayList<>(); if (listCategoria != null && !listCategoria.isEmpty()) { listCatDto = CategoriaMapper.INSTANCE.categoriasToCategoriaDTOs(listCategoria); } List<CategoriaDTO> listCategoriaAll = categoriasCacheableIface.obtenerCategorias(); String numCoincidencia = env.getProperty("num_coincidencia_palabra"); int numCoinc = 2; if (numCoincidencia != null && !numCoincidencia.trim().isEmpty()) { numCoinc = Integer.parseInt(numCoincidencia); } for (CategoriaDTO categoria : listCategoriaAll) { int distance = LevenshteinDistance.computeLevenshteinDistance(nombre, categoria.getNombre()); if (distance <= numCoinc) { listCatDto.add(categoria); } String[] sWords = categoria.getNombre().split(" "); if (sWords.length > 1) { for (String palabra : sWords) { distance = LevenshteinDistance.computeLevenshteinDistance(nombre, palabra); if (distance <= numCoinc) { if (listCatDto.contains(categoria)) { continue; } listCatDto.add(categoria); } } } sWords = nombre.split(" "); if (sWords.length > 1) { for (String palabra : sWords) { String[] cat = categoria.getNombre().split(" "); boolean validarPalabraAproximada = false; if (cat.length > 1) { validarPalabraAproximada = validarPalabraAproximada(categoria.getNombre(), palabra, numCoinc); } if (validarPalabraAproximada) { if (listCatDto.contains(categoria)) { continue; } listCatDto.add(categoria); } distance = LevenshteinDistance.computeLevenshteinDistance(palabra, categoria.getNombre()); if (distance <= numCoinc) { if (listCatDto.contains(categoria)) { continue; } listCatDto.add(categoria); } } } String sTexto = categoria.getNombre(); int encontro = sTexto.indexOf(nombre); if (encontro == -1) { continue; } if (listCatDto.contains(categoria)) { continue; } if (sTexto.length() > 1) { sTexto = sTexto.substring(sTexto.indexOf(nombre), sTexto.length()); while (sTexto.indexOf(nombre) > -1) { sTexto = sTexto.substring(sTexto.indexOf(nombre), sTexto.length()); if (listCatDto.contains(categoria)) { break; } listCatDto.add(categoria); } } } return listCatDto; } private boolean validarPalabraAproximada(String word, String nombre, int numCoinc) { String[] sWords = word.split(" "); if (sWords.length > 1) { for (String palabra : sWords) { int distance = LevenshteinDistance.computeLevenshteinDistance(nombre, palabra); if (distance <= numCoinc) { return true; } } } return false; } } <file_sep>package co.com.diccionario.mb; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; import javax.faces.context.FacesContext; import javax.faces.event.PhaseId; import org.primefaces.model.DefaultStreamedContent; import org.primefaces.model.StreamedContent; @ManagedBean(name = "imagenes") @RequestScoped public class ImagenesBean { public ImagenesBean() { } public StreamedContent getImage() throws IOException { FacesContext context = FacesContext.getCurrentInstance(); if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) { // So, we're rendering the view. Return a stub StreamedContent so // that it will generate right URL. return new DefaultStreamedContent(); } else { // So, browser is requesting the image. Return a real // StreamedContent with the image bytes. String id = context.getExternalContext().getRequestParameterMap().get("id"); if (id.isEmpty()) { return new DefaultStreamedContent(); } Path path = Paths.get(id); return new DefaultStreamedContent(new ByteArrayInputStream(Files.readAllBytes(path))); } } } <file_sep>package co.com.diccionario.mongodb.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Component; import co.com.diccionario.document.Ciudad; import co.com.diccionario.mongodb.iface.CiudadIface; @Component public class CiudadImpl implements CiudadIface { @Autowired MongoTemplate mongoTemplate; @Override public Ciudad findLastId() { Query query = new Query(); query.with(new Sort(Sort.Direction.DESC, "_id")); query.limit(1); Ciudad ciudad = mongoTemplate.findOne(query, Ciudad.class); return ciudad; } } <file_sep>package co.com.diccionario.negocio.iface; import java.util.List; import co.com.diccionario.dto.CiudadDTO; import co.com.diccionario.dto.DepartamentoDTO; import co.com.diccionario.dto.PaisesDTO; public interface ConsultarCatalogosIface { public List<PaisesDTO> obtenerPaises(String nombre); public List<DepartamentoDTO> obtenerDepartamentos(int idPais); public List<DepartamentoDTO> obtenerDepartamentos(int idPais, String nombre); public List<CiudadDTO> obtenerCiudades(int departamento); public List<CiudadDTO> obtenerCiudades(int departamento, String nombre); } <file_sep>package co.com.diccionario.negocio.cacheable.iface; import java.util.List; import co.com.diccionario.dto.CategoriaDTO; public interface CategoriasCacheableIface { public List<CategoriaDTO> obtenerCategorias(); } <file_sep>package co.com.diccionario.negocio.impl; import java.util.logging.Level; import java.util.logging.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import co.com.diccionario.document.Categoria; import co.com.diccionario.document.Ciudad; import co.com.diccionario.document.Departamento; import co.com.diccionario.document.Paises; import co.com.diccionario.dto.CategoriaDTO; import co.com.diccionario.dto.CiudadDTO; import co.com.diccionario.dto.DepartamentoDTO; import co.com.diccionario.dto.PaisesDTO; import co.com.diccionario.mapper.CategoriaMapper; import co.com.diccionario.mapper.CiudadMapper; import co.com.diccionario.mapper.DepartamentoMapper; import co.com.diccionario.mapper.PaisesMapper; import co.com.diccionario.mongodb.iface.CiudadIface; import co.com.diccionario.mongodb.iface.DepartamentoIface; import co.com.diccionario.mongodb.iface.PaisesIface; import co.com.diccionario.mongodb.repository.iface.CategoriaRepository; import co.com.diccionario.mongodb.repository.iface.CiudadesRepository; import co.com.diccionario.mongodb.repository.iface.DepartamentosRepository; import co.com.diccionario.mongodb.repository.iface.PaisesRepository; import co.com.diccionario.negocio.iface.RegistrarCatalogosIface; import co.com.diccionario.utilidades.CacheUtils; @Service public class RegistrarCatalogosImpl implements RegistrarCatalogosIface { @Autowired PaisesRepository paisesRepository; @Autowired DepartamentosRepository departamentosRepository; @Autowired CiudadesRepository ciudadesRepository; @Autowired CategoriaRepository categoriaRepository; @Autowired PaisesIface paisesIface; @Autowired DepartamentoIface departamentoIface; @Autowired CiudadIface ciudadIface; @Autowired CacheUtils cacheUtils; @Override public void registraPaises(PaisesDTO paisesDTO) { Paises paises = PaisesMapper.INSTANCE.paisDTOToPaises(paisesDTO); /* * se busca el maximo id del documento */ Paises lastPais = paisesIface.findLastId(); if (lastPais == null) { paises.setId(1); } else { paises.setId(lastPais.getId() + 1); } paisesRepository.save(paises); } @Override public void registrarDepartamento(DepartamentoDTO departamentoDTO) { Departamento departamento = DepartamentoMapper.INSTANCE.departamentoDTOToDepartamento(departamentoDTO); /* * se busca el maximo id del documento */ Departamento lastDepa = departamentoIface.findLastId(); if (lastDepa == null) { departamento.setId(1); } else { departamento.setId(lastDepa.getId() + 1); } departamentosRepository.save(departamento); } @Override public void registrarCiudad(CiudadDTO ciudadDTO) { Ciudad ciudad = CiudadMapper.INSTANCE.ciudadDTOToCiudad(ciudadDTO); /* * se busca el maximo id del documento */ Ciudad lastCiudad = ciudadIface.findLastId(); ciudad.setId(lastCiudad.getId() + 1); ciudadesRepository.save(ciudad); } @Override public void registrarCategoria(CategoriaDTO categoriaDTO) { Categoria categoria = CategoriaMapper.INSTANCE.categoriDTOToCategoria(categoriaDTO); categoriaRepository.save(categoria); /* * eliminamos la cache asociada a las categorias */ boolean elimina = cacheUtils.clearCacheFromCacheName("categorias"); if (elimina) { Logger.getAnonymousLogger().log(Level.INFO, "Elimino cache categorias"); } } } <file_sep>package co.com.diccionario.mongodb.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Query; import org.springframework.stereotype.Component; import co.com.diccionario.document.Departamento; import co.com.diccionario.mongodb.iface.DepartamentoIface; @Component public class DepartamentoImpl implements DepartamentoIface { @Autowired MongoTemplate mongoTemplate; @Override public Departamento findLastId() { Query query = new Query(); query.with(new Sort(Sort.Direction.DESC, "_id")); query.limit(1); Departamento departamento = mongoTemplate.findOne(query, Departamento.class); return departamento; } } <file_sep>package co.com.diccionario.mongodb.iface; import co.com.diccionario.document.Departamento; public interface DepartamentoIface { Departamento findLastId(); }
097d1bcb9ffcf253b436bad44129a5a014999947
[ "Java" ]
20
Java
juedizor/diccionario
f7c4ad0f6901abaeb561a4465ebf0577b52bbd3f
21eee2732addf7000bd0801d379c19abf0f1dc47
refs/heads/master
<file_sep># Prettify JSON The program takes a JSON file path and returns a pretty printed output. # Quickstart Input: JSON file path Output: pretty printed JSON Example of script launch on Linux, Python 3.5: ```bash $ python pprint_json.py <path to file> [ { "Cells": { "Address": "улица Академика Павлова, дом 10", "AdmArea": "Западный административный округ", "ClarificationOfWorkingHours": null, "District": "район Кунцево", "IsNetObject": "да", "Name": "<NAME>", "OperatingCompany": "Ароматный Мир", "PublicPhone": [ { "PublicPhone": "(495) 777-51-95" } ], ... ``` # Project Goals The code is written for educational purposes. Training course for web-developers - [DEVMAN.org](https://devman.org) <file_sep>import json import sys def load_data(filepath): with open(filepath, encoding='utf-8') as file_object: return json.load(file_object) def prettify_json(data_from_json): return json.dumps(data_from_json, sort_keys=True, indent=4, ensure_ascii=False) if __name__ == '__main__': try: data_from_json = load_data(sys.argv[1]) print(prettify_json(data_from_json)) except IndexError: sys.exit('File name must be specified on the command line') except ValueError: sys.exit('File must be a json') except FileNotFoundError: sys.exit('No such file or directory')
d420f8e4285a6150136af7ff07d7ef44b429c285
[ "Markdown", "Python" ]
2
Markdown
andsedov/4_json
c4b3b35a989b77deca2f62f61925979978555b09
9c681429de5abeb78ff67e9444ce3b49b3778fd1
refs/heads/master
<file_sep>RPM building script Using guide $1 = target_name.spec $2 = architecture_(x86_64) $3 = target_name example bash build.sh check_linux_interface.pl.spec x86_64 check_linux_interface.pl for debugging use bash -x following dependency should be installed: rpm-build rpmdevtools wget <file_sep>#!/usr/bin/env bash # Prepares sources for RPM installation PATH=$PATH:/usr/local/bin # # Currently Supported Operating Systems: #wor_dir # CentOS 6, 7 # # Defning return code check function check_result() { if [ $1 -ne 0 ]; then echo "Error: $2" exit $1 fi } build_signed_rpm() { SPEC_FILE="$1" TARGET="$2" rpmbuild -bb -v --sign --clean --target ${TARGET} ${WORKING_DIR}/rpmbuild/SPECS/${SPEC_FILE} #rpmbuild -bb -v ${WORKING_DIR}/rpmbuild/SPECS/${SPEC_FILE} #expect -exact "Enter pass phrase: " #send -- "blank\r" #expect eof } ## Giveing name to third positional parameters name of target file we want to be executed $3 targ="$3" version=`date +%Y%m%d` release=`date +%H%M%S` CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" WORKING_DIR=`mktemp -d -p /tmp` check_result $? "Cant create TMP Dir" cd $WORKING_DIR git clone --recursive https://github.com/HariSekhon/nagios-plugins.git > /dev/null 2>&1 check_result $? "Can't cloning from git repo" mkdir rpmbuild check_result $? "Can't creating rpmbuild dir" cd rpmbuild mkdir {BUILD,RPMS,SOURCES,SPECS,SRPMS,tmp} check_result $? "Can't creat rpmbuilding sub dirs" cd ../ mkdir ${WORKING_DIR}/${targ}-${version} check_result $? "Cant create TMP Version Dir" mkdir -p ${CURRENT_DIR}/rpmbuild/SOURCES/ check_result $? "Unable Create Source Folder" mkdir -p ${CURRENT_DIR}/rpmbuild/SPECS/ check_result $? "Unable Create SPECS Folder" cd $CURRENT_DIR #rm -rf nagios-plugins/ #git clone --recursive https://github.com/HariSekhon/nagios-plugins.git > /dev/null 2>&1 #check_result $? "Can't cloning from git repo" ## copping spec files from my repo wget https://raw.githubusercontent.com/Galphaa/xsg-RPM-build/master/file.spec > /dev/null 2>&1 check_result $? "Cant download spec file from my repo" mv file.spec ${targ}.spec check_result $? "Problem with renameing spec file to "$targ"" ## changeed mv to cp cp ${targ}.spec "${WORKING_DIR}"/rpmbuild/SPECS/ check_result $? "Can't moving $targ Spec to rpm/SPEC/ " cp ${targ}.spec ${CURRENT_DIR}/rpmbuild/SPECS/ check_result $? "Unable Copy RPM Config" mkdir -p usr/lib64/nagios/plugins/ check_result $? "Cant creat usr/lib64/nagios/plugins/" mkdir -p /usr/lib64/nagios/plugins/ check_result $? "Can't creat /usr/lib64/nagios/plugins/" cp ${WORKING_DIR}/nagios-plugins/${targ} usr/lib64/nagios/plugins/ check_result $? "Can't coppy ${targ} to usr/lib64/nagios/plugins/" cp ${WORKING_DIR}/nagios-plugins/${targ} /usr/lib64/nagios/plugins/ check_result $? "Cat't coppy ${targ} to /usr/lib64/nagios/plugins/" cp -R usr $WORKING_DIR/${targ}-${version} check_result $? "Can't coppy usr/ to working dir" #cp -R etc $WORKING_DIR/${targ}-${version} cd /usr/lib64/nagios/plugins/ chmod -x ${targ} check_result $? "Can't give execution permision in /usr/lib64/nagios/plugins/" cd - cd usr/lib64/nagios/plugins/ chmod -x ${targ} check_result $? "Can't give execution permision in usr/lib64/nagios/plugins/" cd - cd $WORKING_DIR tar zcvf "${targ}-${version}".tar.gz ${targ}-${version} check_result $? "Problem with compressing Downloaded scpript ("$targ") to tar.gz format" ## changed mv to cp cp "${targ}-${version}.tar.gz" ${CURRENT_DIR}/rpmbuild/SOURCES/ check_result $? "Unable Copy Sources" cp ${CURRENT_DIR}/${targ}.spec ${CURRENT_DIR}/rpmbuild/SPECS/ check_result $? "Unable Copy RPM Config" cd $CURRENT_DIR/rpmbuild mv SOURCES/"${targ}-${version}".tar.gz "${WORKING_DIR}"/rpmbuild/SOURCES/ check_result $? "Problem with moving" echo "Setting versions information in SPEC files" sed -i -- "s/__NAME__/${targ}/g" ${WORKING_DIR}/rpmbuild/SPECS/${targ}.spec sed -i -- "s/__VERSION__/${version}/g" ${WORKING_DIR}/rpmbuild/SPECS/${targ}.spec sed -i -- "s/__RELEASE__/${release}/g" ${WORKING_DIR}/rpmbuild/SPECS/${targ}.spec sed -i -- "s/__NAME__/${targ}/g" ${WORKING_DIR}/rpmbuild/SPECS/${targ}.spec sed -i -- "s|__PATH__|"/usr/lib64/nagios/plugins/${targ}"|g" ${WORKING_DIR}/rpmbuild/SPECS/${targ}.spec cd ~ wget https://raw.githubusercontent.com/Galphaa/xsg-RPM-build/master/_.rpmmacros cp .rpmmacros before_.rpmmacros mv _.rpmmacros .rpmmacros check_result $? "Problem with renameing Downloaded macro form git " sed -i -- "s|__PATH__|${WORKING_DIR}|g" .rpmmacros cd - ## Begining RPM building build_signed_rpm $1 $2 check_result $? "Problem with prmbuild tool. (last section of building of RPM package)" mv ${WORKING_DIR}/rpmbuild/RPMS/x86_64/${targ}-${version}-${release}.x86_64.rpm ${CURRENT_DIR}/build/ check_result $? "Problem with moving RPM package to script file location/build directory)" cd - rm .rpmmacros mv before_.rpmmacros .rpmmacros ## removing garbage and preprearing for new sesion rm -f $CURRENT_DIR/usr/lib64/nagios/plugins/* rm -f $CURRENT_DIR/${targ}.spec rm -f $CURRENT_DIR/rpmbuild/SPECS/* rm -f $CURRENT_DIR/rpmbuild/SOURCES/* echo "Mission Accomplished" <file_sep>#!/usr/bin/env bash # Prepares sources for RPM installation PATH=$PATH:/usr/local/bin # # Currently Supported Operating Systems: # # CentOS 6, 7 # # Defning return code check function check_result() { if [ $1 -ne 0 ]; then echo "Error: $2" exit $1 fi } build_signed_rpm() { SPEC_FILE="$1" TARGET="$2" rpmbuild -bb -v --sign --clean --target ${TARGET} ${WORKING_DIR}/rpmbuild/SPECS/${SPEC_FILE} #rpmbuild -bb -v ${WORKING_DIR}/rpmbuild/SPECS/${SPEC_FILE} #expect -exact "Enter pass phrase: " #send -- "blank\r" #expect eof } targ="$3" version=`date +%Y%m%d` release=`date +%H%M%S` # Creating variable for future changing if needed (Dowloaded hariskon/nagios-plugins reposioty and script we need is located in nagios-plugins dirs nagios_plugins="nagios-plugins" CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" WORKING_DIR=`mktemp -d -p /tmp` check_result $? "Cant create TMP Dir" nagios_plugins=nagios-plugins cd $WORKING_DIR git clone --recursive https://github.com/HariSekhon/nagios-plugins.git > /dev/null 2>&1 check_result $? "Can't cloning from git repo" mkdir rpmbuild check_result $? "Can't creating rpmbuild dir" cd rpmbuild mkdir {BUILD,RPMS,SOURCES,SPECS,SRPMS,tmp} check_result $? "Can't creat rpmbuilding sub dirs" cd ../ mkdir ${WORKING_DIR}/${targ}-${version} check_result $? "Cant create TMP Version Dir" mkdir -p ${CURRENT_DIR}/rpmbuild/SOURCES/ check_result $? "Unable Create Source Folder" mkdir -p ${CURRENT_DIR}/rpmbuild/SPECS/ check_result $? "Unable Create SPECS Folder" cd $CURRENT_DIR ## copping spec files from my repo wget https://raw.githubusercontent.com/Galphaa/xsg-RPM-build/master/file.spec > /dev/null 2>&1 check_result $? "Cant download spec file from my repo" mv file.spec ${targ}.spec check_result $? "Problem with renameing spec file to "$targ"" ## changeed mv to cp cp ${targ}.spec ${WORKING_DIR}/rpmbuild/SPECS/ check_result $? "Can't moving $targ Spec to rpm/SPEC/ " cp ${targ}.spec ${CURRENT_DIR}/rpmbuild/SPECS/ check_result $? "Unable Copy RPM Config" mkdir -p usr/lib64/nagios/plugins/ mkdir -p /usr/lib64/nagios/plugins/ cp ${WORKING_DIR}/${nagios_plugins}/${targ} usr/lib64/nagios/plugins/ cp ${WORKING_DIR}/${nagios_plugins}/${targ} /usr/lib64/nagios/plugins/ cd /usr/lib64/nagios/plugins/"${targ}-$version" chmod -x "${targ}" cd - cd usr/lib64/nagios/plugins/"${targ}-$version" chmod -x "${targ}" cd - cp -R usr $WORKING_DIR/${targ}-${version} #cp -R etc $WORKING_DIR/${targ}-${version} cd $WORKING_DIR tar zcvf "${targ}-${version}".tar.gz ${targ}-${version} check_result $? "Problem with compressing Downloaded scpript ("$targ") to tar.gz format" ## changed mv to cp cp "${targ}-${version}".tar.gz ${CURRENT_DIR}/rpmbuild/SOURCES/ check_result $? "Unable Copy Sources" cp ${CURRENT_DIR}/${targ}.spec ${CURRENT_DIR}/rpmbuild/SPECS/ check_result $? "Unable Copy RPM Config" cd $CURRENT_DIR/rpmbuild cp SOURCES/"${targ}-${version}".tar.gz "${WORKING_DIR}"/rpmbuild/SOURCES/ check_result $? "Problem with moving" echo "Setting versions information in SPEC files" sed -i -- "s/__NAME__/${targ}/g" ${WORKING_DIR}/rpmbuild/SPECS/${targ}.spec sed -i -- "s/__VERSION__/${version}/g" ${WORKING_DIR}/rpmbuild/SPECS/${targ}.spec sed -i -- "s/__RELEASE__/${release}/g" ${WORKING_DIR}/rpmbuild/SPECS/${targ}.spec sed -i -- "s/__NAME__/${targ}/g" ${WORKING_DIR}/rpmbuild/SPECS/${targ}.spec sed -i -- "s|__PATH__|"/usr/lib64/nagios/plugins/${targ}"|g" ${WORKING_DIR}/rpmbuild/SPECS/${targ}.spec ## changing macro to our custom rpmmacros cd ~ wget https://raw.githubusercontent.com/Galphaa/xsg-RPM-build/master/beta_.rpmmacros cp .rpmmacros before_.rpmmacros mv beta_.rpmmacros .rpmmacros sed -i -- "s|__PATH__|${WORKING_DIR}|g" .rpmmacros cd - ## Begining RPM building build_signed_rpm $1 $2 check_result $? "Problem with prmbuild tool. (last section of building of RPM package)" ##moving RPM build file to script location mv ${WORKING_DIR}/rpmbuild/RPMS/x86_64/${targ}-${version}-${release}.x86_64.rpm ${CURRENT_DIR}/build/ check_result $? "Problem with moving RPM package to script file location/build directory)" #returning old macro cd - rm .rpmmacros mv before_.rpmmacros .rpmmacros ## removing garbage and preprearing for new sesion rm -rf $CURRENT_DIR/usr/* rm -rf $CURRENT_DIR/usr/lib64/nagios/plugins/* rm -f $CURRENT_DIR/${targ}.spec rm -f $CURRENT_DIR/rpmbuild/SPECS/* rm -f $CURRENT_DIR/rpmbuild/SOURCES/* echo "Mission Accomplished"
f1f465b750985276b0728b5fc37b4c92e8b0f366
[ "Markdown", "Shell" ]
3
Markdown
Galphaa/xsg-RPM-build
3ea841f553ae68ad67197bcf438557c883acf6d2
ce408018c5ee47ce3781daeea1f9a8ed9f33dee5
refs/heads/master
<file_sep>package com.quangcv.dwre.no3_hide_view_ids; import android.content.res.Resources; import android.util.Log; /** * Created by QuangCV on 06-Sep-2019 **/ public class CustomResources extends Resources { private String TAG = CustomResources.class.getSimpleName(); public CustomResources(Resources res) { super(res.getAssets(), res.getDisplayMetrics(), res.getConfiguration()); } // works on uiautomatorviewer @Override public String getResourceName(int resid) throws NotFoundException { Log.e(TAG, "getResourceName: " + super.getResourceName(resid)); return "(name removed)"; } // works on "adb shell dumpsys activity top" @Override public String getResourceEntryName(int resid) throws NotFoundException { Log.e(TAG, "getResourceEntryName: " + super.getResourceEntryName(resid)); return "(name removed)"; } }<file_sep>package com.quangcv.dwre.no2_signature_recognition; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.pm.PackageManager; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.quangcv.dwre.R; import java.security.MessageDigest; /** * Created by QuangCV on 11-Sep-2019 **/ public class LoginActivity extends Activity { private String TAG = LoginActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); final Button button = findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Context ctx = LoginActivity.this; final ProgressDialog dlg = new ProgressDialog(ctx); dlg.setMessage("Connecting..."); dlg.show(); button.postDelayed(new Runnable() { @Override public void run() { String origin = "70:2F:87:6A:67:48:0A:C1:7A:16:81:14:97:49:34:52:26:31:94:2D"; String current = getSignature(ctx, "SHA1"); if (origin.equals(current)) { Toast.makeText(ctx, "Success", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(ctx, "Failure", Toast.LENGTH_SHORT).show(); } TextView note = findViewById(R.id.note); note.setText(current); Log.e(TAG, current); dlg.dismiss(); } }, 1000); } }); } private String getSignature(Context c, String algorithm) { try { byte[] signature = c.getPackageManager() .getPackageInfo(getPackageName(), PackageManager.GET_SIGNATURES) .signatures[0] .toByteArray(); byte[] array = MessageDigest.getInstance(algorithm).digest(signature); StringBuilder builder = new StringBuilder(); for (int i = 0; i < array.length; i++) { String s = Integer.toHexString(0xFF & array[i]); if (s.length() == 1) { builder.append("0"); } builder.append(s); if (i != array.length - 1) { builder.append(':'); } } return builder.toString().toUpperCase(); } catch (Exception e) { e.printStackTrace(); return null; } } }<file_sep>package com.quangcv.dwre.no3_hide_view_ids; import android.content.Context; import android.content.ContextWrapper; import android.content.res.Resources; /** * Created by QuangCV on 06-Sep-2019 **/ public class CustomContextWrapper extends ContextWrapper { private CustomResources resources; public CustomContextWrapper(Context base) { super(base); resources = new CustomResources(base.getResources()); } @Override public Resources getResources() { return resources; } }<file_sep>package com.quangcv.dwre.no3_hide_view_ids; import android.app.Activity; import android.content.Context; import android.os.Build; import android.os.Bundle; import android.view.Gravity; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.TextView; import com.quangcv.dwre.R; /** * Created by QuangCV on 06-Sep-2019 **/ public class SampleActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MyTextView v = new MyTextView(this); v.setId(R.id.my_text_view); v.setGravity(Gravity.CENTER); v.setText("Hello World!"); setContentView(v); } public class MyTextView extends TextView { public MyTextView(Context context) { super(context); } // works on uiautomatorviewer @Override public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(info); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { info.setViewIdResourceName("(name removed)"); } } } // works on uiautomatorviewer // @Override // protected void attachBaseContext(Context newBase) { // super.attachBaseContext(new CustomContextWrapper(newBase)); // } }
0be2bed83128d5dd2c4257ed686481a448cb0eb2
[ "Java" ]
4
Java
catvinhquang/deal-with-reverse-engineering
877f83acee5308336aa041794b82b824d4aa6f30
8584bb1312be247cf947d74bd2d470ab7b8c896f
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Model; using DAO; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace BancoAPI.Controllers { [Route("fapen/produto")] [ApiController] public class ProdutoController : ControllerBase { // GET: api/<ProdutoController> [HttpGet] public List<Produto> Get() { ProdutoDAO objProdDAO = new ProdutoDAO(); List<Produto> lstProduto = objProdDAO.GetProdutos(); return lstProduto.OrderBy(p => p.Nome_Prod).ToList(); } [HttpGet] [Route("QtdeProduto")] public double QtdeProduto() { ProdutoDAO objProdDAO = new ProdutoDAO(); List<Produto> lstProduto = objProdDAO.GetProdutos(); return lstProduto.Count(); } [HttpGet] [Route("MediaValorProduto")] public double MediaValorProduto() { ProdutoDAO objProdDAO = new ProdutoDAO(); List<Produto> lstProduto = objProdDAO.GetProdutos(); return lstProduto.Average(p => p.Val_Total); } [HttpGet] [Route("ValorTotalEstoque")] public double ValorTotalEstoque() { ProdutoDAO objProdDAO = new ProdutoDAO(); List<Produto> lstProduto = objProdDAO.GetProdutos(); return lstProduto.Sum(p => p.Val_Total); } [HttpGet] [Route("ProdutoCaro")] public double ProdutoCaro() { ProdutoDAO objProdDAO = new ProdutoDAO(); List<Produto> lstProduto = objProdDAO.GetProdutos(); return lstProduto.Max(p => p.Val_UnitProd); } [HttpGet] [Route("ProdutoBarato")] public double ProdutoBarato() { ProdutoDAO objProdDAO = new ProdutoDAO(); List<Produto> lstProduto = objProdDAO.GetProdutos(); return lstProduto.Min(p => p.Val_UnitProd); } [HttpGet] [Route("FirstOrDefault")] public Produto FirstOrDefault() { ProdutoDAO objProdDAO = new ProdutoDAO(); List<Produto> lstProduto = objProdDAO.GetProdutos(); return lstProduto.FirstOrDefault(p=> p.Cod_TipoProd == 1); } // GET api/<ProdutoController>/5 [HttpGet("{codProd}")] public Produto Get(int codProd) { ProdutoDAO objProdDAO = new ProdutoDAO(); List<Produto> lstProduto = objProdDAO.GetProdutos(); List<Produto> lstPRodWhere = lstProduto.Where(p => p.Cod_Prod == codProd).Take(1).ToList(); Produto prd = lstPRodWhere.FirstOrDefault(); //Produto prd = objProdDAO.GetProdutoByCode(codProd); return prd; } // POST api/<ProdutoController> [HttpPost] public void Post([FromBody] string value) { } // PUT api/<ProdutoController>/5 [HttpPut] public ActionResult<IEnumerable<string>> Put([FromBody] Produto prd) { int retorno = 0; if (prd.Cod_Prod < 1) { ProdutoDAO objDAO = new ProdutoDAO(); retorno = objDAO.InserirProduto(prd); } else { ProdutoDAO objDAO = new ProdutoDAO(); retorno = objDAO.AtualizarProduto(prd); } if (retorno == 1) { return new string[] { "Produto Inserido ou atualizado com sucesso!" }; } return new string[] { "Produto Não inserido ou atualizado!" }; } [HttpDelete("{codProduto}")] public ActionResult<IEnumerable<string>> Delete(int codProduto) { int retorno = 0; if (codProduto == 0) { return new string[] { "Produto invalido!" }; } else { ProdutoDAO prdDao = new ProdutoDAO(); retorno = prdDao.ExcluirProduto(codProduto); if (retorno == 1) { return new string[] { "Produto excluido!" }; } } return new string[] { string.Empty }; } } } <file_sep>using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DAO; using Model; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace BancoAPI.Controllers { [Route("fapen/login")] [ApiController] public class LoginController : ControllerBase { [HttpGet("{login}")] public Login Get(string login) { LoginDAO objDao = new LoginDAO(); Login lg = new Login(); lg.strLogin = login; return objDao.LogarSemSenha(lg); ; } // POST api/<LoginController> [HttpPost] public Login Post([FromBody] Login value) { Login retorno = null; if(value != null) { LoginDAO objDao = new LoginDAO(); retorno = objDao.Logar(value); } return retorno; } [HttpPut] public ActionResult<IEnumerable<string>> Put([FromBody] Login value) { int retorno = 0; LoginDAO objDao = new LoginDAO(); Login lg = objDao.RetornarLoginPorCliente(value); if (lg == null) { retorno = objDao.CadastrarLogin(value); } else { retorno = objDao.AtualizarSenha(value); } if (retorno == 1) { return new string[] { "Login Inserido ou atualizado com sucesso!" }; } return new string[] { "Login Não inserido ou atualizado!" }; } [HttpDelete("{login}")] public ActionResult<IEnumerable<string>> Delete(string login) { int retorno = 0; if (string.IsNullOrEmpty(login)) { return new string[] { "Login invalido!" }; } else { LoginDAO objDAO = new LoginDAO(); Login lg = new Login(); lg.strLogin = login; retorno = objDAO.ExcluirLogin(lg); if (retorno == 1) { return new string[] { "Login excluido com sucesso!" }; } } return new string[] { string.Empty }; } } } <file_sep>using System; using System.Collections.Generic; using Model; using System.Data; using System.Data.SqlClient; using System.Text; namespace DAO { public class ProdutoDAO:DAO { public List<Produto> GetProdutos() { List<Produto> lstProduto = new List<Produto>(); using (SqlConnection conexao = new SqlConnection(connectionString)) { StringBuilder sbComando = new StringBuilder(); sbComando.AppendLine("SELECT Cod_Prod"); sbComando.AppendLine(",Cod_TipoProd"); sbComando.AppendLine(",Nome_Prod"); sbComando.AppendLine(",Qtd_EstqProd"); sbComando.AppendLine(",Val_UnitProd"); sbComando.AppendLine(",Val_Total"); sbComando.AppendLine(" FROM Produto"); SqlCommand cmd = new SqlCommand(sbComando.ToString(), conexao); cmd.CommandType = CommandType.Text; try { conexao.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Produto prd = new Produto(); int iConvert = 0; double dConvert = 0; if (reader["Cod_Prod"] != null) { prd.Cod_Prod = int.TryParse(reader["Cod_Prod"].ToString(), out iConvert) ? Convert.ToInt32(reader["Cod_Prod"]) : 0; } if (reader["Cod_TipoProd"] != null) { prd.Cod_TipoProd = int.TryParse(reader["Cod_TipoProd"].ToString(), out iConvert) ? Convert.ToInt32(reader["Cod_TipoProd"]) : 0; } prd.Nome_Prod = reader["Nome_Prod"] != null ? reader["Nome_Prod"].ToString() : "Produto inexistente"; if (reader["Qtd_EstqProd"] != null) { prd.Qtd_EstqProd = int.TryParse(reader["Qtd_EstqProd"].ToString(), out iConvert) ? Convert.ToInt32(reader["Qtd_EstqProd"]) : 0; } if (reader["Val_UnitProd"] != null) { prd.Val_UnitProd = double.TryParse(reader["Val_UnitProd"].ToString(), out dConvert) ? Convert.ToDouble(reader["Val_UnitProd"]) : 0; } if (reader["Val_Total"] != null) { prd.Val_Total = double.TryParse(reader["Val_Total"].ToString(), out dConvert) ? Convert.ToDouble(reader["Val_Total"]) : 0; } lstProduto.Add(prd); } reader.Close(); } catch (SqlException ex) { throw ex; } catch (Exception ex) { throw ex; } finally { conexao.Close(); } } return lstProduto; } public Produto GetProdutoByCode(int CodProd) { Produto prod = new Produto(); using (SqlConnection conexao = new SqlConnection(connectionString)) { StringBuilder sbComando = new StringBuilder(); sbComando.AppendLine("SELECT Cod_Prod"); sbComando.AppendLine(",Cod_TipoProd"); sbComando.AppendLine(",Nome_Prod"); sbComando.AppendLine(",Qtd_EstqProd"); sbComando.AppendLine(",Val_UnitProd"); sbComando.AppendLine(",Val_Total"); sbComando.AppendLine(" FROM Produto"); sbComando.AppendLine(" WHERE Cod_Prod = " + CodProd); SqlCommand cmd = new SqlCommand(sbComando.ToString(), conexao); cmd.CommandType = CommandType.Text; try { conexao.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { int iConvert = 0; double dConvert = 0; if (reader["Cod_Prod"] != null) { prod.Cod_Prod = int.TryParse(reader["Cod_Prod"].ToString(), out iConvert) ? Convert.ToInt32(reader["Cod_Prod"]) : 0; } if (reader["Cod_TipoProd"] != null) { prod.Cod_TipoProd = int.TryParse(reader["Cod_TipoProd"].ToString(), out iConvert) ? Convert.ToInt32(reader["Cod_TipoProd"]) : 0; } prod.Nome_Prod = reader["Nome_Prod"] != null ? reader["Nome_Prod"].ToString() : "Produto inexistente"; if (reader["Qtd_EstqProd"] != null) { prod.Qtd_EstqProd = int.TryParse(reader["Qtd_EstqProd"].ToString(), out iConvert) ? Convert.ToInt32(reader["Qtd_EstqProd"]) : 0; } if (reader["Val_UnitProd"] != null) { prod.Val_UnitProd = double.TryParse(reader["Val_UnitProd"].ToString(), out dConvert) ? Convert.ToDouble(reader["Val_UnitProd"]) : 0; } if (reader["Val_Total"] != null) { prod.Val_Total = double.TryParse(reader["Val_Total"].ToString(), out dConvert) ? Convert.ToDouble(reader["Val_Total"]) : 0; } } reader.Close(); } catch (SqlException ex) { throw ex; } catch (Exception ex) { throw ex; } finally { conexao.Close(); } } return prod; } public int InserirProduto(Produto prd) { int retorno = 0; using (SqlConnection con = new SqlConnection(connectionString)) { StringBuilder sbComandoSql = new StringBuilder(); sbComandoSql.AppendLine(" INSERT INTO Produto("); sbComandoSql.AppendLine("Cod_TipoProd"); sbComandoSql.AppendLine(",Nome_Prod"); sbComandoSql.AppendLine(",Qtd_EstqProd"); sbComandoSql.AppendLine(",Val_UnitProd"); sbComandoSql.AppendLine(")"); sbComandoSql.AppendLine("VALUES("); sbComandoSql.AppendLine(" @Cod_TipoProd"); sbComandoSql.AppendLine(" ,@Nome_Prod"); sbComandoSql.AppendLine(" ,@Qtd_EstqProd"); sbComandoSql.AppendLine(" ,@Val_UnitProd "); sbComandoSql.AppendLine(")"); SqlCommand cmd = new SqlCommand(sbComandoSql.ToString(), con); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@Cod_TipoProd", prd.Cod_TipoProd); cmd.Parameters.AddWithValue("@Nome_Prod", prd.Nome_Prod); cmd.Parameters.AddWithValue("@Qtd_EstqProd", prd.Qtd_EstqProd); cmd.Parameters.AddWithValue("@Val_UnitProd", prd.Val_UnitProd); try { con.Open(); retorno = cmd.ExecuteNonQuery(); } catch (SqlException ex) { throw ex; } catch (Exception ex) { throw ex; } finally { con.Close(); } } return retorno; } public int AtualizarProduto(Produto prd) { int retorno = 0; using (SqlConnection con = new SqlConnection(connectionString)) { StringBuilder sbComandoSql = new StringBuilder(); sbComandoSql.AppendLine(" UPDATE Produto SET"); sbComandoSql.AppendLine("Cod_TipoProd = @Cod_TipoProd"); sbComandoSql.AppendLine(",Nome_Prod = @Nome_Prod"); sbComandoSql.AppendLine(",Qtd_EstqProd = @Qtd_EstqProd"); sbComandoSql.AppendLine(",Val_UnitProd = @Val_UnitProd"); sbComandoSql.AppendLine(" WHERE Cod_Prod = @Cod_Prod"); SqlCommand cmd = new SqlCommand(sbComandoSql.ToString(), con); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@Cod_TipoProd", prd.Cod_TipoProd); cmd.Parameters.AddWithValue("@Nome_Prod", prd.Nome_Prod); cmd.Parameters.AddWithValue("@Qtd_EstqProd", prd.Qtd_EstqProd); cmd.Parameters.AddWithValue("@Val_UnitProd", prd.Val_UnitProd); cmd.Parameters.AddWithValue("@Cod_Prod", prd.Cod_Prod); try { con.Open(); retorno = cmd.ExecuteNonQuery(); } catch (SqlException ex) { throw ex; } catch (Exception ex) { throw ex; } finally { con.Close(); } } return retorno; } public int ExcluirProduto(int Cod_Produto) { int retorno = 0; using (SqlConnection con = new SqlConnection(connectionString)) { StringBuilder sbComandoSql = new StringBuilder(); sbComandoSql.AppendLine(" DELETE FROM Produto"); sbComandoSql.AppendLine(" WHERE Cod_Prod = @Cod_Prod"); SqlCommand cmd = new SqlCommand(sbComandoSql.ToString(), con); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@Cod_Prod", Cod_Produto); try { con.Open(); retorno = cmd.ExecuteNonQuery(); } catch (SqlException ex) { throw ex; } catch (Exception ex) { throw ex; } finally { con.Close(); } } return retorno; } } } <file_sep>using System; using System.Net; using System.Net.Http; using System.IO; using System.Net.Http.Formatting; namespace TesteAPIBanco { class Program { static void Main(string[] args) { InserirProduto(); // AtualizarProduto(); //ExcluirProduto(); Console.ReadLine(); } static void InserirProduto() { using (var client = new HttpClient()) { Produto prd = new Produto { CodTipoProd = 1, NomeProd = "Microondas", QtdEstqProd = 4, ValUnitProd = 500 }; client.BaseAddress = new Uri("https://localhost:44366/fapen/"); var response = client.PutAsJsonAsync("produto", prd).Result; if (response.IsSuccessStatusCode) { Console.WriteLine("Sucesso ! " + response.ToString()); } else Console.Write("Erro ao inserir produto: " + response.ToString()); } } static void AtualizarProduto() { using (var client = new HttpClient()) { Produto prd = new Produto { CodProd = 11, CodTipoProd = 1, NomeProd = "Microondas Moderno", QtdEstqProd = 10, ValUnitProd = 550 }; client.BaseAddress = new Uri("https://localhost:44366/fapen/"); var response = client.PutAsJsonAsync("produto", prd).Result; if (response.IsSuccessStatusCode) { Console.WriteLine("Sucesso ao atualizar produto! " + response.ToString()); } else Console.Write("Erro ao atualizar produto: " + response.ToString()); } } static void ExcluirProduto() { int idProduto = 11; using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://localhost:44366/fapen/"); var response = client.DeleteAsync("produto/" + idProduto).Result; if (response.IsSuccessStatusCode) { Console.WriteLine("Sucesso ao excluir produto! " + response.ToString()); } else Console.Write("Erro ao excluir produto: " + response.ToString()); } } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; using Model; using System.Linq; namespace DAO { public class LoginDAO : DAO { public Login Logar(Login lg) { Login objLoginRetorno = new Login(); List<Login> lslLogin = new List<Login>(); SqlConnection conn = new SqlConnection(this.connectionString); StringBuilder sbComando = new StringBuilder(); sbComando.AppendLine("SELECT lg.login"); sbComando.AppendLine(" ,lg.senha"); sbComando.AppendLine(" ,cli.Cod_Cli"); sbComando.AppendLine(" ,cli.Nome_Cli "); sbComando.AppendLine(" ,cli.Data_CadCli"); sbComando.AppendLine(" ,cli.Renda_Cli"); sbComando.AppendLine(" ,cli.Sexo_Cli"); sbComando.AppendLine(" ,cli.Cod_TipoCli"); sbComando.AppendLine(" ,tp.Nome_TipoCli"); sbComando.AppendLine("FROM Login lg"); sbComando.AppendLine("INNER JOIN Cliente cli on cli.Cod_Cli = lg.Cod_Cli"); sbComando.AppendLine("INNER JOIN TipoCli tp on tp.Cod_TipoCli = cli.Cod_TipoCli"); sbComando.AppendLine("WHERE login = '" + lg.strLogin + "'"); sbComando.AppendLine("AND senha = '" + lg.Senha + "'"); SqlCommand objCmd = new SqlCommand(sbComando.ToString(), conn); objCmd.CommandType = CommandType.Text; try { if (conn.State == ConnectionState.Closed) { conn.Open(); SqlDataReader sr = objCmd.ExecuteReader(); while (sr.Read()) { Login objLogin = new Login(); objLogin.Cliente = new Cliente(); objLogin.Cliente.TipoCli = new TipoCliente(); int iConvert = 0; double dConvert = 0; DateTime dtConvert = DateTime.MinValue; if (sr["login"] != null) { objLogin.strLogin = sr["login"].ToString(); } if (sr["senha"] != null) { objLogin.Senha = sr["senha"].ToString(); } if (sr["Cod_Cli"] != null) { objLogin.Cliente.Cod_Cli = int.TryParse(sr["Cod_Cli"].ToString(), out iConvert) ? iConvert : 0; } if (sr["Nome_TipoCli"] != null) { objLogin.Cliente.TipoCli.Nome_TipoCli = sr["Nome_TipoCli"].ToString(); } if (sr["Data_CadCli"] != null) { objLogin.Cliente.Data_CadCli = DateTime.TryParse(sr["Data_CadCli"].ToString(), out dtConvert) ? dtConvert : DateTime.MaxValue; } if (sr["Renda_Cli"] != null) { objLogin.Cliente.Renda_Cli = double.TryParse(sr["Renda_Cli"].ToString(), out dConvert) ? dConvert : 0; } if (sr["Sexo_Cli"] != null) { objLogin.Cliente.Sexo_Cli = sr["Sexo_Cli"].ToString(); } if (sr["Cod_TipoCli"] != null) { objLogin.Cliente.TipoCli.Cod_TipoCli = int.TryParse(sr["Cod_TipoCli"].ToString(), out iConvert) ? iConvert : 0; } lslLogin.Add(objLogin); } objLoginRetorno = lslLogin.FirstOrDefault(); } } catch (SqlException sqlEx) { throw sqlEx; } catch (Exception ex) { throw ex; } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } } return objLoginRetorno; } public Login RetornarLoginPorCliente(Login lg) { Login objLoginRetorno = new Login(); List<Login> lslLogin = new List<Login>(); SqlConnection conn = new SqlConnection(this.connectionString); StringBuilder sbComando = new StringBuilder(); sbComando.AppendLine("SELECT lg.login"); sbComando.AppendLine(" ,lg.senha"); sbComando.AppendLine(" ,cli.Cod_Cli"); sbComando.AppendLine(" ,cli.Nome_Cli "); sbComando.AppendLine(" ,cli.Data_CadCli"); sbComando.AppendLine(" ,cli.Renda_Cli"); sbComando.AppendLine(" ,cli.Sexo_Cli"); sbComando.AppendLine(" ,cli.Cod_TipoCli"); sbComando.AppendLine(" ,tp.Nome_TipoCli"); sbComando.AppendLine("FROM Login lg"); sbComando.AppendLine("INNER JOIN Cliente cli on cli.Cod_Cli = lg.Cod_Cli"); sbComando.AppendLine("INNER JOIN TipoCli tp on tp.Cod_TipoCli = cli.Cod_TipoCli"); sbComando.AppendLine("WHERE lg.Cod_Cli = " + lg.Cliente.Cod_Cli ); SqlCommand objCmd = new SqlCommand(sbComando.ToString(), conn); objCmd.CommandType = CommandType.Text; try { if (conn.State == ConnectionState.Closed) { conn.Open(); SqlDataReader sr = objCmd.ExecuteReader(); while (sr.Read()) { Login objLogin = new Login(); objLogin.Cliente = new Cliente(); objLogin.Cliente.TipoCli = new TipoCliente(); int iConvert = 0; double dConvert = 0; DateTime dtConvert = DateTime.MinValue; if (sr["login"] != null) { objLogin.strLogin = sr["login"].ToString(); } if (sr["senha"] != null) { objLogin.Senha = sr["senha"].ToString(); } if (sr["Cod_Cli"] != null) { objLogin.Cliente.Cod_Cli = int.TryParse(sr["Cod_Cli"].ToString(), out iConvert) ? iConvert : 0; } if (sr["Nome_TipoCli"] != null) { objLogin.Cliente.TipoCli.Nome_TipoCli = sr["Nome_TipoCli"].ToString(); } if (sr["Data_CadCli"] != null) { objLogin.Cliente.Data_CadCli = DateTime.TryParse(sr["Data_CadCli"].ToString(), out dtConvert) ? dtConvert : DateTime.MaxValue; } if (sr["Renda_Cli"] != null) { objLogin.Cliente.Renda_Cli = double.TryParse(sr["Renda_Cli"].ToString(), out dConvert) ? dConvert : 0; } if (sr["Sexo_Cli"] != null) { objLogin.Cliente.Sexo_Cli = sr["Sexo_Cli"].ToString(); } if (sr["Cod_TipoCli"] != null) { objLogin.Cliente.TipoCli.Cod_TipoCli = int.TryParse(sr["Cod_TipoCli"].ToString(), out iConvert) ? iConvert : 0; } lslLogin.Add(objLogin); } objLoginRetorno = lslLogin.FirstOrDefault(); } } catch (SqlException sqlEx) { throw sqlEx; } catch (Exception ex) { throw ex; } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } } return objLoginRetorno; } public Login LogarSemSenha(Login lg) { Login objLoginRetorno = new Login(); List<Login> lslLogin = new List<Login>(); SqlConnection conn = new SqlConnection(this.connectionString); StringBuilder sbComando = new StringBuilder(); sbComando.AppendLine("SELECT lg.login"); sbComando.AppendLine(" ,lg.senha"); sbComando.AppendLine(" ,cli.Cod_Cli"); sbComando.AppendLine(" ,cli.Nome_Cli "); sbComando.AppendLine(" ,cli.Data_CadCli"); sbComando.AppendLine(" ,cli.Renda_Cli"); sbComando.AppendLine(" ,cli.Sexo_Cli"); sbComando.AppendLine(" ,cli.Cod_TipoCli"); sbComando.AppendLine(" ,tp.Nome_TipoCli"); sbComando.AppendLine("FROM Login lg"); sbComando.AppendLine("INNER JOIN Cliente cli on cli.Cod_Cli = lg.Cod_Cli"); sbComando.AppendLine("INNER JOIN TipoCli tp on tp.Cod_TipoCli = cli.Cod_TipoCli"); sbComando.AppendLine("WHERE login = '" + lg.strLogin + "'"); SqlCommand objCmd = new SqlCommand(sbComando.ToString(), conn); objCmd.CommandType = CommandType.Text; try { if (conn.State == ConnectionState.Closed) { conn.Open(); SqlDataReader sr = objCmd.ExecuteReader(); while (sr.Read()) { Login objLogin = new Login(); objLogin.Cliente = new Cliente(); objLogin.Cliente.TipoCli = new TipoCliente(); int iConvert = 0; double dConvert = 0; DateTime dtConvert = DateTime.MinValue; if (sr["login"] != null) { objLogin.strLogin = sr["login"].ToString(); } if (sr["senha"] != null) { objLogin.Senha = sr["senha"].ToString(); } if (sr["Cod_Cli"] != null) { objLogin.Cliente.Cod_Cli = int.TryParse(sr["Cod_Cli"].ToString(), out iConvert) ? iConvert : 0; } if (sr["Nome_TipoCli"] != null) { objLogin.Cliente.TipoCli.Nome_TipoCli = sr["Nome_TipoCli"].ToString(); } if (sr["Data_CadCli"] != null) { objLogin.Cliente.Data_CadCli = DateTime.TryParse(sr["Data_CadCli"].ToString(), out dtConvert) ? dtConvert : DateTime.MaxValue; } if (sr["Renda_Cli"] != null) { objLogin.Cliente.Renda_Cli = double.TryParse(sr["Renda_Cli"].ToString(), out dConvert) ? dConvert : 0; } if (sr["Sexo_Cli"] != null) { objLogin.Cliente.Sexo_Cli = sr["Sexo_Cli"].ToString(); } if (sr["Cod_TipoCli"] != null) { objLogin.Cliente.TipoCli.Cod_TipoCli = int.TryParse(sr["Cod_TipoCli"].ToString(), out iConvert) ? iConvert : 0; } lslLogin.Add(objLogin); } objLoginRetorno = lslLogin.FirstOrDefault(); } } catch (SqlException sqlEx) { throw sqlEx; } catch (Exception ex) { throw ex; } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } } return objLoginRetorno; } public int CadastrarLogin(Login lg) { SqlConnection conn = new SqlConnection(this.connectionString); int retorno = 0; StringBuilder sbComando = new StringBuilder(); sbComando.AppendLine("INSERT INTO LOGIN ("); sbComando.AppendLine(" Cod_Cli"); sbComando.AppendLine(" ,login"); sbComando.AppendLine(" ,senha"); sbComando.AppendLine(" )"); sbComando.AppendLine("VALUES ("); sbComando.AppendLine(" @Cod_Cli"); sbComando.AppendLine(" ,@login"); sbComando.AppendLine(" ,@login"); sbComando.AppendLine(" )"); SqlCommand cmd = new SqlCommand(sbComando.ToString(), conn); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@Cod_Cli", lg.Cliente.Cod_Cli); cmd.Parameters.AddWithValue("@login", lg.strLogin); cmd.Parameters.AddWithValue("@login", lg.Senha); try { if (conn.State == ConnectionState.Closed) { conn.Open(); retorno = cmd.ExecuteNonQuery(); } } catch (SqlException sqlEx) { throw sqlEx; } catch (Exception ex) { throw ex; } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } } return retorno; } public int AtualizarSenha(Login lg) { SqlConnection conn = new SqlConnection(this.connectionString); int retorno = 0; StringBuilder sbComando = new StringBuilder(); sbComando.AppendLine("UPDATE Login "); sbComando.AppendLine(" SET "); sbComando.AppendLine(" senha = @senha"); sbComando.AppendLine("WHERE login = @login "); SqlCommand cmd = new SqlCommand(sbComando.ToString(), conn); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@login", lg.strLogin); cmd.Parameters.AddWithValue("@senha", lg.Senha); try { if (conn.State == ConnectionState.Closed) { conn.Open(); retorno = cmd.ExecuteNonQuery(); } } catch (SqlException sqlEx) { throw sqlEx; } catch (Exception ex) { throw ex; } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } } return retorno; } public int ExcluirLogin(Login lg) { SqlConnection conn = new SqlConnection(this.connectionString); int retorno = 0; StringBuilder sbComando = new StringBuilder(); sbComando.AppendLine("DELETE FROM LOGIN "); sbComando.AppendLine("WHERE login = @login "); SqlCommand cmd = new SqlCommand(sbComando.ToString(), conn); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@login", lg.strLogin); try { if (conn.State == ConnectionState.Closed) { conn.Open(); retorno = cmd.ExecuteNonQuery(); } } catch (SqlException sqlEx) { throw sqlEx; } catch (Exception ex) { throw ex; } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } } return retorno; } } } <file_sep>using System; namespace Model { public class Produto { public int Cod_Prod { get; set; } public int Cod_TipoProd { get; set; } public string Nome_Prod { get; set; } public int Qtd_EstqProd { get; set; } public double Val_UnitProd { get; set; } public double Val_Total { get; set; } public Produto() { } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace Model { public class TipoCliente { public int Cod_TipoCli { get; set; } public string Nome_TipoCli { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace Model { public class Cliente { public int Cod_Cli { get; set; } public TipoCliente TipoCli { get; set; } public string Nome_Cli { get; set; } public DateTime Data_CadCli { get; set; } public double Renda_Cli { get; set; } public string Sexo_Cli { get; set; } } } <file_sep>using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Model; using DAO; namespace BancoAPI.Controllers { [Route("fapen/cliente")] [ApiController] public class ClienteController : ControllerBase { [HttpGet] public List<Cliente> RetornarClientes() { ClienteDAO objDao = new ClienteDAO(); return objDao.RetornarListaCliente(); } [HttpGet("{codCli}")] public Cliente Details(int codCli) { ClienteDAO clienteDAO = new ClienteDAO(); return clienteDAO.RetornarCliente(codCli); } [HttpPut] public ActionResult<IEnumerable<string>> Put([FromBody] Cliente cli) { int retorno = 0; ClienteDAO clienteDAO = new ClienteDAO(); if (cli.Cod_Cli < 1) { retorno = clienteDAO.CadastrarCliente(cli); } else { retorno = clienteDAO.AtualizarCliente(cli); } if (retorno == 1) { return new string[] { "Cliente Inserido ou atualizado com sucesso!" }; } return new string[] { "Cliente Não inserido ou não atualizado!" }; } [HttpDelete("{codCli}")] public ActionResult<IEnumerable<string>> Delete(int codCli) { int retorno = 0; if (codCli == 0) { return new string[] { "Cliente invalido!" }; } else { ClienteDAO clienteDAO = new ClienteDAO(); Cliente cli = new Cliente(); cli.Cod_Cli = codCli; retorno = clienteDAO.ApagarCliente(cli); if (retorno == 1) { return new string[] { "Cliente excluido com sucesso!" }; } } return new string[] { string.Empty }; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.SqlClient; using Model; using System.Linq; namespace DAO { public class ClienteDAO : DAO { public List<Cliente> RetornarListaCliente() { List<Cliente> lstCliente = new List<Cliente>(); using (SqlConnection conn = new SqlConnection(this.connectionString)) { StringBuilder sbQuery = new StringBuilder(); sbQuery.AppendLine("SELECT cli.Cod_Cli"); sbQuery.AppendLine(",tp.Nome_TipoCli"); sbQuery.AppendLine(",cli.Nome_Cli"); sbQuery.AppendLine(",cli.Data_CadCli"); sbQuery.AppendLine(",cli.Renda_Cli"); sbQuery.AppendLine(",cli.Sexo_Cli"); sbQuery.AppendLine(",cli.Cod_TipoCli"); sbQuery.AppendLine(" FROM Cliente cli"); sbQuery.AppendLine(" INNER JOIN TipoCli tp on tp.Cod_TipoCli = cli.Cod_TipoCli"); SqlCommand objCmd = new SqlCommand(sbQuery.ToString(),conn); objCmd.CommandType = CommandType.Text; try { if (conn.State == ConnectionState.Closed) { conn.Open(); SqlDataReader sdReader = objCmd.ExecuteReader(); while (sdReader.Read()) { Cliente cli = new Cliente(); cli.TipoCli = new TipoCliente(); int iConvert = 0; double dConvert = 0; DateTime dtConvert = DateTime.MinValue; if (sdReader["Cod_Cli"]!= null) { cli.Cod_Cli = int.TryParse(sdReader["Cod_Cli"].ToString(), out iConvert) ? iConvert : 0; } if (sdReader["Nome_TipoCli"]!= null ) { cli.TipoCli.Nome_TipoCli = sdReader["Nome_TipoCli"].ToString(); } if(sdReader["Data_CadCli"] != null) { cli.Data_CadCli = DateTime.TryParse(sdReader["Data_CadCli"].ToString(), out dtConvert) ? dtConvert : DateTime.MaxValue; } if(sdReader["Renda_Cli"] != null) { cli.Renda_Cli = double.TryParse(sdReader["Renda_Cli"].ToString(), out dConvert) ? dConvert : 0; } if (sdReader["Sexo_Cli"] != null) { cli.Sexo_Cli = sdReader["Sexo_Cli"].ToString(); } if (sdReader["Cod_TipoCli"] != null) { cli.TipoCli.Cod_TipoCli = int.TryParse(sdReader["Cod_TipoCli"].ToString(), out iConvert) ? iConvert: 0; } lstCliente.Add(cli); } } } catch(SqlException ex) { throw ex; } catch (Exception ex1) { throw ex1; } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } } } return lstCliente; } public Cliente RetornarCliente(int CodCli) { List<Cliente> lstCli = RetornarListaCliente(); Cliente cli = lstCli.Where(c => c.Cod_Cli == CodCli).FirstOrDefault(); return cli; } public int CadastrarCliente(Cliente cli) { SqlConnection conn = new SqlConnection(this.connectionString); int retorno = 0; StringBuilder sbComando = new StringBuilder(); sbComando.AppendLine("INSERT INTO CLIENTE ("); sbComando.AppendLine(" Cod_Cli"); sbComando.AppendLine(" ,Nome_Cli"); sbComando.AppendLine(" ,Data_CadCli"); sbComando.AppendLine(" ,Renda_Cli"); sbComando.AppendLine(" ,Sexo_Cli"); sbComando.AppendLine(" ,Cod_TipoCli"); sbComando.AppendLine(" )"); sbComando.AppendLine("VALUES ("); sbComando.AppendLine(" @Cod_Cli"); sbComando.AppendLine(" ,@Nome_Cli"); sbComando.AppendLine(" ,@Data_CadCli"); sbComando.AppendLine(" ,@Renda_Cli"); sbComando.AppendLine(" ,@Sexo_Cli"); sbComando.AppendLine(" ,@Cod_TipoCli"); sbComando.AppendLine(" )"); SqlCommand cmd = new SqlCommand(sbComando.ToString(),conn); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@Cod_Cli",cli.Cod_Cli); cmd.Parameters.AddWithValue("@Nome_Cli",cli.Nome_Cli); cmd.Parameters.AddWithValue("@Data_CadCli",cli.Data_CadCli); cmd.Parameters.AddWithValue("@Renda_Cli",cli.Renda_Cli); cmd.Parameters.AddWithValue("@Sexo_Cli",cli.Sexo_Cli); cmd.Parameters.AddWithValue("@Cod_TipoCli", cli.TipoCli.Cod_TipoCli); try { if (conn.State == ConnectionState.Closed) { conn.Open(); retorno = cmd.ExecuteNonQuery(); } } catch(SqlException sqlEx) { throw sqlEx; } catch (Exception ex) { throw ex; } finally { if(conn.State == ConnectionState.Open) { conn.Close(); } } return retorno; } public int AtualizarCliente(Cliente cli) { SqlConnection conn = new SqlConnection(this.connectionString); int retorno = 0; StringBuilder sbComando = new StringBuilder(); sbComando.AppendLine("UPDATE CLIENTE "); sbComando.AppendLine(" SET "); sbComando.AppendLine(" Nome_Cli = @Nome_Cli"); sbComando.AppendLine(" ,Data_CadCli = @Data_CadCli"); sbComando.AppendLine(" ,Renda_Cli = @Renda_Cli"); sbComando.AppendLine(" ,Sexo_Cli = @Sexo_Cli"); sbComando.AppendLine(" ,Cod_TipoCli = @Cod_TipoCli"); sbComando.AppendLine("WHERE Cod_Cli = @Cod_Cli "); SqlCommand cmd = new SqlCommand(sbComando.ToString(), conn); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@Cod_Cli", cli.Cod_Cli); cmd.Parameters.AddWithValue("@Nome_Cli", cli.Nome_Cli); cmd.Parameters.AddWithValue("@Data_CadCli", cli.Data_CadCli); cmd.Parameters.AddWithValue("@Renda_Cli", cli.Renda_Cli); cmd.Parameters.AddWithValue("@Sexo_Cli", cli.Sexo_Cli); cmd.Parameters.AddWithValue("@Cod_TipoCli", cli.TipoCli.Cod_TipoCli); try { if (conn.State == ConnectionState.Closed) { conn.Open(); retorno = cmd.ExecuteNonQuery(); } } catch (SqlException sqlEx) { throw sqlEx; } catch (Exception ex) { throw ex; } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } } return retorno; } public int ApagarCliente(Cliente cli) { SqlConnection conn = new SqlConnection(this.connectionString); int retorno = 0; StringBuilder sbComando = new StringBuilder(); sbComando.AppendLine("DELETE FROM CLIENTE "); sbComando.AppendLine("WHERE Cod_Cli = @Cod_Cli "); SqlCommand cmd = new SqlCommand(sbComando.ToString(),conn); cmd.CommandType = CommandType.Text; cmd.Parameters.AddWithValue("@Cod_Cli", cli.Cod_Cli); try { if (conn.State == ConnectionState.Closed) { conn.Open(); retorno = cmd.ExecuteNonQuery(); } } catch (SqlException sqlEx) { throw sqlEx; } catch (Exception ex) { throw ex; } finally { if (conn.State == ConnectionState.Open) { conn.Close(); } } return retorno; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; namespace Model { public class Login { public Cliente Cliente { get; set; } public string strLogin { get; set; } public string Senha { get; set; } } }
58e7b698e1c2b18eaee9f9314effbd5905f0d134
[ "C#" ]
11
C#
engineerellen/2021S1_3LDSDBA_ADO
128b50c2bb370479571500967bca28408f3f98ca
8f71f18f2843cdb3cc6dc9e8dd4c29aefa953cc2
refs/heads/master
<repo_name>vaibhavkharche/neo-foodorderportal<file_sep>/src/main/java/com/neo/config/ApplicationConfiguration.java package com.neo.config; import javax.sql.DataSource; import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Environment; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan({"com.neo.controller", "com.neo.controller.forms", "com.neo.service"}) @SpringBootApplication @EnableAutoConfiguration public class ApplicationConfiguration { public static void main(String[] args) { SpringApplication.run(ApplicationConfiguration.class, args); } @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver vr = new InternalResourceViewResolver(); vr.setViewClass(JstlView.class); vr.setPrefix("/WEB-INF/jsp/"); vr.setSuffix(".jsp"); return vr; } /*@Bean public DataSource dataSource() { BasicDataSource dataSource = new BasicDataSource(); dataSource.setUrl("jdbc:mysql://localhost:3306/neodb"); dataSource.setUsername("root"); dataSource.setPassword("<PASSWORD>"); dataSource.setDriverClassName("com.mysql.driver.Driver"); dataSource.setInitialSize(10); return dataSource; } @Bean public SessionFactory sessionFactory() { org.hibernate.cfg.Configuration configuration = new org.hibernate.cfg.Configuration() .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect") .setProperty("hibernate.show_sql", "true") .configure(); SessionFactory sf = configuration .buildSessionFactory( new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()) //here you apply the custom dataSource .applySetting(Environment.DATASOURCE, dataSource()) .build()); return sf; }*/ } <file_sep>/src/main/resources/log4j.properties log4j.debug=TRUE log4j.rootLogger=INFO,console,R log4j.logger.com.neo=INFO log4j.appender.R=org.apache.log4j.RollingFileAppender log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.R.File=/home/webwerks/vk-workspace/logs/neofoodportal.log log4j.appender.R.MaxFileSize=1M log4j.appender.R.MaxBackupIndex=5 log4j.appender.R.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.R.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss.SSSS} %p %t %c \u2013 %m%n<file_sep>/src/main/java/com/neo/controller/LoginController.java package com.neo.controller; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.neo.controller.forms.LoginForm; import com.neo.service.OrderService; @Controller("loginController") public class LoginController { // @Autowired // OrderService orderService; private static Logger logger = Logger.getLogger(LoginController.class); @RequestMapping(path = "/login", method = RequestMethod.GET) public String getForm(ModelMap model, Model m) { logger.info("login request is being served through GET mode"); LoginForm f = new LoginForm(); f.setCurretTokenNo("1"); // TODO fetch from orderController f.setUserName("abc"); m.addAttribute("loginForm", f); return "login"; } @RequestMapping(path = "/login", method = RequestMethod.POST) public String doLogin(@ModelAttribute LoginForm data) { // TODO check credentials logger.info("username: " + data.getUserName() + " passwd: " + data.getPassword()); return "welcome"; } }
a1f1338447c493318e38274887eb84edaab37a01
[ "Java", "INI" ]
3
Java
vaibhavkharche/neo-foodorderportal
bf6175f9e64c80cedcb8622c8da06bab9dd521cf
afd814afe08b677acc70b13dc7ceeb3821af4022
refs/heads/master
<file_sep>package com.kamalhakim.strategy; public class SepiaFilter implements Filter { @Override public void filter(String filename) { System.out.println("Applying sepia filter to" + filename); } } <file_sep>package com.kamalhakim; import com.kamalhakim.state.Canvas; import com.kamalhakim.state.BrushTool; import com.kamalhakim.state.SelectionTool; import com.kamalhakim.strategy.ImageStorage; import com.kamalhakim.strategy.JpegCompressor; import com.kamalhakim.strategy.PngCompressor; import com.kamalhakim.strategy.SepiaFilter; public class Main { public static void main(String[] args) { /* State pattern */ Canvas canvas = new Canvas(); canvas.setCurrentTool(new BrushTool()); canvas.mouseDown(); canvas.mouseUp(); canvas.setCurrentTool(new SelectionTool()); canvas.mouseDown(); canvas.mouseUp(); /* State pattern end */ /* Strategy pattern */ ImageStorage imageStoreJpg = new ImageStorage(new JpegCompressor(), new SepiaFilter()); imageStoreJpg.store("bird"); ImageStorage imageStorePng = new ImageStorage(new PngCompressor(), new SepiaFilter()); imageStorePng.store("apple"); /* Stategy pattern end */ } } <file_sep>package com.kamalhakim.strategy; public interface Compressor { public void compress(String filename); } <file_sep>package com.kamalhakim.strategy; public interface Filter { public void filter(String filename); }
624d37fb6a96d537b4d1a1023774e819fa3faf17
[ "Java" ]
4
Java
kamal-hakim/design-patterns
ce930e031ec0e68ec84bd95f7fecb7361cab78a7
6533b22f9e40dc04266f3253d9d49b89c6aa6dc2
refs/heads/main
<repo_name>AnubisN/Aus<file_sep>/meetteam/models.py from django.db import models from pages.img_compression import compressImage class AboutTeam(models.Model): profile_photo = models.ImageField(upload_to='photos/%Y/%m/%d') hover_profile_photo = models.ImageField(upload_to='photos/%Y/%m/%d') name = models.CharField(max_length=200) job_title = models.CharField(max_length=200) job_descriptions = models.TextField(blank=False) is_published = models.BooleanField(default=True) def __str__(self): return self.name def save(self, *args, **kwargs): compressed_image = compressImage(self.reviewer_image) self.slider_image = compressed_image super().save(*args, **kwargs) <file_sep>/gallery/models.py from django.db import models from pages.img_compression import compressImage # Create your models here. class GalleryImage(models.Model): image_title = models.CharField(max_length=400) image = models.ImageField(upload_to = 'photos/%Y/%m/%d/') def __str__(self): return self.image_title def save(self, *args, **kwargs): compressed_image = compressImage(self.image) self.slider_image = compressed_image super().save(*args, **kwargs)<file_sep>/servicePage/urls.py from django.urls import path from . import views urlpatterns = [ path('<int:service_id>', views.getServiceDetail, name='serviceDescription'), ] <file_sep>/meetteam/views.py from django.shortcuts import render from .models import AboutTeam def meetourteam(request): aboutteam = AboutTeam.objects.all() context = { 'aboutteam': aboutteam, } return render(request, 'pages/meetourteam.html', context) <file_sep>/indexblog/meta_gen.py import collections import string from io import StringIO import re from django.utils.html import strip_tags # Counts words in template files and insert keywords into page word_count_min = 2 word_length_min = 4 nogo_list = [] # Optional list of words you may not want as meta tags. # meta_keywords ( html string ) => # returns non html keyword list, as a comma seperated string, # for words fitting qualifications as chosen above. def meta_keywords(str_file): c = collections.Counter() strIO_Obj = StringIO.StringIO(str_file) for line in strIO_Obj.readlines(): c.update(re.findall(r"[\w']+", strip_tags(line).lower())) wordlist = [] for word, count in c.most_common(): if len(word) > (word_length_min-1) and count > (word_count_min-1) and word not in nogo_list: wordlist.append(word) return string.join(wordlist, ',') <file_sep>/contact/views.py from django.shortcuts import redirect, render from django.core.mail import send_mail import phone_field from .models import Contact, Enroll from django.contrib.auth.models import User from django.contrib import messages def index(request): """ Display contact page **Context** ``contact`` An instance of :model:`contact.index` **Template** :template:`pages/contact.html` """ if request.method == 'POST': name = request.POST.get('full_name') email = request.POST.get('email') number = request.POST.get('number') message = request.POST.get('message') # num = int(number) try: if name == '' or email == '' or message == '' or number == '': messages.error( request, 'Some of the Field is Empty please check the field before you submit') return redirect('contact') elif len(number) < 10 or len(number) > 10: messages.error( request, 'Phone Number should be 10 Digit Number') return redirect('contact') else: try: num = int(number) user = Contact.objects.create( full_name=name, email=email, phone=number, message=message) messages.success( request, 'Thank you for give your time to share your information') user.save() return redirect('contact') except: messages.error( request, 'Phone Number should be 10 Digit Number') return redirect('contact') except (number.DoesNotexit) as e: return render(request, 'pages/contact.html') else: return render(request, 'pages/contact.html') def enroll(request): if request.method == 'POST': name = request.POST.get('full_name') email = request.POST.get('email') number = request.POST.get('number') qualification = request.POST.get('qualification') course_complete = request.POST.get('course_complete') gpa = request.POST.get('gpa') institution = request.POST.get('institution') parent_name = request.POST.get('parent_name') address = request.POST.get('address') courses = request.POST.get('courses') scores = request.POST.get('scores') planning = request.POST.get('planning') where_to_study = request.POST.get('where_to_study') preferred_course = request.POST.get('preferred_course') preferred_uni = request.POST.get('preferred_uni') declare = request.POST.get('declare') future_use = request.POST.get('future_use') consult_date = request.POST.get('consult') know_us = request.POST.get('know_us') try: if name == '' or email == '' or number == '' or qualification == '' or course_complete == '' or gpa == '' or institution == '' or parent_name == '' or address == '' or courses == '' or where_to_study == '' or preferred_course == '' or preferred_uni == '' or declare == '' or consult_date == '' or know_us == '' or future_use == '': messages.error( request, 'Some of the Field is Empty please check the field before you submit') return redirect('enroll') elif len(number) < 10 or len(number) > 10: messages.error( request, 'Phone Number should be 10 Digit Number') return redirect('enroll') else: try: user = Enroll.objects.create( full_name=name, email=email, phone=number, qualification=qualification, course_completed=course_complete, GPA=gpa, institution_name=institution, parents_Name=parent_name, address=address, courses=courses, scores=scores, planning_to_take_test=planning, where_to_study=where_to_study, preferred_course=preferred_course, preferred_uni=preferred_uni, declare_to_use_information=declare, can_use_details=future_use, consult_date=consult_date, how_do_you_know_us=know_us ) messages.success( request, 'Thank you for give your time to share your information') user.save() return redirect('enroll') except: messages.error( request, 'Phone Number should be 10 Digit Number') return redirect('contact') except(number.DoesNotexit) as e: return render(request, 'pages/enroll.html') else: return render(request, 'pages/enroll.html') <file_sep>/pages/migrations/0007_delete_service.py # Generated by Django 3.1.7 on 2021-05-30 13:06 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('pages', '0006_auto_20210530_1727'), ] operations = [ migrations.DeleteModel( name='Service', ), ] <file_sep>/pages/migrations/0004_service.py # Generated by Django 3.1.7 on 2021-05-30 11:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pages', '0003_testimonial'), ] operations = [ migrations.CreateModel( name='Service', fields=[ ('service_title', models.CharField(max_length=300, primary_key=True, serialize=False)), ('service_description', models.TextField()), ('service_img', models.ImageField(upload_to='photos/%Y/%m/%d/')), ], ), ] <file_sep>/service/migrations/0001_initial.py # Generated by Django 3.1.1 on 2021-05-28 06:04 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Courses', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('course_name', models.CharField(max_length=300)), ('teacher_name', models.CharField(max_length=100)), ('course_start_date', models.DateField()), ('course_description', models.TextField(max_length=200)), ('course_button_name', models.CharField(max_length=100)), ], ), migrations.CreateModel( name='Service', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('hero_img', models.ImageField(upload_to='photos/%Y/%m/%d')), ('hero_title', models.CharField(max_length=300)), ('hero_slogan', models.CharField(max_length=300)), ('hero_subject_name', models.CharField(max_length=100)), ('hero_subject_name_I', models.CharField(max_length=100)), ('hero_button_name', models.CharField(max_length=100)), ], ), ] <file_sep>/messagefromceo/models.py from django.db import models from pages.img_compression import compressImage class Message(models.Model): hero_img = models.ImageField(upload_to='photos/%Y/%m/%d') message_title = models.CharField(max_length=100) message_description = models.TextField() message_description_1st = models.TextField(blank=True) message_description_2nd = models.TextField(blank=True) profile_photo = models.ImageField(upload_to='photo/%Y/%m/%d') def __str__(self): return self.message_title def save(self, *args, **kwargs): compressed_image = compressImage(self.reviewer_image) self.slider_image = compressed_image super().save(*args, **kwargs) <file_sep>/service/migrations/0003_courses_is_published.py # Generated by Django 3.1.1 on 2021-05-28 06:35 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('service', '0002_courses_course_img'), ] operations = [ migrations.AddField( model_name='courses', name='is_published', field=models.BooleanField(default=True), ), ] <file_sep>/visafacts/admin.py from django.contrib import admin from .models import VisaDetail # Register your models here. admin.site.register(VisaDetail)<file_sep>/visafacts/views.py from django.shortcuts import render, get_object_or_404 from .models import VisaDetail # Create your views here. def getVisaDetail(request, visa_id): visaDetail = get_object_or_404(VisaDetail, pk=visa_id) context = { 'visaDetail': visaDetail } return render(request, 'pages/visafact.html', context) <file_sep>/pages/models.py from django.db import models from pages.img_compression import compressImage # Create your models here. class HeroSlider(models.Model): slider_image_name = models.CharField(max_length=200) slider_image = models.ImageField(upload_to='photos/%Y/%m/%d/') slider_image_title = models.CharField(max_length=100) slider_image_description = models.TextField() slider_image_button_name = models.CharField(max_length=20) def __str__(self): return self.slider_image_name def save(self, *args, **kwargs): compressed_image = compressImage(self.slider_image) self.slider_image = compressed_image super().save(*args, **kwargs) class UniversityLogo(models.Model): university_name = models.CharField(max_length=400) university_logo = models.ImageField(upload_to='photos/%Y/%m/%d/') def __str__(self): return self.university_name def save(self, *args, **kwargs): compressed_image = compressImage(self.university_logo) self.slider_image = compressed_image super().save(*args, **kwargs) class Testimonial(models.Model): reviewer_name = models.CharField(max_length=200) reviewer_image = models.ImageField(upload_to='photos/%Y/%m/%d/') reviewer_description = models.TextField() def __str__(self): return self.reviewer_name def save(self, *args, **kwargs): compressed_image = compressImage(self.reviewer_image) self.slider_image = compressed_image super().save(*args, **kwargs) class popup(models.Model): pop_up_heading = models.CharField(max_length=200) pop_up_img = models.ImageField(upload_to='photos/%Y/%m/%d/') button_name = models.CharField(max_length=200) def __str__(self): return self.pop_up_heading def save(self, *args, **kwargs): compressed_image = compressImage(self.pop_up_img) self.slider_image = compressed_image super().save(*args, **kwargs) <file_sep>/service/views.py from django.shortcuts import render from .models import Service, Courses def service(request): services = Service.objects.first courses = Courses.objects.all() context = { 'services': services, 'courses': courses, } return render(request, 'pages/service.html', context) <file_sep>/service/admin.py from django.contrib import admin from .models import Service, Courses admin.site.register(Service) admin.site.register(Courses) <file_sep>/meetteam/admin.py from django.contrib import admin from .models import AboutTeam admin.site.register(AboutTeam) <file_sep>/meetteam/apps.py from django.apps import AppConfig class MeetteamConfig(AppConfig): name = 'meetteam' <file_sep>/pages/admin.py from django.contrib import admin from .models import HeroSlider, UniversityLogo, Testimonial, popup # Register your models here. admin.site.register(popup) admin.site.register(HeroSlider) admin.site.register(UniversityLogo) admin.site.register(Testimonial) <file_sep>/contact/models.py from django.db import models from django.db.models.fields import CharField from phone_field import PhoneField class Contact(models.Model): """ Contact model Fields full_name email phone message """ full_name = models.CharField(max_length=200) email = models.CharField(max_length=200) phone = PhoneField(blank=True, help_text='Contact phone number') message = models.TextField() def __str__(self): return self.full_name class Enroll(models.Model): full_name = models.CharField(max_length=200) email = models.CharField(max_length=200) phone = PhoneField(blank=True, help_text='Contact phone number') qualification = models.CharField(max_length=20) course_completed = models.CharField(max_length=20) GPA = models.CharField(max_length=20) institution_name = models.CharField(max_length=200) parents_Name = models.CharField(max_length=100) address = models.CharField(max_length=50) courses = models.CharField(max_length=100) scores = models.CharField(max_length=20) planning_to_take_test = models.CharField(max_length=200) where_to_study = models.CharField(max_length=100) preferred_course = models.CharField(max_length=200) preferred_uni = models.CharField(max_length=200) declare_to_use_information = models.CharField(max_length=100) can_use_details = models.CharField(max_length=20) consult_date = models.DateField(max_length=200) how_do_you_know_us = models.CharField(max_length=200) <file_sep>/templates/pages/aboutcompany.html {% extends 'base.html' %} {% load static %} {% block css %} <link rel="stylesheet" href="{% static 'css/about.style.css' %}"> {% endblock %} {% block content %} <div class="about-panel"> <div class="hero-image" style="background: url('{{aboutcompany.hero_img.url}}'); background-position: center center; background-repeat: no-repeat; background-attachment:fixed; background-size: cover; height:70vh; filter: brightness(55%);" > </div> <div class="hero-image"></div> <h1 class="hero-img-title">About Us</h1> </div> <section> <div class="about-company"> <div class="container"> <div class="about-section" style=" overflow: hidden; background: url('{{aboutcompany.hero_img.url}}') no-repeat left; background-size: 55%; background-color: #fdfdfd; " > <div class="inner-container"> <h1>{{aboutcompany.about_title}}</h1> <p class="text"> {{aboutcompany.about_description}} </p> <p class="text"> {{aboutcompany.about_description_sub}} </p> <p class="text"> {{aboutcompany.about_description_sub_I}} </p> </div> </div> </div> </div> <!-- <div class="about-founder"> <div class="container"> <div class="row"> <h1>About President KB Shrestha</h1> <div class="col-sm"> <p class="president-description"> Lorem ipsum dolor sit amet consectetur adipisicing elit. Ratione id, sequi libero enim illo perferendis perspiciatis quae laudantium nemo voluptatum non repudiandae impedit nostrum fugiat voluptas maiores iste dolorem pariatur! </p> <p class="president-description-sub"> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nihil quis mollitia quos labore vero explicabo praesentium architecto minus dolorum officiis. Voluptates vero aperiam dolorum doloremque cum quas rerum sapiente assumenda. Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolores ex reiciendis suscipit eaque doloribus reprehenderit officiis amet aperiam delectus veritatis, enim placeat, dolorum quis ea fugit fugiat sit dolorem repellat. </p> <p class="president-description-sub"> Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nihil quis mollitia quos labore vero explicabo praesentium architecto minus dolorum officiis. Voluptates vero aperiam dolorum doloremque cum quas rerum sapiente assumenda. </p> </div> <div class="col-sm"> <img src="./img/img2.jpg" alt="" class="president-img" width="100%"> </div> </div> </div> </div> --> <div class="about-experts id="bg-color"> <div class="container"> <div class="expert-title"> <h1 class="expert-title">Our Expert</h1> </div> <div class="row owl-carousel"> {% for AboutTeam in aboutteam %} <div class="col"> <img src="{{AboutTeam.profile_photo.url}}" alt="Users Photo" class="about-img" id="img14" style="visibility:visible"> <p class="users-name">{{AboutTeam.name}}</p> <p class="job-title">{{AboutTeam.job_title}}</p> </div> {% endfor %} </div> </div> </div> </div> <div class="counselling"> <div class="container"> <div class="row"> <div class="col-sm"> <h1 class="book-free-counselling"> Book Free Counselling </h1> <p class="counselling-description">Lorem ipsum dolor sit amet consectetur adipisicing elit. Laboriosam consequatur ipsum odio dolorum! Laborum ipsa odit ad consequatur rem minima quos, tempora molestiae eligendi, doloribus voluptatum voluptatibus earum consectetur. Iusto.</p> <a href=""><button class="book-a-session">Book a Session</button></a> <p class="email-num-details">Email : <EMAIL> | Number : 9841354543</p> </div> </div> </div> </div> </section> {% block script %} <script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script> <script src="{%static 'js/about.js' %}"></script> {% endblock %} {% endblock %}<file_sep>/pages/migrations/0002_universitylogo.py # Generated by Django 3.1.7 on 2021-05-26 07:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pages', '0001_initial'), ] operations = [ migrations.CreateModel( name='UniversityLogo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('university_name', models.CharField(max_length=400)), ('university_logo', models.ImageField(upload_to='photos/%Y/%m/%d/')), ], ), ] <file_sep>/meetteam/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.meetourteam, name='meetteam'), ] <file_sep>/visafacts/urls.py from django.urls import path from . import views urlpatterns = [ path('<int:visa_id>', views.getVisaDetail, name='visa'), ] <file_sep>/indexabout/apps.py from django.apps import AppConfig class IndexaboutConfig(AppConfig): name = 'indexabout' <file_sep>/pages/migrations/0008_auto_20210530_1923.py # Generated by Django 3.1.7 on 2021-05-30 13:38 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pages', '0007_delete_service'), ] operations = [ migrations.AddField( model_name='heroslider', name='slider_image_button_name', field=models.CharField(blank=True, max_length=20), ), migrations.AddField( model_name='heroslider', name='slider_image_description', field=models.TextField(blank=True), ), migrations.AddField( model_name='heroslider', name='slider_image_title', field=models.CharField(blank=True, max_length=100), ), ] <file_sep>/service/models.py from django.db import models from pages.img_compression import compressImage class Service(models.Model): hero_img = models.ImageField(upload_to='photos/%Y/%m/%d') hero_title = models.CharField(max_length=300) hero_slogan = models.CharField(max_length=300) hero_subject_name = models.CharField(max_length=100) hero_subject_name_I = models.CharField(max_length=100) hero_button_name = models.CharField(max_length=100) def __str__(self): return self.hero_subject_name def save(self, *args, **kwargs): compressed_image = compressImage(self.hero_img) self.slider_image = compressed_image super().save(*args, **kwargs) class Courses(models.Model): course_img = models.ImageField(upload_to='photos/%Y/%m/%d') course_name = models.CharField(max_length=300) teacher_name = models.CharField(max_length=100) course_start_date = models.DateField() course_description = models.TextField(max_length=200) course_button_name = models.CharField(max_length=100) is_published = models.BooleanField(default=True) def __str__(self): return self.course_name def save(self, *args, **kwargs): compressed_image = compressImage(self.course_img) self.slider_image = compressed_image super().save(*args, **kwargs) <file_sep>/pages/views.py from django.shortcuts import get_object_or_404, render from .models import HeroSlider, UniversityLogo, Testimonial, popup from indexblog.models import Blog from messagefromceo.models import Message from meetteam.models import AboutTeam def MessageFromCEO(request, message_id): messages = get_object_or_404(Message, pk=message_id) aboutteam = AboutTeam.objects.all() context = { 'messages': messages, 'aboutteam': aboutteam, } return render(request, 'pages/messagefromceo.html', context) def index(request): popup_message = popup.objects.first heroSlider = HeroSlider.objects.all() universityLogos = UniversityLogo.objects.all() testimonials = Testimonial.objects.all() message = Message.objects.all() blogs = Blog.objects.all() context = { 'popup_message': popup_message, 'heroSlider': heroSlider, 'universityLogos': universityLogos, 'testimonials': testimonials, 'message': message, 'blogs': blogs } return render(request, "pages/index.html", context) <file_sep>/AU/static/js/service.js // owl carousel js start $(document).ready(function () { $(".owl-carousel").owlCarousel({ loop: true, margin:20, autoplay: true, animateIn: "fadeIn", animateOut: "fadeOut", responsiveClass: true, pagination: false, dots: false, responsive: { 0: { items: 1.01, }, 600: { items: 3, }, 1000: { items: 8, }, }, }); // Custom Button $(".my-next-button").click(function() { owl.trigger("next.owl.carousel"); }); $(".my-previous-button").click(function() { owl.trigger("prev.owl.carousel"); }); }); // owl carousel js end<file_sep>/indexabout/admin.py from django.contrib import admin from .models import AboutCompany admin.site.register(AboutCompany) <file_sep>/indexblog/models.py from django.db import models from datetime import datetime from django.urls import reverse from pages.img_compression import compressImage class Blog(models.Model): """ Blog Model Fields blog_title blog_tag blog_image blog_describe is_published list_date ....rest """ blog_title = models.CharField(max_length=700) blog_tag = models.CharField(max_length=400) blog_image = models.ImageField( upload_to='photos/%Y/%m/%d', blank=False, max_length=500) author = models.CharField(max_length=200) blog_describe = models.TextField(blank=False) is_published = models.BooleanField(default=True) list_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.blog_title def get_absolute_url(self): return reverse('blogs', args=[self.id, ]) def save(self, *args, **kwargs): compressed_image = compressImage(self.reviewer_image) self.slider_image = compressed_image super().save(*args, **kwargs) <file_sep>/pages/migrations/0010_popup.py # Generated by Django 3.1.1 on 2021-05-31 03:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pages', '0009_auto_20210530_1925'), ] operations = [ migrations.CreateModel( name='popup', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('pop_up_heading', models.CharField(max_length=200)), ('pop_up_img', models.ImageField(upload_to='photos/%Y/%m/%d/')), ('button_name', models.CharField(max_length=200)), ], ), ] <file_sep>/indexblog/migrations/0002_blog_author.py # Generated by Django 3.1.1 on 2021-05-29 04:22 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('indexblog', '0001_initial'), ] operations = [ migrations.AddField( model_name='blog', name='author', field=models.CharField(default=django.utils.timezone.now, max_length=200), preserve_default=False, ), ] <file_sep>/indexabout/models.py from django.db import models from pages.img_compression import compressImage class AboutCompany(models.Model): about_title = models.CharField(max_length=200, blank=True) hero_img = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True) about_img = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True) seo_tag = models.CharField(max_length=100, blank=True) about_description = models.TextField(blank=True) about_description_sub = models.TextField(blank=True) about_description_sub_I = models.TextField(blank=True) def __str__(self): return self.about_title def save(self, *args, **kwargs): compressed_image = compressImage(self.reviewer_image) self.slider_image = compressed_image super().save(*args, **kwargs) <file_sep>/indexblog/sitemaps.py from django.contrib.sitemaps import Sitemap from .models import Blog class BlogSitemap(Sitemap): def items(self): return Blog.objects.all() <file_sep>/frontend/js/index.js const counters = document.querySelectorAll('.count'); const counterSection = document.querySelector('.counter-section'); function Counter(){ counters.forEach(counter => { counter.innerHTML = '0'; const updateCounter = () => { const target = +counter.getAttribute('data-target'); const c = +counter.innerHTML; const increment = target / 200; if(c < target) { counter.innerText = `${Math.ceil(c + increment)}`; setTimeout(updateCounter, 3); } else{ counter.innerText = target; } }; updateCounter(); }) } ScrollTrigger.create({ trigger:counterSection, onEnter:Counter }) /* Blog section */ var swiper = new Swiper('.blog-slider', { spaceBetween:30, effect: 'fade', loop: true, autoplay:true, mousewheel:{ invert:false, }, pagination:{ el: '.blog-slider__pagination', clickable:true, } }); /* Logos section */ $(document).ready(function(){ $('.customer-logos').slick({ slidesToShow: 6, slidesToScroll: 1, autoplay: true, autoplaySpeed: 1500, arrows: false, dots: false, pauseOnHover: false, responsive: [{ breakpoint: 768, settings: { slidesToShow: 4 } }, { breakpoint: 520, settings: { slidesToShow: 3 } }] }); }); /*Testimonial slider*/ $('#tes-area').owlCarousel({ singleItem:true, transitionStyle:'fadeUp', mouseDrag: false, touchDrag:false, autoPlay: 3000, pagination: true })<file_sep>/AU/urls.py from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', include('pages.urls')), path('gallery/', include('gallery.urls')), path('about/', include('indexabout.urls')), path('visafacts/',include('visafacts.urls')), path('servicePage/',include('servicePage.urls')), # path('message-from-ceo/', include('messagefromceo.urls')), path('meet-our-team/', include('meetteam.urls')), path('service/', include('service.urls')), path('blog/', include('indexblog.urls')), path('contact/', include('contact.urls')), path('admin/', admin.site.urls), ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) <file_sep>/messagefromceo/views.py # from django.shortcuts import render # from .models import Message # from meetteam.models import AboutTeam # def MessageFromCEO(request): # message = Message.objects.get(id=1) # aboutteam = AboutTeam.objects.all() # context = { # 'message': message, # 'aboutteam': aboutteam, # } # return render(request, 'pages/messagefromceo.html', context) <file_sep>/indexblog/urls.py from django.urls import path from . import views # here . refers all data from django.contrib.sitemaps.views import sitemap from .sitemaps import BlogSitemap sitemaps = { 'blogs': BlogSitemap, } urlpatterns = [ path('', views.indexblog, name='blog'), path('<int:blog_id>', views.blog, name='blogs'), path('sitemap.xml', sitemap, {'sitemaps': sitemaps}), ] <file_sep>/servicePage/views.py from django.shortcuts import render,get_object_or_404 from .models import Service # Create your views here. def getServiceDetail(request,service_id): serviceDetail = get_object_or_404(Service, pk=service_id) context = { 'serviceDetail':serviceDetail } return render(request,'pages/serviceDetail.html',context) <file_sep>/templates/pages/serviceDetail.html {% extends 'base.html' %} {% load static %} {% block css %} <link rel="stylesheet" href="{% static 'css/serviceDetail.css' %}"> {% endblock %} {% block content %} {% if serviceDetail %} <section class="service-details"> <div class="static-image"> <div class="service-title"> <h2 class="text-center">{{serviceDetail.service_title}}</h2> </div> </div> <div class="container"> <div class="row"> <div class="col"> <div class="service-box"> <div class="col"> <div class="service-img"> <img src="{{serviceDetail.service_img.url}}" class="img-responsive"> </div> </div> <div class="service-content"> <h3>{{serviceDetail.service_title}}</h3> <p> {{serviceDetail.service_description}} </p> </div> </div> </div> </div> </div> </section> {% endif %} {% endblock %} <file_sep>/pages/migrations/0009_auto_20210530_1925.py # Generated by Django 3.1.7 on 2021-05-30 13:40 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pages', '0008_auto_20210530_1923'), ] operations = [ migrations.AlterField( model_name='heroslider', name='slider_image_button_name', field=models.CharField(max_length=20), ), migrations.AlterField( model_name='heroslider', name='slider_image_description', field=models.TextField(), ), migrations.AlterField( model_name='heroslider', name='slider_image_title', field=models.CharField(max_length=100), ), ] <file_sep>/servicePage/models.py from django.db import models from pages.img_compression import compressImage # Create your models here. class Service(models.Model): service_title = models.CharField(max_length=300) service_description = models.TextField() service_img = models.ImageField(upload_to = 'photos/%Y/%m/%d/') def __str__(self): return self.service_title def save(self, *args, **kwargs): compressed_image = compressImage(self.service_img) self.slider_image = compressed_image super().save(*args, **kwargs)<file_sep>/service/migrations/0002_courses_course_img.py # Generated by Django 3.1.1 on 2021-05-28 06:33 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('service', '0001_initial'), ] operations = [ migrations.AddField( model_name='courses', name='course_img', field=models.ImageField(default=django.utils.timezone.now, upload_to='photos/%Y/%m/%d'), preserve_default=False, ), ] <file_sep>/indexabout/migrations/0001_initial.py # Generated by Django 3.1.1 on 2021-05-27 13:15 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='AboutCompany', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('about_title', models.CharField(blank=True, max_length=200)), ('hero_img', models.ImageField(blank=True, upload_to='photos/%Y/%m/%d')), ('about_img', models.ImageField(blank=True, upload_to='photos/%Y/%m/%d')), ('seo_tag', models.CharField(blank=True, max_length=100)), ('about_description', models.TextField(blank=True)), ('about_description_sub', models.TextField(blank=True)), ('about_description_sub_I', models.TextField(blank=True)), ], ), ] <file_sep>/pages/migrations/0005_auto_20210530_1727.py # Generated by Django 3.1.7 on 2021-05-30 11:42 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('pages', '0004_service'), ] operations = [ migrations.AddField( model_name='service', name='id', field=models.AutoField(auto_created=True, default=1, primary_key=True, serialize=False, verbose_name='ID'), preserve_default=False, ), migrations.AlterField( model_name='service', name='service_title', field=models.CharField(blank=True, max_length=300), ), ] <file_sep>/pages/img_compression.py from io import BytesIO from PIL import Image from django.core.files import File def compressImage(image): img = Image.open(image).convert("RGB") im_io = BytesIO() if image.name.split('.')[1] == 'jpeg' or image.name.split('.')[1] == 'jpg': img.save(im_io , format='jpeg', optimize=True, quality=50) new_image = File(im_io, name="%s.jpeg" %image.name.split('.')[0],) else: img.save(im_io , format='png', optimize=True, quality=50) new_image = File(im_io, name="%s.png" %image.name.split('.')[0],) return new_image<file_sep>/indexabout/views.py from django.shortcuts import render from .models import AboutCompany from meetteam.models import AboutTeam from messagefromceo.models import Message def about(request): aboutcompany = AboutCompany.objects.get(id=1) aboutteam = AboutTeam.objects.all() message = Message.objects.all() context = { 'aboutcompany': aboutcompany, 'aboutteam': aboutteam, 'message': message } return render(request, 'pages/aboutcompany.html', context) <file_sep>/visafacts/models.py from django.db import models from django.db.models.fields import BLANK_CHOICE_DASH from pages.img_compression import compressImage # Create your models here. class VisaDetail(models.Model): visa_title = models.CharField(max_length=400,blank=True) visa_img = models.ImageField(upload_to='photos/%Y/%m/%d') visa_detail = models.TextField(blank=True) visa_2nd_title = models.CharField(max_length=400,blank=True) visa_2nd_detail = models.TextField(blank=True) def __str__(self): return self.visa_title def save(self, *args, **kwargs): compressed_image = compressImage(self.visa_img) self.slider_image = compressed_image super().save(*args, **kwargs)<file_sep>/pages/context_processors.py from messagefromceo.models import Message from visafacts.models import VisaDetail from servicePage.models import Service def message_context_processor(request): message = Message.objects.all() visas = VisaDetail.objects.all() service = Service.objects.all() context = { "message": message, "visas": visas, "service": service } return context <file_sep>/gallery/views.py from django.shortcuts import render from .models import GalleryImage # Create your views here. def getGallery(request): images = GalleryImage.objects.all() context = { 'images':images } return render(request, 'pages/gallery.html',context)<file_sep>/messagefromceo/apps.py from django.apps import AppConfig class MessagefromceoConfig(AppConfig): name = 'messagefromceo'
be2fb2d467a3dc1486d822155e6a3149277d5c7f
[ "JavaScript", "Python", "HTML" ]
52
Python
AnubisN/Aus
d5340cbcb01753c549b869e2ca410ccac7ddb80e
0ba3036404ffc17556af39f7542dee370266f105
refs/heads/master
<repo_name>anguoyang/caffe-windows-opencl<file_sep>/pyprjs/get_caffenet_model_binary.py #!/usr/bin/env python import os import sys import time import hashlib from six.moves import urllib required_keys = ['caffemodel', 'caffemodel_url', 'sha1'] caffemodel = "bvlc_reference_caffenet.caffemodel" caffemodel_url = "http://dl.caffe.berkeleyvision.org/bvlc_reference_caffenet.caffemodel" sha1 = "4c8d77deb20ea792f84eb5e6d0a11ca0a8660a46" caffe_commit = "7<PASSWORD>" def reporthook(count, block_size, total_size): """ From http://blog.moleculea.com/2012/10/04/urlretrieve-progres-indicator/ """ global start_time if count == 0: start_time = time.time() return duration = (time.time() - start_time) or 0.01 progress_size = int(count * block_size) speed = int(progress_size / (1024 * duration)) percent = int(count * block_size * 100 / total_size) sys.stdout.write("\r...%d%%, %d MB, %d KB/s, %d seconds passed" % (percent, progress_size / (1024 * 1024), speed, duration)) sys.stdout.flush() def model_checks_out(filename, sha1): with open(filename, 'rb') as f: return hashlib.sha1(f.read()).hexdigest() == sha1 str_dir = ".\\data" str_model_fn = os.path.join(str_dir, caffemodel) # Check if model exists. if os.path.exists(str_model_fn) and model_checks_out(str_model_fn, sha1): print("Model already exists.") sys.exit(0) # Download and verify model. urllib.request.urlretrieve(caffemodel_url, str_model_fn, reporthook) if not model_checks_out(str_model_fn, sha1): print('ERROR: model did not download correctly! Run this again.') sys.exit(1) <file_sep>/hmprjs/models/README.md caffenet_train_quick_iter_1000.caffemodel caffenet_train_quick_iter_1000.solverstate caffenet_train_quick_iter_2000.caffemodel caffenet_train_quick_iter_2000.solverstate caffenet_train_quick_iter_3000.caffemodel caffenet_train_quick_iter_3000.solverstate caffenet_train_quick_iter_4000.caffemodel caffenet_train_quick_iter_4000.solverstate caffenet_train_quick_iter_5000.caffemodel caffenet_train_quick_iter_5000.solverstate caffenet_train_quick_iter_6000.caffemodel caffenet_train_quick_iter_6000.solverstate <file_sep>/hmprjs/README.md heatmaps.py screenshot: ![](heatmaps_2008_001042.jpg) DataSet Images Directory: ...\places_train: cars fashions places ...\places_test: cars fashions places train caffemodel: ...\caffe-windows-opencl\hmprjs> python lists_train.py ...\caffe-windows-opencl\hmprjs> python lists_test.py ...\caffe-windows-opencl\hmprjs> create_gray_lmdb.cmd ...\caffe-windows-opencl\hmprjs> make_mean.cmd ...\caffe-windows-opencl\hmprjs> train_quick.cmd heatmaps: ...\caffe-windows-opencl\hmprjs> python heatmaps.py <file_sep>/pyprjs/full_conv_mulit.py #!/usr/bin/env python import numpy as np import os import sys import argparse import glob import time import copy import StringIO from collections import OrderedDict import sys sys.path.append('c:\\mingw\\python') print(sys.path) import caffe import matplotlib.pyplot as plt from skimage import transform as sktr def print_data(str_name, data): s = StringIO.StringIO() s.write(str_name) s.write(" : ") s.write(data) s.seek(0) print (s.read()) #s.truncate(0) def convert_mean(binMean, npyMean): blob = caffe.proto.caffe_pb2.BlobProto() bin_mean = open(binMean, 'rb' ).read() blob.ParseFromString(bin_mean) arr = np.array( caffe.io.blobproto_to_array(blob) ) npy_mean = arr[0] np.save(npyMean, npy_mean ) def show_data(str_title, data_fp, padsize=1, padval=0): data = copy.deepcopy(data_fp) data -= data.min() data /= data.max() # force the number of filters to be square n = int(np.ceil(np.sqrt(data.shape[0]))) padding = ((0, n ** 2 - data.shape[0]), (0, padsize), (0, padsize)) + ((0, 0),) * (data.ndim - 3) data = np.pad(data, padding, mode='constant', constant_values=(padval, padval)) # tile the filters into an image data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1))) data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:]) plt.figure(str_title),plt.title(str_title) plt.imshow(data,cmap='gray') plt.axis('off') plt.rcParams['figure.figsize'] = (8, 8) # plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' def convert_full_conv(model_define,model_weight,model_define_fc,model_weight_fc): net = caffe.Net(model_define, model_weight, caffe.TEST) params = ['fc6', 'fc7', 'fc8'] # fc_params = {name: (weights, biases)} fc_params = {pr: (net.params[pr][0].data, net.params[pr][1].data) for pr in params} net_full_conv = caffe.Net(model_define_fc, model_weight, caffe.TEST) params_full_conv = ['fc6-conv', 'fc7-conv', 'fc8-conv'] # conv_params = {name: (weights, biases)} conv_params = {pr: (net_full_conv.params[pr][0].data, net_full_conv.params[pr][1].data) for pr in params_full_conv} for pr, pr_conv in zip(params, params_full_conv): conv_params[pr_conv][0].flat = fc_params[pr][0].flat # flat unrolls the arrays conv_params[pr_conv][1][...] = fc_params[pr][1] net_full_conv.save(model_weight_fc) print 'convert done!' return net_full_conv set_gpu = 1 if set_gpu: caffe.set_mode_gpu() caffe.set_device(0) #caffe.set_device(1) caffe.select_device(0, True) print("GPU mode") else: caffe.set_mode_cpu() print("CPU mode") net_file_fc=".\\data\\bvlc_caffenet_full_conv.prototxt" caffe_model_fc=".\\data\\bvlc_caffenet_full_conv.caffemodel" net_file=".\\data\\bvlc_reference_caffenet.prototxt" caffe_model=".\\data\\bvlc_reference_caffenet.caffemodel" mean_bin=".\\data\\imagenet_mean.binaryproto" mean_npy=".\\data\\imagenet_mean.npy" convert_mean(mean_bin, mean_npy) imagenet_labels_filename = ".\\data\\synset_words.txt" labels = np.loadtxt(imagenet_labels_filename, str, delimiter='\t') if not os.path.isfile(caffe_model_fc): net_full_conv = convert_full_conv(net_file, caffe_model, net_file_fc, caffe_model_fc) else: net_full_conv = caffe.Net(net_file_fc, caffe_model_fc, caffe.TEST) # load input and configure preprocessing str_img_fn = ".\\imgs\\cat.jpg" img = caffe.io.load_image(str_img_fn) img_res = sktr.resize(img, (451, 451) ) h = img_res.shape[0] w = img_res.shape[1] net_full_conv.blobs['data'].reshape(1, 3, h, w) transformer = caffe.io.Transformer({'data': net_full_conv.blobs['data'].data.shape}) transformer.set_mean('data', np.load(mean_npy).mean(1).mean(1)) transformer.set_transpose('data', (2,0,1)) transformer.set_channel_swap('data', (2,1,0)) transformer.set_raw_scale('data', 255.0) # make classification map by forward and print prediction indices at each location out = net_full_conv.forward_all(data=np.asarray([transformer.preprocess('data', img_res)])) show_data("conv1 params", net_full_conv.params['conv1'][0].data.reshape(96*3,11,11)) print_data("blobs['pool5'].data.shape", net_full_conv.blobs['pool5'].data.shape) print ("out prob ...") #print out['prob'][0] print ( out['prob'][0].argmax(axis=0) ) vals = out['prob'][0].argmax(axis=0) va_lists = [] for vas in vals: for va in vas: va_lists.append(va) va_sets = set(va_lists) va_name_idx_maps = {} va_name_num_maps = {} for va in va_sets: str_name = labels[va] va_name_idx_maps[str_name] = va num = 0 for ve_tmp in va_lists: if (va == ve_tmp): num = num+1 va_name_num_maps[str_name] = num va_sort_maps = OrderedDict( sorted(va_name_num_maps.iteritems(), key=lambda d:d[1], reverse = True) ) str_names = [] for name in va_sort_maps.keys(): str_names.append(name) str_title = "net_full_conv" # show net input and confidence map (probability of the top prediction at each location) plt.figure(str_title),plt.title(str_title) str_title = "img_src : %s"%(str_img_fn) plt.subplot(2, 2, 1),plt.title(str_title) plt.imshow(transformer.deprocess('data', net_full_conv.blobs['data'].data[0])) plt.subplot(2, 2, 2),plt.title(str_names[0]) idx = va_name_idx_maps[ str_names[0] ] plt.imshow(out['prob'][0, idx], plt.cm.hot) plt.subplot(2, 2, 3),plt.title(str_names[1]) idx = va_name_idx_maps[ str_names[1] ] plt.imshow(out['prob'][0, idx], plt.cm.hot) plt.subplot(2, 2, 4),plt.title(str_names[2]) idx = va_name_idx_maps[ str_names[2] ] plt.imshow(out['prob'][0, idx], plt.cm.hot) plt.show() <file_sep>/pyprjs/classify.py #!/usr/bin/env python import numpy as np import os import sys import argparse import glob import time import copy import StringIO import sys sys.path.append('c:\\mingw\\python') print(sys.path) import caffe import matplotlib.pyplot as plt def print_data(str_name, data): s = StringIO.StringIO() s.write(str_name) s.write(" : ") s.write(data) s.seek(0) print (s.read()) #s.truncate(0) def convert_mean(binMean, npyMean): blob = caffe.proto.caffe_pb2.BlobProto() bin_mean = open(binMean, 'rb' ).read() blob.ParseFromString(bin_mean) arr = np.array( caffe.io.blobproto_to_array(blob) ) npy_mean = arr[0] np.save(npyMean, npy_mean ) def show_data(str_title, data_p, padsize=1, padval=0): data = copy.deepcopy(data_p) data -= data.min() data /= data.max() # force the number of filters to be square n = int(np.ceil(np.sqrt(data.shape[0]))) padding = ((0, n ** 2 - data.shape[0]), (0, padsize), (0, padsize)) + ((0, 0),) * (data.ndim - 3) data = np.pad(data, padding, mode='constant', constant_values=(padval, padval)) # tile the filters into an image data = data.reshape((n, n) + data.shape[1:]).transpose((0, 2, 1, 3) + tuple(range(4, data.ndim + 1))) data = data.reshape((n * data.shape[1], n * data.shape[3]) + data.shape[4:]) plt.figure(str_title),plt.title(str_title) plt.imshow(data,cmap='gray') plt.axis('off') plt.rcParams['figure.figsize'] = (8, 8) # plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' set_gpu = 1 if set_gpu: caffe.set_mode_gpu() caffe.set_device(0) #caffe.set_device(1) caffe.select_device(0, True) print("GPU mode") else: caffe.set_mode_cpu() print("CPU mode") net_file=".\\data\\bvlc_reference_caffenet.prototxt" caffe_model=".\\data\\bvlc_reference_caffenet.caffemodel" mean_bin=".\\data\\imagenet_mean.binaryproto" mean_npy=".\\data\\imagenet_mean.npy" imagenet_labels_filename = ".\\data\\synset_words.txt" labels = np.loadtxt(imagenet_labels_filename, str, delimiter='\t') convert_mean(mean_bin, mean_npy) net = caffe.Net(net_file,caffe_model,caffe.TEST) show_data("conv1 params", net.params['conv1'][0].data.reshape(96*3,11,11)) print_data("net.params['conv1'][0].data.shape", net.params['conv1'][0].data.shape) transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape}) transformer.set_transpose('data', (2,0,1)) transformer.set_mean('data', np.load(mean_npy).mean(1).mean(1)) transformer.set_raw_scale('data', 255) transformer.set_channel_swap('data', (2,1,0)) input_data=net.blobs['data'].data str_img_fn = ".\\imgs\\cat.jpg" img=caffe.io.load_image(str_img_fn) # Classify. net.blobs['data'].data[...] = transformer.preprocess('data',img) start = time.time() #out = net.forward() out = net.forward(start="conv1", end="prob") print("Caffe net forward in %.2f s." % (time.time() - start)) show_data("conv1", net.blobs['conv1'].data[0]) print_data("net.blobs['conv1'].data.shape", net.blobs['conv1'].data.shape) params = [(k, v[0].data.shape) for k, v in net.params.items()] plt.figure("img") plt.subplot(1,2,1),plt.title("origin") plt.imshow(img) plt.axis('off') plt.subplot(1,2,2),plt.title("subtract mean") plt.imshow(transformer.deprocess('data', input_data[0])) plt.axis('off') data = [(k, v.data.shape) for k, v in net.blobs.items()] feat = net.blobs['prob'].data[0] #print feat plt.figure('prob') plt.plot(feat.flat) top_k = net.blobs['prob'].data[0].flatten().argsort()[-1:-6:-1] print("top_k : ", top_k) prob_data = net.blobs['prob'].data[0] print ("caffe prob : ") for i in np.arange(top_k.size): print("idx_%d : %f, %s" %( top_k[i], prob_data[top_k[i]], labels[top_k[i]] ) ) plt.show() <file_sep>/pyprjs/readme.md # CaffeNet Fully Convolutional Network (win10 mingw64 python) ![](full_conv_mulit.jpg) win10 cmd console: 1. download caffe_net model binary ...> python get_caffenet_model_binary.py 2. run python script ...> python full_conv_mulit.py
c0821350a0c98587dfa10ade4491e022ec924686
[ "Markdown", "Python" ]
6
Python
anguoyang/caffe-windows-opencl
6cbbfb7fbb66ced8352284c0505bf3fc35262e53
05c822be4edb455cdf49715c671a332948072140
refs/heads/master
<repo_name>Touchtap/restaurantsNoah<file_sep>/Podfile use_frameworks! target 'restaurants' do pod 'AFNetworking', '~> 3.0' pod 'SVProgressHUD' pod 'AsyncImageView' end<file_sep>/restaurants/LNTConstants.h // // Constants.h // restaurants // // Created by <NAME> on 12/18/15. // Copyright © 2015 Touchtap. All rights reserved. // #ifndef Constants_h #define Constants_h #endif /* Constants_h */ #define NAVBAR_BGCOLOR @"43E895" #define NAVBAR_TINT @"FFFFFF" #define TABBAR_BGCOLOR @"2A2A2A" #define TABBAR_TINT @"FFFFFF" #define STARTING_URL @"http://www.bottlerocketstudios.com" #define RESTDATA_URL @"http://sandbox.bottlerocketapps.com/BR_iOS_CodingExam_2015_Server/restaurants.json" #define NAVBAR_FONTNAME @"AvenirNext-DemiBold" #define NAVBAR_FONTSIZE 17.0
f5339582b46cf3e5a24d90da98fe70929d5833c6
[ "C", "Ruby" ]
2
Ruby
Touchtap/restaurantsNoah
baf441a7b5b45345f49ba455fdfffc89176ed9b5
f1ddea49f151346e2fb933d61ae6f4e5cdf2943a
refs/heads/master
<repo_name>cruzsbrian/rc-autopilot<file_sep>/in-out.ino #include <Servo.h> #include <Adafruit_BMP183.h> #include <Wire.h> #include <Adafruit_Sensor.h> #include <Adafruit_BNO055.h> #include <utility/imumaths.h> #include <SPI.h> #include <Adafruit_Sensor.h> // You can also use software SPI and define your own pins! #define BMP183_CLK 13 #define BMP183_SDO 12 // AKA MISO #define BMP183_SDI 11 // AKA MOSI // You'll also need a chip-select pin, use any pin! #define BMP183_CS 10 // Output pins #define LED_PIN 13 //#define YAW_OUT_PIN 11 //#define PITCH_OUT_PIN 10 //#define ROLL_OUT_PIN 9 Servo pitchOut; Servo rollOut; Servo yawOut; // Input pins - digital #define CONTROL_PIN 0 // Input pins - analog #define YAW_IN_PIN 6 #define PITCH_IN_PIN 5 #define ROLL_IN_PIN 3 #define THROTTLE_IN_PIN 3 // Other input constants #define INPUT_CENTER 0 Adafruit_BNO055 gyro = Adafruit_BNO055(55); float seaLevelPressure = SENSORS_PRESSURE_SEALEVELHPA; void setup() { pinMode(LED_PIN, OUTPUT); pinMode(YAW_IN_PIN, INPUT); pinMode(PITCH_IN_PIN, INPUT); pinMode(ROLL_IN_PIN, INPUT); digitalWrite(LED_PIN, LOW); Serial.begin(9600); Serial.println("started serial"); pitchOut.attach(11); rollOut.attach(9); yawOut.attach(10); // /* Initialise the sensors */ if(!gyro.begin()) { /* There was a problem detecting the BNO055 ... check your connections */ Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!"); while(1); } delay(100); blink(4); gyro.setExtCrystalUse(true); } void loop() { // pilot stuff unsigned long yawValIn = pulseIn(YAW_IN_PIN, HIGH); unsigned long pitchValIn = pulseIn(PITCH_IN_PIN, HIGH); unsigned long rollValIn = pulseIn(ROLL_IN_PIN, HIGH); // get sensor data sensors_event_t event; gyro.getEvent(&event); float yaw = event.orientation.x; float roll = event.orientation.y; float pitch = event.orientation.z; pitch = clearSteer(pitch, 0); roll = clearSteer(roll, 0); yaw = clearSteer(yaw, 0); pitch = degToPwm(pitch); roll = degToPwm(roll); yaw = degToPwm(yaw); //so that we are adjusting in the correct direction float pitchAdjust = revPWMSignal(pitch); float yawAdjust = revPWMSignal(yaw); /* Display the floating point data */ Serial.print("Yaw: "); Serial.print(yaw, 4); Serial.print("\tPitch: "); Serial.print(pitch, 4); Serial.print("\tRoll: "); Serial.print(roll, 4); Serial.print("\tYaw In: "); Serial.print(yawValIn); Serial.print("\tPitch In: "); Serial.print(pitchValIn); Serial.print("\tRoll In: "); Serial.print(rollValIn); Serial.print("\tPitch Out: "); Serial.print(pitchValIn); Serial.println(""); pitchOut.writeMicroseconds(pitchAdjust); rollOut.writeMicroseconds(roll); yawOut.writeMicroseconds(yawAdjust); //delay(100); } float pwmToDeg(float pwm) { //changes 1000-2000 to 0-180 and handles cases where the input goes above or below the range and returns wierd numbers pwm = (pwm * .18) - 180; if (pwm > 200 || pwm < pwm) { return 0; } else if (pwm > 180) { return 180; } else if (pwm > 82 && pwm < 96) { return 90; } else { return pwm; } } float revPWMSignal(float pwm) { //reverses pwm signal pwm = -(pwm - 1500) + 1500; return pwm; } float degToPwm(float deg) { //converts degrees (from imu) to pwm (to servos) deg = (deg * 55.55) + 1000; return deg; } float clearSteer(float heading, float tgt) { if (abs(tgt - heading) > 180) { if (tgt < 180) { heading -= 360; } else { heading += 360; } } return heading; } void blink(int n) { for (int i = 0; i < n; i++) { digitalWrite(LED_PIN, HIGH); delay(100); digitalWrite(LED_PIN, LOW); delay(100); } } <file_sep>/imu.ino #include <Wire.h> #include <Adafruit_Sensor.h> #include <Adafruit_BNO055.h> #include <utility/imumaths.h> #include <SPI.h> #include <Adafruit_Sensor.h> #include <Adafruit_BMP183.h> // You can also use software SPI and define your own pins! #define BMP183_CLK 13 #define BMP183_SDO 12 // AKA MISO #define BMP183_SDI 11 // AKA MOSI // You'll also need a chip-select pin, use any pin! #define BMP183_CS 10 // Output pins #define LED_PIN 13 #define YAW_OUT_PIN 11 #define PITCH_OUT_PIN 10 #define ROLL_OUT_PIN 9 #define THROTTLE_OUT_PIN 3 // Input pins - digital #define CONTROL_PIN 0 // Input pins - analog #define YAW_IN_PIN 6 #define PITCH_IN_PIN 5 #define ROLL_IN_PIN 3 #define THROTTLE_IN_PIN 3 // Other input constants #define INPUT_CENTER 0 Adafruit_BNO055 gyro = Adafruit_BNO055(55); float seaLevelPressure = SENSORS_PRESSURE_SEALEVELHPA; void setup() { pinMode(LED_PIN, OUTPUT); pinMode(YAW_IN_PIN, INPUT); pinMode(PITCH_IN_PIN, INPUT); pinMode(ROLL_IN_PIN, INPUT); digitalWrite(LED_PIN, LOW); Serial.begin(9600); Serial.println("started serial"); // /* Initialise the sensors */ // if(!gyro.begin()) // { // /* There was a problem detecting the BNO055 ... check your connections */ // Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!"); // while(1); // } // // delay(1000); // blink(4); // // gyro.setExtCrystalUse(true); } void loop() { // pilot stuff unsigned long yawValIn = pulseIn(YAW_IN_PIN, HIGH); unsigned long pitchValIn = pulseIn(PITCH_IN_PIN, HIGH); unsigned long rollValIn = pulseIn(ROLL_IN_PIN, HIGH); // map from analog in range to pwm range // yawValIn = map(yawValIn, 0, 1023, 0, 255); // pitchValIn = map(pitchValIn, 0, 1023, 0, 255); // rollValIn = map(rollValIn, 0, 1023, 0, 255); // throttleValIn = map(throttleValIn, 0, 1023, 0, 255); // get sensor data // sensors_event_t event; // gyro.getEvent(&event); // float yaw = event.orientation.x; // float pitch = event.orientation.y; // float roll = event.orientation.z; /* Display the floating point data */ // Serial.print("Yaw: "); // Serial.print(yaw, 4); // Serial.print("\tPitch: "); // Serial.print(pitch, 4); // Serial.print("\tRoll: "); // Serial.print(roll, 4); Serial.print("\tYaw In: "); Serial.print(yawValIn); Serial.print("\tPitch In: "); Serial.print(pitchValIn); Serial.print("\tRoll In: "); Serial.print(rollValIn); Serial.println(""); delay(100); } void blink(int n) { for (int i = 0; i < n; i++) { digitalWrite(LED_PIN, HIGH); delay(100); digitalWrite(LED_PIN, LOW); delay(100); } } <file_sep>/rc-autopilot.ino #include <Wire.h> #include <Servo.h> #include <Adafruit_Sensor.h> #include <Adafruit_BNO055.h> #include <utility/imumaths.h> #include <SPI.h> #include <Adafruit_Sensor.h> #include <Adafruit_BMP183.h> // Time delay between runs (ms) #define DELAY 5 // Pressure sensor pins //#define BMP183_CLK 13 //#define BMP183_SDO 12 //#define BMP183_SDI 11 //#define BMP183_CS 10 // Output pins #define LED_PIN 13 #define YAW_OUT_PIN 11 #define PITCH_OUT_PIN 10 #define ROLL_OUT_PIN 9 #define THROTTLE_OUT_PIN 3 // Input pins - digital #define CONTROL_PIN 0 // Input pins - analog #define YAW_IN_PIN 0 #define PITCH_IN_PIN 1 #define ROLL_IN_PIN 2 #define THROTTLE_IN_PIN 3 // Other input constants #define INPUT_CENTER 0 // States #define STATE_MANUAL 0 #define STATE_AUTO 1 #define STATE_STRAIGHT_LEVEL 0 #define STATE_TURN 1 // Servo objects Servo yawOut; Servo pitchOut; Servo rollOut; int state = STATE_MANUAL; int autoState = STATE_STRAIGHT_LEVEL; // PID float kpYaw = 0; float kiYaw = 0; float kdYaw = 0; float kpPitch = 0; float kiPitch = 0; float kdPitch = 0; float kpRoll = 0; float kiRoll = 0; float kdRoll = 0; float targetYaw; float targetPitch; float targetRoll; float errYaw; float errPitch; float errRoll; float derrorYaw; float derrorPitch; float derrorRoll; float lastErrYaw; float lastErrPitch; float lastErrRoll; float errAccumYaw; float errAccumPitch; float errAccumRoll; // to detect when pilot lets go/moves controls again bool hasLetGo = false; bool manualTakeover = false; // Sensors Adafruit_BNO055 gyro = Adafruit_BNO055(55); //Adafruit_BMP183 pressure_sensor = Adafruit_BMP183(BMP183_CLK, BMP183_SDO, BMP183_SDI, BMP183_CS); void setup() { // Output pins pinMode(LED_PIN, OUTPUT); yawOut.attach(YAW_OUT_PIN); pitchOut.attach(PITCH_OUT_PIN); rollOut.attach(ROLL_OUT_PIN); // Input pins - digital pinMode(CONTROL_PIN, INPUT); // turn LED off digitalWrite(LED_PIN, LOW); // initialize gyro and pressure sensor bool gyro_result = gyro.begin(); //bool pressure_result = pressure_sensor.begin(); delay(1000); if (!gyro_result) { blink(5); while(true) {} } blink(2); gyro.setExtCrystalUse(true); } void loop() { // get all the inputs // pilot stuff unsigned long yawValIn = pulseIn(YAW_IN_PIN, HIGH); unsigned long pitchValIn = pulseIn(PITCH_IN_PIN, HIGH); unsigned long rollValIn = pulseIn(ROLL_IN_PIN, HIGH); bool autoSwitch = digitalRead(CONTROL_PIN); // get sensor data sensors_event_t event; gyro.getEvent(&event); float yaw = event.orientation.x; float pitch = event.orientation.y; float roll = event.orientation.z; // prevent branch cuts pitch = clearSteer(pitch, 0); roll = clearSteer(roll, 0); yaw = clearSteer(yaw, targetYaw); // update state machine switch (state) { case STATE_MANUAL: // MANUAL CONTROL yawOut.writeMicroseconds(yawValIn); pitchOut.writeMicroseconds(pitchValIn); rollOut.writeMicroseconds(rollValIn); // check switch back to manual from takeover if (!autoSwitch) { manualTakeover = false; } // check switch to auto if (autoSwitch && !manualTakeover) { targetYaw = event.orientation.x; targetPitch = 0; targetRoll = 0; state = STATE_AUTO; } break; case STATE_AUTO: switch(autoState) { case STATE_STRAIGHT_LEVEL: targetPitch = 0; targetRoll = 0; break; case STATE_TURN: break; } pid(yaw, pitch, roll); // check if pilot let go if (yawValIn == INPUT_CENTER && pitchValIn == INPUT_CENTER && rollValIn == INPUT_CENTER) { hasLetGo = true; } // check switch to manual if (!autoSwitch || (hasLetGo && (yawValIn != INPUT_CENTER || pitchValIn != INPUT_CENTER || rollValIn != INPUT_CENTER))) { hasLetGo = false; manualTakeover = true; state = STATE_MANUAL; } break; } delay(DELAY); } void pid(float yaw, float pitch, float roll) { // find errors errYaw = targetYaw - yaw; errPitch = targetYaw - pitch; errRoll = targetRoll - roll; // differentiate errors if (lastErrYaw == 0 || lastErrPitch == 0 || lastErrRoll == 0) { derrorYaw = 0; derrorPitch = 0; derrorRoll = 0; } else { derrorYaw = (errYaw - lastErrYaw) / DELAY; derrorPitch = (errPitch - lastErrPitch) / DELAY; derrorRoll = (errRoll - lastErrRoll) / DELAY; } // integrate errors errAccumYaw += yaw * DELAY; errAccumPitch += pitch * DELAY; errAccumRoll += roll * DELAY; // calculate outputs float yawValOut = kpYaw * errYaw + kiYaw * errAccumYaw + kdYaw * derrorYaw; float pitchValOut = kpPitch * errPitch + kiPitch * errAccumPitch + kdPitch * derrorPitch; float rollValOut = kpRoll * errRoll + kiRoll * errAccumRoll + kdRoll * derrorRoll; yawValOut = degToPwm(yawValOut); pitchValOut = degToPwm(pitchValOut); rollValOut = degToPwm(rollValOut); // write outputs yawOut.writeMicroseconds(yawValOut); pitchOut.writeMicroseconds(pitchValOut); rollOut.writeMicroseconds(rollValOut); } float pwmToDeg(float pwm) { //changes 1000-2000 to 0-180 and handles cases where the input goes above or below the range and returns wierd numbers pwm = (pwm * .18) - 180; if (pwm > 200 || pwm < pwm) { return 0; } else if (pwm > 180) { return 180; } else if (pwm > 82 && pwm < 96) { return 90; } else { return pwm; } } float revPWMSignal(float pwm) { //reverses pwm signal pwm = -(pwm - 1500) + 1500; return pwm; } float degToPwm(float deg) { //converts degrees (from imu) to pwm (to servos) deg = (deg * 55.55) + 1000; return deg; } float clearSteer(float heading, float tgt) { if (abs(tgt - heading) > 180) { if (tgt < 180) { heading -= 360; } else { heading += 360; } } return heading; } void blink(int n) { for (int i = 0; i < n; i++) { digitalWrite(LED_PIN, HIGH); delay(100); digitalWrite(LED_PIN, LOW); delay(100); } }
2df5c4741576cc68f83b985380166007b133374a
[ "C++" ]
3
C++
cruzsbrian/rc-autopilot
1b6eeaddea2dd19c02167bfa7bb2cd7074efa494
64b9428bbf7ff0183a372d443acd35c56262325b
refs/heads/main
<file_sep>import itertools def split(a, n): k, m = divmod(len(a), n) return (a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n)) first = ( list(split(range(-30,512), 15)) ) second = range(-16, 11) third = ( list(split(range(309), 15)) ) fourth = ( list(split(range(100,512), 15))) newList = [first, second, third, fourth] newList = list(itertools.product(*newList)) print(len(newList)) state = "18.0,0.0,69.0,119" state = state.split(",") # for i in range(len(newList)): # if float(state[0]) in newList[i][0] and float(state[1]) == newList[i][1] and float(state[2]) in newList[i][2] and float(state[3]) in newList[i][3]: # print("state[0]", state) # print("range", newList[i]) # print( list(split(range(512), 4)) ) "player_y" # print( list(split(range(309), 4)) ) "next_pipe_dist_to_player" # print( list(split(range(100,512), 4))) next_pipe_top_y" # 1: "player_y" # 2: "player_vel" # 3: "next_pipe_dist_to_player" # 4: "next_pipe_top_y" #if float(state[0]) in newList[i][0] and state[1] == i[1] and float(state[2]) in i[2] and int(state[3]) in i[3]:<file_sep>from ple.games.flappybird import FlappyBird from ple import PLE import random import json import itertools # For Learning curve plot import matplotlib.pyplot as plt class FlappyAgent: def __init__(self): # TODO: you may need to do some initialization for your agent here self.discount = 1.0 self.alpha = 0.1 self.epsilon = 0.1 self.loadQvalues() self.lastAction = 0 self.moves = [] self.lastState = 0 self.gameCount = 0 self.gameDoc = {} self.score = 0 return def split(self, a, n): k, m = divmod(len(a), n) return (a[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n)) def createRanges(self): #Itializing ranges for qvalues and setting inital values [0,0,0] first = ( list(self.split(range(-30,513), 15)) ) second = range(-20, 11) third = ( list(self.split(range(360), 15)) ) fourth = ( list(self.split(range(540), 15))) newList = [first, second, third, fourth] newList = list(itertools.product(*newList)) return newList def loadQvalues(self): """ Load q values """ self.qvalues = [] self.qkeys = self.createRanges() for i in range(len(self.qkeys)): self.qvalues.append([0,0,0]) def compareStates(self, state): for i in range(len(self.qkeys)): if state[0] in self.qkeys[i][0] and state[1] == self.qkeys[i][1] and state[2] in self.qkeys[i][2] and state[3] in self.qkeys[i][3]: state = self.qkeys[i] stateIndex = i break try: return state, stateIndex except: print("shitty state shitty life: ") print(state) with open("data/gameDoc.json", "w") as gameFile: json.dump(self.gameDoc, gameFile) return stateIndex def reward_values(self): """ returns the reward values used for training Note: These are only the rewards used for training. The rewards used for evaluating the agent will always be 1 for passing through each pipe and 0 for all other state transitions. """ return {"positive": 1.0, "tick": 0.0, "loss": -5} def observe(self, s1, a, r, s2, end,): """ this function is called during training on each step of the game where the state transition is going from state s1 with action a to state s2 and yields the reward r. If s2 is a terminal state, end==True, otherwise end==False. Unless a terminal state was reached, two subsequent calls to observe will be for subsequent steps in the same episode. That is, s1 in the second call will be s2 from the first call. """ if(end == False): self.qvalues[s1][2] += 1 self.qvalues[s1][a] = self.qvalues[s1][a] + self.alpha * (r + self.discount * max(self.qvalues[s2][0:2]) - self.qvalues[s1][a]) else: self.qvalues[s1][2] += 1 self.qvalues[s1][a] = self.qvalues[s1][a] + self.alpha * (r + self.discount * 0 - self.qvalues[s1][a]) # TODO: learn from the observation return def training_policy(self, state): """ Returns the index of the action that should be done in state while training the agent. Possible actions in Flappy Bird are 0 (flap the wing) or 1 (do nothing). training_policy is called once per frame in the game while training """ # print("state: %s" % state) state, stateIndex = self.compareStates(state) if random.uniform(0,1) > self.epsilon: exploit = self.qvalues[stateIndex].index(max(self.qvalues[stateIndex][0:2])) action = exploit else: action = random.randint(0,1) return int(action), state, stateIndex def policy(self, state): """ Returns the index of the action that should be done in state when training is completed. Possible actions in Flappy Bird are 0 (flap the wing) or 1 (do nothing). policy is called once per frame in the game (30 times per second in real-time) and needs to be sufficiently fast to not slow down the game. """ print("state: %s" % state) # TODO: change this to to policy the agent has learned # At the moment we just return an action uniformly at random. return random.randint(0, 1) def run_game(nb_episodes, agent): """ Runs nb_episodes episodes of the game with agent picking the moves. An episode of FlappyBird ends with the bird crashing into a pipe or going off screen. """ reward_values = {"positive": 1.0, "negative": 0.0, "tick": 0.0, "loss": 0.0, "win": 0.0} # TODO: when training use the following instead: # reward_values = agent.reward_values env = PLE(FlappyBird(), fps=30, display_screen=True, force_fps=False, rng=None, reward_values = reward_values) # TODO: to speed up training change parameters of PLE as follows: # display_screen=False, force_fps=True env.init() score = 0 while nb_episodes > 0: # pick an action # TODO: for training using agent.training_policy instead action = agent.policy(env.game.getGameState()) # step the environment reward = env.act(env.getActionSet()[action]) print("reward=%d" % reward) # TODO: for training let the agent observe the current state transition score += reward # reset the environment if the game is over if env.game_over(): print("score for this episode: %d" % score) env.reset_game() nb_episodes -= 1 score = 0 def train(nb_episodes, agent): reward_values = agent.reward_values() env = PLE(FlappyBird(), fps=30, display_screen=False, force_fps=True, rng=None, reward_values = reward_values) env.init() score = 0 while nb_episodes > 0: # pick an action state = env.game.getGameState() formattedState = [int(state["player_y"]), int(state["player_vel"]), int(state["next_pipe_dist_to_player"]), int(state["next_pipe_top_y"])] # str(state["player_y"]) + "," + str(state["player_vel"]) + "," + str(state["next_pipe_dist_to_player"]) + "," + str(state["next_pipe_top_y"]) action, correctState, stateIndex = agent.training_policy(formattedState) # step the environment reward = env.act(env.getActionSet()[action]) # print("reward=%d" % reward) # let the agent observe the current state transition getNewState = env.game.getGameState() newState = [int(getNewState["player_y"]), int(getNewState["player_vel"]), int(getNewState["next_pipe_dist_to_player"]), int(getNewState["next_pipe_top_y"])] newState, newStateIndex = agent.compareStates(newState) agent.observe(stateIndex, action, reward, newStateIndex, env.game_over()) score += reward agent.score += reward # reset the environment if the game is over if env.game_over(): print("score for this episode: %d" % score) agent.gameDoc[agent.gameCount] = score agent.gameCount += 1 env.reset_game() nb_episodes -= 1 score = 0 agent.lastState = 0 # if nb_episodes == 0: # with open("data/gameDoc.json", "w") as gameFile: # json.dump(agent.gameDoc, gameFile) agent = FlappyAgent() # train(5000, agent) episodes = [500,500,500,500,500,500,500,500,500,500,500,500] # episodes = [1,1,1,1,1,1] # x = [1,2,3,4,5,6] x = [500,1000,1500,2000,2500,3000,3500,4000,4500,5000,5500,6000] y = [] for episode in episodes: train(episode, agent) y.append(agent.score) title = r"Learning Curve (Q-Learning, $\alpha=0.1$, $\epsilon=0.1$, $\gamma=1.0$)" yMinimum = max(y) yMaximum = min(y) plt.plot(x,y) plt.xlabel('Episodes') plt.ylabel('Score') plt.title(title) plt.show()<file_sep># flappyBird Project 2 for Introduction to Machine Learning class at RU
f0e1d3e41b737f663a932883befad3a74db2c16d
[ "Markdown", "Python" ]
3
Python
franklin18ru/flappyBird
00bd5faa6dfab203ed52f6528826195aa5a2d747
4aee915d9002a0a21c8d9b3d30fada97f019d9d9
refs/heads/master
<repo_name>mikhailadvani/aws_s3sync<file_sep>/README.md # aws_s3sync ## Installation `pip install aws_s3sync` ## Execution #### Pre-requisites Setup the following environment variables * **AWS_ACCESS_KEY_ID** * **AWS_SECRET_ACCESS_KEY** #### Commands `sync_to_s3` `sync_from_s3` #### Arguments ``` -h, --help show this help message and exit -b BUCKET, --bucket BUCKET Upload: Selects the S3 bucket to upload data to. Download: Selects the S3 bucket to download data from -f FILE_PATH, --file_path FILE_PATH Upload: Path of the file to be uploaded. Download: Path to download file to -k KEY, --key KEY Key of the object. Same as file_path is undefined for upload -m {auto,sync,single-part-upload}, --mode {auto,sync,single-part-upload} Mode of upload/download --chunk_size CHUNK_SIZE Size of chunk in multipart upload in MB --multipart_threshold MULTIPART_THRESHOLD Minimum size in MB to upload using multipart ``` ##### Mode * `auto` : Upload: Single-part upload or multi-part upload will be chosen based on the file being smaller/larger than `multipart_threshold` * `sync` : Upload/downloand file to/from S3 only if the local/remote file have different signatures. Checked based on ETag/MD5 * `single-part-upload` : Force single-part upload. Applicable only for files of size larger than `multipart_threshold` <file_sep>/aws_s3sync/__init__.py #!/usr/bin/env python import os import math import boto import argparse import hashlib import time AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] def log(msg): timestamp = time.strftime("%Y-%m-%d %H:%M:%S") print "%s %s" % (timestamp, msg) def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument("-b", "--bucket", type=str, required=True, help="Upload: Selects the S3 bucket to upload data to. Download: Selects the S3 bucket to download data from") parser.add_argument("-f", "--file_path", type=str, required=True, help="Upload: Path of the file to be uploaded. Download: Path to download file to") parser.add_argument("-k", "--key", type=str, default=None, help="Key of the object. Same as file_path is undefined for upload") parser.add_argument("-m","--mode", default='auto', choices=['auto', 'sync', 'single-part-upload'],help="Mode of upload/download") parser.add_argument("--chunk_size", default=5, type=int, help="Size of chunk in multipart upload in MB. Minimum 5. Refer http://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadUploadPart.html") parser.add_argument("--multipart_threshold", default=10, type=int, help="Minimum size in MB to upload using multipart") args = parser.parse_args() if args.key is None: args.key = args.file_path if args.chunk_size < 5: log("Chunk size needs to be a minimum of 5 MB") exit(1) args.chunk_size = args.chunk_size * 1024 *1024 args.multipart_threshold = args.multipart_threshold * 1024 *1024 return args def multipart_upload_to_be_used(file_path, multipart_threshold): file_size = os.stat(file_path).st_size log("event=get_file_size size=%d" % file_size) return file_size > multipart_threshold def need_to_update(s3_connection, bucket_name, file_path, s3_path): bucket = s3_connection.get_bucket(bucket_name) log("event=get_bucket bucket=%s" % bucket_name) key = bucket.get_key(s3_path) log("event=get_key key=%s" % key) if key is None: return True else: local_md5 = hashlib.md5(open(file_path, "rb").read()).hexdigest() log("event=generate_local_signature local_signature=%s" % local_md5) remote_md5 = key.get_metadata('md5') log("event=get_remote_signature remote_signature=%s" % remote_md5) return local_md5 != remote_md5 def need_to_fetch(s3_connection, bucket_name, file_path, s3_path): if not os.path.isfile(file_path): log("event=check_file_exists_locally status=failed") return True else: log("event=check_file_exists_locally status=success") return need_to_update(s3_connection, bucket_name, file_path, s3_path) def simple_upload(s3_connection, bucket_name, file_path, s3_path): bucket = s3_connection.get_bucket(bucket_name) key = boto.s3.key.Key(bucket, s3_path) key.set_metadata('md5', hashlib.md5(open(file_path, "rb").read()).hexdigest()) try: key.set_contents_from_filename(file_path) log("event=upload_complete status=success") except Exception as e: log("event=upload_complete status=failed") log(str(e)) def multipart_upload(s3, bucketname, file_path, s3_path, chunk_size): log("event=get_bucket bucket=%s" % bucketname) bucket = s3.get_bucket(bucketname) log("event=multi_part_request_initiated bucket=%s status=triggered" % bucketname) multipart_upload_request = bucket.initiate_multipart_upload(s3_path, metadata={'md5': hashlib.md5(open(file_path, "rb").read()).hexdigest()}) log("event=multi_part_request_initiated status=success") file_size = os.stat(file_path).st_size chunks_count = int(math.ceil(file_size / float(chunk_size))) for i in range(chunks_count): offset = i * chunk_size remaining_bytes = file_size - offset payload_bytes = min([chunk_size, remaining_bytes]) part_num = i + 1 log("event=upload_part part_num=%d total_parts=%d" % (part_num, chunks_count)) with open(file_path, 'r') as file_pointer: file_pointer.seek(offset) upload_part(file_pointer, multipart_upload_request, part_num, payload_bytes) multipart_upload_request.complete_upload() log("event=upload_complete status=success") def upload_part(file_pointer, multipart_upload_request, part_num, payload_bytes, attempt=1): if attempt > 5: log("event=upload_complete status=failed") multipart_upload_request.cancel_upload() try: multipart_upload_request.upload_part_from_file(fp=file_pointer, part_num=part_num, size=payload_bytes) except Exception as e: pause_between_retries = 30 log("event=upload_part_failed part_num=%d attempt=%d retry_after=%d" % (part_num, attempt, pause_between_retries)) log(str(e)) time.sleep(pause_between_retries) upload_part(file_pointer, multipart_upload_request, part_num, payload_bytes, attempt + 1) def upload(s3_connection, bucketname, file_path, s3_path, mode, chunk_size, multipart_threshold): if multipart_upload_to_be_used(file_path, multipart_threshold) and mode != 'single-part-upload': log("event=start_multipart_upload bucket=%s file_path=%s key=%s chunk_size=%d multipart_threshold=%d" % (bucketname, file_path, s3_path, chunk_size, multipart_threshold)) multipart_upload(s3_connection, bucketname, file_path, s3_path, chunk_size) else: log("event=start_simple_upload bucket=%s file_path=%s key=%s" % (bucketname, file_path, s3_path)) simple_upload(s3_connection, bucketname, file_path, s3_path) def download(s3_connection, bucketname, file_path, s3_path): bucket = s3_connection.get_bucket(bucketname) key = boto.s3.key.Key(bucket, s3_path) try: log("event=start_download key=%s" % s3_path) key.get_contents_to_filename(file_path) log("event=download_complete status=success") except Exception as e: log("event=download_complete status=failed") log(str(e)) def sync_to_s3(): args = parse_arguments() s3_connection = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) log("event=s3_connection state=established") upload_needed = need_to_update(s3_connection, args.bucket, args.file_path, args.key) log("upload_mode=%s" % args.mode) log("upload_needed=%s" % upload_needed) if args.mode != 'sync' or upload_needed: log("event=choose_upload_type") upload(s3_connection, args.bucket, args.file_path, args.key, args.mode, args.chunk_size, args.multipart_threshold) else: log("event=upload_skipped") def sync_from_s3(): args = parse_arguments() s3_connection = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) log("event=s3_connection state=established") download_needed = need_to_fetch(s3_connection, args.bucket, args.file_path, args.key) log("download_mode=%s" % args.mode) log("download_needed=%s" % download_needed) if args.mode != 'sync' or download_needed: download(s3_connection, args.bucket, args.file_path, args.key) else: log("event=download_skipped")<file_sep>/pypi.sh #!/usr/bin/env bash set -e clean() { rm -rf build dist aws_s3sync.egg-info } build() { clean python setup.py sdist python setup.py bdist_wheel } uninstall() { pip uninstall -y aws_s3sync } publishToTestPyPi() { python setup.py register -r https://testpypi.python.org/pypi twine upload dist/* -r testpypi uninstall pip install -i https://testpypi.python.org/pypi aws_s3sync } publishToPyPi() { python setup.py register -r https://pypi.python.org/pypi twine upload dist/* uninstall pip install aws_s3sync } if [ "$1" = 'publish' ]; then if [ "$2" = 'test' ]; then publishToTestPyPi elif [ "$2" = 'prod' ]; then publishToPyPi else echo "No publish target defined" exit 1 fi elif [ "$1" = 'clean' ]; then clean elif [ "$1" = 'build' ]; then build else echo "No task defined" exit 1 fi <file_sep>/cli.py #!/usr/bin/env python import aws_s3sync aws_s3sync.sync_from_s3()
7f82c22809fa69ee0d8fab75bc5cf5a86cfff2c8
[ "Markdown", "Python", "Shell" ]
4
Markdown
mikhailadvani/aws_s3sync
04074dcfda013a601ac94ec221a552968a3d884a
5e6900878d2e13a7f9a76b1704b215e3eee00577
refs/heads/master
<file_sep><?php namespace XLib\Brightpearl; if(!class_exists('\GuzzleHttp\Client')) { require_once __DIR__ . '../../../vendor/autoload.php'; } class DynamicService { public $securityToken; public $applicationRefID; public $accountName; public $targetURL; public $service; public $target; public $endPoint; public $destURL; public $httpClient; public $response; public function __construct() { $this->httpClient = new \GuzzleHttp\Client(); } public function packArgs() { $list = array(); foreach(func_get_args() as $key => $value) { $list[$key] = $value; } return join('/', $list); } public function loadArgs() { $list = array(); foreach(func_get_args() as $key => $value) { $list[$key] = $value; } if(!empty($list)) { $this->service = array_shift($list); } if(!empty($list)) { $this->target = array_shift($list); } if(!empty($list)) { $this->endPoint = array_shift($list); } return $this; } public function buildDestURL() { $this->destURL = (isset($this->endPoint) && $this->endPoint !== null) ? $this->packArgs($this->targetURL, $this->accountName, $this->service, $this->target, $this->endPoint) : $this->packArgs($this->targetURL, $this->accountName, $this->service, $this->target); return $this; } public function send() { if(func_num_args() > 0) { call_user_func_array( array($this, 'loadArgs'), func_get_args() ); } $this->buildDestURL(); $response = $this->httpClient->get($this->destURL, [ 'verify' => false, 'headers' => [ 'brightpearl-app-ref' => $this->applicationRefID, 'brightpearl-account-token' => $this->securityToken ] ] ); if($response->getStatusCode() == 200) { $this->response = $response; return json_decode($this->response->getBody(), true); } return null; } /* private function _createHttpClient() { $arr = array( 'handle' => new \GuzzleHttp\Client(), 'url' => 'https://ws-use.brightpearl.com/public-api', 'accountName' => '_____', 'service' => '', 'target' => '', 'endPoint' => '', 'appRefID' => '_________', 'securityToken' => '__________', 'response' => '', 'returnJSON' => null ); } private function createApiObject($service, $target, $endp) { $this->service = $service; $this->target = $target; $this->endPoint = $endp; $api = new \XLib\Brightpearl\API(); $api->requestUrl = $this->requestURL; $api->accountName = $this->accountName; $api->service = $this->service; $api->target = $this->target; $api->appReferenceId = $this->appRefId; $api->securityToken = $this->securityToken; return $api; } private function sendGetRequest($api) { return ($this->endPoint !== '') ? $api->dynamicGetRequest($this->service, $this->target, $this->endPoint) : $api->dynamicGetRequest($this->service, $this->target); } public function get($service, $target, $endp = '') { $this->service = $service; $this->target = $target; $this->endPoint = $endp; $api = new \XLib\Brightpearl\API(); $api->requestUrl = $this->requestURL; $api->accountName = $this->accountName; $api->service = $this->service; $api->target = $this->target; $api->appReferenceId = $this->appRefId; $api->securityToken = $this->securityToken; if($endp !== '') { $orderResponse = $api->dynamicGetRequest($this->service, $this->target, $this->endPoint); } else { $orderResponse = $api->dynamicGetRequest($this->service, $this->target); } $orderResponse = isset($orderResponse['response']) ? $orderResponse['response'] : null; $this->response = $orderResponse; return $this->response; } public function getJSON($service, $target, $endp='') { $api = $this->createApiObject($service, $target, $endp); if($endp !== '') { $this->sendGetRequest($api); } else { } } public function getWarehouseByName($name=null) { if($name == null) { return null; } $name = strtolower($name); $list = $this->get('warehouse-service', 'warehouse'); if(is_array($list)) { foreach ($list as $key => $val) { if(isset($val['name'])) { $wname = strtolower($val['name']); if(strval($name) === strval($wname)) { return $val; } } } } return null; } public function getWarehouseById($id=null) { if($id == null) { return null; } $list = $this->get('warehouse-service', 'warehouse'); if(is_array($list)) { foreach ($list as $key => $val) { if(isset($val['id'])) { if(intval($id) === intval($val['id'])) { return $val; } } } } return null; } public function getOrderWarehouse($id=null) { if($id == null) return null; $list = $this->get('order-service', 'order', $id); if(is_array($list)) { if(count($list) > 0) { $item = $list[0]; $warehouseId = $item['warehouseId']; $warehouse = $this->getWarehouseById($warehouseId); return $warehouse; } return $list; } } public function getOrderWarehouseName($id=null) { if($id == null) return null; $list = $this->get('order-service', 'order', $id); if(is_array($list)) { if(count($list) > 0) { $item = $list[0]; $warehouseId = $item['warehouseId']; $warehouse = $this->getWarehouseById($warehouseId); return $warehouse['name']; } return $list; } } public function getOrder($id=null) { if($id === null) return null; $list = $this->get('order-service', 'order', $id); if(is_array($list)) { if(count($list) > 0) { return $list[0]; } } return null; } public function getWarehouses() { $list = $this->get('warehouse-service', 'warehouse'); if(is_array($list)) { return $list; } return null; }*/ }<file_sep><?php namespace XLib\Brightpearl; class WebServiceDriver { private $sAuth; private $sAPI; private $tokenAuth; private $webAPI; public function __construct($sAuth=NULL, $sAPI=NULL, $tokenAuth=NULL, $webAPI=NULL) { $this->sAuth = $sAuth; $this->sAPI = $sAPI; $this->tokenAuth = $tokenAuth; $this->webAPI = $webAPI; } public function setStructAuthentication($sAuth) { $this->sAuth = $sAuth; return $this; } public function getStructAuthentication() { return $this->sAuth; } public function setStructAPI($sAPI) { $this->sAPI = $sAPI; return $this; } public function getStructAPI() { return $this->sAPI; } public function setTokenAuthentication($tokenAuth) { $this->tokenAuth = $tokenAuth; return $this; } public function getTokenAuthentication() { return $this->tokenAuth; } public function setWebAPI($webAPI) { $this->webAPI = $webAPI; return $this; } public function getWebAPI() { return $this->webAPI; } }<file_sep>try { if(typeof(xlib) === "undefined") { throw "xlib: missing core library"; } xlib.util = {}; xlib.util.getTypeNameString = function(obj) { var rxFuncName = /function (.{1,})\(/; var res = (rxFuncName).exec((obj).constructor.toString()); return (results && results.length > 1) ? results[1] : ''; }; xlib.util.trimTypeof = function(obj) { return typeof(obj).toString().trim(); }; xlib.util.toArray = function(obj) { var arr = []; if (typeof obj == 'object' && obj.hasOwnProperty) { for (var itr in obj) { if (obj.hasOwnProperty(itr)) { arr.push(obj[itr]); } } } else { for (var itr in obj) { arr.push(obj[itr]); } } return arr; }; xlib.util.walkObject = function() { var args = arguments || []; var target = args[0] || {}, cbfn = args[1] || null, depth = args[2] || 1, node = null; for (node in target) { var current = target[node]; if (target.hasOwnProperty && target.hasOwnProperty(node)) { if (cbfn !== null) { if (cbfn.call({}, current) === false) { break; } } if (typeof current == 'object' || typeof current == 'array' || (current.length && current.length > 0)) { depth++; xlib.util.walkObject(current, cbfn, depth); } } } }; xlib.util.dir = function(obj) { for (var itr in obj) { print(itr, ' = ', obj[itr]); } }; xlib.util.rdirMaxDepth = 20; xlib.util.rdir = function() { var args = xlib.util.toArray(arguments); letobj = arguments[0] || {}, depth = arguments[1] || 1, tab = Array(depth).join('\t'); for (var key in obj) { if (obj[key] == null || !obj[key] || !(key in obj) && !obj.hasOwnProperty(key)) { break; } var node = obj[key]; var type = '[' + typeof(node).toString().trim() + ']'; if (typeof node == 'object' && node !== null && xlib.util.rdirMaxDepth >= depth) { print('\n\n', tab, type, key, '=', '[' + typeof(node) + '] {'); depth++; xlib.util.rdir(node, depth); print(tab, '}'); } else { print(tab, type, key, '=', node); } } }; } catch (err) { console.error(err); }<file_sep><?php namespace XLib\Brightpearl\Warehouse; use \XLib\Utils\Output as XLibOutput; class Janssen { public function sendDropFile($dropFile) { $host = '127.0.0.1'; $user = 'test'; $pass = '123'; $todir = 'ftp_testing/janssen'; $ftp = new \XLib\FTP($host, $user, $pass); $ftp->connect() or die('Failed to connect to FTP'); $ftp->login() or die('Failed to login to FTP'); $ftp->changeDirectory($todir); if(!$ftp->fileExists($dropFile)) { XLibOutput::pl('Sending files to remote server via FTP'); $ftp->putFile($dropFile, $dropFile) or die('Failed to transfer file'); XLibOutput::pl('Finished sending file to remote server.'); } else { XLibOutput::pl('Files not sent. Already exists on remote FTP server.'); } $ftp->close(); if(file_exists($dropFile)) { @unlink($dropFile); } return $this; } public function generateDropFile($data) { if (isset($data['response'])) { $data = $data['response'][0]; } $datetime = '2015-08-19T14:14:29.000-04:00'; $arrDateTime = explode('T', $datetime); $date = $arrDateTime[0]; $time = str_replace(".000-04:00", "+04:00", $arrDateTime[1]); date_default_timezone_set('US/Eastern'); $xmlns = 'http://www.kewill.com/logistics/klic/inbound'; $testing = true; $dom = new \DOMDocument(); $dom->formatOutput = true; $inbound = $dom->createElementNS($xmlns, 'inbound'); $inbound->setAttribute('type', 'tag'); $ediCustomerNumber = $dom->createElement('ediCustomerNumber'); $ediCustomerNumber->nodeValue = ($testing === true) ? '10008392' : '10008520'; $inbound->appendChild($ediCustomerNumber); $ediCustomerDepartment = $dom->createElement('ediCustomerDepartment'); $ediCustomerDepartment->nodeValue = 'klic'; $inbound->appendChild($ediCustomerDepartment); $ediParm1 = $dom->createElement('ediParm1'); $ediParm1->nodeValue = '5'; $inbound->appendChild($ediParm1); $ediParm2 = $dom->createElement('ediParm2'); $ediParm2->nodeValue = 'i'; $inbound->appendChild($ediParm2); $ediParm3 = $dom->createElement('ediParm3'); $ediParm3->nodeValue = 'd'; $inbound->appendChild($ediParm3); $transmitter = $dom->createElement('transmitter'); $transmitter->nodeValue = 'Master &amp; Dynamic'; $inbound->appendChild($transmitter); $receiver = $dom->createElement('receiver'); $receiver->nodeValue = 'Janssen Distribution Center'; $inbound->appendChild($receiver); $ediReference = $dom->createElement('ediReference'); $ediReference->nodeValue = $data['id']; $inbound->appendChild($ediReference); $referenceIndication = $dom->createElement('referenceIndication'); $referenceIndication->nodeValue = '0'; $inbound->appendChild($referenceIndication); $ediFunction = $dom->createElement('ediFunction1'); $ediFunction->nodeValue = '9'; $inbound->appendChild($ediFunction); $ediCustomerSearchName = $dom->createElement('ediCustomerSearchName'); $ediCustomerSearchName->nodeValue = 'MASNEW'; $inbound->appendChild($ediCustomerSearchName); $employeesInitials = $dom->createElement('employeesInitials'); $employeesInitials->nodeValue = 'accj'; $inbound->appendChild($employeesInitials); $order = $dom->createElement('order'); $order->setAttribute('type', 'tag'); $inbound->appendChild($order); // LOADING DATE $loadingDate = $dom->createElement('loadingDate'); # current hour $chour = intval(date('G')); $dt = null; # if before 9am if ($chour < 9) { # set loading date for today $dt = new DateTime('today'); $loadingDate->nodeValue = $dt->format('Y-m-d'); } else { $dt = new \DateTime('tomorrow'); $loadingDate->nodeValue = $dt->format('Y-m-d'); } $order->appendChild($loadingDate); $loadingTime = $dom->createElement('loadingTime'); $loadingTime->nodeValue = '08:00:00'; $order->appendChild($loadingTime); $unloadingDate = $dom->createElement('unloadingDate'); $unloadingDate->nodeValue = $dt->format('Y-m-d'); $order->appendChild($unloadingDate); $unloadingTime = $dom->createElement('unloadingTime'); $unloadingTime->nodeValue = '17:00:00'; $order->appendChild($unloadingTime); $primaryReference = $dom->createElement('primaryReference'); $primaryReference->nodeValue = $data['id']; $order->appendChild($primaryReference); $deliveryTerm = $dom->createElement('deliveryTerm'); $deliveryTerm->nodeValue = 'DDP'; $order->appendChild($deliveryTerm); # CUSTOM ITEMS $customItems = $dom->createElement('customItems'); $order->appendChild($customItems); # CUSTOM ITEMS - countryOfDespatch $countryOfDespatch = $dom->createElement('countryOfDespatch'); $countryOfDespatch->nodeValue = 'NL'; $customItems->appendChild($countryOfDespatch); # CUSTOM ITEMS - countryOfDestination $countryOfDestination = $dom->createElement('countryOfDestination'); $countryOfDestination->nodeValue = $data['parties']['delivery']['countryIsoCode']; $customItems->appendChild($countryOfDestination); #date and time $dateTimeZones = $dom->createElement('dateTimeZones'); $dateTimeZones->setAttribute('type', 'tag'); $order->appendChild($dateTimeZones); #type of date $typeOfDate = $dom->createElement('typeOfDate'); $typeOfDate->nodeValue = '1000'; $dateTimeZones->appendChild($typeOfDate); # date time zone $dateTimeZone = $dom->createElement('dateTimeZone'); $dateTimeZone->nodeValue = date('c'); $dateTimeZones->appendChild($dateTimeZone); # address 0 $address0 = $dom->createElement('address'); $address0->setAttribute('type', 'tag'); $order->appendChild($address0); $addressType0 = $dom->createElement('addressType'); $addressType0->nodeValue = '0'; $address0->appendChild($addressType0); $searchName0 = $dom->createElement('searchName'); $searchName0->nodeValue = 'MASNEW'; $address0->appendChild($searchName0); $relationNumber0 = $dom->createElement('relationNumber'); $relationNumber0->nodeValue = '10008520'; $address0->appendChild($relationNumber0); # address 1 $address1 = $dom->createElement('address'); $address1->setAttribute('type', 'tag'); $order->appendChild($address1); $addressType1 = $dom->createElement('addressType'); $addressType1->nodeValue = '1'; $address1->appendChild($addressType1); $searchName1 = $dom->createElement('searchName'); $searchName1->nodeValue = 'JANVEN'; $address1->appendChild($searchName1); $relationNumber1 = $dom->createElement('relationNumber'); $relationNumber1->nodeValue = '10001004'; $address1->appendChild($relationNumber1); # address 2 $address2 = $dom->createElement('address'); $address2->setAttribute('type', 'tag'); $order->appendChild($address2); $addressType2 = $dom->createElement('addressType'); $addressType2->nodeValue = '2'; $address2->appendChild($addressType2); $searchName2 = $dom->createElement('searchName'); $searchName2->nodeValue = 'JANVEN'; $address2->appendChild($searchName2); $relationNumber2 = $dom->createElement('relationNumber'); $relationNumber2->nodeValue = '10001004'; $address2->appendChild($relationNumber2); # address 3 $address3 = $dom->createElement('address'); $address3->setAttribute('type', 'tag'); $order->appendChild($address3); $addressType3 = $dom->createElement('addressType'); $addressType3->nodeValue = '3'; $address3->appendChild($addressType3); $searchName3 = $dom->createElement('searchName'); $firstInitial = strtoupper(substr($data['parties']['delivery']['addressFullName'], 0, 1)); $orderNumber = $data['id']; $searchName3->nodeValue = $firstInitial . $orderNumber; $address3->appendChild($searchName3); $addressDetails3 = $dom->createElement('addressDetails'); $address3->appendChild($addressDetails3); $nameLine13 = $dom->createElement('nameLine1'); $nameLine13->nodeValue = $data['parties']['delivery']['addressFullName']; $addressDetails3->appendChild($nameLine13); $addressLine13 = $dom->createElement('addressLine1'); $addressLine13->nodeValue = $data['parties']['delivery']['addressLine1']; $addressDetails3->appendChild($addressLine13); $cityName3 = $dom->createElement('cityName'); $cityName3->nodeValue = $data['parties']['delivery']['addressLine3']; $addressDetails3->appendChild($cityName3); $postalCode3 = $dom->createElement('postalCode'); $postalCode3->nodeValue = $data['parties']['delivery']['postalCode']; $addressDetails3->appendChild($postalCode3); $countryCode3 = $dom->createElement('countryCode'); $countryCode3->nodeValue = $data['parties']['delivery']['countryIsoCode']; $addressDetails3->appendChild($countryCode3); $contactInformation3 = $dom->createElement('contactInformation'); $address3->appendChild($contactInformation3); # telephone or mobile phone number $tele = $data['parties']['delivery']['telephone']; if ($tele == '') { $tele = $data['parties']['delivery']['mobileTelephone']; } $telephoneNumber3 = $dom->createElement('telephoneNumber'); $telephoneNumber3->nodeValue = preg_replace("/[^0-9]/", '', $tele); $contactInformation3->appendChild($telephoneNumber3); $timeFrames3 = $dom->createElement('timeFrames'); $timeFrames3->setAttribute('type', 'tag'); $address3->appendChild($timeFrames3); $fromTime3 = $dom->createElement('fromTime'); $fromTime3->nodeValue = '08:00:00'; $timeFrames3->appendChild($fromTime3); $tillTime3 = $dom->createElement('tillTime'); $tillTime3->nodeValue = '17:00:00'; $timeFrames3->appendChild($tillTime3); # address 4 $address4 = $dom->createElement('address'); $address4->setAttribute('type', 'tag'); $order->appendChild($address4); $addressType4 = $dom->createElement('addressType'); $addressType4->nodeValue = '4'; $address4->appendChild($addressType4); $searchName4 = $dom->createElement('searchName'); $firstInitial = strtoupper(substr($data['parties']['delivery']['addressFullName'], 0, 1)); $orderNumber = $data['id']; $searchName4->nodeValue = $firstInitial . $orderNumber; $address4->appendChild($searchName4); $addressDetails4 = $dom->createElement('addressDetails'); $address4->appendChild($addressDetails4); $nameLine14 = $dom->createElement('nameLine1'); $nameLine14->nodeValue = $data['parties']['delivery']['addressFullName']; $addressDetails4->appendChild($nameLine14); $addressLine14 = $dom->createElement('addressLine1'); $addressLine14->nodeValue = $data['parties']['delivery']['addressLine1']; $addressDetails4->appendChild($addressLine14); $cityName4 = $dom->createElement('cityName'); $cityName4->nodeValue = $data['parties']['delivery']['addressLine3']; $addressDetails4->appendChild($cityName4); $postalCode4 = $dom->createElement('postalCode'); $postalCode4->nodeValue = $data['parties']['delivery']['postalCode']; $addressDetails4->appendChild($postalCode4); $countryCode4 = $dom->createElement('countryCode'); $countryCode4->nodeValue = $data['parties']['delivery']['countryIsoCode']; $addressDetails4->appendChild($countryCode4); $contactInformation4 = $dom->createElement('contactInformation'); $address4->appendChild($contactInformation4); # telephone or mobile phone number $tele = $data['parties']['delivery']['telephone']; if ($tele == '') { $tele = $data['parties']['delivery']['mobileTelephone']; } $telephoneNumber4 = $dom->createElement('telephoneNumber'); $telephoneNumber4->nodeValue = preg_replace("/[^0-9]/", '', $tele); $contactInformation4->appendChild($telephoneNumber4); # ORDER ARTICLE LINES foreach ($data['orderRows'] as $key => $value) { $orderId = $key; $orderObj = $value; $articleLine = $dom->createElement('articleLine'); $articleLine->setAttribute('type', 'tag'); $order->appendChild($articleLine); $orderType = $dom->createElement('orderType'); $orderType->nodeValue = '50'; $articleLine->appendChild($orderType); $articleCode = $dom->createElement('articleCode'); $articleCode->nodeValue = $orderObj['productSku']; $articleLine->appendChild($articleCode); $quantity = $dom->createElement('quantity'); $quantity->nodeValue = $orderObj['quantity']['magnitude']; $articleLine->appendChild($quantity); $packageCode = $dom->createElement('packageCode'); $packageCode->nodeValue = 'st'; $articleLine->appendChild($packageCode); $expected = $dom->createElement('expected'); $articleLine->appendChild($expected); $quantitySKU = $dom->createElement('quantitySKU'); $quantitySKU->nodeValue = $orderObj['quantity']['magnitude']; $expected->appendChild($quantitySKU); $grossWeight = $dom->createElement('grossWeight'); $grossWeight->nodeValue = '0.000'; $expected->appendChild($grossWeight); $netWeight = $dom->createElement('netWeight'); $netWeight->nodeValue = '0.000'; $expected->appendChild($netWeight); $quantityPackageCode1 = $dom->createElement('quantityPackageCode1'); $quantityPackageCode1->nodeValue = '0.000'; $expected->appendChild($quantityPackageCode1); $quantityPackageCode2 = $dom->createElement('quantityPackageCode2'); $quantityPackageCode2->nodeValue = '0.000'; $expected->appendChild($quantityPackageCode2); $quantityPackageCode3 = $dom->createElement('quantityPackageCode3'); $quantityPackageCode3->nodeValue = '0.000'; $expected->appendChild($quantityPackageCode3); $quantityPackageCode4 = $dom->createElement('quantityPackageCode4'); $quantityPackageCode4->nodeValue = '0.000'; $expected->appendChild($quantityPackageCode4); } $dom->appendChild($inbound); file_put_contents($data['id'] . '.xml', $dom->saveXML()); return $data['id'] . '.xml'; } } <file_sep><?php namespace XLib\Brightpearl; require_once 'XLibBrightpearlAuth.php'; class Client extends \XLib\Brightpearl\Auth { public $clientData = [ 'handle' => null, 'result' => null, 'statusCode' => null, 'config' => [] ]; public function __construct() { parent::__construct(); $this->clientData['handle'] = new \GuzzleHttp\Client(); } public function getHttpClient() { return $this->clientData['handle']; } public function setHttpClient($obj) { $this->clientData['handle'] = $obj; return $this; } }<file_sep>xlib.type = function(obj) { var cttype = {}; var toString = cttype.toString; $.each('Boolean Number String Function Array Date RegExp Object Error'.split(' '), function(idx, name) { cttype['[object ' + name + ']'] = name.toLowerCase(); }); if(obj == null) { return obj + ''; } return typeof obj === "object" || typeof obj == "function" ? cttype[toString.call(obj)] || "object" : typeof obj; }; xlib.isEmpty = function(obj) { for(var i in obj) { if(obj.hasOwnProperty(i)) { return false; } } return true; }; xlib.initMemberPath = function(aTarget, aPath, aOverwrite) { aOverwrite = aOverwrite || false; if(typeof aPath == "object" || aPath instanceof Array) { for(var i=0; i < aPath.length; i++) { xlib.buildPath(aTarget, aPath[i], aOverwrite); } } else { aPath = aPath.split('.') || []; for(var i=0; i < aPath.length; i++) { var index = aPath[i]; if(!aTarget[index] || aOverwrite == true || xlib.isEmpty(aTarget[index])) { aTarget[index] = {}; } aTarget = aTarget[index]; } } return aTarget; }; var fn1 = function() { var cx = {}, xl = this; $.extend (xl.type, { isWindow: function(obj) { return (obj instanceof Window) ? true : false; }, isObject: function(obj) { return (typeof obj === "object" && obj instanceof Object && !obj.hasOwnProperty('length')) ? true : false; }, isArray: function(obj) { return (typeof obj === "object" && obj instanceof Array && obj.hasOwnProperty('length') && obj.length && obj.length >= 0) ? true : false; } }); pl(this); return xl; }; var ret = fn1.apply(xlib); <file_sep><?php namespace XLib\Brightpearl; require_once 'XLibBrightpearlAuth.php'; require_once 'XLibBrightpearlClient.php'; class Request { public $requestData = [ 'service' => null, 'target' => null, 'endPoint' => null, 'destURL' => null, 'targetURL' => null, 'httpClientConfig' => null, 'result' => null, 'response' => null ]; private $_auth; private $_client; private $_httpClient; public function __construct() { $this->_auth = new \XLib\Brightpearl\Auth(); $this->_client = new \XLib\Brightpearl\Client(); $this->_httpClient = $this->_client->clientData['handle']; $this->loadDefaults(); if(func_num_args() > 0) { $args = []; foreach(func_get_args() as $key => $value) { $args[$key] = $value; } $str = call_user_func_array(array(__CLASS__, 'loadArgs'), $args); } } public function loadDefaults() { $arr = [ 'targetURL' => 'https://ws-use.brightpearl.com/public-api', 'httpClientConfig' => array( 'verify' => false, 'headers' => [ 'brightpearl-app-ref' => $this->_auth->get('appRefId'), 'brightpearl-account-token' => $this->_auth->get('securityToken') ] ) ]; $tmp = array_merge($this->requestData, $arr); $this->requestData = $tmp; return $this; } public function &getAuth() { return $this->_auth; } public function &getClient() { return $this->_client; } public function &getHttpClient() { return $this->_httpClient; } public function __get($name) { if(array_key_exists($name, $this->requestData)) { return $this->requestData[$name]; } elseif($name == null || $name == flase || !$name) { return $this->requestData; } return $this; } public function getAll() { return $this->requestData; } public function &getAllByRef() { return $this->requestData; } public function __set($name, $value) { $this->requestData[$name] = $value; return $this; } public function packArgs() { $list = []; foreach(func_get_args() as $k => $v) { $list[$k] = $v; } return join('/', $list); } public function loadArgs() { $list = []; foreach(func_get_args() as $k => $v) { $list[$k] = $v; } if(!empty($list)) { $this->service = array_shift($list); } if(!empty($list)) { $this->target = array_shift($list); } if(!empty($list)) { $this->endPoint = array_shift($list); } return $this; } public function buildDestURL() { $pAuth =& $this->getAuth(); if(!empty($this->requestData['service']) && !empty($this->requestData['target'])) { $this->requestData['destURL'] = (isset($this->requestData['endPoint']) && $this->requestData['endPoint'] !== null) ? $this->packArgs($this->requestData['targetURL'], $pAuth->get('accountName'), $this->requestData['service'], $this->requestData['target'], $this->requestData['endPoint']) : $this->packArgs($this->requestData['targetURL'], $pAuth->get('accountName'), $this->requestData['service'], $this->requestData['target']); } return $this; } public function sendGet() { if(func_num_args() > 0) { call_user_func_array( array($this, 'loadArgs'), func_get_args() ); $this->buildDestURL(); } $client = $this->getHttpClient(); $result = $client->get( $this->requestData['destURL'], $this->requestData['httpClientConfig'] ); pr($this->requestData['httpClientConfig']); if(isset($result->getStatusCode) && $result->getStatusCode() == 200) { $this->requestData['response'] = json_decode($result->getBody(), true); $this->requestData['result'] = $result; return $this->requestData['response']; } return $this; } }<file_sep><?php namespace XLib\Brightpearl; class StructAPI { private $accountName; private $serviceSubject; private $serviceTarget; private $serviceTargetURL; private $serviceHostURL; private $accountSecurityToken; private $applicationReferenceID; public function __construct($accountName = NULL, $serviceSubject = NULL, $serviceTarget = NULL, $serviceTargetURL = NULL, $serviceHostURL = NULL, $accountSecurityToken = NULL, $applicationReferenceID = NULL) { $this->accountName = $accountName; $this->serviceSubject = $serviceSubject; $this->serviceTarget = $serviceTarget; $this->serviceTargetURL = $serviceTargetURL; $this->serviceHostURL = $serviceHostURL; $this->accountSecurityToken = $accountSecurityToken; $this->applicationReferenceID = $applicationReferenceID; } public function setAccountName($account) { $this->accountName = $account; return $this; } public function getAccountName() { return $this->accountName; } public function setServiceSubject($subject) { $this->serviceSubject = $subject; return $this; } public function getServiceSubject() { return $this->serviceSubject; } public function setServiceTarget($target) { $this->serviceTarget = $target; return $this; } public function getServiceTarget() { return $this->serviceTarget; } public function setServiceTargetURL($targetURL) { $this->serviceTargetURL = $targetURL; return $this; } public function getServiceTargetURL() { return $this->serviceTargetURL; } public function setServiceHostURL($serviceHostURL) { $this->serviceHostURL = $serviceHostURL; return $this; } public function getServiceHostURL() { return $this->serviceHostURL; } public function setAccountSecurityToken($accountSecurityToken = NULL) { $this->accountSecurityToken = $accountSecurityToken; return $this; } public function getAccountSecurityToken() { return $this->accountSecurityToken; } public function setApplicationReferenceID($applicationReferenceID = NULL) { $this->applicationReferenceID = $applicationReferenceID; return NULL; } public function getApplicationReferenceID() { return $this->applicationReferenceID; } }<file_sep><?php namespace XLib; require_once 'XLib.php'; class Constants { public static function getAll($sorted=true) { $constants = array_keys( get_defined_constants() ); if($sorted === true) { sort($constants); } return $constants; } public static function exists($name) { return defined($name); } public static function search($pattern, $regex=true) { if($regex === true) { return preg_grep( $pattern, Constants::getAll() ); } else { return array_search( $pattern, Constants::getAll() ); } return null; } public static function defined($name, $value) { return define($name, $value); } // requires PHP extension uopz public static function redefine($name, $value) { if(\XLib\Engine::extLoaded('uopz')) { if(Constants::exists($name)) { uopz_undefine($name); Constants::define($name, $value); } } return false; } }<file_sep><?php namespace XLib\Brightpearl\Warehouse; use \XLib\Utils\Output as XLibOutput; #require_once __DIR__ . '../../../States.php'; // warehouse 12 class Samson { public function sendDropFile($dropFiles) { $host = '127.0.0.1'; $user = 'test'; $pass = '123'; $todir = 'ftp_testing/samson/inbox'; $ftp = new \XLib\FTP($host, $user, $pass); $ftp->connect() or die('Failed to connect to FTP'); $ftp->login() or die('Failed to login to FTP'); $ftp->changeDirectory($todir); if(!$ftp->fileExists($dropFiles['S']) && !$ftp->fileExists($dropFiles['P'])) { XLibOutput::pl('Sending files to remote server via FTP'); $ftp->putFile($dropFiles['S'], $dropFiles['S']) or die('Failed to transfer file: S'); $ftp->putFile($dropFiles['P'], $dropFiles['P']) or die('Failed to transfer file: P'); XLibOutput::pl('Finished sending files to remote server.'); } else { XLibOutput::pl('Files not sent. Already exists on remote FTP server.'); } $ftp->close(); if(file_exists($dropFiles['S'])) { @unlink($dropFiles['S']); } if(file_exists($dropFiles['P'])) { @unlink($dropFiles['P']); } return $this; } public function generateDropFile($data, $sMethods=null) { if(isset($data['response'])) { $data = $data['response'][0]; } $state = $data['parties']['delivery']['addressLine4']; $countryCode = $data['parties']['delivery']['countryIsoCode']; $stateAbbrev = null; $isResidential = null; $shippingMethod = ''; if($data['parties']['delivery']['companyName'] === '') { XLibOutput::pl('Is residential delivery address'); $isResidential = true; } else { XLibOutput::pl('Not residential delivery address'); $isResidential = false; } if(strlen($state) > 2) { if($countryCode == 'US') { $stateAbbrev = \XLib\States::usStateToAbbrev($state); } else { $stateAbbrev = \XLib\States::canadaStateToAbbrev($state); } } else { $stateAbbrev = $state; } // get shipping method if($sMethods !== null) { $sMethodId = intval($data['delivery']['shippingMethodId']); $sMethod = ''; foreach ($sMethods as $key => $value) { if(intval($value['id']) === $sMethodId) { $sMethod = $value['name']; } } XLibOutput::pl('Shipping method: ' . $sMethod); } else { $sMethod = ''; } // MDE S $result_s = array( $data['id'], // order number '', // cosignee number - blank $data['parties']['delivery']['addressFullName'], // cosignee name or desc $data['parties']['delivery']['addressLine1'], // addr line 1 $data['parties']['delivery']['addressLine2'], // addr line 2 $data['parties']['delivery']['addressLine3'], // city $stateAbbrev, #$orderResponse['parties']['delivery']['addressLine4'], // state $data['parties']['delivery']['postalCode'], // mail code / postal code '', // purchase order number '', // requested fright carrier '', // release number '', // release date '', // requested shipping date '', // received date '', // hold for received date 'P', // prepaid or collect P|C '', // third party '', // COD '', // COD amount '', '', '', '', ($isResidential == true) ? 'Y' : 'N', // is commercial '', '', $sMethod, '', '', '', '', '', '', '', '', '', '' ); // MDE P $orderRows = $data['orderRows']; $output = ''; foreach($orderRows as $key => $value) { $id = $key; $item = $value; if(isset($item['productSku'])) { $result_p = array ( $data['id'], // Shipment / order number '', // Invoice number $item['productSku'], // Item Number '', // Item Description '', // Quantity '', // Unit Price '', // Unit Of Measure '', // Model Number '', // Purchase Order number '', // Reference field '', // Reference field '', // Reference field '', // Shipper defined instructions intval($item['quantity']['magnitude']), // Quantity Ordered '', // Unit Of Measure '', // Exception Code '', // Exception Comments '', // Serial Numbers 1 '', // Serial Numbers 2 '', // Serial Numbers 3 '', // Serial Numbers 4 '', // Serial Numbers 5 '', // Serial Numbers 6 '', // Serial Numbers 7 '', '' ); $str = join(',', $result_p); $output .= $str . "\n"; } } $file_s = 'MDE' . substr($data['id'], strlen($data['id'])-4) . 'S' . '.' . strval(date('z')+1); file_put_contents($file_s, join(',', $result_s)); $file_p = 'MDE' . substr($data['id'], strlen($data['id'])-4) . 'P' . '.' . strval(date('z')+1); file_put_contents($file_p, join(',', $result_p)); return array( 'S' => $file_s, 'P' => $file_p ); } }<file_sep><?php namespace XLib; // COMPAT PHP 5.3+ class ObjectProperty { const READ_ERROR = 0xFF00A0; const WRITE_ERROR = 0xFF00A1; public $_data = array(); public function __construct($name, $value, $permissions = array()) { $this->_data['name'] = $name; $this->_data['value'] = $value; $this->_data = array_merge( $this->_data, array_merg( array( 'writeable' => TRUE, 'readable' => TRUE, 'configurable' => TRUE ), $permissions ) ); } private function _getName() { return $this->_data['name']; } private function _getValue() { return $this->_data['value']; } private function _getConfigurable() { return $this->_data['configurable']; } private function _getWritable() { return $this->_data['writable']; } private function _getReadable() { return $this->_data['readable']; } private function _setName($name) { $this->_data['name'] = $name; return $this; } private function _setValue($value) { $this->_data['value'] = $value; return $this; } private function _setConfigurable($configurable) { $this->_data['configurable'] = $configurable; return $this; } private function _setWritable($writable) { if ($this->_getConfigurable() === true) { $this->_data['writable'] = $writable; } return $this; } private function _setReadable($readable) { if ($this->_getConfigurable() === true) { $this->_data['readable'] = $readable; } return $this; } public function getName() { return $this->_getName(); } public function getValue() { if ($this->_getReadable() === true) { return $this->_getValue(); } return $this::READ_ERROR; } public function setName($name) { if ($this->_getConfigurable() === true) { return $this->_setName($name); } return $this::WRITE_ERROR; } public function setValue($value) { if ($this->_getConfigurable() === true && $this->_getWritable() === true) { return $this->_setValue($value); } return $this::WRITE_ERROR; } public function configure(array $permissions) { $this->_data = array_merge( $this->_data, array_merge( $this->_data, $permissions ) ); return $this; } } // compat php5.3 class Object { const PROPERTY_NAME_NOT_EXIST = 0xFF00B0; const PROPERTY_VALUE_NOT_EXIST = 0xFF00B1; const PROPERTY_LIST_EMPTY = 0xFF00B2; const METHOD_NAME_NOT_EXIST = 0xFF00B3; const METHOD_VALUE_NOT_EXIST = 0xFF00B4; const METHOD_LIST_EMPTY = 0xFF00B5; private $_data = array( 'properties' => array(), 'method' => array() ); public function addProperty($name, $value) { $this->_data['properties'][$name] = new ObjectProperty($name, $value); return $this; } public function addMethod($name, $fn) { $this->_data['methods'][$name] = new ObjectProperty($name, $fn); return $this; } public function callMethod($name, array $args = null, &$context = null) { if ($this->methodExists($name) === true) { // get method from name $fn = $this->_data['methods'][$name]->getValue(); // if we have args defined if ($args !== null) { // and if a context is defined if ($context !== null) { // call the function inside the specified context return call_user_func_array( array($context, $fn), $args ); } else { // if no context, just call the function with args return call_user_func_array($fn, $args); } } // no context or args defined, just call the function return call_user_func($fn); } } public function propertyExists($name) { return (array_key_exists($name, $this->_data['properties'])) ? true : false; } public function methodExists($name) { return (array_key_exists($name, $this->_data['methods'])) ? true : false; } public function getPropertyObject($name) { if ($this->propertyExists($name) === true) { return $this->_data['properties'][$name]; } return $this::PROPERTY_NAME_NOT_EXIST; } public function getMethodObject($name) { if ($this->methodExists($name) === true) { return $this->_data['methods'][$name]; } return $this::METHOD_NAME_NOT_EXIST; } public function getProperty($name) { if ($this->propertyExists($name) === true) { return $this->_data['properties'][$name]->getValue(); } return $this::PROPERTY_NAME_NOT_EXIST; } public function getMethod($name) { if ($this->methodExists($name) === true) { return $this->_data['methods'][$name]->getValue(); } return $this::METHOD_NAME_NOT_EXIST; } public function setProperty($name, $value) { if ($this->propertyExists($name) === true) { $this->_data['properties'][$name] = new ObjectProperty($name, $value); } return $this; } public function setMethod($name, $fn) { if ($this->methodExists($name) === true) { $this->_data['methods'][$name] = new ObjectProperty($name, $fn); } return $this; } public function removeProperty($name) { if ($this->propertyExists($name) === true) { return delete($this->_data['properties'][$name]); } return $this::PROPERTY_NAME_NOT_EXIST; } public function removeMethod($name) { if ($this->methodExists($name) === true) { return delete($this->_data['methods'][$name]); } return $this::METHOD_NAME_NOT_EXIST; } public function getPropertyList() { if (count($this->_data['properties']) > 0) { return array_keys($this->_data['properties']); } return $this::PROPERTY_LIST_EMPTY; } public function getMethodList() { if (count($this->_data['methods']) > 0) { return array_keys($this->_data['methods']); } return $this::METHOD_LIST_EMPTY; } public function getPropertyValueList() { $keys = $this->getPropertyList(); if ($keys !== $this::PROPERTY_LIST_EMPTY) { $ret = array(); foreach ($keys as $key) { $ret[$key] = $this->getProperty($key); } return $ret; } return $this::PROPERTY_LIST_EMPTY; } public function getMethodValueList() { $keys = $this->getMethodList(); if ($keys !== $this::METHOD_LIST_EMPTY) { $ret = array(); foreach ($keys as $key) { $ret[$key] = $this->getMethod($key); } return $ret; } return $this::METHOD_LIST_EMPTY; } }<file_sep><?php namespace XLib; require_once 'XLibObject.php'; class FTP { public $info = array( 'host' => null, 'username' => null, 'password' => <PASSWORD>, 'port' => 21, 'passive' => true, 'transferMode' => FTP_BINARY ); public $handle = null; public $connected = null; public $loggedin = null; public $errors = array(); public $errorStatus = false; public function __construct($host=null, $username=null, $password=<PASSWORD>, $port=21, $passive=true, $transferMode=FTP_BINARY) { $this->info['host'] = $host; $this->info['username'] = $username; $this->info['password'] = $<PASSWORD>; $this->info['port'] = $port; $this->info['passive'] = $passive; $this->info['transferMode'] = $transferMode; $this->handle = null; $this->connected = null; $this->loggedin = null; $this->errors = array(); $this->errorStatus = false; } public function error($message, $fatal=true) { $this->errors[] = array( 'message' => $message, 'fatal' => $fatal ); $this->errorStatus = true; return $this; } public function flushErrors() { $this->errors = array(); $this->errorStatus = false; return $this; } public function getLastError() { if(count($this->errors) > 0) { $len = count($this->errors); return $this->errors[$len - 1]; } return false; } public function toggleTransferMode() { $this->info['transferMode'] = (FTP_ASCII === $this->info['transferMode']) ? FTP_BINARY : FTP_ASCII; return $this; } public function setTransferMode($mode=FTP_BINARY) { if(FTP_BINARY !== $mode && FTP_ASCII !== $mode) { $this->error("Invalid transferMode: $mode"); return false; } $this->info['transferMode'] = $mode; return $this; } public function getTransferMode() { return $this->info['transferMode']; } public function connect() { if(!$this->getLastError()) { $this->handle = ftp_connect( $this->info['host'], $this->info['port'] ); if(false === $this->handle) { $this->error("Unable to connect to " . $this->info['host']); return false; } if($this->info['passive']) { ftp_pasv($this->handle, true); } $this->connected = true; return $this; } return false; } public function close() { if($this->connected) { return ftp_close($this->handle); } return false; } public function login() { if($this->connected && !$this->getLastError()) { $login = ftp_login( $this->handle, $this->info['username'], $this->info['password'] ); if(false !== $login) { $this->loggedin = true; return $this; } else { $this->loggedin = false; $this->error('FTP Login failed for user: ' . $this->info['username']); return false; } } return null; } public function canAction() { return ($this->connected && $this->loggedin && !$this->getLastError()); } public function directoryExists($path) { if ($this->canAction()) { $dir = ftp_pwd($this->handle); if (ftp_chdir($this->handle, $path) && $dir) { ftp_chdir($this->handle, $dir); return TRUE; } return FALSE; } return NULL; } public function changeDirectory($path) { if($this->canAction()) { if($this->directoryExists($path)) { $res = ftp_chdir($this->handle, $path); if(false !== $res) { return true; } $this->error('Unable to change to remote path: ' . $path, false); return false; } return false; } return null; } public function fileExists($path) { if($this->canAction()) { if(-1 === ftp_size($this->handle, $path)) { return false; } return true; } return null; } public function getFileSize($path) { if($this->canAction()) { $size = ftp_size($this->handle, $path); if(-1 === $size) { $this->error('Remote file not found: ' . $path, false); return false; } return true; } return null; } public function putFile($localPath, $remotePath) { if($this->canAction()) { $fp = ftp_put($this->handle, $remotePath, $localPath, $this->getTransferMode()); if(false === $fp) { $this->toggleTransferMode(); $fp = ftp_put($this->handle, $remotePath, $localPath, $this->getTransferMode()); if(false === $fp) { $this->toggleTransferMode(); $this->error('Unable to put file from ' . $localPath . ' to ' . $remotePath, false); return false; } } return true; } return null; } public function getFile($localPath, $remotePath) { if($this->canAction()) { $fp = ftp_get($this->handle, $remotePath, $localPath, $this->getTransferMode()); if(false === $fp) { $this->toggleTransferMode(); $fp = ftp_get($this->handle, $remotePath, $localPath, $this->getTransferMode()); if(false === $fp) { $this->toggleTransferMode(); $this->error('Unable to get file from ' . $localPath . ' to ' . $remotePath, false); return false; } } return true; } return null; } public function deleteFile($path) { if($this->canAction()) { $fd = ftp_delete($this->handle, $path); if(false === $fd) { $this->error('Unable to delete remote file: ' . $path, false); return false; } return true; } return null; } public function listFiles($path='.') { if($this->canAction()) { $list = ftp_nlist($this->handle, $path); if(false === $list) { $this->error('Unable to list files in remote path ' . $path, false); return false; } return $list; } return null; } public function getPwd() { if($this->canAction()) { return ftp_pwd($this->handle); } return null; } } /* class FTP extends \XLib\Object { public function __construct($host = null, $username = null, $password = null, $port = 21, $passive = true, $transferMode = FTP_BINARY) { $this->info = array( 'host' => $host, 'username' => $username, 'password' => $<PASSWORD>, 'port' => $port, 'passive' => $passive, 'transferMode' => $transferMode ); $this->handle = null; $this->connected = null; $this->loggedin = null; $this->errors = array(); $this->errorStatus = false; } public function error($msg, $fatal=true) { $this->errors[] = array( 'msg' => $msg, 'fatal' => $fatal ); $this->errorStatus = true; return $this; } public function flushErrors() { $this->errors = array(); $this->errorStatus = false; return $this; } public function getLastError() { $len = count($this->errors); if($len > 0) { return $this->errors[$len-1]; } return false; } public function toggleTransferMode() { $this->info['transferMode'] = (FTP_ASCII === $this->info['transferMode']) ? FTP_BINARY : FTP_ASCII; return $this; } public function setTransferMode($mode=FTP_BINARY) { if(FTP_BINARY !== $mode && FTP_ASCII !== $mode) { $this->error("Invalid transfer mode: $mode"); return false; } $this->info['transferMode'] = $mode; return $this; } public function getTransferMode() { return $this->info['transferMode']; } public function connect() { if(!$this->getlastError()) { $this->handle = @ftp_connect($this->info['host'], $this->info['port']); if(false === $this->handle) { $this->error("Unable to connect to $this->info['host']"); return false; } if($this->info['passive']) { ftp_pasv($this->handle, true); } $this->connected = true; return $this; } return false; } public function close() { if($this->connected) { return @ftp_close($this->handle); } return false; } public function login() { if($this->connected && !$this->getLastError()) { $login = @ftp_login($this->handle, $this->info['username'], $this->info['password']); if(false !== $login) { $this->loggedin = true; return $this; } else { $this->loggedin = false; $this->error("FTP Login failed for user: $this->info['username']"); return false; } } } public function canAction() { return ($this->connected && $this->loggedin && !$this->getLastError()); } public function directoryExists() { if($this->canAction()) { $dir = @ftp_pwd($this->handle); if(@ftp_chdir($this->handle, $path) && $dir) { @ftp_chdir($this->handle, $dir); return true; } return false; } return null; } public function changeDirectory($path) { if($this->canAction()) { if($this->directoryExists($path)) { $res = @ftp_chdir($this->handle, $path); if(false !== $res) { return true; } $this->error("Unable to change to remote path: $path", false); return false; } return false; } return null; } public function fileExists($filePath) { if($this->canAction()) { if(-1 === @ftp_size($this->handle, $path)) { return false; } return true; } return null; } public function getFileSize($path) { if($this->canAction()) { $size = @ftp_size($this->handle, $path); if(-1 === $size) { $this->error("Remote file not found: $path", false); return false; } return $size; } return null; } public function putFile($localPath, $remotePath) { if($this->canAction()) { $fp = @ftp_put($this->handle, $remotePath, $localPath, $this->getTransferMode()); if(false === $fp) { $this->toggleTransferMode(); $fp = @ftp_put($this->handle, $remotePath, $localPath, $this->getTransferMode()); if(false === $fp) { $this->toggleTransferMode(); $this->error("Unable to put file from $localPath to $remotePath", false); return false; } } return true; } return null; } public function getFile($localPath, $remotePath) { if($this->canAction()) { $fp = @ftp_get($this->handle, $localPath, $remotePath, $this->getTransferMode()); if(false === $fp) { $this->toggleTransferMode(); $fp = @ftp_get($this->handle, $localPath, $remotePath, $this->getTransferMode()); if(false === $fp) { $this->toggleTransferMode(); $this->error("Unable to get file from $remotePath to $localPath", false); return false; } } return true; } return null; } public function deleteFile($path) { if($this->canAction()) { $fd = @ftp_delete($this->handle, $path); if(false === $fd) { $this->error("Could not delete remote file: $path", false); return false; } return true; } return null; } public function listFiles($path='.') { if($this->canAction()) { $list = @ftp_nlist($this->handle, $path); if(false === $list) { $this->error("Unable to list files in remote path: $path", false); return false; } return $list; } return null; } public function getPWD() { if($this->canAction()) { return @ftp_pwd($this->handle); } return null; } } */<file_sep><?php namespace XLib\Object { class Property { public $name; public $value; public function __construct($name, $value = null) { $this->name = $name; $this->value = $value; } } class Object { private $data = array(); private $mem; public function __construct() { } } }<file_sep><?php require_once 'SimpleCache.php'; require_once 'XLib.php'; use \XLib\XLib as XLib; \XLib\XLib::loadClass(array( 'Config', 'Object', 'States', 'Brightpearl', 'Cache', 'Context', 'BrightpearlUtils', 'BrightpearlAuth', 'BrightpearlClient', 'BrightpearlRequest' )); require_once __DIR__ . '../../../vendor/autoload.php'; define('XL_DEBUG_OUTPUT_HTML', false); function _doh() { return (defined('XL_DEBUG_OUTPUT_HTML') && XL_DEBUG_OUTPUT_HTML === true); } function vd() { $args = func_get_args(); $hrep = _doh(); foreach ($args as $arg) { if ($hrep) echo '<pre>'; var_dump($arg); if ($hrep) echo '</pre>'; } } function ve() { $args = func_get_args(); $hrep = _doh(); foreach ($args as $arg) { if ($hrep) echo '<pre>'; var_export($arg); if ($hrep) echo '</pre>'; } } function pr() { $args = func_get_args(); $hrep = _doh(); foreach ($args as $arg) { if ($hrep) echo '<pre>'; print_r($arg); if ($hrep) echo '</pre>'; } } function pl() { $args = func_get_args(); $hrep = _doh(); foreach ($args as $arg) { if ($hrep) echo '<pre>'; print($arg); print("\n"); if ($hrep) echo '</pre>'; } } <file_sep><?php namespace XLib\Brightpearl; class Requests { public static $service; public static $target; public static function setService($service) { self::$service = $service; } public static function getService() { return self::$service; } public static function setTarget($target) { self::$target = $target; } public static function getTarget() { return self::$target; } public static function getProductbyId($pid) { self::setService('product-service'); self::setTarget('product'); return self::getService() . '/' . self::getTarget() . '/' . $pid; } }<file_sep><?php namespace XLib; require_once 'XLib.php'; use \XLib\XLib as XMain; XMain::loadClass('Object', 'XLib'); class Config extends \XLib\Object { private static $list = array(); public function __construct() { } public static function exists($name) { return (isset(Config::$list[$name])); } public static function set($name, $value) { Config::$list[$name] = $value; return true; } public static function get($name) { if(Config::exists($name)) { return Config::$list[$name]; } return null; } }<file_sep><?php namespace XLib\Brightpearl; class Cache { public function __construct() { } }<file_sep><?php namespace XLib\Brightpearl; class Utils { static public function packArgs() { $list = []; foreach(func_get_args() as $k => $v) { $list[$k] = $v; } return join('/', $list); } }<file_sep><?php namespace XLib; class Exception { public static $_errorList = array(); public static $_warningList = array(); public static $_noticeList = arrray(); public static $_pageErrorList = array(); public static $_pageWarningList = array(); public static function setErrorReporting($level=E_ALL) { error_reporting($level); } public static $displayErrorList = array(); public static function errorToString($errno) { switch($errno) { case E_USER_ERROR: return 'E_USER_ERROR'; break; case E_USER_WARNING: return 'E_USER_WARNING'; break; case E_USER_NOTICE: return 'E_USER_NOTICE'; break; default: return null; } } public static function handle($errno, $errstr, $errfile, $errline) { if(!error_reporting() && $errno) { return; } switch($errno) { case E_USER_ERROR: self::error($errno, $errstr, $errfile, $errline); break; case E_USER_WARNING: self::warning($errno, $errstr, $errfile, $errline); break; case E_USER_NOTICE: self::notice($errno, $errstr, $errfile, $errline); break; default: self::unknown($errno, $errstr, $errfile, $errline); break; } return true; } public static function hasError() { return (count(self::_errorList) > 0); } public static function hasWarning() { return (count(self::_warningList) > 0); } public static function hasNotice() { return (count(self::_noticeList) > 0 ); } public static function error($errno, $errstr, $errfile, $errline) { $errno = self::errorToString($errno); self::_errorList[] = array ( 'err' => $errno, 'msg' => $errstr, 'file' => $errfile, 'line' => $errline ); } public static function warning($errno, $errstr, $errfile, $errline) { $errno = self::errorToString($errno); self::_warningList[] = array( 'err' => $errno, 'msg' => $errstr, 'file' => $errfile, 'line' => $errline ); } public static function notice($errno, $errstr, $errfile, $errline) { $errno = self::errorToString($errno); self::_noticeList[] = array( 'err' => $errno, 'msg' => $errstr, 'file' => $errfile, 'line' => $errline ); } public static function unknown($errno, $errstr, $errfile, $errline) { } }<file_sep><?php namespace XLib\Brightpearl; class TokenAuthentication { private $sAuthObject; private $token; public function __construct($sAuthObject = NULL) { $this->sAuthObject = $sAuthObject; } public function setAuthenticationObject($sAuthObject = NULL) { $this->token = NULL; if (is_object($sAuthObject)) { $this->sAuthObject = $sAuthObject; return $this; } return NULL; } public function getAuthenticationObject() { return $this->sAuthObject; } public function setToken($token) { $this->token = $token; return $this; } public function getToken() { return $this->token; } public function requestToken() { if ($this->sAuthObject === NULL) { return NULL; } $ch = curl_init(); $cred = array( 'apiAccountCredentials' => array( 'emailAddress' => $this->sAuthObject->getEmailAddress(), 'password' => $<PASSWORD>() ) ); $encodedCred = json_encode($cred); $url = $this->sAuthObject->getTargetURL(); $headers = array('Content-Type: application/json'); $cOpt = array( CURLOPT_URL => $url, CURLOPT_HTTPHEADER => $headers, CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $encodedCred, CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_SSL_VERIFYHOST => FALSE, CURLOPT_SSL_VERIFYPEER => FALSE ); curl_setopt_array($ch, $cOpt); $res = curl_exec($ch); if (FALSE === $res) { curl_close($ch); return NULL; } #var_dump($this->sAuthObject); #echo "\n"; #var_dump($res); #echo "\n"; #var_dump(curl_error($ch)); $data = json_decode($res); curl_close($ch); $this->setToken($data->response); return $this; } }<file_sep><?php namespace XLib; abstract class Enum { final public function __construct($value) { $self = new \ReflectionClass($this); if(!in_array($value, $self->getConstants())) { throw \IllegalArgumentException(); } $this->value = $value; } final public function __toString() { return $this->value; } }<file_sep><?php namespace XLib\Utils; define('XL_DEBUG_OUTPUT_HTML', false); class Output { static public function _doh() { return (defined('XL_DEBUG_OUTPUT_HTML') && XL_DEBUG_OUTPUT_HTML === true); } static public function vd() { $args = func_get_args(); $hrep = self::_doh(); foreach ($args as $arg) { if ($hrep) echo '<pre>'; var_dump($arg); if ($hrep) echo '</pre>'; } } static public function ve() { $args = func_get_args(); $hrep = self::_doh(); foreach ($args as $arg) { if ($hrep) echo '<pre>'; var_export($arg); if ($hrep) echo '</pre>'; } } static public function pr() { $args = func_get_args(); $hrep = self::_doh(); foreach ($args as $arg) { if ($hrep) echo '<pre>'; print_r($arg); if ($hrep) echo '</pre>'; } } static public function pl() { $args = func_get_args(); $hrep = self::_doh(); foreach ($args as $arg) { if ($hrep) echo '<pre>'; print($arg); print("\n"); if ($hrep) echo '</pre>'; } } } <file_sep><?php namespace XLib\Brightpearl; if(!class_exists('\XLib\Http\Client')) { require_once __DIR__ . '../Http.php'; } class DynamicService2 { public $securityToken; public $applicationRefID; public $accountName; public $targetURL; public $service; public $target; public $endPoint; public $destURL; public $httpClient; public $response; public function __construct() { $this->httpClient = new \XLib\Http\Client(); $this->httpClient->setHeader('brightpearl-account-token', '______'); $this->httpClient->setHeader('brightpearl-app-ref', '________'); $this->httpClient->setOpt(CURLOPT_SSL_VERIFYHOST, false); $this->httpClient->setOpt(CURLOPT_SSL_VERIFYPEER, false); } public function packArgs() { $list = array(); foreach(func_get_args() as $key => $value) { $list[$key] = $value; } return join('/', $list); } public function loadArgs() { $list = array(); foreach(func_get_args() as $key => $value) { $list[$key] = $value; } if(!empty($list)) { $this->service = array_shift($list); } if(!empty($list)) { $this->target = array_shift($list); } if(!empty($list)) { $this->endPoint = array_shift($list); } return $this; } public function buildDestURL() { $this->destURL = (isset($this->endPoint) && $this->endPoint !== null) ? $this->packArgs($this->targetURL, $this->accountName, $this->service, $this->target, $this->endPoint) : $this->packArgs($this->targetURL, $this->accountName, $this->service, $this->target); return $this; } public function send() { if(func_num_args() > 0) { call_user_func_array( array($this, 'loadArgs'), func_get_args() ); } $this->buildDestURL(); $this->httpClient->get($this->destURL); if($this->httpClient->http_status_code == 200) { $this->response = $this->httpClient->response; return json_decode($this->response, true); } return array( $this->httpClient->http_error, $this->httpClient->http_error_message, $this->httpClient->http_status_code, $this->httpClient->response ); } }<file_sep><?php namespace XLib\Brightpearl; class Auth { private $authData = [ 'accountName' => '', 'appRefId' => '', 'securityToken' => '', 'targetURL' => '' ]; public function __construct() { $this->loadDefaults(); } public function loadDefaults() { $arrDefault = array( 'appRefId' => '_______', 'securityToken' => '_______', 'targetURL' => 'https://ws-use.brightpearl.com/public-api', 'accountName' => '________' ); $this->authData = array_merge($this->authData, $arrDefault); } public function has($key) { return isset($this->authData[$key]); } public function set($key, $val) { $this->authData[$key] = $val; return $this; } public function remove($key) { if($this->has($key)) { $this->authData[$key] = null; unset($this->authData[$key]); return !$this->has($key); } return false; } public function get($key) { if($this->has($key)) { return $this->authData[$key]; } return $this; } public function getAll() { $arr = []; foreach($this->authData as $key => $val) { $arr[$key] = $val; } return $arr; } }<file_sep><?php namespace XLib; require_once 'XLibObject.php'; if(!defined('XL_DEBUG_OUTPUT_HTML')) { define('XL_DEBUG_OUTPUT_HTML', false); } class Utils extends \XLib\Object { public static function debugOutputHtml() { return (defined('XL_DEBUG_OUTPUT_HTML') && XL_DEBUG_OUTPUT_HTML === true); } public static function vd() { $args = func_get_args(); $hr = self::debugOutputHtml(); foreach($rgs as $arg) { if($hr) { echo '<pre>'; } var_dump($arg); if($hr) { echo '</pre>'; } } } public static function ve() { $args = func_get_args(); $hr = self::debugOutputHtml(); foreach($args as $arg) { if($hr) { echo '<pre>'; } var_export($arg); if($hr) { echo '</pre>'; } } } public static function pr() { $args = func_get_args(); $hr = self::debugOutputHtml(); foreach($args as $arg) { if($hr) { echo '<pre>'; } print_r($arg); if($hr) { echo '</pre>'; } } } public static function pl() { $args = func_get_args(); $hr = self::debugOutputHtml(); foreach($args as $arg) { if($hr) { echo '<pre>'; } echo($arg); if($hr) { echo '</pre>'; } } } }<file_sep>xlib.pref.set('capability.policy.policynames', 'localfilelinks'); xlib.pref.set('capability.policy.localfilelinks.checkloaduri.enabled', 'allAccess'); xlib.pref.set('capability.policy.localfilelinks.sites', '127.0.0.1');<file_sep>try { if(typeof(xlib) === "undefined") { throw "xlib: missing core library"; } xlib.event = function(obj) { if (obj) return this.mixin(obj); return this; }; xlib.event.prototype.mixin = function(obj) { for (var key in obj) { this[key] = obj[key]; } return this; }; xlib.event.prototype.on = xlib.event.prototype.addEventListener = function(event, fn) { this.__events = this.__events || {}; (this.__events[event] = this.__events[event] || []).push(fn); return this; } xlib.event.prototype.once = function(event, fn) { var self = this; this.__events = this.__events || {}; function on() { self.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; } xlib.event.prototype.off = xlib.event.prototype.removeListener = xlib.event.prototype.removeAllListeners = xlib.event.prototype.removeEventListener = function(event, fn) { this.__events = this.__events || {}; if (0 === arguments.length) { this.__events = {}; return this; } var events = this.__events[event] || false if (!events) return this; if (1 === arguments.length) { delete this.__events[event]; return this; } var cb; for (var i = 0; i < events.length; i++) { cb = events[i]; if (cb === fn || cb.fn === fn) { events.splice(i, 1); break; } } return this; } xlib.event.prototype.emit = xlib.event.prototype.trigger = function(event) { this.__events = this.__events || {}; var args = [].slice.call(arguments, 1), events = this.__events[event] || false, i = 0, len = events.length; if (events) { events = events.slice(0); for (; i < len; ++i) { events[i].apply(this, args); } } return this; } xlib.event.prototype.listeners = function(event) { this.__events = this.__events || {}; return this.__events[event] || []; } xlib.event.prototype.hasListeners = function(event) { return !!this.listeners(event).length; } xlib._ready = (typeof (xlib._ready) == "undefined") ? [] : xlib._ready; xlib._readyProcessQueue = function XLibReadyProcessQueue() { if(typeof(xlib._ready) !== "undefined" && xlib._ready.length > 0) { var xlrlen = xlib._ready.length; for(var i=0; i < xlrlen; ++i) { xlib._ready.shift().call(this, this, xlib); } } else { xlib._ready = []; } delete xlib['_initReady']; delete xlib['_ready']; return xlib.ready; }; xlib.ready = function XLibReady() { var args = (arguments && arguments.length > 0) ? xlib.toArray(arguments) : null; if(!args || args === null) { return (xlib.hasOwnProperty('_ready') && xlib.hasOwnProperty('_readyProcessQueue') && xlib._ready.length > 0) ? false : true; } var len = args.length; for(var i=0; i < len; ++i) { if(typeof(xlib._ready) !== "undefined" && typeof(args[i]) !== "undefined") { xlib._ready.push(args[i]); } else { xlib._ready = []; } } return xlib.ready; }; xlib._onLoad = []; xlib.onLoad = function() { var ret = xlib.ready.apply(this, arguments); return (typeof ret === "function") ? xlib.onLoad : ret; }; } catch (err) { console.error(err); }<file_sep><?php namespace XLib; class System { public function getCurrentUser() { return get_current_user(); } public function getDefinedConstants($cat=false) { return get_defined_constants($cat); } public function getExtensionFunctions($module) { return get_extension_funcs($module); } public function getIncludePath() { return get_include_path(); } public function getIncludedFiles() { return get_included_files(); } public function getLoadedExtensions($zendex=false) { return get_loaded_extensions($zendex); } public function getResourceUsage($who=0) { return getrusage($who); } public function memoryGetPeakUsage($realUsage=false) { return memory_get_peak_usage($realUsage); } }<file_sep>try { if(typeof(xlib) === "undefined") { throw "xlib: missing core library"; } var _xlOatEvent = new xlib.event(); _xlOatEvent.on('load-devtools', function() { try { xlib.loader('resource://gre/modules/devtools/Loader.jsm', window).devtools; } catch (err) { } }); _xlOatEvent.on('load-xlib-app', function() { }); /*_xlOatEvent.on('load-xlib-ui', function() { xlib.ui = {}; xlib.ui.tree = {}; xlib.ui.tree.view = { data: [ ['1.1.1', 'Version unstable. Testing disabled.', 'ACTIONS' ], [ '1.2.1', 'Version unstable. Testing disabled.', 'ACTIONS' ], [ '1.3.1', 'Version unstable. Testing disabled.', 'ACTIONS' ] ], treeBox: null, selection: null, get rowCount() { return this.data.length; }, getCellText: function(row, column) { return this.data[row][column.index]; }, setTree: function(treebox) { this.treeBox = treebox; } }; });*/ _xlOatEvent.on('check-first-run', function() { // check for default OAT preferences var oatTest_1_1_1_enable = xlib.pref.get('oat.testing.1_1_1.enable'); var oatTest_1_2_1_enable = xlib.pref.get('oat.testing.1_2_1.enable'); var oatTest_1_3_1_eanble = xlib.pref.get('oat.testing.1_3_1.enable'); if (oatTest_1_1_1_enable == null) { xlib.pref.set('oat.testing.1_1_1.enable', true); xlib.pref.set('oat.testing.1_2_1.enable', true); xlib.pref.set('oat.testing_1_3_1.enable', true); } }); // before window load _xlOatEvent.emit('load-devtools'); _xlOatEvent.emit('load-xlib-app'); // after window load window.addEventListener('load', function() { xlib._readyProcessQueue(); _xlOatEvent.emit('load-xlib-ui'); _xlOatEvent.emit('check-first-run'); // xlib.app.startBrowserToolbox(); xlib.selector('#oat-output').view = xlib.ui.tree.view; var enable111 = xlib.selector('#oat-options-enable111'); var enable121 = xlib.selector('#oat-options-eanble121'); var enable131 = xlib.selector('#oat-options-enable131'); xlib.testing = {}; xlib.testing.options = {}; xlib.testing.options.menuitems = $('#oat-panel button[type="menu"]').find('menuitem'); xlib.testing.options.enable111 = $(xlib.testing.options.menuitems[0]).attr('checked') || 'false'; xlib.testing.options.eanble121 = $(xlib.testing.options.menuitems[1]).attr('checked') || 'false'; xlib.testing.options.enable131 = $(xlib.testing.options.menuitems[2]).attr('checked') || 'false'; xlib.pref.set('oat.testing.1_1_1.enable', xlib.testing.options.enable111); xlib.pref.set('oat.testing.1_2_1.enable', xlib.testing.options.enable121); xlib.pref.set('oat.testing.1_3_1.enable', xlib.testing.options.enable131); $(xlib.testing.options.menuitems[0]).unbind('click'); $(xlib.testing.options.menuitems[1]).unbind('click'); $(xlib.testing.options.menuitems[2]).unbind('click'); $(xlib.testing.options.menuitems[0]).on('click', function() { xlib.pref.set('oat.testing.1_1_1.enable', (xlib.testing.options.enable111 == 'true') ? 'false' : 'true'); }); $(xlib.testing.options.menuitems[1]).on('click', function() { xlib.pref.set('oat.testing.1_2_1.enable', (xlib.testing.options.enable121 == 'true') ? 'false' : 'true'); }); $(xlib.testing.options.menuitems[2]).on('click', function() { xlib.pref.set('oat.testing_1_3_1.enable', (xlib.testing.options.enable131 == 'true') ? 'false' : 'true'); }); //BrowserToolboxProcess.init(); //HUDService.toggleBrowserConsole(); }, false); } catch (err) { console.error(err); }<file_sep><?php namespace XLib; class HttpVariables { const POST = 0x001; const GET = 0x002; public static function exists($name, $type='get') { $type = strtolower($type); if($type === 'get') { return (isset($_GET[$name])); } elseif($type == 'post') { return (isset($_POST[$name])); } else { return (isset($_POST[$name]) || isset($_GET[$name])); } return null; } public static function get($name, $type='get') { $type = strtolower($type); if(self::exists($name, $type)) { if($type === 'get') { return $_GET[$name]; } elseif($type === 'post') { return $_POST[$name]; } else { if(self::exists($name, 'get')) { return $_GET[$name]; } elseif(self::exists($name, 'post')) { return $_POST[$name]; } return null; } return null; } return null; } public static function set($name, $value, $type='get') { $type = strtolower($type); if($type === 'get') { $_GET[$name] = $value; } elseif($type === 'post') { $_POST[$name] = $value; } else { $_GET[$name] = $value; $_POST[$name] = $value; } return true; } }<file_sep> (function (context, undef) { let Cc = context.Cc = Components.classes; let Ci = context.Ci = Components.interfaces; let Cu = context.Cu = Components.utils; Cu.import("resource://gre/modules/XPCOMUtils.jsm", context); Cu.import('resource://gre/modules/Services.jsm', context); Cu.import('resource://gre/modules/AddonManager.jsm', context); Cu.import('resource://gre/modules/FileUtils.jsm', context); context._$G = this; })(this); (function (context, undef) { var xl = { _G: context, sandbox: {}, data: {}, pl: function() { console.log.apply(console, arguments); return this; }, dir: function() { console.dir.apply(console, arguments); return this; } }; xl.cache = { data: {}, exists: function(name) { return this.data.hasOwnProperty(name); }, has: function(name) { return this.exists(name); }, set: function(name, val) { this.data[name] = val; return this; }, get: function(name) { return (this.exists(name)) ? this.data[name] : null; }, getAll: function() { return this.data; }, remove: function(name) { if(this.exists(name)) { try { delete(this.data[name]); } catch(err) { } } }, del: function(name) { return this.remove(name); }, removeAll: function() { this.data = []; return this; }, delAll: function() { return this.removeAll(); } }; xl.findContract = function(name) { var list = (!xl.cache.has('cckeys')) ? xl.cache.set('cckeys', Object.keys(Cc)).get('cckeys') : xl.cache.get('cckeys'); for(var i=0, j=list.length; i < j; i++) { if(list[i].toLowerCase().contains(name.toLowerCase())) { return Components.classes[list[i]]; } } return null; }; xl.findInterface = function(name) { var list = (!xl.cache.has('cikeys')) ? xl.cache.set('cikeys', Object.keys(Ci)).get('cikeys') : xl.cache.get('cikeys'); for(var i=0, j=list.length; i < j; i++) { if(list[i].toLowerCase().contains(name.toLowerCase())) { return Components.interfaces[list[i]]; } } }; xl.getService = function(cname, iname) { var cobj = Cc && Cc[cname] || Components.classes[cname] || this.findContract(cname); try { switch(typeof(iname)) { case 'object': return cobj.getService(iname); break; case 'string': return cobj.getService(Ci && Ci[iname] || Components.interfaces[iname] || this.findInterface(iname)); break; default: return cobj.getService(); } } catch (err) { return err; } }; xl.createInstance = function(cname, iname) { var cobj = Cc && Cc[cname] || Components.classes[cname] || this.findContract(cname); try { switch(typeof(iname)) { case 'object': return cobj.createInstance(iname); break; case 'string': return cobj.createInstance(Ci && Ci[iname] || Components.interfaces[iname] || this.findInterface(iname)); break; default: return null; } } catch (err) { return err; } }; xl.getAddons = function(callback) { Cu.import('resource://gre/modules/AddonManager.jsm'); return AddonManager.getAddonsByTypes(['extensions'], callback); }; xl.topWindow = function() { return xl.getService('window-mediator', 'nsIWindowMediator').getMostRecentWindow('navigator:browser'); }; xl.activeWindow = function() { return window.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIWebNavigation).QueryInterface(Ci.nsIDocShellTreeItem).rootTreeItem.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindow); }; xl.util = { keys: function(obj) { return Object.keys(obj); }, loadScript: function(path, context) { context = context || {}; Services.scriptloader.loadSubScriptWithOptions(path, { target: context, charset: 'UTF-8', ignoreCache: true }); return context; }, guid: function() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } }; xl.file = function(path) { var XLFile = function(path) { this.handle = new FileUtils.File(path); for(var item in this.handle) { try { this[item] = this.handle[item]; } catch(err) { } } this.read = function() { var fiStream = xl.ff.createInstance('file-input-stream', 'nsIFileInputStream'); var siStream = xl.ff.createInstance('scriptableinputstream', 'nsIScriptableInputStream'); var data = new String(); fiStream.init(this.handle, 1, 0, false); siStream.init(fiStream); data += siStream.read(-1); siStream.close(); fiStream.close(); return data; }; this.write = function(data, mode) { try { var foStream = xl.ff.createInstance('file-output-stream', 'nsIFileOutputStream'); var flags = 0x02 | 0x08 | 0x20; if(mode == 'a') { flags = 0x02 | 0x10; } foStream.init(this.handle, flags, 664, 0); foStream.write(data, data.length); foStream.close(); return true; } catch(err) { console.error(err); return false; } }; this.create = this.touch = function() { try { this.handle.create(this.handle.NORMAL_FILE_TYPE, 0777); return true; } catch(err) { return false; } }; this.remove = this.unlink = this.delete = this.del = function() { try { this.handle.remove(false); return true; } catch(err) { return false; } }; this.mkdir = function() { try { this.handle.create(this.handle.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY); return true; } catch(err) { return false; } } return this; }; return new XLFile(path); }; Cu.import('resource://gre/modules/osfile.jsm', xl.file); Cu.import('resource://gre/modules/FileUtils.jsm', xl.file); xl.path = { createAlias: function(path, alias) { Components.utils.import('resource://gre/modules/Services.jsm'); Components.utils.import('resource://gre/modules/FileUtils.jsm'); var res = Services.io.getProtocolHandler('resource').QueryInterface(Components.interfaces.nsIResProtocolHandler); var afile = new FileUtils.File(path); var auri = Services.io.newFileURI(afile); res.setSubstitution(alias, auri); return this; } }; xl.http = function(url, callback) { let xhr = xl.ff.createInstance('xmlhttprequest', 'nsIXMLHttpRequest'); let handle = ev => { evf(m => xhr.removeEventListener(m, handle, !1)); switch(ev.type) { case 'load': if(xhr.status == 200) { callback(xhr.response); break; } default: console.error('XHR Error fetching URL ' + url + ' status: ' + xhr.statusText); break; } }; let evf = f => ['load', 'error', 'abort'].forEach(f); evf(m => xhr.addEventListener(m, handle, false)); xhr.mozBackgroundRequest = true; xhr.open('GET', url, true); xhr.channel.loadFlags |= Ci.nsIRequest.LOAD_ANONYMOUS | Ci.nsIRequest.LOAD_BYPASS_CACHE | Ci.nsIRequest.INHIBIT_PERSISTENT_CACHING; xhr.send(null); }; xl.pref = {}; Object.defineProperty(xl.pref, '_service', { enumerable: false, get: function() { return xl.ff.getService('preferences-service;1', 'nsIPrefBranch'); }, set: function() { return null; } }); xl.pref.type = function(name) { switch(this._service.getPrefType(name)) { case this._service.PREF_STRING: return 'string'; break; case this._service.PREF_INT: return 'int'; break; case this._service.PREF_BOOL: return 'bool'; break; case this._service.PREF_INVALID: return 'invalid'; break; default: return false; } return null; }; xl.pref.get = function(name) { switch(this.type(name)) { case 'string': return this._service.getComplexValue(name, xl.ff.findInterface('nsISupportsString')).data; case 'int': return this._service.getIntPref(name); case 'bool': return this._service.getBoolPref(name); default: return false; } return null; }; xl.pref.set = function(name, value) { var ret; switch(typeof(value)) { case 'string': if(value.length === 1) { ret = this._service.setCharPref(name, value); } else { var tmp = xl.ff.createInstance('supports-string', 'nsISupportsString'); tmp.data = value; ret = this._service.setComplexValue(name, xl.ff.findInterface('nsISupportsString'), tmp); } break; case 'number': ret = this._service.setIntPref(name, value); break; case 'boolean': ret = this._service.setBoolPref(name, value); break; default: ret = null; } return ret; }; xl.pref.del = function(name) { return this._service.deleteBranch(name); }; xl.pref.list = function(name) { return this._service.getChildList(name); }; context.xl = xl; }(this)); (function (context, undef) { function XLEvent() { this.subjects = {}; }; XLEvent.prototype.create = function(subject) { this.subjects[subject] = []; }; XLEvent.prototype.has = function(subject) { return this.subjects.hasOwnProperty(subject); }; XLEvent.prototype.get = function(subject) { if(!this.has(subject)) return null; return this.subjects[subject]; }; XLEvent.prototype.subscribe = function(subject, name, callback) { this.get(subject).push({ name: name, callback: callback }); return this; }; XLEvent.prototype.remove = XLEvent.prototype.unsubscribe = function(subject, name) { this.subjects[subject] = this.get(subject).filter(function(value) { if(value.name == name) return false; return true; }); return this; }; XLEvent.prototype.publish = function(subject) { var args = Array.prototype.slice.call(arguments, 1); var subs = this.get(subject); for(var i=0, j=subs.length; i < j; i++) { subs[i].callback.apply(null, args); } return this; } context.event = new XLEvent(); }(xl)); Object.defineProperty(xl, '$doc', { enumerable: false, get: function() { return gBrowser.contentDocument || document; }, set: function() { return; } }); Object.defineProperty(xl, '$win', { enumerable: false, get: function() { return gBrowser.contentWindow || window; }, set: function() { return; } }); xl.event.create('xl:load'); xl.event.subscribe('xl:load', 'extend', function(context) { context.extend = function(target, source) { source = source || {}; var toString = Object.prototype.toString, testObject = toString.call({}); for(var property in source) { if(source[property] && testObject === toString.call(source[property])) { target[property] = target[property] || {}; this.extend(target[property], source[property]); } else { target[property] = source[property]; } } return target; }; }); xl.event.subscribe('xl:load', '$', function(context) { context.$ = function(sel, cx) { sel = sel.trim(); cx = cx || document || window.document || gBrowser.contentDocument || gBrowser.contentWindow && gBrowser.contentWindow.document; if(sel.charAt(0) == '<' && sel.charAt(sel.length-1) == '>') { var fragment = document.createDocumentFragment(); var element = document.createElement('span'); element.innerHTML = sel; fragment.appendChild(element); return fragment.childNodes[0].firstChild; } else { if(sel.charAt(0) == '#') { return [cx.getElementById(sel.slice(1))]; } else if(sel.charAt(0) == '.') { return [].slice.call(cx.getElementsByTagName(sel.slice(1))); } else { var list = [].slice.call(cx.getElementsByTagName(sel)); if(list.length > 0) return list; else return [].slice.call(cx.querySelectorAll(sel) || [cx.querySelector(sel)]); } } return this; }; }); xl.event.subscribe('xl:load', '$on', function(context) { context.$on = function(element, event, callback) { if(typeof element == 'string') { element = xl.$(element); } for(var i=0; i < element.length; i++) { element[i].addEventListener(event, callback, false); } return this; }; }); xl.event.subscribe('xl:load', '$addClass', function(context) { context.$addClass = function(element, cname) { element.className = (element.className + ' ' + cname).trim(); return this; }; }); xl.event.subscribe('xl:load', '$removeClass', function(context) { context.$removeClass = function(element, cname) { element.className = element.className.replace(cname, '').trim(); } }); xl.event.publish('xl:load', xl);<file_sep><?php namespace XLib\Brightpearl; class WebAPI { private $sAPIObject; public function __construct($sAPIObject = NULL) { $this->sAPIObject = $sAPIObject; } public function setAPIObject($sAPIObject) { $this->sAPIObject = $sAPIObject; return $this; } public function getAPIObject() { return $this->sAPIObject; } public function sendRequest() { $ch = curl_init(); $headers = array(); $headers[] = 'GET ' . $this->sAPIObject->getServiceTargetURL() . '/' . $this->sAPIObject->getAccountName() . '/' . $this->sAPIObject->getServiceSubject() . '/' . $this->sAPIObject->getServiceTarget() . ' HTTP/1.1'; $headers[] = 'Host: ' . $this->sAPIObject->getServiceHostURL(); $headers[] = 'Connection: keep-alive'; $headers[] = 'CSP: active'; $headers[] = 'brightpearl-account-token: ' . $this->sAPIObject->getAccountSecurityToken(); $headers[] = 'brightpearl-app-ref: ' . $this->sAPIObject->getApplicationReferenceID(); $headers[] = 'User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36'; $headers[] = 'Accept: */*'; $headers[] = 'DNT: 1'; $headers[] = 'Accept-Encoding: gzip, deflate, sdch'; $headers[] = 'Accept-Language: en-US,en;q=0.8'; $headers[] = 'Cookie: optimizelyEndUserId=oeu1436898932050r0.5986172466073185; __lc.visitor_id.5706611=S1436898932.5e345719e1; overlay_enabled=false; optimizelySegments=%7B%221035238168%22%3A%22search%22%2C%221037617913%22%3A%22false%22%2C%221052543630%22%3A%22gc%22%2C%221806960290%22%3A%22none%22%7D; optimizelyBuckets=%7B%7D; iv=c2b21be2-84a8-40ba-92b9-a8ea78b77ccb; _mkto_trk=id:135-BBD-722&token:_<PASSWORD>; vscr_vid=13f0e3f75cb9b19d001610df06000000; vscr_sid=13f13f42440a774800179a4c04000000; lc_window_state=minimized; __utma=78278087.1041246323.1436898933.1436999306.1437003080.4; __utmc=78278087; __utmz=78278087.1436899151.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); __utmv=78278087.|4=idio%20identifier=c2b21be2-84a8-40ba-92b9-a8ea78b77ccb=1'; curl_setopt($ch, CURLOPT_URL, $this->sAPIObject->getServiceTargetURL() . '/' . $this->sAPIObject->getAccountName() . '/' . $this->sAPIObject->getServiceSubject() . '/' . $this->sAPIObject->getServiceTarget() ); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); $res = curl_exec($ch); if (FALSE === $res) { return NULL; } return $res; } }<file_sep><?php namespace XLib; class Script { }<file_sep> //}); if(xlib.hasOwnProperty('oat')) { delete xlib.oat; } (function xlib_upgrade (context) { var xl = xlib; xl.has = function(str) { return this.hasOwnProperty(str); }; this.exists = function(str, context) { context = context || window; return (context.hasOwnProperty && context.hasOwnProperty(str)); }; this.proxy = function(target, cbfn, args) { return cbfn.apply(target, args); }; this.initObjectPath = function(path, target) { if(typeof path === 'object' && path instanceof Array) { for(var i=0; i < path.length; i++) { this.initObjectPath(path[i], target); } } //path = path.split('.') || []; path = path.split && path.split('.') || []; var len = path.length; for(var i=0; i < len; i++) { var current = path[i]; if(target.hasOwnProperty) { if(!target.hasOwnProperty(current)) { target[current] = {}; } } target = target[current]; } pl(target); return target; }; }).apply(xlib); (function xlib_oat_xulTree (context) { this.oat = (function(context) { var ret = {}; ret.treeView = { childData: [ ['OAG 1.1.1', 'Test Message.', 'Some Actions Here'], ['OAG 1.2.1', 'Test Message.', 'Some Actions Here'], ['OAG 1.3.1', 'Test Message.', 'Some Actions Here'] ], treeBox: null, selection: null, get rowCount() { return this.childData.length; }, setTree: function (treeBox) { this.treeBox = treeBox; } }; return ret; })(xlib); }).apply(xlib, [xlib]); <file_sep>try { if(typeof(xlib) === "undefined") { throw "xlib: missing core library"; } xlib.app = {}; xlib.app.restart = function() { xlib.getService('toolkit/app-startup', 'nsIAppStartup').quit(Ci.nsIAppStartup.eForceQuit | Ci.nsIAppStartup.eRestart); }; xlib.app.startBrowserToolbox = function() { return BrowserToolboxProcess.init(); }; } catch (err) { console.error(err); }<file_sep> var oatImgAlt = new XLibPlugin().init(); $.extend (oatImgAlt, { getDocument: function() { return gBrowser.contentDocument; }, getWindow: function() { return gBrowser.contentWindow; } }); oatImgAlt.getStyle = function(target, prop) { if(target.currentStyle) { return target.currentStyle[prop]; } else if (this.getWindow().getComputedStyle) { return this.getDocument() .defaultView .getComputedStyle(target, null) .getPropertyValue(prop); } return null; }; oatImgAlt.runTest = function() { try { var chkbox = Boolean($('#oat-chkbox-oag111').attr('checked')); if(chkbox == true) { var list = Oatlib.html.getAllImages(); window.list = list; var output = _$('#oat-output')[0]; var treeViewObj = output.view.QueryInterface(Ci.nsITreeView); var data = []; window.imageData = data; list.images.forEach(function(aValue, aIndex) { data.push (['1.1.1', 'image [src] ' + aValue.getAttribute('src'), 'disabled', aValue]); }); list.bgimages.forEach(function(aValue, aIndex) { data.push(['1.1.1', 'bgimage [src] ' + aValue.url, 'disabled', aValue.elem]) }); var oatImgTreeView = Oatlib.xul.createTreeView(data); oatImgTreeView.selectionChanged = function() { console.log(this, ' -- args: ', arguments); } output.view = oatImgTreeView; window.imageData = data; return data; } } catch(err) { pl(err); } return false; } /* var self = $(this); var node = self[0]; var src = self.attr('src'); var role = self.attr('role') || ''; var alt = self.attr('alt') || false; var msg = ''; if (!src.match(/^http|https/) && !src.match(/data\:image/)) { src = tdoc.location.protocol+'//'+tdoc.location.host+'/'+src; } if (!IsHidden(node)) { if(alt != false && alt == '') { var info = OAT.CreateImageInfo('Image alt is blank, considered presentational.', src); } else if(alt && typeof alt == 'string' && alt.search(/[^\s\t]/g) == -1) { var err = OAT.CreateImageError('Image alt must be empty or a valid string.', src); $(err).data ({ target: self, border: self.css('border') || '' }); $(err).click (function () { OAT.ToggleNodeHighlight($(this)); OAT.ScrollTo($(this)); }) .appendTo(OAT.Results); } else if(role && role == 'presentation') { var err = OAT.CreateImageInfo('Image marked as presentational', src); $(err).data ({ target: self, border: self.css('border') || '' }); $(err).click (function () { OAT.ToggleNodeHighlight($(this)); OAT.ScrollTo($(this)); }) .appendTo(OAT.Results); } else if(alt == false) { var err = OAT.CreateImageError('Image alt is missing.', src); $(err).data ({ target: self, border: self.css('border') || '' }); $(err).click (function () { OAT.ToggleNodeHighlight($(this)); OAT.ScrollTo($(this)); }) .appendTo(OAT.Results); pl(src); } else { if(alt) { if(getCamelCase(alt) !== false) { var err = OAT.CreateImageError('Image alt contains camelCase text.', src); $(err).data ({ target: self, border: self.css('border') || '' }); $(err).click (function () { OAT.ToggleNodeHighlight($(this)); OAT.ScrollTo($(this)); }) .appendTo(OAT.Results); } else { var info = OAT.CreateImageInfo('Image alt: '+alt, src); $(info).data ({ target: self, border: self.css('border') || '' }); $(info).click (function () { OAT.ToggleNodeHighlight($(this)); OAT.ScrollTo($(this)); }) .appendTo(OAT.Results); } } if(self.attr('ismap')) { var warn = OAT.CreateImageWarning('Server-side image map found.', src); $(warn).data ({ target: self, border: self.css('border') || '' }); $(warn).click (function () { OAT.ToggleNodeHighlight($(this)); OAT.ScrollTo($(this)); }) .appendTo(OAT.Results); } } } });*/<file_sep><?php namespace XLib\Brightpearl; require_once 'SimpleCache.php'; require_once 'DynamicService.php'; require_once 'vendor/autoload.php'; class Brightpearl extends \SimpleCache { public $handle = null; public $cache = null; public $dyService = null; public function __construct() { $this->handle = new \XLib\Brightpearl\DynamicService(); $this->cache = new \SimpleCache(); $this->dyService = new \XLib\Brightpearl\DynamicService(); } public function cacheSet($key, $val) { $this->cache->store($key, $val); return $this; } public function cacheGet($key) { return $this->cache->retrieve($key); } public function isCached($key) { return boolval($this->cache->isCached($key)); } public function getDynamicService() { return $this->handle; } public function getHandle() { return $this->handle; } public function orderCached($id) { $name = "order-$id"; return ($this->isCached($name)); } public function cacheOrder($id) { $name = "order-$id"; if(!$this->orderCached($id)) { $data = $this->dyService->getOrder($id); $this->store($name, $data); } return ($this->isCached($name)); } public function trimResponse($res=null) { if($res === null) return null; if(isset($res['response'])) { $res = $res['response']; } if(count($res) <= 0) { return -1; } return $res; } public function storeOrderData($data=null) { if($data == null) return null; $res = $this->trimResponse($data); if(isset($data['response'])) { $data = $data['response']; } elseif(count($data) <= 0) { return -1; } $name = 'order-' . strval($data['id']); if(!$this->orderCached($name)) { $data = $this->trimResponse( $this->dyService->getOrder($data['id']) ); $this->store($name, $data); return true; } return false; } public function getOrderData($id=null) { if($id == null) return null; if($this->orderExists($id)) { $name = 'order-' . $id; return $this->retrieve($name); } return false; } }<file_sep>if(typeof(xlib) !== "undefined") { xlib = undefined; } var xlib = {}; xlib.version = "0.1.5.38"; xlib._ready = []; xlib.app = {}; var oatImgAlt = {}; xlib.loader = function(path, cx) { return Components.classes['@mozilla.org/moz/jssubscript-loader;1'] .getService(Components.interfaces.mozIJSSubScriptLoader) .loadSubScript(path, cx || {}, "UTF-8"); }; let {Constructor: CC, classes: Cc, interfaces: Ci, utils: Cu, results: Cr, manager: Cm} = Components; var pl = function () { console.log.apply(console, arguments); }; var dir = function() { console.dir.apply(console, arguments); }; var clr = function(n) { console.log("\n".repeat(n || 30)); }; xlib.typeof = function(aName) { var t = window[aName] || this[aName] || aName; if(t instanceof Object) { if(t instanceof Array) return 'Array'; else return 'Object'; } if(t instanceof Number) return 'number'; if(t instanceof String) return 'string'; if(t instanceof Boolean) return 'boolean'; return typeof(t); }; xlib.typeName = function(obj) { var cttype = {}; var toString = cttype.toString; $.each('Boolean Number String Function Array Date RegExp Object Error'.split(' '), function(idx, name) { cttype['[object ' + name + ']'] = name.toLowerCase(); }); if(obj == null) { return obj + ''; } return typeof obj === "object" || typeof obj == "function" ? cttype[toString.call(obj)] || "object" : typeof obj; }; xlib.createAlias = function(aliasName, path) { Components.utils.import("resource://gre/modules/Services.jsm"); var resourceProto = Services.io.getProtocolHandler("resource") .QueryInterface(Components.interfaces.nsIResProtocolHandler); var aliasFile = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsILocalFile); aliasFile.initWithPath(path); var aliasURI = Services.io.newFileURI(aliasFile); resourceProto.setSubstitution(aliasName, aliasURI); } xlib.createUniqueID = function(len) { len = len || 12; var ret = 'x'.repeat(len); if(ret.length) { ret.replace(/[xy]/g, function(c) { var ss = Math.random()*16|0, v = c == 'x' ? ss : (ss&0x3|0x8); return v.toString(16); }); return ret; } return false; }; xlib.toASCII = function(aString) { aString = aString || false; if(typeof(aString) === "string") { var len = aString.length; var ret = []; for(var i=0; i < len; ++i) { ret.push(aString.charCodeAt(i)); } return [ret, ret.join(' ')]; } else if(typeof(aString) === "object") { if(aString.length >= 0) { var len = aString.length; var ret = []; for(var i=0; i < len; ++i) { ret.push((new String(aString[i])).charCodeAt(0)); } return [ret, ret.join(' ')]; } } return false; } xlib.selector = function(sel, context) { context = context || document; if (sel.charAt(0) == '#') { return context.getElementById(sel.substr(1)); } else { var ch = sel.charAt(0); if (ch !== '<' && ch !== '#' && ch !== '.') { return [].slice.call(context.getElementsByTagName(sel)); } return [].slice.call(context.querySelectorAll(sel)); } return null; }; xlib.loader = function(aPath, aObject) { aObject = aObject || window; return Services.scriptloader.loadSubScript(aPath, aObject, 'UTF-8'); }; xlib.findClass = function(aURL) { if (typeof(Components.classes[aURL]) != 'undefined') { return Components.classes[aURL]; } for (var key in Components.classes) { if (key.search(aURL) > -1) { return Components.classes[key]; } } return null; }; xlib.findInterface = function(aInterface) { if (typeof(Components.interfaces[aInterface]) != 'undefined') { return Components.interfaces[aInterface]; } for (var key in Components.interfaces) { if (key.search(aInterface) > -1) { return Components.interfaces[key]; } } }; xlib.getService = function(aURL, aInterface) { var ret, _c, _i; try { _c = Cc[aURL] || this.findClass(aURL); switch (typeof(aInterface)) { case 'object': ret = _c.getService(aInterface); break; case 'string': ret = _c.getService(Ci[aInterface] || this.findInterface(aInterface)); break; default: ret = _c.getService(); } } catch (err) { ret = err; } return ret; }; xlib.createInstance = function(aURL, aInterface) { var ret, _c = this.findClass(aURL); try { switch (typeof(aInterface)) { case 'object': ret = _c.createInstance(aInterface); break; case 'string': ret = _c.createInstance(this.findInterface(aInterface)); break; default: ret = null; } } catch (err) { ret = err; } return ret; }; xlib.toArray = function(obj) { var arr = []; if(typeof(obj) === "object" && obj.hasOwnProperty) { for(var itr in obj) { if(obj.hasOwnProperty(itr)) { arr.push(obj[itr]); } } } else { for(var itr in obj) { arr.push(obj[itr]); } } return arr; }; xlib.walkObject = function() { var args = arguments || []; var target = args[0] || {}, cbfn = args[1] || null, depth = args[2] || 1, node = null; for(node in target) { var current = target[node]; if(target.hasOwnProperty && target.hasOwnProperty(node)) { if(cbfn !== null) { if(cbfn.call({}, current) === false) { break; } } if(typeof current == 'object' || typeof current == 'array' || (current.length && current.length > 0)) { depth++; xlib.walkObject(current, cbfn, depth); } } } }; xlib.iterator = function(items) { return new (function XLibIterator (items) { this.index = 0; this.items = items; this.first = function first() { this.reset(); return this.next(); }; this.next = function next() { return this.items[this.index++]; }; this.hasNext = function hasNext() { return this.index <= this.items.length; }; this.reset = function reset() { this.index = 0; }; this.each = function each(cbfn) { for(var item = this.first(); this.hasNext(); item = this.next()) { cbfn(item); } }; })(items); }; xlib.initMemberPath = function(aTarget, aPath, aOverwrite) { aOverwrite = aOverwrite || false; if(typeof aPath == "object" || aPath instanceof Array) { for(var i=0; i < aPath.length; i++) { xlib.buildPath(aTarget, aPath[i], aOverwrite); } } else { aPath = aPath.split('.') || []; for(var i=0; i < aPath.length; i++) { var index = aPath[i]; if(!aTarget[index] || aOverwrite == true || xlib.isEmpty(aTarget[index])) { aTarget[index] = {}; } aTarget = aTarget[index]; } } return aTarget; }; var Plugin = function (elem, options) { this.elem = elem; this.$elem = $(elem); this.options = options; this.metadata = this.$elem.data('plugin-options'); }; Plugin.prototype = { defaults: { }, init: function() { this.config = $.extend({}, this.defaults, this.options, this.metadata); // init return this; }, _n: function() { } } Plugin.defaults = Plugin.prototype.defaults; $.fn.plugin = function(options) { return this.each(function() { new Plugin(this, options).init(); }); }; window.XLibPlugin = Plugin; xf.XLibPlugin = Plugin; var __xlibLoad = { app: function() { return xlib.loader('chrome://oat/content/xlib.app.js', window); }, pref: function() { return xlib.loader('chrome://oat/content/xlib.pref.js', window); }, event: function() { return xlib.loader('chrome://oat/content/xlib.event.js', window); }, util: function() { return xlib.loader('chrome://oat/content/xlib.util.js', window); }, eventHandlers: function() { return xlib.loader('chrome://oat/content/xlib.eventHandlers.js', window); }, moz: function() { return xlib.loader('chrome://oat/content/xlib.moz.js', window); }, file: function() { return xlib.loader('chrome://oat/content/xlib.file.js', window); }, oat: function() { return xlib.loader('chrome://oat/content/xlib.oat.js', window); } }; var __OatlibLoad = { Oatlib: function() { return xlib.loader('chrome://oat/content/Oatlib.js', window); }, imageAltTest: function() { return xlib.loader('chrome://oat/content/Oatlib.imageAltTest.js', window); } } __xlibLoad.app(); __xlibLoad.pref(); __xlibLoad.event(); __xlibLoad.util(); //__xlibLoad.eventHandlers(); __xlibLoad.moz(); __xlibLoad.file(); __OatlibLoad.Oatlib(); __OatlibLoad.imageAltTest(); function loadXL() { //xlib.loader('file://D:\\Oracle\\chrome\\content\\xlib.jqEx.js', window); if(typeof (xf) == "undefined" || !window.hasOwnProperty('xf')) { xlib.loader('file://D:\\Oracle\\chrome\\content\\xlib.fw.js'); } xlib.loader('file://D:\\Oracle\\chrome\\content\\xlib.js'); } function loadXFPlugins() { xlib.loader('file://D:\\Oracle\\chrome\\content\\xlib.fw.plugins.js'); } function loadOGHAG() { // images xlib.loader('D:\\Oracle\\chrome\\content\\legacy\\chrome\\content\\images.js'); } xl.query = function() { var args = Array.prototype.slice.call(arguments); var sel = args.shift() || null; var cx; if($.isArray(args) && args.length >= 1) { cx = args[0] && !args[0] instanceof Window ? args[0] : document; } else { cx = args && !args instanceof Window ? args : document; } sel = (typeof sel == "string" && sel.charAt(0) == '#' || sel.charAt(0) == '.' && sel.indexOf(':') != -1) && sel.replace(/\:/g, '\\:') || sel; return $(sel, cx); }; function _$() { return xl.query.apply($, arguments); } /* $.fn.xlib = function() { var cx = this.context || null; var args = $.makeArray(arguments); var cmd = args[0] || null; this.getContextNamespace = function() { var ns = this.context && this.context.ownerGlobal.document.firstElementChild.namespaceURI; return (typeof(ns) == "string" && ns.length > 0) ? ns : null; }; this.isContextHTML = function() { var ns = this.getContextNamespace(); return (ns != null) && ns.search(/\.html/gi) != -1 ? true : (ns != null) ? false : null; }; this.isContextXUL = function() { var ns = this.getContextNamespace(); return (ns != null) && ns.search(/\.xul/gi) != -1 ? true : (ns != null) ? false : null; }; if(cmd != null) { if(cmd == 'isContextXUL') { return (cx != null) && cx.owner } } return this; }; }); */ if(typeof (OGHAG) === "undefined") { var OGHAG = {}; } OGHAG.createDocumentFragment = function(obj) { var df = document.createDocumentFragment(); if(obj && obj.nodeType) { df.appendChild(obj); } return df; } OGHAG.isHidden = function (obj) { //OGHAG.LOG(obj.nodeName+','+obj.offsetWidth+','+obj.offsetHeight+','+obj.offsetTop+','+obj.offsetLeft); if (obj.offsetWidth === 0 && obj.offsetHeight === 0 && obj.offsetTop === 0 && obj.offsetLeft === 0) { return true; // This is an ADF shortcut. If we are an ADF Application then text which is hidden to screen readers has // an offsetTop of -99999 //if (OGHAG.SRMode != 'NA'){ // if (obj.offsetTop == -99999) // return false; // else // return true; //} /*var out = false; try { //This could have really nasty performance impact..... var objStyle = obj.ownerDocument.defaultView.getComputedStyle(obj, ''); if (objStyle.getPropertyValue('display') == 'none' || objStyle.getPropertyValue('visibility') == 'hidden') // if (obj.style.display == 'none' || obj.style.visibility == 'hidden') { return true; } else { if (obj.parentNode.nodeType == 1) { out = OGHAG.isHidden(obj.parentNode); } } } catch (err) { return out; }*/ } else { return false } return out; } xlib.createSandbox = function(aUrl, aSandboxName) { aUrl = aUrl || null; aSandboxName = aSandboxName || xlib.generateUniqueId(16); let sandbox = new Cu.Sandbox(gBrowser.ownerGlobal, { sandboxPrototype: gBrowser.ownerGlobal, wantXrays: false, sandboxName: 'xlib-sandbox-' + aSandboxName }); return sandbox; } xlib.dev = {}; xlib.dev.test1 = function() { xlib.dev.xwin = window.getGroupMessageManager("browsers"); xlib.dev.xwin }; xlib.ready(function() { console.log('Created OAT event listeners...'); _$('#oat-btn-run').unbind().click(function() { var chkbox = Boolean($('#oat-chkbox-oag111').attr('checked')); if(chkbox == true) { oatImgAlt.runTest(); } }); }); window.addEventListener('load', function() { console.log('Loaded OAT...'); _$('#oat-btn-run').unbind().click(function() { var chkbox = Boolean($('#oat-chkbox-oag111').attr('checked')); if(chkbox == true) { oatImgAlt.runTest(); } }); console.log('Processing queue....'); xlib._readyProcessQueue(); }) <file_sep><?php namespace XLib; class String { private $originalString; private $currentString; public function __construct($value='') { $this->originalString = $value; $this->currentString = $value; } private function &value() { return $this->currentString; } public function getValue() { return $this->currentString; } public function setValue($value) { $this->currentString = $value; return $this; } public function setOriginalValue($value) { $this->originalString = $value; return $this; } public function getOriginalValue() { return $this->originalString; } public function trimLeft() { return preg_replace("/^\\s{2,}/m", '', $this->value()); } public function trimRight() { return preg_replace("/\\s{2,}$/m", '', $this->value()); } public function trim() { $this->currentString = $this->trimLeft(); $this->currentString = $this->trimRight(); return $this->currentString; } public function splitLine() { $ret = array(); foreach(preg_split("/((\r?\n)|(\r\n?))/", $this->value()) as $line) { $ret[] = $line; } return $ret; } public function splitLine2() { return explode(PHP_EOL, $this->value()); } }<file_sep><?php namespace XLib\Brightpearl; class StructAuthentication { private $emailAddress; private $password; private $targetURL; public function __construct($email = NULL, $pass = NULL, $target = NULL) { $this->emailAddress = $email; $this->password = $<PASSWORD>; $this->targetURL = $target; } public function setEmailAddress($email) { $this->emailAddress = $email; return $this; } public function getEmailAddress() { return $this->emailAddress; } public function setPassword($pass) { $this->password = $<PASSWORD>; } public function getPassword() { return $this->password; } public function setTargetURL($target) { $this->targetURL = $target; return $this; } public function getTargetURL() { return $this->targetURL; } }<file_sep><?php namespace XLib\Brightpearl; require __DIR__ . '/../../vendor/autoload.php'; if(!class_exists('SimpleCache')) { require_once 'SimpleCache.php'; } class StructAuthentication { private $emailAddress; private $password; private $targetURL; public function __construct($email = NULL, $pass = NULL, $target = NULL) { $this->emailAddress = $email; $this->password = $<PASSWORD>; $this->targetURL = $target; } public function setEmailAddress($email) { $this->emailAddress = $email; return $this; } public function getEmailAddress() { return $this->emailAddress; } public function setPassword($pass) { $this->password = $<PASSWORD>; } public function getPassword() { return $this->password; } public function setTargetURL($target) { $this->targetURL = $target; return $this; } public function getTargetURL() { return $this->targetURL; } } ; class StructAPI { private $accountName; private $serviceSubject; private $serviceTarget; private $serviceTargetURL; private $serviceHostURL; private $accountSecurityToken; private $applicationReferenceID; public function __construct($accountName = NULL, $serviceSubject = NULL, $serviceTarget = NULL, $serviceTargetURL = NULL, $serviceHostURL = NULL, $accountSecurityToken = NULL, $applicationReferenceID = NULL) { $this->accountName = $accountName; $this->serviceSubject = $serviceSubject; $this->serviceTarget = $serviceTarget; $this->serviceTargetURL = $serviceTargetURL; $this->serviceHostURL = $serviceHostURL; $this->accountSecurityToken = $accountSecurityToken; $this->applicationReferenceID = $applicationReferenceID; } public function setAccountName($account) { $this->accountName = $account; return $this; } public function getAccountName() { return $this->accountName; } public function setServiceSubject($subject) { $this->serviceSubject = $subject; return $this; } public function getServiceSubject() { return $this->serviceSubject; } public function setServiceTarget($target) { $this->serviceTarget = $target; return $this; } public function getServiceTarget() { return $this->serviceTarget; } public function setServiceTargetURL($targetURL) { $this->serviceTargetURL = $targetURL; return $this; } public function getServiceTargetURL() { return $this->serviceTargetURL; } public function setServiceHostURL($serviceHostURL) { $this->serviceHostURL = $serviceHostURL; return $this; } public function getServiceHostURL() { return $this->serviceHostURL; } public function setAccountSecurityToken($accountSecurityToken = NULL) { $this->accountSecurityToken = $accountSecurityToken; return $this; } public function getAccountSecurityToken() { return $this->accountSecurityToken; } public function setApplicationReferenceID($applicationReferenceID = NULL) { $this->applicationReferenceID = $applicationReferenceID; return NULL; } public function getApplicationReferenceID() { return $this->applicationReferenceID; } } class TokenAuthentication { private $sAuthObject; private $token; public function __construct($sAuthObject = NULL) { $this->sAuthObject = $sAuthObject; } public function setAuthenticationObject($sAuthObject = NULL) { $this->token = NULL; if (is_object($sAuthObject)) { $this->sAuthObject = $sAuthObject; return $this; } return NULL; } public function getAuthenticationObject() { return $this->sAuthObject; } public function setToken($token) { $this->token = $token; return $this; } public function getToken() { return $this->token; } public function requestToken() { if ($this->sAuthObject === NULL) { return NULL; } $ch = curl_init(); $cred = array( 'apiAccountCredentials' => array( 'emailAddress' => $this->sAuthObject->getEmailAddress(), 'password' => $this->sAuthObject-><PASSWORD>() ) ); $encodedCred = json_encode($cred); $url = $this->sAuthObject->getTargetURL(); $headers = array('Content-Type: application/json'); $cOpt = array( CURLOPT_URL => $url, CURLOPT_HTTPHEADER => $headers, CURLOPT_POST => TRUE, CURLOPT_POSTFIELDS => $encodedCred, CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_SSL_VERIFYHOST => FALSE, CURLOPT_SSL_VERIFYPEER => FALSE ); curl_setopt_array($ch, $cOpt); $res = curl_exec($ch); if (FALSE === $res) { curl_close($ch); return NULL; } #var_dump($this->sAuthObject); #echo "\n"; #var_dump($res); #echo "\n"; #var_dump(curl_error($ch)); $data = json_decode($res); curl_close($ch); $this->setToken($data->response); return $this; } } class WebAPI { private $sAPIObject; public function __construct($sAPIObject = NULL) { $this->sAPIObject = $sAPIObject; } public function setAPIObject($sAPIObject) { $this->sAPIObject = $sAPIObject; return $this; } public function getAPIObject() { return $this->sAPIObject; } public function sendRequest() { $ch = curl_init(); $headers = array(); $headers[] = 'GET ' . $this->sAPIObject->getServiceTargetURL() . '/' . $this->sAPIObject->getAccountName() . '/' . $this->sAPIObject->getServiceSubject() . '/' . $this->sAPIObject->getServiceTarget() . ' HTTP/1.1'; $headers[] = 'Host: ' . $this->sAPIObject->getServiceHostURL(); $headers[] = 'Connection: keep-alive'; $headers[] = 'CSP: active'; $headers[] = 'brightpearl-account-token: ' . $this->sAPIObject->getAccountSecurityToken(); $headers[] = 'brightpearl-app-ref: ' . $this->sAPIObject->getApplicationReferenceID(); $headers[] = 'User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36'; $headers[] = 'Accept: */*'; $headers[] = 'DNT: 1'; $headers[] = 'Accept-Encoding: gzip, deflate, sdch'; $headers[] = 'Accept-Language: en-US,en;q=0.8'; $headers[] = 'Cookie: optimizelyEndUserId=oeu1436898932050r0.5986172466073185; __lc.visitor_id.5706611=S1436898932.5e345719e1; overlay_enabled=false; optimizelySegments=%7B%221035238168%22%3A%22search%22%2C%221037617913%22%3A%22false%22%2C%221052543630%22%3A%22gc%22%2C%221806960290%22%3A%22none%22%7D; optimizelyBuckets=%7B%7D; iv=c2b21be2-84a8-40ba-92b9-a8ea78b77ccb; _mkto_trk=id:135-BBD-722&token:_<PASSWORD>933144-79793; vscr_vid=13f0e3f75cb9b19d001610df06000000; vscr_sid=13f13f42440a774800179a4c04000000; lc_window_state=minimized; __utma=78278087.1041246323.1436898933.1436999306.1437003080.4; __utmc=78278087; __utmz=78278087.1436899151.2.2.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided); __utmv=78278087.|4=idio%20identifier=c2b21be2-84a8-40ba-92b9-a8ea78b77ccb=1'; curl_setopt($ch, CURLOPT_URL, $this->sAPIObject->getServiceTargetURL() . '/' . $this->sAPIObject->getAccountName() . '/' . $this->sAPIObject->getServiceSubject() . '/' . $this->sAPIObject->getServiceTarget() ); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); $res = curl_exec($ch); if (FALSE === $res) { return NULL; } return $res; } } class WebServiceDriver { private $sAuth; private $sAPI; private $tokenAuth; private $webAPI; public function __construct($sAuth=NULL, $sAPI=NULL, $tokenAuth=NULL, $webAPI=NULL) { $this->sAuth = $sAuth; $this->sAPI = $sAPI; $this->tokenAuth = $tokenAuth; $this->webAPI = $webAPI; } public function setStructAuthentication($sAuth) { $this->sAuth = $sAuth; return $this; } public function getStructAuthentication() { return $this->sAuth; } public function setStructAPI($sAPI) { $this->sAPI = $sAPI; return $this; } public function getStructAPI() { return $this->sAPI; } public function setTokenAuthentication($tokenAuth) { $this->tokenAuth = $tokenAuth; return $this; } public function getTokenAuthentication() { return $this->tokenAuth; } public function setWebAPI($webAPI) { $this->webAPI = $webAPI; return $this; } public function getWebAPI() { return $this->webAPI; } } class Requests { public static $service; public static $target; public static function setService($service) { self::$service = $service; } public static function getService() { return self::$service; } public static function setTarget($target) { self::$target = $target; } public static function getTarget() { return self::$target; } public static function getProductbyId($pid) { self::setService('product-service'); self::setTarget('product'); return self::getService() . '/' . self::getTarget() . '/' . $pid; } } class API { public $requestUrl; public $accountName; public $service; public $target; public $appReferenceId; public $securityToken; public function __construct() { } public function sendGetRequest() { $client = new \GuzzleHttp\Client(); $result = $client->get( $this->requestUrl . '/' . $this->accountName . '/' . $this->service . '/' . $this->target, [ 'verify' => false, 'headers' => [ 'brightpearl-app-ref' => $this->appReferenceId, 'brightpearl-account-token' => $this->securityToken ] ] ); if($result->getStatusCode() == 200) { return json_decode($result->getBody(), true); } return null; } public function dynamicGetRequest() { $args = func_get_args(); $client = new \GuzzleHttp\Client(); $result = $client->get( $this->requestUrl . '/' . $this->accountName . '/' . join($args, '/'), [ 'verify' => false, 'headers' => [ 'brightpearl-app-ref' => $this->appReferenceId, 'brightpearl-account-token' => $this->securityToken ] ] ); if($result->getStatusCode() == 200) { return json_decode($result->getBody(), true); } return null; } } # use this for simplicity class DynamicService { public $requestURL = 'https://ws-use.brightpearl.com/public-api'; public $accountName = '______'; public $service = ''; public $target = ''; public $appRefId = '_________'; public $securityToken = '_______________'; public $endPoint = ''; public $response; public $returnJSON = false; private $_struct = array(); public function __construct() { } private function _st($name=null) { if($name) { return (isset($this->_struct[$name])) ? $this->_struct[$name] : null; } return $this->_struct; } private function _createHttpClient() { $arr = array( 'handle' => new \GuzzleHttp\Client(), 'url' => 'https://ws-use.brightpearl.com/public-api', 'accountName' => '____________', 'service' => '', 'target' => '', 'endPoint' => '', 'appRefID' => '___________', 'securityToken' => '______________', 'response' => '', 'returnJSON' => null ); } private function createApiObject($service, $target, $endp) { $this->service = $service; $this->target = $target; $this->endPoint = $endp; $api = new \XLib\Brightpearl\API(); $api->requestUrl = $this->requestURL; $api->accountName = $this->accountName; $api->service = $this->service; $api->target = $this->target; $api->appReferenceId = $this->appRefId; $api->securityToken = $this->securityToken; return $api; } private function sendGetRequest($api) { return ($this->endPoint !== '') ? $api->dynamicGetRequest($this->service, $this->target, $this->endPoint) : $api->dynamicGetRequest($this->service, $this->target); } public function get($service, $target, $endp = '') { $this->service = $service; $this->target = $target; $this->endPoint = $endp; $api = new \XLib\Brightpearl\API(); $api->requestUrl = $this->requestURL; $api->accountName = $this->accountName; $api->service = $this->service; $api->target = $this->target; $api->appReferenceId = $this->appRefId; $api->securityToken = $this->securityToken; if($endp !== '') { $orderResponse = $api->dynamicGetRequest($this->service, $this->target, $this->endPoint); } else { $orderResponse = $api->dynamicGetRequest($this->service, $this->target); } $orderResponse = isset($orderResponse['response']) ? $orderResponse['response'] : null; $this->response = $orderResponse; return $this->response; } public function getJSON($service, $target, $endp='') { $api = $this->createApiObject($service, $target, $endp); if($endp !== '') { $this->sendGetRequest($api); } else { } } public function getWarehouseByName($name=null) { if($name == null) { return null; } $name = strtolower($name); $list = $this->get('warehouse-service', 'warehouse'); if(is_array($list)) { foreach ($list as $key => $val) { if(isset($val['name'])) { $wname = strtolower($val['name']); if(strval($name) === strval($wname)) { return $val; } } } } return null; } public function getWarehouseById($id=null) { if($id == null) { return null; } $list = $this->get('warehouse-service', 'warehouse'); if(is_array($list)) { foreach ($list as $key => $val) { if(isset($val['id'])) { if(intval($id) === intval($val['id'])) { return $val; } } } } return null; } public function getOrderWarehouse($id=null) { if($id == null) return null; $list = $this->get('order-service', 'order', $id); if(is_array($list)) { if(count($list) > 0) { $item = $list[0]; $warehouseId = $item['warehouseId']; $warehouse = $this->getWarehouseById($warehouseId); return $warehouse; } return $list; } } public function getOrderWarehouseName($id=null) { if($id == null) return null; $list = $this->get('order-service', 'order', $id); if(is_array($list)) { if(count($list) > 0) { $item = $list[0]; $warehouseId = $item['warehouseId']; $warehouse = $this->getWarehouseById($warehouseId); return $warehouse['name']; } return $list; } } public function getOrder($id=null) { if($id === null) return null; $list = $this->get('order-service', 'order', $id); if(is_array($list)) { if(count($list) > 0) { return $list[0]; } } return null; } public function getWarehouses() { $list = $this->get('warehouse-service', 'warehouse'); if(is_array($list)) { return $list; } return null; } } class Cache extends \SimpleCache { public $handle = null; public $cache = null; public $dyService = null; public function __construct() { $this->handle = new \XLib\Brightpearl\DynamicService(); $this->cache = new \SimpleCache(); $this->dyService = new \XLib\Brightpearl\DynamicService(); } public function set($key, $val) { $this->cache->store($key, $val); return $this; } public function get($key) { return $this->cache->retrieve($key); } public function isCached($key) { return boolval($this->cache->isCached($key)); } public function getDynamicService() { return $this->handle; } public function getHandle() { return $this->handle; } public function orderExists($id=null) { if($id == null) return null; $name = 'order-' . $id; if($this->cache->isCached($name)) { return true; } return false; } public function storeOrder($id=null) { if($id == null) return null; $name = 'order-' . $id; if(!$this->orderExists($name)) { $data = $this->dyService->getOrder($id); $this->store($name, $data); } if($this->cache->isCached($name)) { return true; } return false; } public function trimResponse($res=null) { if($res === null) return null; if(isset($res['response'])) { $res = $res['response']; } if(count($res) <= 0) { return -1; } return $res; } public function storeOrderData($data=null) { if($data == null) return null; $res = $this->trimResponse($data); if(isset($data['response'])) { $data = $data['response']; } elseif(count($data) <= 0) { return -1; } $name = 'order-' . strval($data['id']); if(!$this->orderExists($name)) { $data = $this->trimResponse( $this->dyService->getOrder($data['id']) ); $this->store($name, $data); return true; } return false; } public function getOrderData($id=null) { if($id == null) return null; if($this->orderExists($id)) { $name = 'order-' . $id; return $this->retrieve($name); } return false; } } <file_sep><?php namespace XLib; require_once 'XLibConfig.php'; use \XLib\Config as XConfig; require_once 'XLibEnum.php'; use \XLib\Enum as XEnum; XConfig::set('XLIB_INCLUDE_DIR', str_replace('\\', '/', __DIR__)); XConfig::set('XLIB_NAMESPACE', __NAMESPACE__); XConfig::set('XLIB_OUTPUT_HTML', true); class Types extends XEnum { const Null = 0x000; const Parameter = 0x001; const Variable = 0x002; const Object = 0x003; const ObjectProperty = 0x004; const ObjectMethod = 0x005; const Configuration = 0x006; const MemoryAddress = 0x007; const MemoryBlock = 0x008; const MemorySector = 0x009; const MemoryCache = 0x010; const MemoryCacheFragment = 0x011; const MemoryCacheCluster = 0x012; const ReadError = 0xF00; const WriteError = 0xF01; } class XLib { const PATH_SEPARATOR = '/'; const PATH_SEP = '/'; const NEWLINE = PHP_EOL; const ENDLINE = PHP_EOL; const ENDOFLINE = PHP_EOL; const EOL = PHP_EOL; public static function convertPath($path) { return str_replace('\\', '/', $path); } public static function getCurrentDirName() { return end(explode(\XLib\XLib::PATH_SEP, \XLib\XLib::convertPath(__DIR__))); } public static function loadClass($path, $prefix='XLib') { if(is_array($path)) { foreach ($path as $item) { \XLib\XLib::loadClass($item, $prefix); } } else { $fpath = $path; if (false === strpos($path, $prefix)) { $fpath = $prefix . $path; } $rpath = str_replace('\\', '/', __DIR__) . \XLib\XLib::PATH_SEP . $fpath . '.php'; if(file_exists($rpath)) { require_once($rpath); return true; } else { return false; } } return null; } public static function is_same(&$obj1, &$obj2) { return gettype($obj1) === gettype($obj2); } public static function is_ref(&$arg1, &$arg2) { if(!self::is_same($arg1, $arg2)) { return false; } $same = false; if(is_array($arg1)) { do { $key = uniqid("is_ref_", true); } while(array_key_exists($key, $arg1)); if(array_key_exists($key, $arg2)) { return false; } $data = uniqid('is_ref_data_', true); $arg1[$key] =& $data; if(array_key_exists($key, $arg2)) { if($arg2[$key] === $data) { $same = true; } } unset($arg1[$key]); } elseif(is_object($arg1)) { if(get_class($arg1) !== get_class($arg2)) { return false; } $obj1 = array_keys(get_object_vars($arg1)); $obj2 = array_keys(get_object_vars($arg2)); do { $key = uniqid('is_ref_', true); } while(in_array($key, $obj1)); if(in_array($key, $obj2)) { return false; } $data = uniqid('is_ref_data_', true); $arg1->$key =& $data; if(isset($arg2->$key)) { if($arg2->$key === $data) { $same = true; } } unset($arg1->$key); } elseif(is_resource($arg1)) { if(get_resource_type($arg1) !== get_resource_type($arg2)) { return false; } return ((string) $arg1) === ((string) $arg2); } else { if($arg1 !== $arg2) { return false; } do { $key = uniqid('is_ref_', true); } while($key === $arg1); $tmp = $arg1; $arg1 = $key; $same = $arg1 === $arg2; $arg1 = $tmp; } return $same; } public static function getVarName($var) { foreach($GLOBALS as $name => $value) { if($value === $var) { return $name; } } return false; } } class Engine { public static function extLoaded($name) { return extension_loaded($name); } } class DynamicBuilder { public static function funcArray() { $args = func_get_args(); $arr = []; foreach($args as $val) { $arr[] = $val; } return $arr; } public static function classArray() { $args = func_get_args(); $arr = []; foreach($args as $val) { $arr[] = $val[ array_keys($val)[0] ]; } return $arr; } } <file_sep>try { if(typeof(xlib) === "undefined") { throw "xlib: missing core library"; } xlib.file = function(aPath) { var xlibFile = function(aPath) { this.handle = new FileUtils.File(aPath); for(var itr in this.handle) { try { this[itr] = this.handle[itr]; } catch (err) {}; } this.read = function() { var fis = xlib.createInstance('file-input-stream', 'nsIFileInputStream'); var sis = xlib.createInstance('scriptableinputstream', 'nsIScriptableInputStream'); var data = new String(); fis.init(this.handle, 1, 0, false); sis.init(fis); data += sis.read(-1); sis.close(); fis.close(); return data; }; this.write = function(data, mode) { try { var fos = xlib.createInstance('file-output-stream', 'nsIFileOutputStream'); var flags = 0x02 | 0x08 | 0x20; if(mode == 'a') { flags = 0x02 | 0x10; } fos.init(this.handle, flags, 664, 0); fos.write(data, data.length); fos.close(); return true; } catch (err) { console.error(err); return false; } }; this.touch = function() { try { this.handle.create(this.handle.NORMAL_FILE_TYPE, 0777); return true; } catch (err) { return false; } } this.del = function() { try { this.handle.remove(false); return true; } catch (err) { return false; } } return this; }; return new xlibFile(aPath); }; xlib.defaultPathLocations = { "chrome": "AChrom", "plugins": "APlugns", "components": "ComsD", "defaultProfile": "DefProfRt", "defaults": "DefRt", "desktop": "Desk", "downloads": "DfltDwnld", "home": "Home", "pref": "PrfDef", "profile": "ProfD", "tmp": "TmpD", "userchrome": "UChrm" }; } catch (err) { console.error(err); } var xl = {}; let {TextEncoder, OS} = Cu.import('resource://gre/modules/osfile.jsm', {}); let decoder = new TextDecoder(); let promise = OS.File.read('D:\\XPE\\file1.txt'); <file_sep><?php namespace XLib; class XLib { public static function convertPath($path) { return str_replace('\\', '/', $path); } public static function is_same(&$obj1, &$obj2) { return gettype($obj1) === gettype($obj2); } public static function is_ref(&$arg1, &$arg2) { if(!self::is_same($arg1, $arg2)) { return false; } $same = false; if(is_array($arg1)) { do { $key = uniqid("is_ref_", true); } while(array_key_exists($key, $arg1)); if(array_key_exists($key, $arg2)) { return false; } $data = uniqid('is_ref_data_', true); $arg1[$key] =& $data; if(array_key_exists($key, $arg2)) { if($arg2[$key] === $data) { $same = true; } } unset($arg1[$key]); } elseif(is_object($arg1)) { if(get_class($arg1) !== get_class($arg2)) { return false; } $obj1 = array_keys(get_object_vars($arg1)); $obj2 = array_keys(get_object_vars($arg2)); do { $key = uniqid('is_ref_', true); } while(in_array($key, $obj1)); if(in_array($key, $obj2)) { return false; } $data = uniqid('is_ref_data_', true); $arg1->$key =& $data; if(isset($arg2->$key)) { if($arg2->$key === $data) { $same = true; } } unset($arg1->$key); } elseif(is_resource($arg1)) { if(get_resource_type($arg1) !== get_resource_type($arg2)) { return false; } return ((string) $arg1) === ((string) $arg2); } else { if($arg1 !== $arg2) { return false; } do { $key = uniqid('is_ref_', true); } while($key === $arg1); $tmp = $arg1; $arg1 = $key; $same = $arg1 === $arg2; $arg1 = $tmp; } return $same; } public static function getVarName($var) { foreach($GLOBALS as $name => $value) { if($value === $var) { return $name; } } return false; } }<file_sep>var Oatlib = new XLibPlugin().init(); $.extend(Oatlib, { htmldoc: function() { return gBrowser.contentDocument; }, htmlwin: function() { return gBrowser.contentWindow; }, xuldoc: function() { return getTopWin().document; }, xulwin: function() { return getTopWin(); }, xul: { doc: function() { return getTopWin().document; }, win: function() { return getTopWin(); }, createTreeView: function(data) { return { childData: data, treeBox: null, selection: null, get rowCount() { return this.childData.length; }, setTree: function(treeBox) { this.treeBox = treeBox; }, getCellText: function(idx, column) { return this.childData[idx][column.index]; }, setCellText: function(idx, column, str) { return this.childData[idx][column.index] = str; }, //isContainer: function(idx) { return this.visibleData[idx][1]; }, //isContainerOpen: function(idx) { return this.visibleData[idx][2]; }, isContainerEmpty: function(idx) { return false; }, isSeparator: function(idx) { return false; }, isSorted: function() { return false; }, isEditable: function(idx, column) { return false; }, appendRow: function(data) { return this.childData.push(data); }, }; }, clearOutputPanel: function() { $('#oat-output')[0].view = {}; } }, html: { doc: function() { return gBrowser.contentDocument; }, win: function() { return gBrowser.contentWindow; }, getStyle: function(target, prop) { if(target.currentStyle) { return target.currentStyle[prop]; } else if (Oatlib.html.win().getComputedStyle) { return Oatlib.html.doc() .defaultView .getComputedStyle(target, null) .getPropertyValue(prop); } return null; }, getBackgroundImages: function(cx) { var list = []; cx = cx || Oatlib.html.doc(); $('*', cx).each(function() { var bgstyle = Oatlib.html.getStyle(this, 'background-image'); if(bgstyle && bgstyle != "none") { list.push({ elem: this, rawUrl: bgstyle, url: bgstyle.replace(/^url\(["']?/, '').replace(/["']?\)$/, '') }); } }); return list; }, getImages: function(cx) { cx = cx || Oatlib.html.doc(); var list = []; return $('img,[role="img"],input[type="img"]', cx).toArray(); }, getAllImages: function(cx) { cx = cx || Oatlib.html.doc(); list = { images: Oatlib.html.getImages(cx), bgimages: Oatlib.html.getBackgroundImages(cx) }; return list; }, getVisibleImages: function(cx) { cx = cx || Oatlib.html.doc(); var list = $(':visible', cx).map(function(node) { var $elem = $(this); // not hidden and isn't a tracking pixel.... if ($elem.is(':visible') && $elem.width() > 1 && $elem.height() > 1) { } }); } } }); <file_sep>try { if(typeof(xlib) === "undefined") { throw "xlib: missing core library"; } xlib.moz = {}; xlib.moz.devtools = Cu.import('resource://gre/modules/devtools/Loader.jsm', {}).devtools; xlib.moz.toggleBrowserConsole = function XLMOZ_toggleBrowserConsole() { HUDService.toggleBrowserConsole(); } xlib.moz.toggleBrowserToolbox = function XLMOZ_toggleBrowserToolbox() { BrowserToolboxProcess.init(); } } catch (err) { console.error(err); }<file_sep><?php namespace XLib; class Context { static public function hasGlobal($name) { return (array_key_exists($name, $GLOBALS)) ? true : false; } static public function getGlobal($name) { return (self::hasGlobal($name)) ? $GLOBALS[$name] : null; } static public function getDefinedObjects() { $ret = []; foreach($GLOBALS as $varName => $varValue) { $current =& $GLOBALS[$varName]; $type = gettype($current); $list = ['is_object']; foreach($list as $key => $func) { $res = call_user_func($func, $current); if($res) { if($func == 'is_object') { $ret[] =& $GLOBALS[$varName]; } } } } return $ret; } static public function getDefinedVars() { $ret = []; foreach ($GLOBALS as $varName => $varValue) { $current = $GLOBALS[$varName]; $type = gettype($current); $list = ['is_array', 'is_bool', 'is_numeric', 'is_string', 'is_object', 'is_resource']; foreach ($list as $lkey => $lfunc) { $res = call_user_func($lfunc, $current); if ($res) { $ret[$varName] =& $GLOBALS[$varName]; } } } return $ret; } static public function getDeclaredClasses() { return get_declared_classes(); } static public function getDefinedFunctions() { return get_defined_functions(); } static public function getInternalFunctions() { return self::getDefinedFunctions()['internal']; } static public function getUserFunctions() { return self::getDefinedFunctions()['user']; } }<file_sep><?php namespace XLib\Brightpearl; class API { public $requestUrl; public $accountName; public $service; public $target; public $appReferenceId; public $securityToken; public function __construct() { } public function sendGetRequest() { $client = new \GuzzleHttp\Client(); $result = $client->get( $this->requestUrl . '/' . $this->accountName . '/' . $this->service . '/' . $this->target, [ 'verify' => false, 'headers' => [ 'brightpearl-app-ref' => $this->appReferenceId, 'brightpearl-account-token' => $this->securityToken ] ] ); if($result->getStatusCode() == 200) { return json_decode($result->getBody(), true); } return null; } public function dynamicGetRequest() { $args = func_get_args(); $client = new \GuzzleHttp\Client(); $result = $client->get( $this->requestUrl . '/' . $this->accountName . '/' . join($args, '/'), [ 'verify' => false, 'headers' => [ 'brightpearl-app-ref' => $this->appReferenceId, 'brightpearl-account-token' => $this->securityToken ] ] ); if($result->getStatusCode() == 200) { return json_decode($result->getBody(), true); } return null; } }
a26630baa482d40249b6988dcec132198ee9c490
[ "JavaScript", "PHP" ]
48
PHP
xpence/portfolio
629681e48beb0d275ca0cb5a0fc4e0289a3cfd8c
17eab9b4ea2aada79c45abe5120078473e0fecef
refs/heads/master
<repo_name>yijingz1227/EventWebService<file_sep>/src/algorithm/GeoRecommendation.java package algorithm; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import db.DBConnection; import db.DBConnectionFactory; import entity.Item; // Recommendation based on geo distance and similar categories. public class GeoRecommendation { public List<Item> recommendItems(String userId, double lat, double lon) { List<Item> recommendedItems = new ArrayList<>(); DBConnection conn = DBConnectionFactory.getConnection(); if (conn == null) { return recommendedItems; } // Step 1 Get all favorited itemIds Set<String> itemIds = conn.getFavoriteItemIds(userId); // Step 2 Get all categories of favorited items Map<String, Integer> allCategories = new HashMap<>(); for (String id : itemIds) { Set<String> categories = conn.getCategories(id); for (String category : categories) { if (!allCategories.containsKey(category)) { allCategories.put(category, 0); } allCategories.replace(category, allCategories.get(category) + 1); } } List<Entry<String, Integer>> categoryList = new ArrayList<>(allCategories.entrySet()); Collections.sort(categoryList, new Comparator<Entry<String, Integer>>() { @Override public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) { return Integer.compare(o2.getValue(), o1.getValue()); } }); // Step 3 Do search based on category, filter out favorited items, sort by // distance Set<String> visitedItemIds = new HashSet<>(); for (Entry<String, Integer> entry : categoryList) { String category = entry.getKey(); List<Item> result = conn.searchItems(lat, lon, category); for (Item item : result) { if (visitedItemIds.add(item.getItemId()) && !itemIds.contains(item.getItemId())) { recommendedItems.add(item); } } } Collections.sort(recommendedItems, new Comparator<Item>() { @Override public int compare(Item o1, Item o2) { return Double.compare(o1.getDistance(), o2.getDistance()); } }); conn.close(); return recommendedItems; } }
4d4fa5106a544923671fb8a3942d937b7bbb75b9
[ "Java" ]
1
Java
yijingz1227/EventWebService
4833a3e0e9517d5244de2e0e7565497ad1815cfe
382b854ba4498eac112475ee09af36f389c88698
refs/heads/master
<repo_name>asepridwan1989/h8-p0-w4<file_sep>/exercise-15.js function changeVocals (str) { //code di sini var vokal = 'aAiIuUeEoO'; var konson = 'bBjJvVfFpP'; var tampung =''; for (var i = 0; i<str.length;i++){ var status = false; for(var j =0; j<vokal.length;j++){ if(str[i] === vokal[j]){ tampung += konson[j]; status = true; } }if(status === false){ tampung +=str[i]; } } return tampung; } function reverseWord (str) { //code di sini var tampung =''; for(var i =str.length-1; i>=0;i--){ tampung += str[i]; } return tampung; } function setLowerUpperCase (str) { //code di sini var abjadLow = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']; var abjadUp = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']; var tampung =''; for(i=0;i<str.length;i++){ var status = false; for (j=0;j<26;j++){ if(str[i] === abjadUp[j]){ tampung += abjadLow[j]; status = true; }else if(str[i] === abjadLow[j]){ tampung += abjadUp[j]; status = true; } } if(status === false){ tampung += str[i]; } } return tampung; } function removeSpaces (str) { //code di sini var tampung3 =''; for(i=0;i<str.length;i++){ if(str[i] !== ' '){ tampung3 += str[i]; } } return tampung3; } function passwordGenerator (name) { //code di sini if(name.length <=5){ return 'Minimal karakter yang diinputkan adalah 5 karakter'; } var ganti = changeVocals(name); // console.log(ganti); var balik = reverseWord(ganti); // console.log(balik); var kapital = setLowerUpperCase(balik); // console.log(kapital); var remove = removeSpaces(kapital); // console.log(remove); return remove; } console.log(passwordGenerator('<PASSWORD>')); // '<PASSWORD>' console.log(passwordGenerator('<PASSWORD>')); // '<PASSWORD>' console.log(passwordGenerator('<PASSWORD>')); // '<PASSWORD>' console.log(passwordGenerator('<PASSWORD>')); // 'Minimal karakter yang diinputkan adalah 5 karakter' <file_sep>/exercise-18.js function kaliTerusRekursif(angka) { // you can only write your code here! var numString = String(angka); var total = 0; if (numString.length ===1) total= total + Number(numString); else total = kaliTerusRekursif(total + Number(numString[0]) * kaliTerusRekursif(Number(numString.slice(1)))); return total; } // TEST CASES console.log(kaliTerusRekursif(66)); // 8 console.log(kaliTerusRekursif(3)); // 3 console.log(kaliTerusRekursif(24)); // 8 console.log(kaliTerusRekursif(654)); // 0 console.log(kaliTerusRekursif(1231)); // 6
6b937ce96723b28866ee0fa030795399edeae8e5
[ "JavaScript" ]
2
JavaScript
asepridwan1989/h8-p0-w4
ac07e63e8fcd07bb1bf53d337771dd6b669e1700
7380578e55558a0d7ff65bfe9f0ef760137e408f
refs/heads/master
<file_sep>install golang compiler # go build # ./blockchain Usage: createblockchain -address ADDRESS - Create a blockchain and send genesis block reward to ADDRESS createwallet - Generates a new key-pair and saves it into the wallet file getbalance -address ADDRESS - Get balance of ADDRESS listaddresses - Lists all addresses from the wallet file print - Print all the blocks of the blockchain reindexutxo - Rebuilds the UTXO set send -from FROM -to TO -amount AMOUNT - Send AMOUNT of coins from FROM address to TO<file_sep>To compile: gcc -g -o data data.c -lssl -lcrypto Generate BTC key pair openssl ecparam -genkey -name secp256k1 -noout -out ec256-key-pair.pem openssl ec -in ec256-key-pair.pem -pubout -out pubkey.pem openssl ec -in ec256-key-pair.pem -pubout -outform DER -out pubkey.der <file_sep>package main import ( "bytes" "encoding/gob" "log" "time" ) type Block struct { Timestamp int64 Transactions []*Transaction Prev []byte Hash []byte Nonce int } func NewBlock(transactions []*Transaction, prev []byte) *Block { result := &Block{time.Now().Unix(), transactions, prev, []byte{}, 0} a := NewProofOfWork(result) b, c := a.Run() result.Hash = c[:] result.Nonce = b return result } func GenesisBlock(coinbase *Transaction) *Block { return NewBlock([]*Transaction{coinbase}, []byte{}) } func (b *Block) Txhash() []byte { var txs [][]byte for _, tx := range b.Transactions { txs = append(txs, tx.Order()) } a := NewMerkleTree(txs) return a.RootNode.Data } func (b *Block) Order() []byte { var a bytes.Buffer c := gob.NewEncoder(&a) d := c.Encode(b) if d != nil { log.Panic(d) } return a.Bytes() } func Disorder(d []byte) *Block { var a Block b := gob.NewDecoder(bytes.NewReader(d)) c := b.Decode(&a) if c != nil { log.Panic(c) } return &a } <file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <openssl/crypto.h> #define SHA256_DIGEST_LENGTH 32 struct block { unsigned char prevHash[SHA256_DIGEST_LENGTH]; int blockData; struct block *link; }*head; void addBlock(int); void verifyChain(); void alterNthBlock(int, int); void hackChain(); int hashCompare(unsigned char*, unsigned char*); void hashPrinter(); //void printAllBlocks(); void addBlock(int data) { if (head == NULL) { head = malloc(sizeof(struct block)); SHA256("", sizeof(""), head->prevHash); head->blockData = data; return; } struct block *currentBlock = head; while (currentBlock->link) { currentBlock = currentBlock->link; } struct block *newBlock = malloc(sizeof(struct block)); currentBlock->link = newBlock; newBlock->blockData = data; SHA256(toString(*currentBlock), sizeof(*currentBlock), newBlock->prevHash); } void verifyChain() { if (head == NULL) { printf("Blockchain is empty! Please add some blocks first!\n"); return; } struct block *curr = head->link, *prev = head; int count = 1; while (curr) { printf("%d\t[%d]\t", count++, curr->blockData); hashPrinter(SHA256(toString(*prev), sizeof(*prev), NULL), SHA256_DIGEST_LENGTH); printf(" -------- "); hashPrinter(curr->prevHash, SHA256_DIGEST_LENGTH); if (hashCompare(SHA256(toString(*prev), sizeof(*prev), NULL), curr->prevHash)) printf("Successful verification\n"); else printf("verification failed\n"); prev = curr; curr = curr->link; } } void alterNthBlock(int n, int newData) { struct block *curr = head; if (curr == NULL) { printf("Nth block does not exist!\n"); return; } int count = 0; while (count != n) { if (curr->link == NULL && count != n) { printf("Nth block does not exist!\n"); return; }else if (count == n) { break; } curr = curr->link; count++; } printf("Before: "); printBlcok(curr); curr->blockData = newData; printf("\nAfter: "); printBlcok(curr); } void hackChain() { struct block *curr = head, *prev; if (curr == NULL) { printf("Blockchain is empty!"); return; } while (1) { prev = curr; curr = curr->link; if (curr == NULL) { return; } if (!hashCompare(SHA256(toString(*prev), sizeof(*prev), NULL), curr->prevHash)) { hashPrinter ( SHA256(toString(*prev), sizeof(*prev), curr->prevHash), SHA256_DIGEST_LENGTH ); printf("\n"); } } } unsigned char* toString(struct block b) { unsigned char *str = malloc(sizeof(unsigned char) *sizeof(b)); memcpy(str, &b, sizeof(b)); return; } void hashPrinter(unsigned char hash[], int length) { for (int i = 0; i < length; i++) { printf("%02x", hash[i]); } } int hashCompare(unsigned char *str1, unsigned char *str2) { for (int i = 0; i < SHA256_DIGEST_LENGTH; ++i) { if (str1[i] != str2[i]) { return 0; } } return 1; } void printBlcok(struct block *b) { printf("%p]t", b); hashPrinter(b->prevHash, sizeof(b->prevHash)); printf("\t[%d]\t", b->blockData); printf("%p\n", b->link); } void printAllBlocks() { struct block *curr = head; int count = 0; while (curr) { printBlcok(curr); curr = curr->link; } } int main() { int c, n, r; printf("1. Add block\n2.Add n random blocks\n3.Alter Nth block\n4.Print all blocks\n5.Verify blockchain\n6.Hack blockchain\n"); while (1) { printf("Your choice: "); scanf("%d", &c); switch(c) { case 1: printf("Enter data: "); scanf("%d", &n); addBlock(n); break; case 2: printf("How many blocks to enter? : "); scanf("%d", &n); for (int i = 0; i < n; ++i) { r = rand()%(n*10); printf("Entering: %d\n", r); addBlock(r); } break; case 3: printf("Which block to alter? : "); scanf("%d", &n); printf("Enter the value: "); scanf("%d", &r); alterNthBlock(n, r); break; case 4: printAllBlocks(); break; case 5: verifyChain(); break; case 6: hackChain(); break; default: printf("Wrong choice!\n"); break; } } return 0; } //gcc Blockchain.c -o Blockchain.c.o -lcrypto //./Blockchain.c.o <file_sep>package main import ( "fmt" "strconv" ) func (cli *CLI) print() { a := NewBlockchain() defer a.db.Close() b := a.Iterator() for { block := b.Next() fmt.Printf("Block: %x \n", block.Hash) fmt.Printf("Previous block: %x\n", block.Prev) c := NewProofOfWork(block) fmt.Printf("PoW: %s\n\n", strconv.FormatBool(c.Validate())) for _, tx := range block.Transactions { fmt.Println(tx) } fmt.Printf("\n\n") if len(block.Prev) == 0 { break } } } <file_sep>#include <iostream> #include <queue> #include <stdlib.h> #include <time.h> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; void createTree (TreeNode* root, int n) { if (!root) return; queue<TreeNode*> *q = new queue<TreeNode*>; q->push(root); int cnt = 1; while (!q->empty()) { TreeNode *node = new TreeNode; node = q->front(); q->pop(); if (node -> left == NULL) { TreeNode *l = new TreeNode; l -> val = (2 * node -> val) + 1; node -> left = l; q->push(l); ++cnt; if (cnt == n) break; } if (node -> right == NULL) { TreeNode *r = new TreeNode; r -> val = (2 * node -> val) + 2; node -> right = r; q->push(r); ++cnt; if (cnt == n) break; } } } /*void levelOrder(TreeNode *root) { queue<TreeNode*> *Q = new queue<TreeNode*>; Q->push(root); while (!Q->empty()) { TreeNode *p = Q->front(); Q->pop(); cout << p -> val << " "; if (p -> left != NULL) Q->push(p -> left); if (p -> right != NULL) Q->push(p -> right); } }*/ int main(int argc, char const *argv[]) { //cout << "Please enter the total number of nodes in the checkpoint tree." << endl; int n = 2047; TreeNode *root = new TreeNode; root -> val = 0; createTree (root, n); //levelOrder(root); int arr[] = {500, 100, 300, 250, 150, 500, 600, 350, 200, 150}; vector<int> lIDs, rIDs; int links[11] = {0}; int k = sizeof(arr)/sizeof(arr[0]); srand((unsigned) time(NULL)); for (int i = 0; i < 10; ++i) { int lDeposits = 0, rDeposits = 0; cout << "Round " << i + 1 << ": the IDs of the validators who finalized this checkpoint is "; for (int j = 0; j < k; ++j) { if ((rand()%10) <= 4) { lDeposits += arr[j]; lIDs.push_back(j); }else { rDeposits += arr[j]; rIDs.push_back(j); } } if (lDeposits > rDeposits) { links[i + 1] = root -> left -> val; root = root -> left; for (int h = 0; h < lIDs.size(); ++h) { cout << lIDs[h] << " "; } lIDs.clear(); rIDs.clear(); cout << "The total deposits is: " << lDeposits << endl; }else { links[i + 1] = root -> right -> val; root = root -> right; for (int g = 0; g < rIDs.size(); ++g) { cout << rIDs[g] << " "; } lIDs.clear(); rIDs.clear(); cout << "The total deposits is: " << rDeposits << endl; } } cout << "The blockchain is "; for (int a = 0; a < 11; ++a) { cout << links[a] << " -> "; } return 0; } <file_sep># Blockchain_Learning Introduction to Blockchain Technology <file_sep>// // See http://fm4dd.com/openssl/eckeycreate.shtm // #include <stdio.h> #include <stdlib.h> #include <openssl/bio.h> // bio io streams for openssl #include <openssl/err.h> #include <openssl/ssl.h> #include <openssl/obj_mac.h> //needed for elliptic curve #include <openssl/ec.h> //needed for elliptic curve #define BuffSize 1024 void report_and_exit(const char* msg) { perror(msg); ERR_print_errors_fp(stderr); exit(-1); } void init_ssl() { // SSL_library_init(); OpenSSL_add_all_algorithms(); //initialize table for all ciphers and digests ERR_load_BIO_strings(); SSL_load_error_strings(); } void cleanup(SSL_CTX* ctx, BIO* bio, EC_KEY *myecc, EVP_PKEY *pkey) { EVP_PKEY_free(pkey); EC_KEY_free(myecc); //SSL_CTX_free(ctx); BIO_free_all(bio); ERR_free_strings(); } int main(int c, const char* argv[]) { EC_KEY *key=NULL; //Key pair EVP_PKEY *pkey=NULL; //PublicKey BIO *outbio=NULL; //Stream int eccgrp; init_ssl(); //Initialize OpenSSL // //.....Create BIOs // outbio = BIO_new(BIO_s_file()); outbio = BIO_new_fp(stdout, BIO_NOCLOSE); // //.....Create key /* ---------------------------------------------------------- * * Create a EC key sructure, setting the group type from NID * * ---------------------------------------------------------- */ eccgrp = OBJ_txt2nid("secp256k1"); key = EC_KEY_new_by_curve_name(eccgrp); /* -------------------------------------------------------- * * For cert signing, we use the OPENSSL_EC_NAMED_CURVE flag* * ---------------------------------------------------------*/ EC_KEY_set_asn1_flag(key, OPENSSL_EC_NAMED_CURVE); /* -------------------------------------------------------- * * Create the public/private EC key pair here * * ---------------------------------------------------------*/ if (! (EC_KEY_generate_key(key))) BIO_printf(outbio, "Error generating the ECC key."); /* -------------------------------------------------------- * * Converting the EC key into a PKEY structure let us * * handle the key just like any other key pair. * * ---------------------------------------------------------*/ pkey=EVP_PKEY_new(); if (!EVP_PKEY_assign_EC_KEY(pkey,key)) BIO_printf(outbio, "Error assigning ECC key to EVP_PKEY structure."); /* ---------------------------------------------------------- * * Here we print the private/public key data in PEM format. * * ---------------------------------------------------------- */ if(!PEM_write_bio_PrivateKey(outbio, pkey, NULL, NULL, 0, 0, NULL)) BIO_printf(outbio, "Error writing private key data in PEM format"); if(!PEM_write_bio_PUBKEY(outbio, pkey)) BIO_printf(outbio, "Error writing public key data in PEM format"); // //.....Exit // cleanup(NULL,outbio,key,pkey); exit(0); } <file_sep>package main import ( "bytes" "math/big" ) var bf_58 = []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz") func Bf_58Encode(input []byte) []byte { var a []byte c := big.NewInt(0).SetBytes(input) d := big.NewInt(int64(len(bf_58))) e := big.NewInt(0) f := &big.Int{} for c.Cmp(e) != 0 { c.DivMod(c, d, f) a = append(a, bf_58[f.Int64()]) } ReverseBytes(a) for b := range input { if b == 0x00 { a = append([]byte{bf_58[0]}, a...) } else { break } } return a } func Bf_58Decode(input []byte) []byte { a := big.NewInt(0) c := 0 for b := range input { if b == 0x00 { c++ } } d := input[c:] for _, b := range d { e := bytes.IndexByte(bf_58, b) a.Mul(a, big.NewInt(58)) a.Add(a, big.NewInt(int64(e))) } result := a.Bytes() result = append(bytes.Repeat([]byte{byte(0x00)}, c), result...) return result }
70c9e80e505d72539acc6315f1c106bbb89fbdbf
[ "Markdown", "Text", "C", "Go", "C++" ]
9
Markdown
LikeUforNoReason/Blockchain_Learning
7732d147cd8a1a4e365e4f057e1e955786ae547c
2b6d1f1f07e1cd4b66e49ae65c46c0f8ac5f8cf8
refs/heads/master
<file_sep>--- title: "Cleaning Up" layout: "post" generator: pagination use: - posts --- When you are ready to shutdown your Deis cluster, simply issue: ```sh $ aws cloudformation delete-stack --stack-name deis ``` <file_sep>--- title: "Installing Deis" layout: "post" generator: pagination use: - posts --- We'll need both `deis` (the Deis CLI) and `deisctl` (the Deis provision tool). Both clients are automatically built when we ship new releases of Deis, and be grabbed with our install scripts. > **Note:** To find out the latest version of Deis, simply go to the [releases page](https://github.com/deis/deis/releases) ```console $ curl -sSL http://deis.io/deisctl/install.sh | sh -s <version> # e.g. 1.11.2 $ curl -sSL http://deis.io/deis-cli/install.sh | sh ``` Both scripts will dump the binaries in the current working directory. We probably want them somewhere else: ```console $ mv ./deis* /usr/local/bin/ ``` Confirm using: ```console $ deisctl --version $ deis --version ``` > **Note:** the version numbers _may not match_. ### Clone Deis * [Fork deis](https://github.com/deis/deis/fork) to your account * Clone Deis: ```sh git clone [email protected]:<username>/deis.git cd deis ``` > **Note:** replace `<username>` with your github username Make sure we're using the correct version of the code (as used above) ```sh $ git fetch --tags $ git checkout v<version> ``` <file_sep>--- title: "Application Configuration" layout: "post" generator: pagination use: - posts --- All configuration for applications should be set using the environment. This is done using `deis config`. Each change to the configuration will result in a new deployment. ## Setting Environment Variables To set an environment variable, use the `deis config:set` command: ```sh $ deis config:set DATABASE_USER=myapp $ deis config:set DATABASE_PASSWORD=<PASSWORD> $ deis config:set DATABASE_HOST=my.db.host ``` To minimize the number of deployments, you should attempt to set multiple environment variables at the same time: ```sh $ deis config:set DATABASE_USER=myapp DATABASE_PASSWORD=<PASSWORD> DATABASE_HOST=my.db.host Creating config... done, v# === <random>-<words> DATABASE_PASSWORD: <PASSWORD> DEIS_APP: <random>-<words> DATABASE_HOST: my.db.host DATABASE_USER: myapp ``` ## Using Environment Files Lastly, you can use a `.env` file to store your environment settings. You can easily create a `.env` file from the existing configuration using `deis config:pull`: ```sh $ deis config:pull ``` This will create an `.env` file containing the current environment, for example: ```ini DATABASE_USER=myapp DATABASE_PASSWORD=<PASSWORD> DATABASE_HOST=my.db.host ``` You can (create or) make changes to this file and deploy them using `deis config:push`: ```sh $ echo "MEMCACHE_HOST=localhost:11211" >> .env $ deis config:push Creating config... done, v# === <random>-<words> DEIS_APP: <random>-<words> DATABASE_USER=myapp DATABASE_PASSWORD=<PASSWORD> DATABASE_HOST=my.db.host MEMCACHE_HOST=localhost:11211 ``` This will _merge_ the config with the existing environment. ## Reviewing Configuration You can easily review the configuration using `deis config:list`. ```sh $ deis config:list === <random>-<words> Config DATABASE_HOST my.db.host DATABASE_PASSWORD <PASSWORD> DATABASE_USER myapp MEMCACHE_HOST localhost:11211 ``` ## Deleting Environment Variables To remove an environment variable, we can use `deis config:unset`. As with `deis config:set` you should specify multiple variables to minimize deployments. ```sh $ deis config:unset DATABASE_USER DATABASE_PASSWORD DATABASE_HOST ``` > **Note:** environment variables are not automatically removed from `.env` ## Updating .env Once you have deleted environment variables, you may want to update the local .env to match the current state of things. You do this with `deis config:pull`: ```sh $ deis config:pull -o ``` <file_sep>--- title: "Creating a User" layout: "post" generator: pagination use: - posts --- To deploy applications to the Deis cluster, you must first register a user with the controller. This is done using the `deis register` command. To register, you must supply the controller address. The first account registered will be granted super user priviledges. The controller address is always `http://deis.<domain>`, where `<domain>` is the value we supplied to `deisctl config platform set domain=` when setting up Deis (e.g. `<elb-IP>.xip.io`). ```sh $ deis register http://deis.<elb-IP>.xip.io username: <username> password: password (confirm): email: <email> Registered <username> Logged in as <username> ``` ## Deploying via git If you plan on using `git push` to deploy applications to Deis, you must provide your SSH public key. Use the `deis keys:add` command to upload your default SSH public key: ```sh $ deis keys:add Found the following SSH public keys: 1) id_rsa.pub Which would you like to use with Deis? 1 Uploading /Users/myuser/.ssh/id_rsa.pub to Deis... done ``` <file_sep>--- title: "Scaling Containers" layout: "post" generator: pagination use: - posts --- Let's try scaling up more containers of our app. Pick any application currently deployed to the Deis cluster and `cd` into the application directory. Then we can scale using the `deis scale` command. ## Buildpacks If the application was deployed using a buildpack, we want to scale the `web` processes: ```sh $ deis scale web=3 Scaling processes... but first, coffee! done in 133s === <random>-<words> Processes --- web: web.1 up (v2) web.2 up (v2) web.3 up (v2) ``` If we refresh our browser a few times, we see three containers responding to traffic. ## Dockerfiles and Docker Images When using a `Dockerfile` or Docker image, deis will scale the `CMD` process to 1. To increase this use: ```sh deis scale cmd=3 Scaling processes... but first, coffee! done in 46s === <random>-<words> Processes --- cmd: cmd.1 up (v2) cmd.2 up (v2) cmd.3 up (v2) ```<file_sep>--- title: "Setting Up Deis" layout: "post" generator: pagination use: - posts --- Now, we have the a cluster of CoreOS instances and a domain we can use to access the cluster. It's time to actually setup Deis on the hosts. We'll need one of the public IPs of our instances (these were output by the provision script). Any one will do. Then, we set an environment variable so our local `deisctl` knows who to talk to: ```sh $ export DEISCTL_TUNNEL=<instance-IP> ``` We also provide the SSH key we used to provision the hosts. This is used by the `deis run` command to log into the host machine and schedule one-off tasks: ```sh $ deisctl config platform set sshPrivateKey=~/.ssh/deis-$USER ``` Now, we need to have `deisctl` tell our CoreOS cluster what our domain will be. Note that this is the domain one level above what the apps will be called (i.e. the domain we set here is `<elb-IP>.xip.io`, and our apps will be `app-name.<elb-IP>.xip.io`). ```console $ deisctl config platform set domain=<elb-IP>.xip.io ``` *Finally*, we can install and start the platform. This will take about 20 minutes for the platform to fully start, as it's pulling each component's Docker image from Docker Hub. ```console $ deisctl install platform $ deisctl start platform ``` What exactly did this do? `deisctl` talked to [fleet](https://github.com/coreos/fleet), the CoreOS cluster scheduler, and asked it to run the Deis components on the cluster. We can use `deisctl list` to see on which hosts the components ended up. <file_sep>--- layout: default title: Home generator: pagination pagination: max_per_page: 100 use: - posts --- This workshop will familiarize you with [Deis](http://deis.io), [Docker](http://docker.io), and deploying them to [Amazon AWS](http://aws.amazon.com). <a href="./installation" class="btn btn-primary btn-lg btn-block">Get Started <i class="fa fa-arrow-circle-o-right"></i></a> <file_sep>--- title: "Installing AWS Tools" layout: "post" generator: pagination use: - posts --- To deploy to AWS, we'll need to install the AWS CLI tools and configure them with AWS account credentials: ```sh $ sudo pip install awscli pyyaml $ aws configure AWS Access Key ID [None]: *************** AWS Secret Access Key [None]: ************************ Default region name [None]: us-west-1 Default output format [None]: ``` If you get an error because you don't already have `pip`, you'll need to install it first: ```sh $ sudo easy_install pip ``` Create a new keypair for Deis and upload it to EC2: ```sh $ ssh-keygen -q -t rsa -f ~/.ssh/deis-$USER -N '' -C deis-$USER $ aws ec2 import-key-pair --key-name deis --public-key-material file://~/.ssh/deis-$USER.pub ``` <file_sep>--- title: "Installing Docker" layout: "post" generator: pagination use: - posts --- ## Mac OS X First, install [Docker Toolbox](https://www.docker.com/docker-toolbox). Then, in a terminal run: ```sh $ docker-machine create -d virtualbox --virtualbox-memory 2048 dev # Create & Start a VM using VirtualBox $ eval "$(docker-machine env dev)" # Setup shell ``` ## Linux * Use the official installation shell script: `curl -sSL https://get.docker.com/ | sh` * To see what the script does, view [https://get.docker.com/](https://get.docker.com/) * *Most distros have a much-too-old version of Docker in their package repositories* - using this script should give us the latest ## Confirming Successful Installation To confirm Docker is working properly run `docker info`. <file_sep>--- title: "Deploying Using a Dockerfile" layout: "post" generator: pagination use: - posts --- In addition to using the pre-defined buildpacks, you can create a completely custom environment by deploying a `Dockerfile`. This will build the docker image on the Deis cluster and deploy it. To use a `Dockerfile`, simply add it to the root of your repository. ## Create a Dockerfile There are three rules that _must_ be adhered to for deploying a `Dockerfile` to Deis: 1. The Dockerfile must `EXPOSE` only one port 2. The port **must** be listening for a HTTP connection 3. A default `CMD` must be specified for running the container Here we create a simple `Dockerfile` that installs `jekyll` and serves up an example blog: ```docker FROM ubuntu:wily RUN apt-get update -qq RUN apt-get install -y -q ruby ruby-dev ruby-posix-spawn python-pygments git build-essential nodejs RUN gem install -V rdiscount jekyll RUN git clone https://github.com/maciakl/Sample-Jekyll-Site.git blog WORKDIR blog EXPOSE 4000 CMD ["jekyll", "serve", "-H", "0.0.0.0"] ``` ## Deploying to Deis As when deploying using a buildpack, you simply need to create the application, and push to it. ```sh $ deis create $ git push deis master ``` To verify that it deployed successfully, you can run deis open to pull up the site in your browser.<file_sep><div class="well sidebar-nav"> <ul class="nav"> <li><a href="{{ site.url }}/">Get Started</a></li> {% for article in page.pagination.items %} <li><a href="{{ site.url }}{{ article.url }}">{{ article.title }}</a></li> {% endfor %} </ul> </div> <file_sep>--- title: "Configuring DNS" layout: "post" generator: pagination use: - posts --- We'll need to configure DNS to point to our Deis cluster. Normally we would use a real domain name and create an appropriate DNS record for Deis, but for this workshop we will fake it by using [xip.io](http://xip.io) and one of the IP addresses for the ELB. The ELB hostname can be found in the output of the `./provision-ec2-cluster.sh` command, and will look like `deis-DeisWebELB-<id>.us-east-1.elb.amazonaws.com`. ## Using a custom domain To setup a custom domain for real-world usage, you simply point a CNAME record to the ELB, for example `lb.example.org`. ```sh $ dig lb.example.org CNAME +short deis-deiswebelb-<id>.us-east-1.elb.amazonaws.com. ``` ## Using xip.io [xip.io](http://xip.io) is a free service that automatically resolves `some-string.<elb-IP>.xip.io` to the IP in the hostname. While it's not recommended to create A records for AWS ELBs, as the actual IPs can change, for short-lived clusters, this should work just fine. First, we need to get an IP for our ELB: ```sh $ host deis-deiswebelb-<id>.us-east-1.elb.amazonaws.com deis-deiswebelb-<id>.us-east-1.elb.amazonaws.com has address <ip> deis-deiswebelb-<id>.us-east-1.elb.amazonaws.com has address <ip> ``` Then, we can compose a domain as `some-string.<elb-IP>.xip.io`. For example: ```console $ dig <some-string>.<elb-IP>.xip.io A +short <ip> ``` <file_sep>--- title: "Deploying to AWS" layout: "post" generator: pagination use: - posts --- The Deis project has community-contributed provision scripts for various providers in the deis `contrib` directory. These provision scripts provision a cluster of CoreOS machines (3 by default) with some system tweaks for Deis. We also configure things like EBS volumes and their mount points, install some helper scripts, etc. First, we need to tell Deis to use our key. Edit `contrib/aws/cloudformation.json` to confirm the key: ```javascript [ { "ParameterKey": "KeyPair", "ParameterValue": "deis" } ] ``` We should also add it to our local SSH agent so it's offered when we try to log into the machines: ```sh $ ssh-add ~/.ssh/deis-$USER ``` Generate a new discovery URL and deploy the deis cluster: ```sh $ make discovery-url $ cd contrib/aws $ ./provision-aws-cluster.sh deis Creating CloudFormation stack deis { "StackId": "arn:aws:cloudformation:us-east-1:69326027886:stack/deis/<UUID>" } Waiting for instances to be provisioned (CREATE_IN_PROGRESS, 600s) ... Waiting for instances to be provisioned (CREATE_IN_PROGRESS, 590s) ... Waiting for instances to be provisioned (CREATE_COMPLETE, 580s) ... Waiting for instances to pass initial health checks (600s) ... Waiting for instances to pass initial health checks (590s) ... Waiting for instances to pass initial health checks (580s) ... Instances are available: <id> <ip> <instance type> <region> running <id> <ip> <instance type> <region> running <id> <ip> <instance type> <region> running Using ELB <elb URL> Your Deis cluster has been successfully deployed to AWS CloudFormation and is started. Please continue to follow the instructions in the documentation. Enabling proxy protocol 1 ``` At this point you have a CoreOS cluster deployed in AWS CloudFormation. > **Note:** you may wish to copy down the instance details for future reference <file_sep>--- title: "Installation" layout: "post" generator: pagination use: - posts --- There are three parts to the install: ### Docker: <a href="../installing-docker"><img src="../images/docker.png" alt="Docker"></a> ### Deis: <a href="../installing-deis"><img src="../images/deis.png" alt="Deis"></a> ### AWS: <a href="../installing-aws-tools"><img src="../images/aws.png" alt="AWS"></a> <file_sep>--- layout: default title: About generator: pagination use: - posts --- This workshop is maintained by [Engine Yard](https://www.engineyard.com). <file_sep>FROM ubuntu:wily RUN apt-get update -qq RUN apt-get install -y -q ruby ruby-dev ruby-posix-spawn python-pygments git build-essential nodejs RUN gem install -V rdiscount jekyll RUN git clone https://github.com/maciakl/Sample-Jekyll-Site.git blog WORKDIR blog EXPOSE 4000 CMD ["jekyll", "serve", "-H", "0.0.0.0"] <file_sep>--- title: "Deploying Applications" layout: "post" generator: pagination use: - posts --- Deis supports deployment via [Heroku Buildpacks](https://devcenter.heroku.com/articles/buildpacks), [Dockerfiles](https://docs.docker.com/reference/builder/), and [Docker Images](https://docs.docker.com/introduction/understanding-docker/). There are Heroku buildpacks available for common setups for many different languages. Deis will automatically recognize the appropriate buildpack to use based on the contents of your repository. Supported buildpacks are: - [Ruby](https://github.com/heroku/heroku-buildpack-ruby) - [Node.js](https://github.com/heroku/heroku-buildpack-nodejs) - [Clojure](https://github.com/heroku/heroku-buildpack-clojure) - [Python](https://github.com/heroku/heroku-buildpack-python) - [Java](https://github.com/heroku/heroku-buildpack-java) - [Gradle](https://github.com/heroku/heroku-buildpack-gradle) - [Grails](https://github.com/heroku/heroku-buildpack-grails) - [Scala](https://github.com/heroku/heroku-buildpack-scala) - [Play](https://github.com/heroku/heroku-buildpack-play) - [PHP](https://github.com/heroku/heroku-buildpack-php) <file_sep>--- title: "Tasks" layout: "post" generator: pagination use: - posts --- Best practices (12-factor) tell us that we should run maintenance and deployment tasks — such as database migrations — as one-off processes. Deis allows you to do this easily using `deis run`. The `deis run` command will spin up a new container (`web` or `cmd` process) in which it will run the given command, and then the container will be destroyed. We use `deis run` like so: ```sh $ deis run <cmd> ``` For example, if we want to run a rake migration, we might use: ```sh $ deis run rake db:migrate ``` <file_sep>--- title: "Custom Processes" layout: "post" generator: pagination use: - posts --- By default, Deis supports two processes, which it will automatically start when the container is deployed: 1. `web` — for applications deployed using a buildpack 2. `cmd` - for applications deployed using a `Dockerfile` or docker image You can also specify your own processes, that can then be started, and scaled independently. This is done by adding a `Procfile` in the root of your application. ## Creating New Processes To create a new process type, you simply define it in the `Procfile`, using the following pattern: ```yaml <process name>: <command> ``` For example, we could add a process type that will run a task workers within our codebase: ```yaml processor: python /workers/process-files.py translator: ruby /workers/translate-file.py ``` ## Starting & Scaling Processes To start or scale a process, we use the `deis scale` command. We can run any different number of instances of each process type. ```sh $ deis scale processor=2 translator=4 ``` ## Restarting Processes To restart processes use `deis ps:restart`. To restart all processes of a given type use: ```sh $ deis ps:restart web Restarting processes... but first, coffee! done in 14s === <random>-<words> Processes --- web: web.1 up (v2) web.2 up (v2) web.3 up (v2) ``` To restart a single process simply specify it's number: ```sh $ deis ps:restart web.1 Restarting processes... but first, coffee! done in 11s === <random>-<words> Processes --- web: web.1 up (v2) web.2 up (v2) web.3 up (v2) ``` ## Monitoring Processes You can see what is currently running on the cluster using `deis ps`: ```sh $ deis ps === <random>-<words> Processes --- web: web.1 up (v2) web.2 up (v2) web.3 up (v2) processor.1 up (v2) processor.2 up (v2) translator.1 up (v2) translator.2 up (v2) translator.3 up (v2) translator.4 up (v2) ``` <file_sep># Docker/Deis Workshop This workshop will familiarize you with Docker/Deis and deployment on AWS. You can see the resulting workshop at <http://dshafik.github.io/deis-docker-workshop> ## Installation This workshop uses [Sculpin](https://sculpin.io), a static site generator written in PHP. If you have PHP installed locally, you can run it using: ```sh $ sculpin generate --watch --server ``` Or, if you have a Docker environment, you can build it and run it using the Dockerfile: ```sh $ docker build -t dshafik/deis-docker-workshop . $ docker run -d -P dshafik/deis-docker-workshop ``` You can then check `docker ps` to see which port is bound to port `8000`. <file_sep># Contributing > **Note:** *Do not* submit pull-requests against the `gh-pages` branch It's super easy to contribute, all you need is some Markdown knowledge. ## Forking You should be working in a fork, see the [following documentation](https://help.github.com/articles/fork-a-repo/) ## Before Making Any Changes ### Fetch The Latest Changes from upstream > On the `master` branch ```sh $ git fetch --all $ git rebase upstream/master ``` ### Create a New Branch ```sh $ git checkout -b reason-for-changes ``` ### Install Sculpin In order to test your edited or new examples, you'll need to have Sculpin installed in your dev environment. Please see the [Sculpin "Get Started"](https://sculpin.io/getstarted/) guide for installation instructions. ## Editing an Existing Page: Find the file in `source/_posts`, e.g. `1-install.md` and edit using Markdown. ## Creating a New File Files are named with a numeric prefix to indicate their ordering in the table of contents. Create a new file in `source/_posts` with the correct numeric prefix (e.g. `13-whats-next.md`) Each file starts with the meta-data: ```yaml --- title: "Page Title Here" layout: "post" generator: pagination use: - posts --- ``` - title: The title of the page - layout: The layout to use (always post) The last three lines are required to make the page show the Table of Contents. ## Testing Your Changes In the root directory, to test run: ```sh $ sculpin generate --watch --server ``` Then visit <http://localhost:8000> ## After Making Your Changes ### Commit Your Changes ```sh $ git add source/_posts/FILE.md $ git commit -m "DESCRIPTION OF CHANGES" $ git push origin master ``` ## Publishing Your Changes > **Note:** You should only do this to test, you should not perform pull-requests against this branch. In the root directory, to publish run: ```sh $ ./publish.sh "COMMIT MESSAGE HERE" ``` ## Pushing Changes Back Upstream To contribute your changes back, simply perform a [Pull Request](https://help.github.com/articles/using-pull-requests/) against the master branch. <file_sep>--- title: "Managing Releases" layout: "post" generator: pagination use: - posts --- Each time you deploy an application to Deis, or change it's configuration, a new release is created and deployed. You can review these releases using `deis releases`: ```sh $ deis releases === <random>-<words> Releases v4 3 minutes ago $USER deployed <sha1> v3 1 hour 17 minutes ago $USER added DATABASE_HOST v2 6 hours 2 minutes ago $USER deployed <sha1> v1 6 hours 2 minutes ago $USER deployed $USER/repo ``` ## Rollbacks You can rollback to any previous release using `deis rollback`. This will create a new release using the previous release: ```sh $ deis rollback v2 Rolled back to v2 $ deis releases === <random>-<words> Releases v5 Just now $USER rolled back to v2 v4 3 minutes ago $USER deployed <sha1> v3 1 hour 17 minutes ago $USER added DATABASE_HOST v2 6 hours 2 minutes ago $USER deployed <sha1> v1 6 hours 2 minutes ago $USER deployed $USER/repo ``` <file_sep>#!/bin/bash if [ $# -ne 1 ]; then echo "usage: ./publish.sh \"commit message\"" exit 1; fi rm -Rf .sculpin sculpin install sleep 2 sculpin generate --env=prod sculpin install sleep 2 git stash git checkout gh-pages sleep 2 cp -R output_prod/* . rm -rf output_* git add . git commit -a -m "$1" git push origin --all git checkout master git stash pop rm -Rf .sculpin sculpin install <file_sep>--- title: "Deploying Using a Buildpack" slug: deploy-buildpack layout: "post" generator: pagination use: - posts --- ## Deploying a Ruby Application Now that we have a working Deis cluster, let's see Deis in action by deploying a sample Ruby app. Clone the Deis `example-ruby-sinatra` app somewhere: ```sh $ git clone <EMAIL>:deis/example-ruby-sinatra.git $ cd example-ruby-sinatra ``` We then create an app for Deis: ```sh $ deis create Creating application... done, created <random>-<words> Git remote deis added ``` This will automatically add the Deis git remote: We see that there's a new remote for pushing our app: ```sh $ git remote -v deis ssh://[email protected]:2222/<random>-<words>.git (fetch) deis ssh://[email protected]:2222/<random>-<words>.git (push) origin [email protected]:deis/example-ruby-sinatra.git (fetch) origin [email protected]:deis/example-ruby-sinatra.git (push) ``` We can then deploy using `git push`: ```sh $ git push deis master Counting objects: 110, done. Delta compression using up to 4 threads. Compressing objects: 100% (57/57), done. Writing objects: 100% (110/110), 23.28 KiB | 0 bytes/s, done. Total 110 (delta 47), reused 110 (delta 47) -----> Ruby app detected -----> Compiling Ruby/Rack -----> Using Ruby version: ruby-1.9.3 -----> Installing dependencies using 1.7.12 Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4 --deployment Fetching gem metadata from http://rubygems.org/.......... Using bundler 1.7.12 Installing tilt 1.3.6 Installing rack 1.5.2 Installing rack-protection 1.5.0 Installing sinatra 1.4.2 Your bundle is complete! Gems in the groups development and test were not installed. It was installed into ./vendor/bundle Bundle completed (3.36s) Cleaning up the bundler cache. -----> Discovering process types Procfile declares types -> web Default process types for Ruby -> rake, console, web -----> Compiled slug size is 15M -----> Building Docker image remote: Sending build context to Docker daemon 15.09 MB remote: build context to Docker daemon Step 0 : FROM deis/slugrunner ---> 84828c0a7562 Step 1 : RUN mkdir -p /app ---> Running in e2ab6a1fd7bb ---> 322c62cb1a38 Removing intermediate container e2ab6a1fd7bb Step 2 : WORKDIR /app ---> Running in cb47ac3e4226 ---> f6c947361212 Removing intermediate container cb47ac3e4226 Step 3 : ENTRYPOINT /runner/init ---> Running in b04a7480d20d ---> 99d57affda58 Removing intermediate container b04a7480d20d Step 4 : ADD slug.tgz /app ---> 411f6180993a Removing intermediate container 0966164da96b Step 5 : ENV GIT_SHA 6b1a9488ac7f37fab78e69b20118d48d6294b8f3 ---> Running in 8204e135091e ---> 9d39bbb4c0a1 Removing intermediate container 8204e135091e Successfully built 9d39bbb4c0a1 -----> Pushing image to private registry -----> Launching... done, <random>-<words>:v2 deployed to Deis http://<random>-<words>.172.16.17.32.xip.io To learn more, use `deis help` or visit http://deis.io To ssh://git@deis.<elb-IP>.xip.io:2222/<random>-<words>.git * [new branch] master -> master ``` To verify that it deployed successfully, you can run `deis open` to pull up the site in your browser. ## Deploying a PHP Application This process is identical to deploying the Ruby application: Clone the Deis `example-php` app somewhere: ```sh $ git clone <EMAIL>:deis/example-php.git $ cd example-php ``` We then create an app for Deis: ```sh $ deis create Creating application... done, created <random>-<words> Git remote deis added ``` This will automatically add the Deis git remote: We see that there's a new remote for pushing our app: ```sh $ git remote -v deis ssh://[email protected]:2222/<random>-<words>.git (fetch) deis ssh://[email protected]:2222/<random>-<words>.git (push) origin <EMAIL>:deis/example-php.git (fetch) origin <EMAIL>:deis/example-php.git (push) ``` We can then deploy using `git push`: ```sh $ git push deis master Counting objects: 218, done. Delta compression using up to 4 threads. Compressing objects: 100% (157/157), done. Writing objects: 100% (218/218), 368.95 KiB | 0 bytes/s, done. Total 218 (delta 52), reused 218 (delta 52) -----> PHP app detected -----> Resolved composer.lock requirement for PHP to version 5.6.4. -----> Installing system packages... - PHP 5.6.4 - Apache 2.4.10 - Nginx 1.6.0 -----> Installing PHP extensions... - zend-opcache (automatic; bundled) -----> Installing dependencies... Composer version 1.0.0-alpha10 2015-04-14 21:18:51 Loading composer repositories with package information Installing dependencies from lock file - Installing slim/slim (2.6.2) Downloading: 100% Generating optimized autoload files -----> Preparing runtime environment... -----> Discovering process types Procfile declares types -> web Default process types for PHP -> web -----> Compiled slug size is 72M -----> Building Docker image remote: Sending build context to Docker daemon 75.23 MB remote: build context to Docker daemon Step 0 : FROM deis/slugrunner ---> 84828c0a7562 Step 1 : RUN mkdir -p /app ---> Using cache ---> 322c62cb1a38 Step 2 : WORKDIR /app ---> Using cache ---> f6c947361212 Step 3 : ENTRYPOINT /runner/init ---> Using cache ---> 99d57affda58 Step 4 : ADD slug.tgz /app ---> f33397529d55 Removing intermediate container f04e32ac723c Step 5 : ENV GIT_SHA f6a3d7266ff307c51d7bd7515ae2dca47306104f ---> Running in 5e4e398e429c ---> 88ae870d4969 Removing intermediate container 5e4e398e429c Successfully built 88ae870d4969 -----> Pushing image to private registry -----> Launching... done, <random>-<words>:v2 deployed to Deis http://<random>-<words>.<elb-IP>.xip.io To learn more, use `deis help` or visit http://deis.io To ssh://git@deis.<elb-IP>.xip.io:2222/<random>-<words>.git * [new branch] master -> master ``` To verify that it deployed successfully, you can run `deis open` to pull up the site in your browser. <file_sep>FROM ubuntu:wily RUN apt-get update RUN apt-get install -y -q php5-cli php5-curl git ADD . /site WORKDIR /site RUN /site/sculpin install CMD /site/sculpin generate --server EXPOSE 8000 <file_sep>--- title: "Deploying using Docker Images" layout: "post" generator: pagination use: - posts --- > **Note:** currently Deis requires you to use Docker 1.5 You can also deploy fully-backed Docker images — for examples those created by your continuous integration system. Images **must** be pushed to Docker hub (or a private registry) prior to deployment on Deis. > **Note:** support for Docker registry authentication is coming soon. This means your image _must_ be public. ## Build and Push The Image As with using a `Dockerfile`, you must still adhere to the following when deploying to Deis: 1. The docker image must `EXPOSE` only one port 2. The port **must** be listening for a HTTP connection 3. A default `CMD` must be specified for running the container Once you have a `Dockerfile` that meets this criteria, you can build the docker image like so: ```sh $ docker build -t <username>/<image> . # Don't forget the period at the end! $ docker push <username>/<image>:latest ``` > **Note:** You can test this in the root of the repository for this tutorial ## Deploying to Deis To deploy, we must first create an application on the controller, which requires a local working directory: ```sh $ mkdir -p /tmp/app-name $ cd /tmp/app-name $ deis create ``` > **Note:** The deis client uses the name of the current directory as the default app name. Then you can have Deis simply pull the image and deploy it: ```sh $ deis pull <username>/<image>:latest ``` To verify that it deployed successfully, you can run deis open to pull up the site in your browser.<file_sep>--- title: "Custom Domains" layout: "post" generator: pagination use: - posts --- It is possible to use a custom domain with your application. To do this, use the `deis domains` command. ## Adding a Domain To add a domain use `deis domains:add`: ```sh $ deis domains:add example.org Adding example.org to <random>-<words>... done ``` You should then create a `CNAME` record pointing to the original deis assigned domain. ## Reviewing Domains You can review all current domains using `deis domains:list`. ```sh $ deis domains:list === <random>-<words> Domains example.org ``` ## Removing a Domain To remove a domain, use `deis domain:remove`: ```sh $ deis domains:remove example.org Removing example.org from <random>-<words>... done ```
82f6507dad86ba4f53dfce5775f9b2501c807188
[ "Markdown", "HTML", "Dockerfile", "Shell" ]
27
Markdown
dshafik/deis-docker-workshop
5ddc8143d03b54101ff781902bf0777b6d409962
95a7bcf3f9bee561e385109c3219ff1d078cc45f
refs/heads/master
<file_sep># -*- coding: utf-8 -*- { 'name': "GCM", 'summary': """ Gestion des contrats de maintenance""", 'description': """ Ce module consiste à gérer les contrats de maintenance.\n un contrat de maintenance est structuré de cette façon: \n - Client\n - date de signature\n - date d'expiration\n - objet\n - prix et mode de paiement\n - obligations client\n - obligations prestataire\n - responsabilité\n les champs 'obligations clients','obligations prestataire' et 'responsabilité' sont à choix multiple, on peut utiliser les données qu'on déjà entrer à la creation d'un nouveau contrat. """, 'author': "My Company", 'website': "http://www.yourcompany.com", # Categories can be used to filter modules in modules listing # Check https://github.com/odoo/odoo/blob/master/odoo/addons/base/module/module_data.xml # for the full list 'category': 'Uncategorized', 'version': '0.1', # any module necessary for this one to work correctly 'depends': ['base','contacts','account','project'], # always loaded 'data': [ # 'security/ir.model.access.csv', 'views/templates.xml', 'views/views.xml', 'views/records.xml', 'data/sequence.xml', ], # only loaded in demonstration mode 'demo': [ 'demo/demo.xml', ], 'application': 'True' }<file_sep># -*- coding: utf-8 -*- from odoo import models, fields, api #***Contract's object***# class object(models.Model): _inherit = 'project.project' # object_id = fields.Integer(string = 'Object') #***object's tasks***# class task(models.Model): _inherit = 'project.task' #***contract's Client***# class client(models.Model): _inherit = 'res.partner' # client_id = fields.Integer() #***contract's payement***# class payment(models.Model): _inherit = 'account.payment' #***Obligations Client***# class obligation_clt(models.Model): _name = 'contract.obligclt' name = fields.Char(string="Obligation client",required=True) #***Obligations Prestataire***# class obligation_prest(models.Model): _name = 'contract.obliprest' name = fields.Char(string="Obligation prestataire", required=True) #***Responsabilité***# class responsabilite(models.Model): _name = 'contract.responsability' name = fields.Char(string="responsability", required=True) #***contract***# class contract(models.Model): _name = 'contract.contract' # _inherit = ['res.partner', 'account.payement'] # ___Contract ID___# my_seq = fields.Char('Sequence',readonly=True) #___Dates___# starting_date = fields.Date(string="date of contract", required=True) deadline_date = fields.Date(string="deadline", required=True) #___Agreements___# obligclt_id = fields.Many2many('contract.obligclt',string="Obligations Client")#,default=lambda self: self.env['contract.obligclt'].search([])) obligpres_id = fields.Many2many('contract.obliprest',string="Obligations prestataire")#,default=lambda self: self.env['contract.obliprest'].search([])) responsability_id = fields.Many2many('contract.responsability',string="Responsabilities")#,default=lambda self: self.env['contract.responsability'].search([])) #___Object___# object_id = fields.Many2one('project.project',string="Object")#,default=lambda self: self.env['project.project'].search([]),required=True) #___Client___# client_id = fields.Many2one('res.partner',string="Client")#,default=lambda self: self.env['res.partner'].search([]),required=True) #___Payment___# payment_id = fields.Many2one('account.payment', string="Payment")#, default=lambda self: self.env['account.payment'].search([]),required=True) @api.model def create(self, vals): vals['my_seq'] = self.env['ir.sequence'].next_by_code('contract.contract') return super(contract, self).create(vals) <file_sep>This Odoo module is done to manage maintenance contracts. A maintenance contract is structured this way: - Client - Signature date - Due date - Object - Price and payment method - Client’s obligations - Recipient’s obligations - Responsibilities The following fields ‘Client’s obligations’, ’ Recipient’s obligations’ and ’ Responsibilities’ are multiple choices so the data entered can be used again on creating a new contract.
9411d7ec1c4a848243e015ffacf8327717ebd47e
[ "Markdown", "Python" ]
3
Python
badrsa10/-management-of-maintenance-contracts
d61f84707e455fbdda161c8fdea00fe3dccba5a7
3f04ba7beff962ab915d22cbc1ea12e0a088b016
refs/heads/master
<repo_name>decek/hvmc<file_sep>/src/hvmc_collisions.cpp #include "hvmc_collisions.h" <file_sep>/src/hvmc_physics.cpp #include "hvmc_physics.h" void RigidBody::Update( f32 dt ) { } void RigidBody::ApplyForce( vec2 const& f ) { } void RigidBody::ApplyImpulse( vec2 const& impulse, vec2 const& contactVector ) { } void RigidBody::SetKinematic() { I = iI = m = im = 0.f; } bool PhysicsSystem::Init() { gravity = vec2{ 0.f, -9.81f }; return true; } void PhysicsSystem::Cleanup() { rigidBodies.clear(); } RigidBody* PhysicsSystem::AddSphere( vec2 const& pos, f32 radius ) { RigidBody* body = new RigidBody; body->forces = { 0.f, 0.f }; body->im = 1.f; // 1 kg body->iI = 1.f; body->position = pos; body->velocity = { 0.f, 0.f }; body->collider.type = RIGID_BODY_SPHERE; body->collider.radius = radius; rigidBodies.push_back( body ); return body; } RigidBody* PhysicsSystem::AddBox( vec2 const& pos, vec2 const& dims ) { RigidBody* body = new RigidBody; body->forces = { 0.f, 0.f }; body->im = 1.f; // 1 kg body->position = pos; body->velocity = { 0.f, 0.f }; body->collider.type = RIGID_BODY_BOX; body->collider.dims = dims; rigidBodies.push_back( body ); return body; } RigidBody* PhysicsSystem::AddWall( vec2 const& pos, vec2 const& dims ) { RigidBody* body = new RigidBody; body->im = 0.f; body->position = pos; body->collider.type = RIGID_BODY_BOX; body->collider.dims = dims; rigidBodies.push_back( body ); return body; } void PhysicsSystem::Update( f32 dt ) { } <file_sep>/src/hvmc_collisions.h #ifndef HVMC_COLLISIONS_H #define HVMC_COLLISIONS_H #include "hvmc_math.h" #endif
e40f70984c84329337442ab5b89a3eefec8be2ce
[ "C", "C++" ]
3
C++
decek/hvmc
f3a727605768d678edf533b49bdf826ebeaeb726
5765b449f128457bf769390619a937e63ae6f1d3
refs/heads/master
<file_sep>new Vue({ el: '#app', data: { firstTurnO: true, gamePlaying: false, activePlayerO: true, showWinner: false, state: {}, wins: {O: 0, X: 0} }, methods: { checkActiveO() { return this.activePlayerO && this.gamePlaying? 'player--active' : null; }, checkActiveX() { return !this.activePlayerO && this.gamePlaying? 'player--active' : null; }, move(event) { if (this.gamePlaying) { const activePlayer = this.activePlayerO? 'O' : 'X'; const turn = this.activePlayerO? 'radio-unchecked' : 'cross'; const icon = ` <i class="icon-big icon-${turn}"></i> `; const elTest = event.target.closest('.box'); if (elTest) { const el = elTest.className.split(' ')[1]; if (!this.state[el]) { this.state[el] = icon; this.addMove(activePlayer, el.split('')[3]); this.checkWin(activePlayer); this.checkDraw(); this.activePlayerO = !this.activePlayerO; } } // console.log(this.state); } }, newGame() { this.startGame(); }, startGame() { this.activePlayerO = this.firstTurnO; this.firstTurnO = !this.firstTurnO; this.gamePlaying = true; this.state = {}; this.state.X = []; this.state.O = []; this.state.winCombos = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]; this.state.winner = ''; this.showWinner = false; }, addMove(activePlayer, squareNo) { this.state[activePlayer].push(squareNo); }, checkWin(activePlayer) { const moves = (this.state[activePlayer].sort((a,b) => a-b)).join(''); this.state.winCombos.forEach(cur => { const replaceRegex = `.*${cur[0]}.*${cur[1]}.*${cur[2]}.*`; const regexWin = new RegExp(replaceRegex); const result = regexWin.test(moves); if (result) { this.state.winner = `player ${activePlayer} wins!!!` this.showWinner = true; this.gamePlaying = false; this.wins[activePlayer]++; } }); }, checkDraw() { if (this.state.X.length + this.state.O.length == 9 && this.state.winner == '') { this.state.winner = 'draw'; this.showWinner = true; this.gamePlaying = false; } }, resetWins() { this.wins = {O:0,X:0}; } } });
be2d284097924df319d66c7e4a3fec0611fd2ebc
[ "JavaScript" ]
1
JavaScript
munib2002/Tic-Tac-Toe
49224eba19d41ddef2a63a2ab2d6a03db32bf731
e3d5e30847f8fa3413bcd7fa969a8796ffaa8b15
refs/heads/master
<file_sep># DataConverter Tool that takes data from heterogeneous sources and converts it to a canonical format. ## How to Build ``` ./gradlew clean build ``` ## How to Run and Test Output ``` ./gradlew run -PappArgs="[${fileName}]" ``` where fileName can be 'input1.tsv', 'input2.csv', 'input3.tsv', or 'input4.csv' ``` diff output.csv reference-output.csv ``` there shouldn't be any differences <file_sep>package com.company; import org.apache.commons.csv.CSVRecord; import org.apache.commons.lang.WordUtils; public class Handler3 extends RowHandler { @Override public DataEntry handle(CSVRecord record) { String[] tokens = record.get(0).split(", "); String first = tokens[1]; String last = tokens[0]; String email = record.get(1); String title = optionallyEncloseInQuotes(WordUtils.capitalize(record.get(2))); String mentor = record.get(3); if (!mentor.isEmpty()) { tokens = record.get(3).split(", "); mentor = tokens[1] + " " + tokens[0]; } tokens = record.get(4).split(" "); String date = encloseInQuotes(tokens[0].substring(0,3)+" "+tokens[1]+" "+tokens[2]); String score = record.get(5); StringBuilder sb = new StringBuilder(); int len = score.length(); for (int i = 0; i < len; i++) { if (i % 3 == 0 && i > 0) { sb.insert(0, ","); } sb.insert(0, score.charAt(len - i - 1)); } score = optionallyEncloseInQuotes(sb.toString()); return new DataEntry(first, last, email, title, mentor, date, score); } } <file_sep>#Wed Feb 01 18:33:30 PST 2017 <file_sep>apply plugin: 'java' apply plugin: 'application' repositories { jcenter() } dependencies { compile group: 'org.apache.commons', name: 'commons-csv', version: '1.1' compile group: 'commons-lang', name: 'commons-lang', version: '2.6' } mainClassName = 'com.company.Main' run { if (project.hasProperty("appArgs")) { args Eval.me(appArgs) } } <file_sep>package com.company; import org.apache.commons.csv.CSVRecord; import org.apache.commons.lang.WordUtils; import java.util.HashMap; import java.util.List; import java.util.Map; public class Handler2 extends RowHandler { private Map<String, DataEntry> entriesMap = new HashMap<>(); @Override public DataEntry handle(CSVRecord record) { String first = WordUtils.capitalize(record.get(0)); String last = WordUtils.capitalize(record.get(1)); String email = record.get(2); String title = optionallyEncloseInQuotes(WordUtils.capitalize(record.get(3).replaceAll("/",", "))); String date = encloseInQuotes(record.get(5)); String score = optionallyEncloseInQuotes(record.get(6).replace("K", ",000").replace("M", ",000,000")); DataEntry entry = new DataEntry(first, last, email, title, record.get(4), date, score); entriesMap.put(record.get(2), entry); return entry; } @Override public List<DataEntry> postProcessing(List<DataEntry> entries) { for (DataEntry entry : entriesMap.values()) { DataEntry mentor = entriesMap.get(entry.getMentor()); if (mentor != null) { entry.setMentor(mentor.getFirst()+" "+mentor.getLast()); } } return entries; } } <file_sep>rootProject.name='converter'
10b441e292e9a96b4dc60f856269115f1c39f46f
[ "Markdown", "Java", "INI", "Gradle" ]
6
Markdown
tiludropdancer/DataConverter
3aeb80a2344c6c7d4bb19063324c283f1eabd7eb
eca6a5bfa60a322239e484c96ceedb52c0b6263d
refs/heads/master
<repo_name>mh801/PFU<file_sep>/lib/framework/bin/presa.php #!/usr/local/bin/php <?php $project = new Presa(); fwrite(STDOUT, "Please enter your project name (include path or will be generated in bin folder): \n"); $project_name = fgets(STDIN); fwrite(STDOUT, "Do you want to include the user class for authentication (y/n)? (Y) : \n This is only currently compatible with MySQL.\n"); $user = fgets(STDIN); $user = ($user=='')?'Y':$user; fwrite(STDOUT,"What is your projects url?: \n"); $base_path = fgets(STDIN); fwrite(STDOUT,"What would you like to use for your default pagination limit?: \n"); $page_limit = fgets(STDIN); fwrite(STDOUT,"What would you like to use for your encryption salt?: \n"); $salt = fgets(STDIN); fwrite(STDOUT,"What is your database host address?: \n"); $db_host = fgets(STDIN); fwrite(STDOUT, "What is your project database name?: \n"); $db_name = fgets(STDIN); fwrite(STDOUT, "What is your project database user name?: \n"); $db_uname = fgets(STDIN); fwrite(STDOUT, "What is your project database password?: \n"); $db_pass = fgets(STDIN); $project->__set('name',$project_name); $project->__set('user',$user); $project->__set('salt',$salt); $project->__set('page_limit',$page_limit); $project->__set('base_path',$base_path); $project->__set('db',$db_name); $project->__set('db_user',$db_user); $project->__set('db_pass',$db_pass); $project->__set('db_host',$db_host); $project->__set('path',$project_name); $project->mkPDir($project_name); $project->dbExec(); $project->writeConfig(); // Exit correctly exit(0); class Presa{ public function __set($property = null, $value = null) { if ($property !== null and $property !== null) { $this->$property = $value; } return; } // get undeclared property public function __get($property) { if (isset($this->$property)){ return $this->$property; } } public function dbExec(){ $this->_dbHandle = @mysql_connect('localhost', $this->db_user, $this->db_pass); $sql = 'CREATE TABLE IF NOT EXISTS `Users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(50) NOT NULL, `last_name` varchar(50) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(128) NOT NULL, `is_active` tinyint(1) NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `modified_at` datetime NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;'; mysql_query($sql, $this->_dbHandle); fwrite(STDOUT,"Users table created succesfully\n"); if ($this->_dbHandle != 0) { if (mysql_select_db($this->db, $this->_dbHandle)) { return 1; } else { return 0; } } else { return 0; } } function createUserTable(){ $sql = 'CREATE TABLE IF NOT EXISTS `Users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(50) NOT NULL, `last_name` varchar(50) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(128) NOT NULL, `is_active` tinyint(1) NOT NULL, `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `modified_at` datetime NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `email` (`email`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;'; mysql_query($sql, $this->_dbHandle); fwrite(STDOUT,"Users table created succesfully\n"); } function createConfig($values = array()){ } function copyFiles($path){ copy('../../../index.php',$path.'/index.php'); copy('../../bootstrap.php',$path.'/lib/bootstrap.php'); copy('presa.php',$path.'/lib/framework/bin/presa.php'); copy('../cache/cache.php',$path.'/lib/framework/cache/cache.php'); copy('../config/inflection.php',$path.'/lib/framework/config/inflection.php'); copy('../config/routing.php',$path.'/lib/framework/config/routing.php'); copy('../controller/basecontroller.php',$path.'/lib/framework/controller/basecontroller.php'); copy('../model/basemodel.php',$path.'/lib/framework/model/basemodel.php'); copy('../model/inflection.php',$path.'/lib/framework/model/inflection.php'); copy('../model/sqlquery.php',$path.'/lib/framework/model/sqlquery.php'); copy('../session/session.php',$path.'/lib/framework/session/session.php'); copy('../template/template.php',$path.'/lib/framework/template/template.php'); copy('../util/brain.php',$path.'/lib/framework/util/brain.php'); copy('../util/debug.php',$path.'/lib/framework/util/debug.php'); copy('../../../public/.htaccess',$path.'/public/.htaccess'); copy('../../../public/index.php',$path.'/public/index.php'); copy('../../../public/css/calendar.css',$path.'/public/css/calendar.css'); copy('../../../public/js/jquery-1.6.2.min.js',$path.'/public/js/jquery-1.6.2.min.js'); copy('../../../public/js/jquery-ui-1.8.16.custom.min.js',$path.'/public/js/jquery-ui-1.8.16.custom.min.js'); } function mkPDir ($path) { $pathArr = explode("/",$path); $end = count($pathArr)-1; fwrite(STDOUT,$pathArr[$end]."\n"); fwrite(STDOUT,$path."\n"); if(mkdir($path)){ fwrite(STDOUT,"creating " . $path ."\n"); if(mkdir($path . '/application')){ fwrite(STDOUT,"creating " . $path ."/application\n"); if(mkdir($path . '/application/controllers')){ fwrite(STDOUT,"creating " . $path ."/application/controllers\n"); if($this->user == Y){ if(mkdir($path . '/application/controllers/user')){ fwrite(STDOUT,"creating " . $path ."/application/controllers/user\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } } }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/application/helpers')){ fwrite(STDOUT,"creating " . $path ."/application/helpers\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/application/models')){ fwrite(STDOUT,"creating " . $path ."/application/models\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/application/views')){ fwrite(STDOUT,"creating " . $path ."/application/views\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/lib')){ fwrite(STDOUT,"creating " . $path ."/lib\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/lib/framework')){ fwrite(STDOUT,"creating " . $path ."/lib/framework\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/lib/framework/bin')){ fwrite(STDOUT,"creating " . $path ."/lib/framework/bin\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/lib/framework/cache')){ fwrite(STDOUT,"creating " . $path ."/lib/framework/cache\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/lib/framework/config')){ fwrite(STDOUT,"creating " . $path ."/lib/framework/config\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/lib/framework/controller')){ fwrite(STDOUT,"creating " . $path ."/lib/framework\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/lib/framework/model')){ fwrite(STDOUT,"creating " . $path ."/lib/framework/model\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/lib/framework/session')){ fwrite(STDOUT,"creating " . $path ."/lib/framework/session\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/lib/framework/template')){ fwrite(STDOUT,"creating " . $path ."/lib/framework/template\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/lib/framework/util')){ fwrite(STDOUT,"creating " . $path ."/lib/framework/util\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/public')){ fwrite(STDOUT,"creating " . $path ."/public\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/public/css')){ fwrite(STDOUT,"creating " . $path ."/public/css\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/public/img')){ fwrite(STDOUT,"creating " . $path ."/public/img\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/public/js')){ fwrite(STDOUT,"creating " . $path ."/public/js\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/scripts')){ fwrite(STDOUT,"creating " . $path ."/scripts\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/tmp')){ fwrite(STDOUT,"creating " . $path ."/tmp\n"); if(mkdir($path . '/tmp/cache')){ fwrite(STDOUT,"creating " . $path ."/tmp/cache\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/tmp/sessions')){ fwrite(STDOUT,"creating " . $path ."/sessions\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } if(mkdir($path . '/tmp/logs')){ fwrite(STDOUT,"creating " . $path ."/tmp/logs\n"); }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } }else{ fwrite(STDOUT,"There was a problem creating directories, please check your file permissions\n"); } } $this->copyFiles($path); } function writeConfig(){ $fileName = $this->path . '/lib/framework/config/config.php'; $handle = fopen($fileName, 'a'); fwrite($handle,"<?php \n"); fwrite($handle,"/** Configuration Variables **/ \n\n"); fwrite($handle,"define ('DEVELOPMENT_ENVIRONMENT',true);"); fwrite($handle,"\n"); fwrite($handle,"define('DEBUG_MODE',false);"); fwrite($handle,"\n"); fwrite($handle,"define('PASSWORD_SALT','" . $this->salt . "');"); fwrite($handle,"\n"); fwrite($handle,"define('DB_NAME', '" . $this->db . "');"); fwrite($handle,"\n"); fwrite($handle,"define('DB_USER', '" . $this->db_user . "');"); fwrite($handle,"\n"); fwrite($handle,"define('DB_PASSWORD', '" . $this->db_pass . "');"); fwrite($handle,"\n"); fwrite($handle,"define('DB_HOST', '" . $this->db_host . "');"); fwrite($handle,"\n"); fwrite($handle,"define('BASE_PATH','" . $this->base_path . "');"); fwrite($handle,"\n"); fwrite($handle,"define('PAGINATE_LIMIT', '" . $this->page_limit . "');"); fwrite($handle,"\n"); fclose($handle); } } ?><file_sep>/application/helpers/application/form.php <?php class Form extends upload { protected $element = array(); protected $action; protected $method = 'post'; protected $html = ''; protected $name = ''; protected $type =''; protected $class = ''; protected $fieldset = true; protected $wrapper_class = ''; protected $label = array(); function __construct(){ } function type($type=''){ $this->type = $type; } function useFieldset($param = true,$class=''){ $this->fieldset = $param; $this->wrapper_class = $class; } function addName($name=''){ $this->name = $name; } function addClass($class=''){ $this->class = $class; } function addLabel($for = '', $value='',$class=''){ $this->label[$for] = '<label for="' . $for . '" class="' . $class . '">' . $value . '</label><br/>'; } function addElement($type = null, $name ='', $value = '', $validate = false, $class = ''){ $this->element[$name] = new FormElement($type, $name, $value, $validate, $class); } function addAction($action = 'post'){ $this->action = $action; } public function render(){ /* render default fieldset? */ if($this->fieldset){ $this->html .= '<fieldset class="base-form"><form name="'. $this->name .'" enctype="'.$this->type.'" action="'. $this->action .'" method="'. $this->method .'" class="'. $this->class .'">'; }else{ $this->html .= '<div class="form-wrapper '.$this->wrapper_class.'">'; } foreach($this->element as $key=>$element){ $this->html .= '<div class="form-text">'; if(array_key_exists($key,$this->label)){ $this->html .= $this->label[$key]; } $this->html .= $element->getHtml(); $this->html .='</div>'; } $this->html .= '</form>'; if($this->fieldset){ $this->html .= '</fieldset>'; }else{ $this->html .= '</div>'; } return $this->html; } } ?><file_sep>/lib/framework/model/orm.php <?php require ROOT . DS . 'db'. . DS . 'adodb5' . DS . 'adodb.inc.php'; require ROOT . DS . 'db'. . DS . 'adodb5' . DS . 'adodb-active-record.inc.php'; class ORM extends ADOdb_Active_Record{ protected $DB; protected $model; protected $class; function __construct(){ $this->DB = NewADOConnection('mysql'); $this->DB->connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME,$this->_table); ADOdb_Active_Record::SetDatabaseAdapter($this->db); var_dump($this->class); die(); } }<file_sep>/lib/framework/template/template.php <?php class Template { protected $variables = array(); protected $_controller; protected $_action; protected $_params; function __construct($controller,$action,$params) { $this->_controller = $controller; $this->_action = $action; #make params available without call in all templates $this->_params = $params; } /** Set Variables **/ function set($name,$value) { $this->variables[$name] = $value; } function renderJSON(){ $jsonArray = array(); foreach($this->variables as $key=>$val){ $jsonArray[$key][] = $val; } echo json_encode($jsonArray); } /** Display Template **/ function render($noRender = 0, $doNotRenderHeader = 0) { $form = new Form(); $html = new HTML(); extract($this->variables); if($noRender == 0){ if ($doNotRenderHeader == 0) { if (file_exists(ROOT . DS . 'application' . DS . 'views' . DS . $this->_controller . DS . 'layout.phtml')) { include (ROOT . DS . 'application' . DS . 'views' . DS . $this->_controller . DS . 'layout.phtml'); } else { include (ROOT . DS . 'application' . DS . 'views' . DS . 'layout' . DS . 'layout.phtml'); } } if (file_exists(ROOT . DS . 'application' . DS . 'views' . DS . $this->_controller . DS . $this->_action . '.phtml')) { include (ROOT . DS . 'application' . DS . 'views' . DS . $this->_controller . DS . $this->_action . '.phtml'); } if ($doNotRenderHeader == 0) { if (file_exists(ROOT . DS . 'application' . DS . 'views' . DS . $this->_controller . DS . 'footer.phtml')) { include (ROOT . DS . 'application' . DS . 'views' . DS . $this->_controller . DS . 'footer.phtml'); } else { include (ROOT . DS . 'application' . DS . 'views' . DS . 'layout' . DS .'footer.phtml'); } } } } }<file_sep>/lib/framework/config/inflection.php <?php /** Irregular Words $irregularWords = array( 'singular' => 'plural' ); **/ $irregularWords = array( 'category' => 'categories' );<file_sep>/lib/framework/config/config.php <?php /*****************************/ /** Configuration Variables **/ /****************************/ define ('DEVELOPMENT_ENVIRONMENT',true); define('DEBUG_MODE',false); define('PASSWORD_SALT','<PASSWORD>'); /* So we can use any dev DB we want */ if(DEVELOPMENT_ENVIRONMENT){ define('DB_NAME', 'mhcommerce'); define('DB_USER', 'root'); define('DB_PASSWORD', ''); define('DB_HOST', '127.0.0.1'); /*always use trailing slash */ define('BASE_PATH','http://m.mac/'); }else{ define('DB_NAME', 'mhcommerce'); define('DB_USER', 'root'); define('DB_PASSWORD', ''); define('DB_HOST', 'localhost'); /*always use trailing slash */ define('BASE_PATH','http://m.mac/'); } define('PAGINATE_LIMIT', '25'); /* project bubble Variables */ define('API_KEY','a335d92b50574c1c3afc78e8d5539a365efdf8ba'); define('API_URL','https://thereadystore.projectbubble.com/api'); /* Mail default recipient */ define('EMAIL_ADDRESS','<EMAIL>');<file_sep>/lib/framework/util/debug.php <?php class Debug { protected $_file = null; protected $_data = array(); function setData($data = null){ if(null != $data){ $this->_data[] = $data; } } function getData(){ if(null != $this->_data){ return $this->_data; } return false; } function setFile($file = null){ if(null != $file){ $this->_file = $file; } } function getFile(){ if(null != $this->_file){ return $this->_file; } return false; } function get($fileName) { if(null != $this->_file){ $fileName = ROOT.DS.'tmp'.DS.'logs'.DS.$this->_file; }else{ $fileName = ROOT.DS.'tmp'.DS.'logs'.DS.$fileName; } if (file_exists($fileName)) { $handle = fopen($fileName, 'rb'); $variable = fread($handle, filesize($fileName)); fclose($handle); return unserialize($variable); } else { return null; } } function set($fileName,$variable) { if(null != $this->_file){ $fileName = ROOT.DS.'tmp'.DS.'logs'.DS.$this->_file; }else{ $fileName = ROOT.DS.'tmp'.DS.'logs'.DS.$fileName; } $handle = fopen($fileName, 'a'); foreach($variable as $key=>$d){ if(!is_array($d)){ fwrite($handle, $key. ' => ' . $d . "\n"); }else{ foreach($d as $k=>$x){ if(!is_array($x)){ fwrite($handle, $k .' => '. $x . "\n"); }else{ foreach($x as $k1=>$x1){ if(!is_array($x1)){ fwrite($handle, $k1 .' => '. $x1 . "\n"); }else{ fwrite($handle, $k1 .' => '. implode(',',$x1) . "\n"); } } } } } } fclose($handle); } } <file_sep>/application/controllers/main/maincontroller.php <?php class mainController extends BaseController{ function main(){ $this->set('title', 'PFU'); } function index(){ $this->set('title', 'PFU'); } } <file_sep>/application/models/user/user.php <?php class User extends BaseModel { protected $password; function getPassword(){ if(isset($this->password)){ return $this->password; }else{ return false; } } function setPassword($password = null){ if(null != $password){ $this->password = $password; }else{ return false; } } function getEmail(){ if(isset($this->email)){ return $this->email; }else{ return false; } } function setEmail($email = null){ if(null != $email){ $this->email = $email; }else{ return false; } } function setIsActive($param = 0){ $this->is_active = $param; } function getIsActive(){ if(isset($this->is_active)){ return $this->is_active; } return false; } function loadByEmail($email = null){ if(null != $email){ $user = $this->custom('SELECT * FROM users WHERE email ="' . $email .'" LIMIT 1'); if($user){ if($user[0] != null){ return $user[0]; } }else{ return false; } } } } <file_sep>/lib/bootstrap.php <?php require_once (ROOT . DS . 'lib' . DS .'framework' . DS . 'config' . DS . 'config.php'); require_once (ROOT . DS . 'lib' . DS .'framework' . DS . 'config' . DS . 'routing.php'); require_once (ROOT . DS . 'lib' . DS .'framework' . DS . 'config' . DS . 'inflection.php'); require_once (ROOT . DS . 'lib' . DS .'framework' . DS . 'util' . DS . 'brain.php'); require_once (ROOT . DS . 'lib' . DS .'framework' . DS . 'util' . DS . 'debug.php');<file_sep>/application/helpers/application/html.php <?php class HTML { private $js = array(); function shortenUrls($data) { $data = preg_replace_callback('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', array(get_class($this), '_fetchTinyUrl'), $data); return $data; } private function _fetchTinyUrl($url) { $ch = curl_init(); $timeout = 5; curl_setopt($ch,CURLOPT_URL,'http://tinyurl.com/api-create.php?url='.$url[0]); curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); $data = curl_exec($ch); curl_close($ch); return '<a href="'.$data.'" target = "_blank" >'.$data.'</a>'; } function sanitize($data) { return mysql_real_escape_string($data); } function link($text, $path, $class='', $prompt = false,$confirmMessage = "Are you sure?") { $path = str_replace(' ','-',$path); if ($prompt) { $data = '<a href="javascript:void(0);" onclick="javascript:jumpTo(\''.$path.'\',\''.$confirmMessage.'\')" class="'.$class.'">'.$text.'</a>'; } else { $data = '<a href="'.$path.'" class="'.$class.'">'.$text.'</a>'; } return $data; } function includeJs($fileName) { $data = '<script src="'.BASE_PATH.'/js/'.$fileName.'.js"></script>'; $data .= "\n"; return $data; } function includeCss($fileName,$media ='all') { $data = '<link rel="stylesheet" type="text/css" href="'.BASE_PATH.'/css/'.$fileName.'.css" media="'.$media.'" />'; $data .= "\n"; return $data; } function imgTag($fileName,$ext ='jpg',$class="",$width=null,$height=null) { $data = '<img src="'.BASE_PATH.'img/'.$fileName.'.'.$ext.'" class="'.$class.'" '; if($width != null){ $data .= ' width="'.$width.'px" '; } if($height != null){ $data .= ' height="'.$width.'px" '; } $data .= "/>"; return $data; } }<file_sep>/lib/framework/controller/basecontroller.php <?php class BaseController { protected $_controller; protected $_action; protected $_template; protected $_params; protected $_form; protected $_debug; protected $_session; public $doNotRenderHeader; public $render; function beforeAction(){ $session = new Session(); if(isset($_COOKIE['PHPSESSID']) && $this->_session = $session->get($_COOKIE['PHPSESSID']) ){ $this->set('session',$this->_session['data']); }else{ $this->set('session', ''); } } function afterAction(){ } function __construct($controller, $action, $params = array()) { global $inflect; if(DEBUG_MODE == true){ $this->_debug = new Debug(); $this->_debug->setFile('Controller-'.ucfirst($controller).'-'.date("Ymd")); } if($params){ foreach($params as $key=>$param){ $this->_params[$key] = $param; } if(DEBUG_MODE == true){ $this->_debug->setData($this->_params); } } $this->_controller = ucfirst($controller); $this->_action = $action; if(DEBUG_MODE == true){ $debugData = array(); $debugData['controller'] = $this->_controller; $debugData['action'] = $this->_action; $this->_debug->setData($debugData); } $model = ucfirst($inflect->singularize($controller)); $this->doNotRenderHeader = 0; $this->render = 1; $this->$model = new $model; $this->_form = new Form(); if($action){ $this->_template = new Template($controller,$action,$this->_params); }else{ $this->_template = new Template($controller,'main',$this->_params); } if(DEBUG_MODE == true){ $this->_debug->set($this->_debug->getFile(),$this->_debug->getData()); } } function set($name,$value) { $this->_template->set($name,$value); if(DEBUG_MODE == true){ $var = array(); if(is_array($value)){ $var[] = implode(',',$value); }else{ $var[$name] = $value; } $this->_debug->setData($var); $this->_debug->set($this->_debug->getFile(),$this->_debug->getData()); } } function getParams($param = null){ if(isset($param) && $param){ return $this->_params[$param]; } return $this->_params; } function getJsonParams($param = null){ if($param){ return json_encode($this->_params[$param]); } return json_encode($this->_params); } function noRender(){ $this->render = false; } function __destruct() { if ($this->render) { $this->_template->render($this->doNotRenderHeader); } } } <file_sep>/lib/framework/session/session.php <?php class Session { protected $_file; protected $session_id = null; function __construct(){ } public function __set($property = null, $value = null) { if ($property !== null and $property !== null) { $this->$property = $value; } return; } // get undeclared property public function __get($property) { if (isset($this->$property)){ return $this->$property; } } function setId($id = null){ if(null != $id){ $this->session_id = $id; } } function getId(){ if(null != $this->session_id){ return $this->session_id; } return false; } function setFile(){ if(null != $this->session_id){ $this->_file = $this->session_id; } } function getFile(){ if(null != $this->_file){ return $this->_file; } return false; } function destroy(){ // Initialize the session. // If you are using session_name("something"), don't forget it now! session_start(); // Unset all of the session variables. $_SESSION = array(); // If it's desired to kill the session, also delete the session cookie. // Note: This will destroy the session, and not just the session data! if (ini_get("session.use_cookies")) { $params = session_get_cookie_params(); setcookie(session_name(), '', time() - 42000, $params["path"], $params["domain"], $params["secure"], $params["httponly"] ); } // Finally, destroy the session. session_destroy(); } function get($fileName) { $fileName = ROOT.DS.'tmp'.DS.'sessions'.DS.$fileName; if (file_exists($fileName)) { $handle = fopen($fileName, 'rb'); $variable = fread($handle, filesize($fileName)); fclose($handle); return unserialize($variable); } else { return null; } } function set($variable) { session_start(); $this->session_id = session_id(); //setcookie('session',session_id()); ini_set('session.save_path',ROOT.'/..'.DS.'tmp'.DS.'sessions'.DS.$this->_file); $_SESSION['ip'] = $_SERVER['REMOTE_ADDR']; $_SESSION['data'] = $variable; $fileName = ROOT.DS.'tmp'.DS.'sessions'.DS.$this->session_id; $handle = fopen($fileName, 'a'); fwrite($handle, serialize($_SESSION)); fclose($handle); } } <file_sep>/application/controllers/user/usercontroller.php <?php class userController extends BaseController{ function login(){ $this->_form->addName('login'); $this->_form->addClass('login'); $this->_form->addAction('/user/validate'); $this->_form->addLabel('email','Email','form'); $this->_form->addElement('text','email', 'Email Address', true); $this->_form->addLabel('password','Password','form'); $this->_form->addElement('password','password', 'Password', true, 'password'); $this->_form->addElement('submit','LogIn', 'Log In', false, 'submit'); $html = $this->_form->render(); $this->set('form',$html); $this->set('title', 'Log In To Account'); } function checkuser(){ $session = new Session(); $response = array(); $response['msg']='No Input'; $response['success']=false; $exp = explode('@',$this->getParams('email')); if($exp[1] == ''){ $response['msg']='Email Must be a valid address'; $response['success']=false; }else{ if(isset($_COOKIE['PHPSESSID']) && isset($session) && $session->get($_COOKIE['PHPSESSID']) != null){ $response['msg']='You are already registered'; $response['success']=false; }else{ $user = $this->User->loadByEmail($this->getParams('email')); if($user != null){ $response['msg']='Already a user with this email address'; $response['success']=false; }else{ $response['msg']='Email is valid'; $response['success']=true; } } } $this->noRender(); echo json_encode($response); } function logout(){ $session = new Session(); $session->destroy(); header("location:/user/login"); } function account(){ $session = new Session(); if(isset($_COOKIE['PHPSESSID']) && isset($session) && $session->get($_COOKIE['PHPSESSID']) != null){ $this->set('title', 'Manage Account'); $this->_form->useFieldset(false,'change-pass'); $this->_form->addName('changepass'); $this->_form->addClass('login'); $this->_form->addAction('/user/updatepass'); $this->_form->addLabel('old_password','Current Password <span class="small">(that you logged in with)</span>','reqd'); $this->_form->addElement('password','old_password', 'Password', true, 'curr-password'); $this->_form->addLabel('password','New Password','form reqd'); $this->_form->addElement('password','password', '<PASSWORD>', true, 'new-password'); $this->_form->addLabel('verify_password','Verify Password','<PASSWORD>'); $this->_form->addElement('password','verify_password', '<PASSWORD>', true, 'verify-password'); $this->_form->addElement('submit','update', 'Update Password', false, 'submit'); $html = $this->_form->render(); $this->set('form',$html); }else{ header('location:/user/login'); } } function updatepass(){ $session = new Session(); $user = $this->User->loadByEmail($this->_session['data']->__get('email')); if($this->matchPassword($this->getParams('old_password'),$this->_session['data']->__get('password'))){ if(isset($_COOKIE['PHPSESSID']) && isset($session) && $session->get($_COOKIE['PHPSESSID']) != null){ $this->User->prepareData($this->getParams()); $data = $this->User->getData(); array_pop($data); $this->User->setData($data); $this->User->setId($this->_session['data']->__get('id')); $this->User->setIsActive(1); $this->generatePasswordHash($this->User->getPassword()); //var_dump($this->User); $this->User->save(true); if($this->User->getId()){ $response['success'] = true; $response['msg'] = 'Your password has been updated'; }else{ $response['success'] = false; $response['msg'] = 'There was a problem updating your account'; } }else{ $response['success'] = false; $response['msg'] = 'You must be logged in to modify your account'; } }else{ $response['success'] = false; $response['msg'] = 'You entered the incorrect current password'; } $this->noRender(); echo json_encode($response); } function register(){ $this->_form->addName('register'); $this->_form->addClass('register'); $this->_form->addAction('/user/add'); $this->_form->addLabel('first_name','First Name','form'); $this->_form->addElement('text','first_name', 'First Name', true); $this->_form->addLabel('last_name','Last Name','form'); $this->_form->addElement('text','last_name', 'Last Name', true); $this->_form->addLabel('email','Email','form'); $this->_form->addElement('text','email', 'Email Address', true); $this->_form->addLabel('password','Password','<PASSWORD>'); $this->_form->addElement('password','<PASSWORD>', '<PASSWORD>', true, '<PASSWORD>'); $this->_form->addLabel('verify_password','Verify Password','<PASSWORD>'); $this->_form->addElement('password','<PASSWORD>_password', '<PASSWORD>', true, '<PASSWORD>'); $this->_form->addElement('submit','submit', 'Register', false, 'submit'); $html = $this->_form->render(); $this->set('form',$html); $this->set('title', 'Register Account'); } function add(){ $this->User->prepareData($this->getParams()); $data = $this->User->getData(); array_pop($data); $this->User->setData($data); $this->User->setIsActive(1); $this->generatePasswordHash($this->User->getPassword()); $this->User->save(); header("location:/user/login"); // redirectAction('user','login'); } function validate(){ $user = $this->User->loadByEmail($this->getParams('email')); if($user && array_key_exists('User',$user)){ if($this->matchPassword($this->getParams('password'),$user['User']['password'])){ $this->User->setData($user['User']); $session = new Session(); $session->setFile(); $session->set($this->User); header("location:/"); redirectAction('main','main'); }else{ $msg = new Message(); $msg->setMessage('Your email and password combination do not match'); header("location:/user/login"); redirectAction('user','login'); } } } function delete(){ $this->set('title', 'PFU'); } function update(){ $this->set('title', 'Edit Account'); } private function getSalt(){ return base_64_encode(PASSWORD_SALT); } private function encryptPass( $pass_hash, $salt_hash ){ $pass = $<PASSWORD> . $<PASSWORD>; $this->User->setPassword( $<PASSWORD> . $<PASSWORD> ); return $pass; } private function generateSaltHash(){ return substr( sha1(PASSWORD_SALT . str_pad( dechex( mt_rand() ), 8, '0', STR_PAD_LEFT ), -8 ),-8); } private function generatePasswordHash($password){ $salt_hash = $this->generateSaltHash(); $hash = $this->encryptPass(sha1($password), $salt_hash ); return $hash; } private function matchPassword($password,$userPass){ $password_hash = substr($this->generatePasswordHash($password),8); if($password_hash == substr($userPass,8)){ return true; } return false; } } <file_sep>/application/helpers/application/message.php <?php class Message { protected $_message; function setMessage($msg = null){ if(null != $msg){ $this->_message = $msg; }else{ $this->_message = ''; } } function getMessage(){ if(isset($this->_message)){ return $this->_message; } return false; } }<file_sep>/application/models/main/main.php <?php class Main extends BaseModel { /* empty constructor will prevent app from trying to cache a model without a table */ function __construct(){ } } <file_sep>/lib/framework/model/basemodel.php <?php class BaseModel extends SQLQuery { protected $_model; protected $_data = array(); function __construct() { global $inflect; $this->connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME); $this->_limit = PAGINATE_LIMIT; $this->_model = get_class($this); $this->_table = strtolower($inflect->pluralize($this->_model)); if (!isset($this->abstract)) { $this->_describe(); } } // set undeclared property public function __set($property = null, $value = null) { if ($property !== null and $property !== null) { $this->$property = $value; } return; } // get undeclared property public function __get($property) { if (isset($this->$property)){ return $this->$property; } } function getId(){ if(isset($this->id)){ return $this->id; }else{ return false; } } function setId($id = null){ if(null != $id){ $this->id = $id; }else{ return false; } } function prepareData($data = null){ foreach($data as $key=>$d){ if($key != 'submit'){ $this->_data[$key] = $d; } } } public function getData(){ if($this->_data){ return $this->_data; }else{ return false; } } public function setData($data = null){ if($data != null){ foreach($data as $key=>$data){ $this->$key = $data; } return true; } if($this->_data){ foreach($this->_data as $key=>$data){ $this->$key = $data; } return true; }else{ return false; } } function __destruct() { } } <file_sep>/application/helpers/application/formelement.php <?php class FormElement{ protected $type; protected $name; protected $value; protected $validate; public $html; protected $class; function __construct($type = null, $name ='', $value = '', $validate = false, $class = ''){ $this->type = $type; $this->name = $name; if($type != 'file'){ $this->value = $value; } $this->validate = $validate; $this->class =$class; } public function getHTML(){ switch ($this->type){ case 'text': $this->html = '<div class="form-text"><input type = "text" name="'. $this->name .'" value="'. $this->value .'"'; $this->html .= ($this->validate == true)?' class="reqd ' . $this->class . '"':' class="'. $this->class . '"'; $this->html .= '/></div>'; return $this->html; break; case 'hidden': $this->html = '<input type = "hidden" name="'. $this->name .'" value="'. $this->value .'"/>'; return $this->html; break; case 'textArea': $this->html = '<div class="form-textarea"><textarea cols="40" rows="5" name="'. $this->name .'"'; $this->html .= ($this->validate == true)?' class="reqd ' . $this->class . '"':' class="'. $this->class . '"'; $this->html .= '>'; $this->html .= $this->value; $this->html .= '</textarea></div>'; return $this->html; break; case 'password': $this->html = '<div class="form-password"><input type = "password" name="'. $this->name .'" value="'. $this->value .'"'; $this->html .= ($this->validate == true)?' class="reqd ' . $this->class . '"':' class="'. $this->class . '"'; $this->html .= '/></div>'; return $this->html; break; case 'select': $this->html = '<div class="form-select"><select name="'. $this->name .'"'; $this->html .= ($this->validate == true)?' class="reqd ' . $this->class . '"':' class="'. $this->class . '"'; $this->html .= '>'; foreach($this->value as $option=>$value){ $this->html .= '<option value="'. $option .'">'. $value .'</option>'; } $this->html .= '</select></div>'; return $this->html; break; case 'multiselect': $this->html = '<div class="form-multiselect"><select name="'. $this->name .'"'; $this->html .= ($this->validate == true)?' class="reqd ' . $this->class . '"':' class="'. $this->class . '"'; $this->html .= ' MULTIPLE>'; foreach($this->value as $option=>$value){ $this->html .= '<option value="'. $option .'">'. $value .'</option>'; } $this->html .= '<select'; $this->html .= '/></div>'; return $this->html; break; case 'radio': $this->html = '<div class="form-radio"><input type = "radio" name="'. $this->name .'" value="'. $this->value .'"'; $this->html .= ($this->validate == true)?' class="reqd ' . $this->class . '"':' class="'. $this->class . '"'; $this->html .= '/>'. $this->value . '</div>'; return $this->html; break; case 'checkbox': $this->html = '<div class="form-checkbox"><input type = "checkbox" name="'. $this->name .'" value="'. $this->value .'"'; $this->html .= ($this->validate == true)?' class="reqd ' . $this->class . '"':' class="'. $this->class . '"'; $this->html .= '/>'. $this->value . '</div>'; return $this->html; break; case 'file': $this->html ='<div class="form-file"><input type = "file" name="'. $this->name .'" value="'. $this->value .'"'; $this->html .= ($this->validate == true)?' class="reqd ' . $this->class . '"':' class="'. $this->class . '"'; $this->html .= '/></div>'; return $this->html; break; case 'submit': $this->html = '<div class="form-submit"><input type = "submit" name="'. $this->name .'" value="'. $this->value .'"'; $this->html .= ($this->validate == true)?' class="reqd ' . $this->class . '"':' class="'. $this->class . '"'; $this->html .= '/></div>'; return $this->html; break; default: $this->html = '<div class="form-text"><input type = "text" name="'. $this->name .'" value="'. $this->value .'"'; $this->html .= ($this->validate == true)?' class="reqd ' . $this->class . '"':' class="'. $this->class . '"'; $this->html .= '/></div>'; return $this->html; break; return $this->html; } } } ?><file_sep>/config/config.php <?php /** Configuration Variables **/ define ('DEVELOPMENT_ENVIRONMENT',true); define('DB_NAME', 'mhcommerce'); define('DB_USER', 'root'); define('DB_PASSWORD', ''); define('DB_HOST', 'localhost'); define('BASE_PATH','http://m.mac/'); define('PAGINATE_LIMIT', '25');
98f08bddbcb7162170b15bf65460253445641820
[ "PHP" ]
19
PHP
mh801/PFU
dfcb416fc798888053796a068d4864f010c14e5c
070eb2ff7672dbd9705b7d0483328e4a8d02ae22
refs/heads/master
<file_sep>#include <stdio.h> #include <zmq.h> #include <unistd.h> #include <string.h> int main(void) { void *ctx, *sock; int ret = 0; char data[1024]; ctx = zmq_ctx_new(); sock = zmq_socket(ctx, ZMQ_SUB); zmq_setsockopt(sock, ZMQ_SUBSCRIBE, "", 0); ret = zmq_connect(sock, "tcp://127.0.0.1:5555"); while (1) { bzero(data, sizeof(data)); if (ret = zmq_recv(sock, data, sizeof(data) - 1, 0) < 0) printf("SUB : zmq_recv faild"); printf("SUB:recv msg : %s\n", data); sleep(2); } zmq_close(sock); zmq_ctx_destroy(ctx); return 0; } <file_sep>#pragma once #ifndef _HUFFMAN_H #define _HUFFMAN_H //huffman树树节点结构 typedef struct _htNode { char symbol; struct _htNode *left, *right; }htNode; //huffman树 根结点 typedef struct _htTree { htNode *root; }htTree; //label结点 typedef struct _hlNode { char symbol; char *code; struct _hlNode *next; }hlNode; //label表 typedef struct _hlTable { hlNode *first; hlNode *last; }hlTable; //使用指定字符串inputString,创建huffman树 htTree *buildTree(char *inputString); //使用创建的huffmanTree树,创建hlTable表 hlTable *buildTable(htTree *huffmanTree); //使用table表,对指定字符串stringToEncode进行编码压缩(逐字符编码成二进制数) void encode(hlTable *table, char *stringToEncode); //使用huffman tree,解压指定的编码stringToDecode void decode(htTree *tree, char *stringToDecode); #endif <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include "huffman.h" #include "queue.h" //遍历huffman树结点,形成table链表 void traversalTree(htNode *treeNode, hlTable **table, int k, char code[256]) { //若当前树节点左右叶子为空(即自身为叶子节点) if (treeNode->left == NULL &&treeNode->right == NULL) { //code尾部加\0,定义新结点aux code[k] = '\0'; hlNode *aux = (hlNode *)malloc(sizeof(hlNode)); aux->code = (char *)malloc( sizeof(char) * (strlen(code) + 1) ); strcpy(aux->code, code); aux->symbol = treeNode->symbol; aux->next = NULL; //table增加第一个aux结点 if ((*table)->first == NULL) { (*table)->first = aux; (*table)->last = aux; } //table尾部增加aux结点 ,形成table链表 else { (*table)->last->next = aux; (*table)->last = aux; } } //若当前树节点左叶子不为空,code中加0,向下递归遍历 if (treeNode->left != NULL) { code[k] = '0'; traversalTree(treeNode->left, table, k + 1, code); } //若当前树节点右叶子不为空,code中加1,向下递归遍历 if (treeNode->right != NULL) { code[k] = '1'; traversalTree(treeNode->right, table, k + 1, code); } } hlTable *buildTable(htTree *huffmanTree) { hlTable *table = (hlTable *)malloc(sizeof(hlTable)); table->first = NULL; table->last = NULL; int k = 0; char code[256]; traversalTree(huffmanTree->root, &table, k, code); return table; } htTree * buildTree(char * inputString) { // 字符出现次数统计(所有字符对应的ASCII码对应的整型范围:0-127) int *probability = (int*)malloc(sizeof(int) * 256); //256个int内存空间 //初始化 for (int i = 0; i < 256; i++) { probability[i] = 0; } //使用ASCII的整型数值作为索引统计 for (int j = 0; inputString[j] != '\0'; j++) { probability[(unsigned char)inputString[j]]++; } //初始化huffman队列的头指针 pQueue *huffmanQueue; initPQueue(&huffmanQueue); //遍历所有的ASCIII码(0-256)对应的字符,若出现次数不为0,定义htNode结点 加入到huffman队列中去 for (int k = 0; k < 256; k++) { if (probability[k] != 0) { htNode *aux = (htNode *)malloc(sizeof(htNode)); aux->left = NULL; aux->right = NULL; aux->symbol = (char)k; //ASCIII码整型转成字符 addPQueue(&huffmanQueue, aux, probability[k]); } } free(probability); //生成huffman树 while (huffmanQueue->size != 1) { int priority = huffmanQueue->first->probability; priority += huffmanQueue->first->next->probability; //前两个结点频率(最小两个值)的和生成新的huffman树结点频率 htNode * left = getPQueue(&huffmanQueue); htNode * right = getPQueue(&huffmanQueue); htNode * newNode = (htNode *)malloc(sizeof(htNode)); newNode->left = left; newNode->right = right; addPQueue(&huffmanQueue, newNode, priority); } //队列中剩余的一个结点即为根结点 htTree *hufTree = (htTree *)malloc(sizeof(htTree)); hufTree->root = getPQueue(&huffmanQueue); return hufTree; } void encode(hlTable *table, char *stringToEncode) { hlNode *traversal; printf("stringToEncode is: %s \n\nEncoding...\n\n", stringToEncode); for (int i = 0; stringToEncode[i] != '\0'; i++) { traversal = table->first; //每个字符都需要从Table中第一个位置找起 while (traversal->symbol != stringToEncode[i]) //逐字符 全遍历 { traversal = traversal->next; } printf("%s ", traversal->code); } printf("\n"); } void decode(htTree *tree, char * stringToDecode) { htNode *traversal = tree->root; printf("\n\nDecoding.... \n\nstringToDecode is: %s \n\nDecoding String:\n\n", stringToDecode); //逐字符(0左/1右)遍历huffman树 for (int i = 0; stringToDecode[i] != '\0'; i++) { //遍历到最后一个叶子节点 即为解码后的字符 if (traversal->left == NULL && traversal->right == NULL) { printf("%c", traversal->symbol); traversal = tree->root; } if (stringToDecode[i] == '0') { traversal = traversal->left; } if (stringToDecode[i] == '1') { traversal = traversal->right; } if (stringToDecode[i] != '0' &&stringToDecode[i] != '1') { printf("Input String cannot be decoded correctly\n"); return; } } //if (traversal->left == NULL && traversal->right == NULL) //{ //} } <file_sep> target_file = 'sql_test' compile_tool = 'g++' inc_path = [ ] src = [Glob('*.cpp')] lib_path = [ ] libs = [ 'mysqlclient', 'z' ] defines = [] ccflags = ['-O3','-Wall', '-std=c++11'] env=Environment( CXX = compile_tool ) for flag in ccflags: env.AppendUnique(CPPFLAGS=[flag]) for path in inc_path: env.AppendUnique(CPPPATH=[path]) for deb in defines: env.AppendUnique(CPPDEFINES=[deb]) for path in lib_path: env.AppendUnique(LIBPATH=[path]) for lib in libs: env.AppendUnique(LIBS=[lib]) env.Append(CCCOMSTR="CC $SOURCES") env.Append(LINKCOMSTR="LINK $TARGET") env.Program(target = target_file, source=src) <file_sep>int driver11_test(void) { return 11; }<file_sep>#include <string.h> #include <libxml/parser.h> /* 对指定编码格式的外部数据,转换成libxml使用UTF-8格式 */ unsigned char * convert(unsigned char *in, char *encoding) { unsigned char *out; int ret, size, out_size, temp; /* 定义一个编码处理器指针 */ xmlCharEncodingHandlerPtr handler; size = (int)strlen((const char *)in) + 1; /* 输入数据长度 */ out_size = size * 2 - 1; /* 输出数据长度 */ out = (unsigned char *)malloc((size_t)out_size); /* 存放输出数据 */ if (out) { /* 查找内建的编码处理器 */ handler = xmlFindCharEncodingHandler(encoding); if (!handler) { free(out); out = NULL; } } if (out) { temp = size - 1; /* 对输入数据进行编码转换 */ ret = handler->input(out, &out_size, in, &temp); if (ret || temp - size + 1) { /* 转换不成功 */ if (ret) { /* 转换失败 */ printf("conversion wasn't successful.\n"); } else { /* 只转换了一部分数据 */ printf("conversion wasn't successful. converted: %i octets.\n", temp); } free(out); out = NULL; } else { /* 转换成功 */ out = (unsigned char *)realloc(out, out_size + 1); out[out_size] = 0; /* 输出的末尾加上null终止符 */ } } else { printf("no mem\n"); } return (out); } int main(int argc, char **argv) { unsigned char *content, *out; xmlDocPtr doc; xmlNodePtr rootnode; char *encoding = "ISO-8859-1"; if (argc <= 1) { printf("Usage: %s content\n", argv[0]); return (0); } content = (unsigned char *)argv[1]; /* 转换成libxml2使用的UTF-8格式 */ out = convert(content, encoding); doc = xmlNewDoc(BAD_CAST "1.0"); rootnode = xmlNewDocNode(doc, NULL, (const xmlChar *)"root", out); xmlDocSetRootElement(doc, rootnode); /* 以ISO-8859-1格式输出文档内容 */ xmlSaveFormatFileEnc("-", doc, encoding, 1); return (0); }<file_sep>/* 格式化输出库 Boost.Format */ #include <iostream> #include "boost/format.hpp" int main(int argc, char const *argv[]) { std::cout << \ // Boost.Format 类使用置于两个百分号之间的数字作为占位符 // boost::format("%1%.%2%.%3%") % 16 % 9 % 2008 // 16.9.2008 boost::format("%2%.%1%.%3%") % 16 % 9 % 2008 // 9.16.2008 << std::endl; std::cout << \ // 因为操作器 std::showpos() 通过 boost::io::group() 与数字 99 连接, // 所以只要显示 99 , 在它前面就会自动加上 + 号 boost::format("%1% %2% %1%") % boost::io::group(std::showpos, 99) % 100 << std::endl; // 如果需要 + 号仅在 99 第一次输出时显示, 则需要改造格式化占位符 std::cout << boost::format("%|1$+| %2% %1%") % 99 % 100 << std::endl; // 不引用数据的方法 std::cout << boost::format("%|+| %|| %||") % 99 % 100 % 99 << std::endl; // 这看起来就像 std::printf() ,但是 Boost.Format 库有类型安全的优点 std::cout << boost::format("%+d %5d %d") % 99 % 100 % 99 << std::endl; std::cout << boost::format("%+s %s %s") % "ccc" % 100 % 99 << std::endl; return 0; } <file_sep>#pragma once int module12_test(void);<file_sep>#include "boost/interprocess/managed_shared_memory.hpp" #include "boost/interprocess/sync/named_mutex.hpp" #include <boost/interprocess/sync/interprocess_mutex.hpp> #include <boost/interprocess/managed_shared_memory.hpp> #include <boost/interprocess/sync/named_condition.hpp> #include <boost/interprocess/sync/scoped_lock.hpp> #include "boost/thread.hpp" #include <iostream> void test1() { boost::interprocess::managed_shared_memory managed_shm(boost::interprocess::open_or_create, "shm", 1024); int *i = managed_shm.find_or_construct<int>("Integer")(); boost::interprocess::named_mutex named_mtx(boost::interprocess::open_or_create, "mtx"); named_mtx.lock(); ++(*i); std::cout << *i << std::endl; named_mtx.unlock(); } void test2() { boost::interprocess::managed_shared_memory managed_shm(boost::interprocess::open_or_create, "shm", 1024); int *i = managed_shm.find_or_construct<int>("Integer")(); boost::interprocess::interprocess_mutex *mtx = managed_shm.find_or_construct<boost::interprocess::interprocess_mutex>("mtx")(); mtx->lock(); ++(*i); std::cout << *i << std::endl; mtx->unlock(); // managed_shm.destroy<int>("Integer"); } void test3() { boost::interprocess::managed_shared_memory managed_shm(boost::interprocess::open_or_create, "shm", 1024); int *i = managed_shm.find_or_construct<int>("Integer")(0); boost::interprocess::named_mutex named_mtx(boost::interprocess::open_or_create, "mtx"); boost::interprocess::named_condition named_cnd(boost::interprocess::open_or_create, "cnd"); boost::interprocess::scoped_lock<boost::interprocess::named_mutex> lock(named_mtx); while (*i < 10) { if (*i % 2 == 0) { ++(*i); named_cnd.notify_all(); named_cnd.wait(lock); } else { std::cout << *i << std::endl; ++(*i); named_cnd.notify_all(); named_cnd.wait(lock); } } named_cnd.notify_all(); boost::interprocess::shared_memory_object::remove("shm"); boost::interprocess::named_mutex::remove("mtx"); boost::interprocess::named_condition::remove("cnd"); } void test4() { try { boost::interprocess::managed_shared_memory managed_shm(boost::interprocess::open_or_create, "shm", 1024); int *i = managed_shm.find_or_construct<int>("Integer")(0); boost::interprocess::interprocess_mutex *mtx = managed_shm.find_or_construct<boost::interprocess::interprocess_mutex>("mtx")(); boost::interprocess::interprocess_condition *cnd = managed_shm.find_or_construct<boost::interprocess::interprocess_condition>("cnd")(); boost::interprocess::scoped_lock<boost::interprocess::interprocess_mutex> lock(*mtx); while (*i < 10) { if (*i % 2 == 0) { ++(*i); cnd->notify_all(); cnd->wait(lock); } else { std::cout << *i << std::endl; ++(*i); cnd->notify_all(); cnd->wait(lock); } } cnd->notify_all(); } catch (...) { std::cout << "exception" << std::endl; } boost::interprocess::shared_memory_object::remove("shm"); } int main(int argc, char const *argv[]) { test4(); return 0; } <file_sep>#include <boost/tuple/tuple.hpp> #include <boost/tuple/tuple_io.hpp> #include <boost/any.hpp> #include <boost/variant.hpp> #include <string> #include <iostream> #include <vector> void test1() { // typedef std::pair<std::string, std::string> person; // person p("Boris", "Schaeling"); // std::cout << p.first.c_str() << p.second.c_str() << std::endl; typedef boost::tuple<std::string, std::string> person; person p("Boris", "Schaeling"); std::cout << p << std::endl; } void test2() { typedef boost::tuple<std::string, std::string, int> person; person p("Boris", "Schaeling", 43); std::cout << p << std::endl; std::cout << p.get<0>() << std::endl; boost::get<0>(p); p.get<1>() = "Becker"; std::cout << boost::make_tuple("Boris", "Schaeling", 43) << std::endl; std::string s = "Boris"; std::cout << boost::make_tuple(boost::ref(s), "Schaeling", 43) << std::endl; } void test3() { // Tier 的特殊之处在于它包含的所有元素都是引用类型的 typedef boost::tuple<std::string &, std::string &, int &> person; std::string firstname = "Boris"; std::string surname = "Schaeling"; int shoesize = 43; person p = boost::tie(firstname, surname, shoesize); // person p = boost::make_tuple(boost::ref(firstname), boost::ref(surname), boost::ref(shoesize)); surname = "Becker"; shoesize = 4; std::cout << p << std::endl; } void test4() { boost::any a = 1; std::cout << boost::any_cast<int>(a) << std::endl; a = 3.14; std::cout << boost::any_cast<double>(a) << std::endl; a = true; std::cout << boost::any_cast<bool>(a) << std::endl; a = std::string("Hello, world!"); std::cout << boost::any_cast<std::string>(a) << std::endl; if (!a.empty()) { const std::type_info &ti = a.type(); std::cout << ti.name() << std::endl; } } void test5() { boost::variant<double, char, std::string> v; v = 3.14; std::cout << boost::get<double>(v) << std::endl; v = 'A'; std::cout << boost::get<char>(v) << std::endl; v = "Hello, world!"; std::cout << boost::get<std::string>(v) << std::endl; std::cout << v << std::endl; } std::vector<boost::any> vector; struct output : public boost::static_visitor<> { template <typename T> void operator()(T &t) const { vector.push_back(t); } }; void test6() { boost::variant<double, char, std::string> v; v = 3.14; boost::apply_visitor(output(), v); v = 'A'; boost::apply_visitor(output(), v); v = "Hello, world!"; boost::apply_visitor(output(), v); } int main(int argc, char const *argv[]) { test6(); return 0; } <file_sep> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <zmq.h> int main(int argc, char const *argv[]) { void *zmq_ctx = zmq_ctx_new(); void *socket = zmq_socket(zmq_ctx, ZMQ_REQ); if (zmq_connect(socket, "tcp://localhost:5559") < 0) { return -1; } int ret; while (true) { zmq_msg_t msg; zmq_msg_init_size(&msg, 5); memcmp(zmq_msg_data(&msg), "hello", 5); zmq_msg_send(&msg, socket, 0); zmq_msg_close(&msg); sleep(1); zmq_msg_init(&msg); ret = zmq_msg_recv(&msg, socket, 0); char *string = new char[ret + 1]; memcpy(string, zmq_msg_data(&msg), ret); zmq_msg_close(&msg); string[ret] = 0; printf(string); fflush(stdout); delete[] string; } zmq_close(socket); zmq_ctx_destroy(zmq_ctx); return 0; } <file_sep>#include <iostream> #include <string.h> #include <unistd.h> #include "zmq.hpp" // #define CXX_PROCESS #ifdef CXX_PROCESS int main(int argc, char const *argv[]) { zmq::context_t ctx(1); zmq::socket_t socket(ctx, ZMQ_REQ); socket.connect("tcp://localhost:5555"); while (1) { zmq::message_t msg("hello world\n", 13); if (!socket.send(msg)) { std::cout << "REQ : zmq_send faild" << std::endl; break; } zmq::message_t request; socket.recv(request); std::printf("%s\n", request.data()); sleep(1); } return 0; } #else int main(int argc, char const *argv[]) { int ret; char data[1024]; void *ctx, *socket; ctx = zmq_ctx_new(); socket = zmq_socket(ctx, ZMQ_REQ); zmq_connect(socket, "tcp://localhost:5555"); while (1) { if ((ret = zmq_send(socket, "hello", 5, 0)) < 0) printf("REQ : zmq_send faild"); sleep(3); bzero(data, sizeof(data) - 1); if ((ret = zmq_recv(socket, data, sizeof(data) - 1, 0)) < 0) printf("REQ : zmq_recv faild"); printf("REQ : recv msg %s\n", data); } zmq_close(socket); zmq_ctx_destroy(ctx); return 0; } #endif <file_sep>// 线索二叉树 #include <stdio.h> #include <stdlib.h> // 线索存储标志位 // Link(0):表示指向左右孩子的指针 // Thread(1):表示指向前屈后继的线索 typedef enum {Link, Thread} PointerTag; typedef struct BiThrNode { char data; struct BiThrNode *lchild, *rchild; PointerTag ltag, rtag; }BiThrNode, *BiThrTree; // 全局变量,始终指向刚刚访问过的结点 BiThrTree g_pre; // 先序遍历 void preOder(BiThrNode *root) { if (root == NULL) { printf("_"); return; } printf("%c", root->data); preOder(root->lchild); preOder(root->rchild); return; } // 中序遍历线索 void InThreadingOder(BiThrNode *root) { if (root == NULL){ return; } InThreadingOder(root->lchild); // 如果该结点无左孩子,设置ltag为1,并lchild指向刚刚访问的结点 if (!root->lchild) { root->ltag = Thread; root->lchild = g_pre; } if (!root->rchild) { g_pre->rtag = Thread; g_pre->rchild = root; } g_pre = root; InThreadingOder(root->rchild); return; } /* A B E C D F 前序: ABC__D__E_F__ */ // 创建二叉树,前序遍历创建 void CreateBiThrTree(BiThrTree *T) { char c; scanf("%c", &c); if (' ' == c) { *T = NULL; } else { *T = (BiThrNode *)malloc(sizeof(BiThrNode)); (*T)->data = c; (*T)->ltag = Link; (*T)->rtag = Link; CreateBiThrTree(&((*T)->lchild)); CreateBiThrTree(&((*T)->rchild)); } } void InThreading(BiThrTree *p, BiThrTree T) { g_pre = (BiThrNode *)malloc(sizeof(BiThrNode)); g_pre->ltag = Link; g_pre->rtag = Thread; g_pre->rchild = g_pre; if (!T) { g_pre->lchild = g_pre; } else { g_pre->lchild = T; g_pre = T; InThreadingOder(T); g_pre->rchild = T; g_pre->rtag = Thread; T->rchild = g_pre; } } int main(int argc, char const *argv[]) { BiThrTree tree = NULL; CreateBiThrTree(&tree); preOder(tree); printf("\n"); // InThreading(tree); return 0; } <file_sep>// 责任链模式:很多对象由每一个对象对其下家的引用而接起来形成一条链 // 系统可以在不影响客户端的情况下动态的重新组织链和分配责任。 // 处理者有两个选择:承担责任或者把责任推给下家。一个请求可以最终不被任何接收端对象所接受。 #include "Handler.h" int main() { //创建责任链 //一般将责任大(最有可能处理用户请求)的对象放在前面 Handler *beijing = new Beijing(); Handler *tianjin = new Tianjin(); Handler *shanghai = new Shanghai(); Handler *guangdong = new Guangdong(); beijing->setNextHandler(tianjin); tianjin->setNextHandler(shanghai); shanghai->setNextHandler(guangdong); //用户进行请求 //从责任链的第一个对象开始 beijing->handleRequest("10029812340930091"); return 0; } <file_sep>/* C++11特性 */ #include <iostream> #include <vector> #include <array> #include <initializer_list> #include <algorithm> // decltype // 拖尾返回类型 // template <typename T, typename U> template<typename T = int, typename U = int> // 默认参数 auto add(T x, U y) -> decltype(x + y) // c++11 // auto add(T x, U y) // c++14 { return x + y; } class A { public: A(int _a, float _b): a(_a), b(_b) {} private: int a; float b; }; class Magic { public: Magic(std::initializer_list<int> list) { std::cout << *list.begin() << std::endl; } }; // 类型别名模板 template< typename T, typename U> class SuckType { public: T a; U b; SuckType(int value):a(value),b(value){} }; template <typename T> using NewType = SuckType<int, T>; // 合法 // 委托构造 class Base { public: int value1; int value2; Base() { value1 = 1; } Base(int value) : Base() { // 委托 Base() 构造函数 value2 = 2; } }; // 继承构造 struct D { D(int i) { std::cout << "1" << std::endl; } D(double d,int i){ std::cout << "2" << std::endl; } D(float f,int i,const char* c){ std::cout << "3" << std::endl; } //...等等系列的构造函数版本 }; struct E:D { using D::D; //关于基类各构造函数的继承一句话搞定 //...... }; void foo(int *p, int len) { return; } int main() { // nullptr // char *ptr = nullptr; // constexpr // constexpr int num = 5; // auto // for(auto itr = vec.begin(); itr != vec.end(); ++itr); // decltype // int i = 0, j = 2; // std::cout << add(i, j) << std::endl; // 区间迭代 // std::vector<int> v(2, 10); // for (auto &i : v) // { // std::cout << i << std::endl; // } // 初始化列表 // A a{1, 20.2}; // Magic magic = {1,2,3,4,5}; // std::vector<int> v1 = {1, 2, 3, 4}; // 尖括号 >, 使得模板使用 >> 合法 // std::vector<std::vector<int>> wow; // 类型别名模板 // NewType<int> t(5); // // 继承构造 // E b(1); // E c(2.2, 1); // E d(2.2, 1, "111"); // Lambda 表达式 // 1) []不捕获任何变量。 // 2) [&]捕获外部作用域中所有变量,并作为引用在函数体中使用(按引用捕获)。 // 3) [=]捕获外部作用域中所有变量,并作为副本在函数体中使用(按值捕获)。注意值捕获的前提是变量可以拷贝,且被捕获的变量在 // 4) [=,&foo]按值捕获外部作用域中所有变量,并按引用捕获foo变量。 // 5) [bar]按值捕获bar变量,同时不捕获其他变量。 // 6) [this]捕获当前类中的this指针,让lambda表达式拥有和当前类成员函数同样的访问权限。如果已经使用了&或者=,就默认添加此选项 // int a = 0; // auto f1 = [=] { return a; }; // a+=1; // std::cout << f1() << std::endl; //输出0 // int b = 0; // auto f2 = [&b] { return b; }; // b+=1; // std::cout << f2() << std::endl; //输出1 // int a = 0; // // auto f1 = [=] { return a++; }; //error // auto f2 = [=] () mutable { return a++; }; //OK // auto a = [] { std::cout << "A" << std::endl; }; // auto b = [] { std::cout << "B" << std::endl; }; // // a = b; // 非法,lambda无法赋值 // auto c = a; // 合法,生成一个副本 // std::vector<int> v(10); // int a = 0; // int b = 1; // std::generate(v.begin(), v.end(), [&a, &b] { int value = b; b = b + a; a = value; return value; }); std::vector<int> v = { 1, 2, 3, 4, 5, 6 }; // int even_count = 0; // for_each(v.begin(), v.end(), [&even_count](int val){ // if(!(val & 1)){ // ++ even_count; // } // }); // std::cout << "The number of even is " << even_count << std::endl; // 新增容器 std::array // std::array 保存在栈内存中,相比堆内存中的 std::vector,我们能够灵活的访问这里面的元素,从而获得更高的性能 // std::array<int, 4> arr = {1,2,3,4}; // // C 风格接口传参 // // foo(arr, arr.size()); // 非法, 无法隐式转换 // foo(&arr[0], arr.size()); // foo(arr.data(), arr.size()); // // 使用 `std::sort` // std::sort(arr.begin(), arr.end()); return 0; }<file_sep>#include "queue.h" #include <stdio.h> #include <stdlib.h> void initPQueue(pQueue **queue) { *queue = (pQueue *)malloc(sizeof(pQueue)); (*queue)->first = NULL; (*queue)->size = 0; //return; } void addPQueue(pQueue **queue, TYPE val, unsigned int priority) { if ((*queue)->size == MAX_SZ) { printf("\nQueue is Full.\n"); return; //跳出函数 } pQueueNode *aux = (pQueueNode *)malloc(sizeof(pQueueNode)); //临时结点 aux->probability = priority; aux->val = val; //若是第一个huffmanQueue队列结点 //放在最前面队首 if ((*queue)->size == 0 || (*queue)->first == NULL) { aux->next = NULL; (*queue)->first = aux; (*queue)->size = 1; return; } else //比较priority大小,从小到大顺序插入队列 { //频率小于第一个结点,插最前面 if (priority <= (*queue)->first->probability) { aux->next = (*queue)->first; (*queue)->first = aux; (*queue)->size++; return; } //频率大于第一结点时 else { pQueueNode * iterator = (*queue)->first; //遍历下一结点,未到最后一个结点时 while (iterator->next != NULL) { //频率比下一个结点频率小,插到其前面 if (priority <= iterator->next->probability) { aux->next = iterator->next; iterator->next = aux; (*queue)->size++; return; } //频率比下一个结点频率大时,遍历下一个 iterator = iterator->next; } //遍历最后一个结点时(没有比此频率priority小的),放到队列最后 if (iterator->next == NULL) { aux->next = NULL; iterator->next = aux; (*queue)->size++; return; } } } //free(aux); //jo } TYPE getPQueue(pQueue **queue) { TYPE returnVal; if ((*queue)->size > 0) { returnVal = (*queue)->first->val; (*queue)->first = (*queue)->first->next; (*queue)->size--; } else { printf("\nQueue is empty.\n"); } return returnVal; }<file_sep>int module11_test(void) { return 11; }<file_sep>#include <stdio.h> #include "module1.1.h" #include "module1.2.h" #include "module2.1.h" #include "module2.2.h" #include "driver1.1.h" #include "driver1.2.h" #include <pthread.h> void *func(void *) { } int main(void) { printf("module test:%d,%d,%d,%d\n", module11_test(), module12_test(), module21_test(), module22_test()); printf("driver test:%d,%d\n", driver11_test(), driver12_test()); pthread_t pid; pthread_create(&pid, NULL, func, NULL); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <zmq.hpp> #if 0 int main(int argc, char const *argv[]) { zmq::context_t zmq_ctx(1); zmq::socket_t socket(zmq_ctx, ZMQ_REP); socket.bind("tcp://*:5560"); while (true) { zmq::message_t request; socket.recv(&request); puts((const char *)request.data()); zmq::message_t reply(5); memcpy((void *)reply.data(), "world", 5); socket.send(reply); } return 0; } #else // 向socket发送数据, 数据为string static int s_send(void *socket, char *string); // 从socket接收数据, 并将数据以字符串的形式返回 static char *s_recv(void *socket); int main() { int rc; // 1.初始化上下文 void *context = zmq_ctx_new(); // 2.创建套接字、连接代理的DEALER端 void *responder = zmq_socket(context, ZMQ_REP); rc = zmq_connect(responder, "tcp://localhost:5560"); if(rc == -1) { perror("zmq_connect"); zmq_close(responder); zmq_ctx_destroy(context); return -1; } // 3.循环接收、响应 while(1) { // 4.先等待接收数据 char *request = s_recv(responder); if(request == NULL) { perror("s_recv"); free(request); zmq_close(responder); zmq_ctx_destroy(context); return -1; } printf("Request: %s\n", request); free(request); // 休眠1秒再进行响应 sleep(1); // 5.响应 rc = s_send(responder, "World"); if(rc < 0) { perror("s_send"); zmq_close(responder); zmq_ctx_destroy(context); return -1; } } // 6.关闭套接字、销毁上下文 zmq_close(responder); zmq_ctx_destroy(context); return 0; } static int s_send(void *socket, char *string) { int rc; zmq_msg_t msg; zmq_msg_init_size(&msg, 5); memcpy(zmq_msg_data(&msg), string, strlen(string)); rc = zmq_msg_send(&msg, socket, 0); zmq_msg_close(&msg); return rc; } static char *s_recv(void *socket) { int rc; zmq_msg_t msg; zmq_msg_init(&msg); rc = zmq_msg_recv(&msg, socket, 0); if(rc == -1) return NULL; char *string = (char*)malloc(rc + 1); memcpy(string, zmq_msg_data(&msg), rc); zmq_msg_close(&msg); string[rc] = 0; return string; } #endif<file_sep>// 观察者模式 -- 可以理解为发布-订阅模式 // 观察者(Observer)模式的定义:指多个对象间存在一对多的依赖关系, // 当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。 // 这种模式有时又称作发布-订阅模式、模型-视图模式,它是对象行为型模式。 /* 【例1】利用观察者模式设计一个程序,分析“人民币汇率”的升值或贬值对进口公司的进口产品成本或出口公司的出口产品收入以及公司的利润率的影响。 【例2】利用观察者模式设计一个学校铃声的事件处理程序。 */ #include "observer.h" #include "subject.h" int main() { ConcreteSubject *subject = new ConcreteSubject(); // 被观察者类 Observer *obA = new ConcreteObserverA("observerA", -1); // 观察者A Observer *obB = new ConcreteObserverB("observerB", -1); // 观察者B // 添加观察者 subject->Attach(obA); subject->Attach(obB); subject->SetState(0); subject->Notify(); subject->SetState(1); subject->Notify(); subject->Detach(obA); subject->SetState(0); subject->Notify(); delete obA; delete obB; delete subject; return 0; } // 输出结果: // observerA update state :0 // observerB update state :0 // observerA update state :1 // observerB update state :1 // observerB update state :0<file_sep>#ifndef _HANDLER_H_ #define _HANDLER_H_ #include <iostream> #include <list> #include <string> #include <algorithm> using namespace std; /* 责任链模式 有很多的对象可以处理请求, 但是用户并不感知是那个对象处理了他的请求。 */ //抽象类 class Handler { public: virtual void handleRequest(string number) = 0; virtual void setNextHandler(Handler *handler) = 0; }; //具体处理者1 class Beijing : public Handler { public: Beijing(); void handleRequest(string number) override; void setNextHandler(Handler *handler) override; private: Handler *myHandler; list<string> numberList; }; //具体处理者2 class Shanghai : public Handler { public: Shanghai(); void handleRequest(string number) override; void setNextHandler(Handler *handler) override; private: Handler *myHandler; list<string> numberList; }; //具体处理者3 class Tianjin : public Handler { public: Tianjin(); void handleRequest(string number) override; void setNextHandler(Handler *handler) override; private: Handler *myHandler; list<string> numberList; }; //具体处理者4 class Guangdong : public Handler { public: Guangdong(); void handleRequest(string number) override; void setNextHandler(Handler *handler) override; private: Handler *myHandler; list<string> numberList; }; #endif<file_sep>/* 所谓贪心算法是指,在对问题求解时,总是做出在 当前看来是最好的选择 。 也就是说,不从整体最优上加以考虑,他所做出的仅是在某种意义上的 局部最优解 。 1.建立数学模型来描述问题。 2.把求解的问题分成若干个子问题。 3.对每一子问题求解,得到子问题的局部最优解。 4.把子问题的解局部最优解合成原来解问题的一个解。 */ #include <stdio.h> int main(int argc, char const *argv[]) { return 0; } <file_sep>CC = gcc CXX = g++ D = SRCS += $(wildcard *.cpp) OBJS += $(patsubst %.cpp, %.o, $(SRCS)) TARGETS += $(SRCS:%.cpp=%) INCLUDE += -I$(PWD)/../../opencv-4.5.0/include/opencv4 LIB_PATH = -L$(PWD)/../../opencv-4.5.0/lib LIB_LINK += -lopencv_core -lopencv_highgui -lopencv_imgcodecs \ -lopencv_videoio -lopencv_video -lopencv_imgproc CFLAGS += -g -Wall -std=c++11 all:$(TARGETS) $(TARGETS):%:%.o $(CXX) $^ -o $@ $(INCLUDE) $(LIB_PATH) $(LIB_LINK) $(CFLAGS) # @rm -rf $(OBJS) %.o:%.cpp $(CXX) -c $< -o $@ $(CFLAGS) $(INCLUDE) .PHONY: clean clean: @rm -rf $(TARGETS) $(OBJS) D: gcc $(demo) -o $(demo) $(INCLUDE) $(LIB_PATH) $(LIB_LINK) $(CFLAGS)<file_sep>#include <iostream> #include <vector> #include <string> #include <unistd.h> int main(int argc, char const *argv[]) { const std::string path{ "./" }; const std::vector<std::string> files {"test", "Makefile", "thread.cpp", "thread.cpp"}; for (auto& name : files) { const std::string tmp = path + name; fprintf(stdout, "file or directory name: \"%s\": ", name.c_str()); if (access(tmp.c_str(), 0) == 0) fprintf(stdout, "exist, "); else fprintf(stdout, "not exist, "); if (access(tmp.c_str(), 4) == 0) fprintf(stdout, "has read premission, "); else fprintf(stdout, "does not have read premission, "); if (access(tmp.c_str(), 2) == 0) fprintf(stdout, "has write premission, "); else fprintf(stdout, "does not have write premission, "); if (access(tmp.c_str(), 6) == 0) fprintf(stdout, "has both read and write premission\n"); else fprintf(stdout, "has neither read nor write premission\n"); } return 0; } <file_sep>#include <iostream> #include "Singleton.hpp" class Test { public: void run() { std::cout << "Singleton test" << std::endl; } }; int main(int argc, char const *argv[]) { Singleton<Test>::getInstance()->run(); Singleton<Test>::releaseSingletonAddress(); return 0; } <file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <libxml/xmlmemory.h> #include <libxml/parser.h> /* 解析storyinfo节点,打印keyword节点的内容 */ void parseStory(xmlDocPtr doc, xmlNodePtr cur) { xmlChar *key; cur = cur->xmlChildrenNode; while (cur != NULL) { /* 找到keyword子节点 */ if (!xmlStrcmp(cur->name, (const xmlChar *)"keyword")) { key = xmlNodeListGetString(doc, cur->xmlChildrenNode, 1); printf("keyword: %s\n", key); xmlFree(key); } cur = cur->next; /* 下一个子节点 */ } return; } /* 解析文档 */ static void parseDoc(char *docname) { /* 定义文档和节点指针 */ xmlDocPtr doc; xmlNodePtr cur; /* 进行解析,如果没成功,显示一个错误并停止 */ doc = xmlParseFile(docname); if (doc == NULL) { fprintf(stderr, "Document not parse successfully. \n"); return; } /* 获取文档根节点,若无内容则释放文档树并返回 */ cur = xmlDocGetRootElement(doc); if (cur == NULL) { fprintf(stderr, "empty document\n"); xmlFreeDoc(doc); return; } /* 确定根节点名是否为story,不是则返回 */ if (xmlStrcmp(cur->name, (const xmlChar *)"story")) { fprintf(stderr, "document of the wrong type, root node != story"); xmlFreeDoc(doc); return; } /* 遍历文档树 */ cur = cur->xmlChildrenNode; while (cur != NULL) { /* 找到storyinfo子节点 */ if (!xmlStrcmp(cur->name, (const xmlChar *)"storyinfo")) { parseStory(doc, cur); /* 解析storyinfo子节点 */ } cur = cur->next; /* 下一个子节点 */ } xmlFreeDoc(doc); /* 释放文档树 */ return; } int main(int argc, char **argv) { char *docname; if (argc <= 1) { printf("Usage: %s docname\n", argv[0]); return 0; } docname = argv[1]; parseDoc(docname); return (0); }<file_sep>#include "Uuid.h" #include <string.h> #include <iostream> namespace Utils{ char *UUID::uuidStr = new char[37]; char* UUID::Generate(uuid_t *uuid) { uuid_t __uuid; uuid_generate(__uuid); uuid_unparse(__uuid, uuidStr); if (uuid) { strcpy((char *)uuid, (const char *)&__uuid); } return uuidStr; } char* UUID::GenerateLower(uuid_t *uuid) { uuid_t __uuid; uuid_generate_random(__uuid); uuid_unparse_lower(__uuid, uuidStr); if (uuid) { strcpy((char *)uuid, (const char *)&__uuid); } return uuidStr; } char* UUID::GenerateUpper(uuid_t *uuid) { uuid_t __uuid; uuid_generate_time(__uuid); uuid_unparse_upper(__uuid, uuidStr); if (uuid) { strcpy((char *)uuid, (const char *)&__uuid); } return uuidStr; } int UUID::Type(uuid_t &uuid) { return uuid_type(uuid); } int UUID::Variant(uuid_t &uuid) { return uuid_variant(uuid); } int UUID::Compare(uuid_t &uuid1, uuid_t &uuid2) { return uuid_compare(uuid1, uuid2); } time_t UUID::Time(uuid_t &uuid) { struct timeval tv; time_t time_reg = uuid_time(uuid, &tv); #ifdef DEBUG fprintf(stdout, "uuid time: (%ld, %ld): %s\n", tv.tv_sec, tv.tv_usec, ctime(&time_reg)); #endif return time_reg; } void UUID::Clear(uuid_t &uuid) { uuid_clear(uuid); } bool UUID::isNull(uuid_t &uuid) { return uuid_is_null(uuid); } int UUID::Test(const char * uuidStr, int isValid) { #ifdef DEBUG static const char * validStr[2] = {"invalid", "valid"}; #endif uuid_t uuidBits; int parsedOk; parsedOk = uuid_parse(uuidStr, uuidBits) == 0; #ifdef DEBUG printf("%s is %s .", uuidStr, validStr[isValid]); #endif if (parsedOk != isValid) { #ifdef DEBUG printf(" says %s\n", validStr[parsedOk]); #endif return -1; } return 0; } } int main(int argc, char const *argv[]) { std::cout << Utils::UUID::Generate() << std::endl; std::cout << Utils::UUID::GenerateLower() << std::endl; std::cout << Utils::UUID::GenerateUpper() << std::endl; return 0; } <file_sep># CBase C语言基础 # CppBase C++基础 # DataStruct 数据结构 # DesignPattern C++设计模式 # EnginManager 工程管理 # ThirdParty 第三方库使用demo # Utils <file_sep># CMake 最低版本号要求 cmake_minimum_required (VERSION 2.8) # 项目信息 project(demo) # 指定生成目标 add_executable(demo demo.cpp)<file_sep>#include <stdio.h> //@CallbackFun 指向函数的指针类型 typedef void (*CallbackFun)(double height, void *contex); CallbackFun m_pCallback; //1.定义函数onHeight(回调函数) void onHeight(double height, void *contex) { if (contex != NULL) { int *num = (int*)(contex); printf("contex is %d", *num); } printf("current height is %lf", height); } //@registHeightCallback 注册函数名 void RegistCallback(CallbackFun callback) { m_pCallback = callback; } void printHeightFun(double height) { int num = 5; m_pCallback(height, (void*)&num); } int main() { //注册onHeight函数,即通过registHeightCallback的参数将onHeight函数指针 RegistCallback(onHeight); double h = 99; printHeightFun(99); return 0; }<file_sep>#include <iostream> #include <stdlib.h> #include "zlib.h" using namespace std; #define MaxBufferSize 1024 * 10 int main() { FILE *File_src; FILE *File_tmp; FILE *File_dest; unsigned long len_src; unsigned long len_tmp; unsigned long len_dest; unsigned char *buffer_src = new unsigned char[MaxBufferSize]; unsigned char *buffer_tmp = new unsigned char[MaxBufferSize]; unsigned char *buffer_dest = new unsigned char[MaxBufferSize]; File_src = fopen("src.txt", "r"); len_src = fread(buffer_src, 1, MaxBufferSize - 1, File_src); fclose(File_src); // 压缩 compress2(buffer_tmp, &len_tmp, buffer_src, len_src, MAX_MEM_LEVEL); File_tmp = fopen("tmp.txt", "w"); fwrite(buffer_tmp, 1, len_tmp, File_tmp); fclose(File_tmp); // 解压 uncompress(buffer_dest, &len_dest, buffer_tmp, len_tmp); File_dest = fopen("dest.txt", "w"); fwrite(buffer_dest, 1, len_dest, File_dest); fclose(File_dest); delete[] buffer_src; delete[] buffer_tmp; delete[] buffer_dest; return 0; }<file_sep>// 约瑟夫 --- 数3出局 #include <stdio.h> #include <stdlib.h> typedef struct Josephus { int data; struct Josephus *next; }node; node *create(int n) { node *p = NULL, *head; head = (node *)malloc(sizeof(node)); p = head; node *s; int i = 1; if (0 != n) { while (i <= n) { s = (node *)malloc(sizeof(node)); s->data = i++; p->next = s; p = s; } s->next = head->next;// 循环链表 } free(head); return s->next; } int main(int argc, char const *argv[]) { int i; int n = 41; int m = 3; node *p = create(n); node *tmp; m = n % m; while (p != p->next) { for (i = 1; i < m; i++) { p = p->next; } printf("%d->", p->next->data); tmp = p->next; p->next = tmp->next; free(tmp); p = p->next; } printf("%d->", p->data); return 0; } <file_sep># CMake 最低版本号要求 cmake_minimum_required (VERSION 2.8) # 项目信息 project (demo) # 工程版本号 set (VERSION_MAJOR 1) set (VERSION_MINOR 0) # 加入一个配置头文件,用于处理 CMake 对源码的设置 configure_file ( "${PROJECT_SOURCE_DIR}/config.h.in" "${PROJECT_SOURCE_DIR}/config.h" ) # 是否使用自己的 calc 库 option (USE_MYMATH "Use provided math implementation" OFF) option (DEBUG "Use debug for gdb" OFF) if (DEBUG) # 调试 set(CMAKE_BUILD_TYPE "Debug") set(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g -ggdb") else () # release版本优化编译 set(CMAKE_CXX_FLAGS_RELEASE "$ENV{CXXFLAGS} -O3 -Wall") endif (DEBUG) # 是否加入 calc 库 if (USE_MYMATH) include_directories ("${PROJECT_SOURCE_DIR}/math") add_subdirectory (math) set (EXTRA_LIBS ${EXTRA_LIBS} calc) endif (USE_MYMATH) # 查找当前目录下的所有源文件 # 并将名称保存到 DIR_SRCS 变量 aux_source_directory(. DIR_SRCS) # 指定生成目标 add_executable(demo ${DIR_SRCS}) target_link_libraries (demo ${EXTRA_LIBS}) # 指定安装路径 install (TARGETS demo DESTINATION bin) install (FILES "${PROJECT_SOURCE_DIR}/config.h" DESTINATION include)<file_sep>#include <iostream> #include "libxml/parser.h" #include "libxml/tree.h" using namespace std; int main(int argc, char *argv[]) { //定义文档指针 xmlDocPtr doc = xmlNewDoc(BAD_CAST "1.0"); //定义节点指针 xmlNodePtr root_node = xmlNewNode(NULL, BAD_CAST "root"); //设置根节点 xmlDocSetRootElement(doc, root_node); //在根节点中直接创建节点 xmlNewTextChild(root_node, NULL, BAD_CAST "newNode1", BAD_CAST "newNode1 content"); xmlNewTextChild(root_node, NULL, BAD_CAST "newNode2", BAD_CAST "newNode2 content"); xmlNewTextChild(root_node, NULL, BAD_CAST "newNode3", BAD_CAST "newNode3 content"); //创建一个节点,设置其内容和属性,然后加入根结点 xmlNodePtr node = xmlNewNode(NULL, BAD_CAST "node2"); xmlNodePtr content = xmlNewText(BAD_CAST "NODE CONTENT"); xmlAddChild(root_node, node); xmlAddChild(node, content); xmlNewProp(node, BAD_CAST "attribute", BAD_CAST "yes"); //创建一个儿子和孙子节点 node = xmlNewNode(NULL, BAD_CAST "son"); xmlAddChild(root_node, node); xmlNodePtr grandson = xmlNewNode(NULL, BAD_CAST "grandson"); xmlAddChild(node, grandson); xmlAddChild(grandson, xmlNewText(BAD_CAST "This is a grandson node")); //存储xml文档 int nRel = xmlSaveFormatFile("create_xml.xml", doc, XML_DOC_HTML); // int nRel = xmlSaveFile("create_xml.xml", doc); if (nRel != -1) { cout << "create_xml文档被创建,写入" << nRel << "个字节" << endl; } //释放文档内节点动态申请的内存 xmlFreeDoc(doc); return 0; }<file_sep>#include <iostream> #include <gflags/gflags.h> #include <glog/logging.h> // ./gflags_test -help // 1 2 3 // FLAGS_gray 默认值 帮助信息 DEFINE_bool(gray, false, "When this option is on, treat images as grayscale ones"); DEFINE_int32(resize_width, 0, "Width images are resized to"); DEFINE_int64(resize_height, 0, "Height images are resized to"); DEFINE_string(encode_type, "222", "Optional: What type should we encode the image as ('png','jpg',...)."); // 在另一文件使用,澄清 // DECLARE_string(encode_type); // ./gflags_test -encode_type=123456 传参 int main(int argc, char const *argv[]) { // 初始化日志库 ::google::InitGoogleLogging(argv[0]); // 输出到文件 FLAGS_logtostderr = 0; //是否打印到控制台 FLAGS_alsologtostderr = 0; //打印到日志同时是否打印到控制台 ::google::SetLogDestination(google::GLOG_INFO, "log-");// 输出到文件 //下面设置帮助信息 // bool类型特殊 ::google::SetUsageMessage("gray --encode_type=yuv --resize_width=200 --resize_height=200 ...\n"); //解析命令行参数,参数true时,解析完参数后argc=1,argv只保留了argv[0] //参数flase时,解析完参数后argc个数不变,argv顺序会变化 ::google::ParseCommandLineFlags(&argc, const_cast<char ***>(&argv), true); // if (argc < 4) { //如果参数个数小于指定值,显示帮助信息 // ::google::ShowUsageWithFlagsRestrict(argv[0], "tools/convert_imageset"); // return 1; // } //参数的使用 const bool is_gray = FLAGS_gray; const int32_t resize_width = FLAGS_resize_width; const int64_t resize_height = FLAGS_resize_height; const std::string encode_type = FLAGS_encode_type; LOG(ERROR) << is_gray << ":" << resize_width << ":" << resize_height << ":" << encode_type; LOG(INFO) << "Hello, World!"; return 0; } <file_sep>#include <iostream> #include <typeinfo> using namespace std; template <class T> void f2(T &&t) { const type_info &t0 = typeid(t); const type_info &t1 = typeid(int); cout << (t0.name() == t1.name()) << ":" << t << endl; } template <class T> void f3(T &&val) { T t = val; } template <class F, class T1, class T2> void flip(F f, T1&& t1, T2&& t2) { f(forward<T2>(t2), forward<T1>(t1)); } int main(int argc, char const *argv[]) { int num = 10; // int && a = num; //右值引用不能初始化为左值 int &&a = 10; a = 100; cout << a << endl; int i = 0; const int ci = 2; f2(move(i)); //i是一个int,模板参数类型T是int,因为非const可以转化为const f2(ci); //ci是一个const int,模板参数T是int f2(5); f3(i); f3(ci); f3(5); return 0; } <file_sep>/* 共享内存 */ #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess/mapped_region.hpp> #include <iostream> void test1() { boost::interprocess::shared_memory_object shdmem(boost::interprocess::open_or_create, "Highscore", boost::interprocess::read_write); shdmem.truncate(1024); std::cout << shdmem.get_name() << std::endl; boost::interprocess::offset_t size; if (shdmem.get_size(size)) { std::cout << size << std::endl; } } void test2() { boost::interprocess::shared_memory_object shdmem(boost::interprocess::open_or_create, "Highscore", boost::interprocess::read_write); shdmem.truncate(1024); boost::interprocess::mapped_region region(shdmem, boost::interprocess::read_write); std::cout << std::hex << "0x" << region.get_address() << std::endl; std::cout << std::dec << region.get_size() << std::endl; boost::interprocess::mapped_region region2(shdmem, boost::interprocess::read_only); std::cout << std::hex << "0x" << region2.get_address() << std::endl; std::cout << std::dec << region2.get_size() << std::endl; } void test3() { boost::interprocess::shared_memory_object shdmem(boost::interprocess::open_or_create, "Highscore", boost::interprocess::read_write); shdmem.truncate(1024); boost::interprocess::mapped_region region(shdmem, boost::interprocess::read_write); char *i1 = static_cast<char *>(region.get_address()); strcpy(i1, "123124jkdjvskdlvjsdkljgskdlgjskldgjsdklgjsl"); boost::interprocess::mapped_region region2(shdmem, boost::interprocess::read_only); char *i2 = static_cast<char *>(region2.get_address()); std::cout << i2 << std::endl; // 如果 remove() 没有被调用, 那么,即使进程终止,共享内存还会一直存在 bool removed = boost::interprocess::shared_memory_object::remove("Highscore"); std::cout << removed << std::endl; } int main() { test3(); return 0; } <file_sep>/* 字符串操作 */ #include <iostream> #include <locale> #include <clocale> #include <cstring> #include <vector> #include "boost/algorithm/string.hpp" #include "boost/algorithm/string/regex.hpp" // 全局区域设置可以使用类 std::locale 中的静态函数 global() 改变 void test1() { std::locale loc; std::cout << loc.name() << std::endl; std::cout << std::strcoll("ä", "z") << std::endl; // 73, 字符串比较 == strcmp std::locale::global(std::locale("en_US.UTF-8")); std::cout << std::strcoll("ä", "z") << std::endl; // -25 std::cout << loc.name() << std::endl; } // Boost.StringAlgorithms void test2() { std::setlocale(LC_ALL, "en_US.UTF-8"); std::string s = "<NAME>"; // 不改变源数据 std::cout << boost::algorithm::to_upper_copy(s) << std::endl; // BORIS SCHäLING std::cout << boost::algorithm::to_lower_copy(s, std::locale("C")) << std::endl; // boris schäling // 改变源数据 std::cout << s << std::endl; // Boris Schäling boost::algorithm::to_upper(s); std::cout << s << std::endl; // BORIS SCHäLING boost::algorithm::to_lower(s, std::locale("C")); std::cout << s << std::endl; // boris schäling } void test3() { std::locale::global(std::locale("en_US.UTF-8")); std::string s = "<NAME>iling 0 "; // 去除copy修改源数据 std::cout << "erase_first_copy-->" << boost::algorithm::erase_first_copy(s, "i") << std::endl; std::cout << "erase_nth_copy-->" << boost::algorithm::erase_nth_copy(s, "i", 0) << std::endl; std::cout << "erase_last_copy-->" << boost::algorithm::erase_last_copy(s, "i") << std::endl; std::cout << "erase_all_copy-->" << boost::algorithm::erase_all_copy(s, "i") << std::endl; std::cout << "erase_head_copy-->" << boost::algorithm::erase_head_copy(s, 5) << std::endl; std::cout << "erase_tail_copy-->" << boost::algorithm::erase_tail_copy(s, 8) << std::endl; } void test4() { std::string s = "<NAME>"; boost::iterator_range<std::string::iterator> r = boost::algorithm::find_first(s, "Boris"); std::cout << r << std::endl; r = boost::algorithm::find_first(s, "xyz"); std::cout << r << std::endl; } void test5() { std::vector<std::string> v; v.push_back("Boris"); v.push_back("Schäling"); v.push_back("test"); std::cout << boost::algorithm::join(v, " ") << std::endl; std::cout << boost::algorithm::join(v, "++") << std::endl; } void test6() { std::string s = "<NAME>"; std::cout << boost::algorithm::replace_first_copy(s, "B", "D") << std::endl; std::cout << boost::algorithm::replace_nth_copy(s, "B", 0, "D") << std::endl; std::cout << boost::algorithm::replace_last_copy(s, "B", "D") << std::endl; std::cout << boost::algorithm::replace_all_copy(s, "B", "D") << std::endl; std::cout << boost::algorithm::replace_head_copy(s, 5, "Doris") << std::endl; std::cout << boost::algorithm::replace_tail_copy(s, 8, "Becker") << std::endl; } void test7() { // std::string s = "\t <NAME> \t"; // std::cout << "." << boost::algorithm::trim_left_copy(s) << "." << std::endl; // std::cout << "." << boost::algorithm::trim_right_copy(s) << "." << std::endl; // std::cout << "." << boost::algorithm::trim_copy(s) << "." << std::endl; std::string s = "--<NAME>--"; std::cout << "." << boost::algorithm::trim_left_copy_if(s, boost::algorithm::is_any_of("-")) << "." << std::endl; std::cout << "." << boost::algorithm::trim_right_copy_if(s, boost::algorithm::is_any_of("-")) << "." << std::endl; std::cout << "." << boost::algorithm::trim_copy_if(s, boost::algorithm::is_any_of("-")) << "." << std::endl; std::string str = "123456789<NAME>123456789"; std::cout << "." << boost::algorithm::trim_left_copy_if(str, boost::algorithm::is_digit()) << "." << std::endl; std::cout << "." << boost::algorithm::trim_right_copy_if(str, boost::algorithm::is_digit()) << "." << std::endl; std::cout << "." << boost::algorithm::trim_copy_if(str, boost::algorithm::is_digit()) << "." << std::endl; } void test8() { std::string s = "<NAME>"; std::cout << boost::algorithm::starts_with(s, "Boris") << std::endl; std::cout << boost::algorithm::ends_with(s, "Schäling") << std::endl; std::cout << boost::algorithm::contains(s, "is") << std::endl; std::cout << boost::algorithm::lexicographical_compare(s, "Boris") << std::endl; // 0表示字串存在与s } void test9() { std::string s = "<NAME>"; std::vector<std::string> v; boost::algorithm::split(v, s, boost::algorithm::is_space()); // 以空格为裁剪依据,得到《Boris》《Schäling》 std::cout << v.size() << std::endl; } void test10() { std::string s = "<NAME>"; boost::iterator_range<std::string::iterator> r = boost::algorithm::find_regex(s, boost::regex("\\w\\s\\w")); std::cout << r << std::endl; } int main(int argc, char const *argv[]) { test10(); return 0; } <file_sep>#include <stdio.h> typedef void (*UnityTestFunction)(void); #define RUN_TEST(func) UnityDefaultTestRun(func, #func, __LINE__) void UnityDefaultTestRun(UnityTestFunction Func, const char* FuncName, const int FuncLineNum) { printf("FuncName = %s, FuncLineNum = %d\n", FuncName, FuncLineNum); Func(); } void test() { printf("222222222222222\n"); } int main(int argc, char const *argv[]) { RUN_TEST(test); return 0; } <file_sep>/******************************************************************** * 多种排序函数头文件 * ******************************************************************** * void bubbling_sort(int a[], int n); 冒泡排序 * * void insert_sort(int a[], int n); 插入排序 * * void select_sort(int a[], int n); 选择排序 * * void Quick_Sort(int arr[], int start, int end); 快速排序 * ********************************************************************/ #ifndef _MY_SORT_H #define _MY_SORT_H /*参数说明 * 冒泡排序 ****************************** * a ----待排序数组 * n ----数组长度 ******************************/ void Bubbling_Sort(int a[], int n) { int i, j; int tmp; for (i = 0; i < n-1; i++) { for (j = 0; j < n-1-i; j++) { if (a[j] > a[j+1]) { tmp = a[j]; a[j] = a[j+1]; a[j+1] = tmp; } } } } /*参数说明 * 插入排序 ****************************** * a ----待排序数组 * n ----数组长度 ******************************/ void Insert_Sort(int a[], int n) { int i, j; int tmp; for (i = 1; i < n; i++) { tmp = a[i]; j = i; while(tmp < a[j-1]) { a[j] = a[j-1]; j--; if (j <= 0) break; } a[j] = tmp; } } /*参数说明 * 选择排序 ******************************** * a ----待排序数组 * n ----数组长度 ********************************/ void Select_Sort(int a[], int n) { int tmp, min; for (int i = 0; i < n-1; i++) { min = i; for(int j = i+1; j < n; j++) if (a[j] < a[min]) min = j;//获取最小数的下标 if(i != min) { tmp = a[i]; a[i] = a[min]; a[min] = tmp; } } } /*参数说明 * 快速排序 ************************************* * arr ----待排序数组 * start --需排序的开始位置 * end ----需排序的结束位置 *************************************/ void Quick_Sort(int arr[], int start, int end) { if (start >= end) return; int i = start; int j = end; int baseval = arr[start]; // 基准数 while (i < j) { // 从右向左找比基准数小的数 while (i < j && arr[j] >= baseval) j--; if (i < j) { arr[i] = arr[j]; i++; } // 从左向右找比基准数大的数 while (i < j && arr[i] < baseval) i++; if (i < j) { arr[j] = arr[i]; j--; } } // 把基准数放到i的位置 arr[i] = baseval; // 递归 Quick_Sort(arr, start, i - 1); //分组好的两部分分别再次使用快速排序 Quick_Sort(arr, i + 1, end); } #endif<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #define DEBUG // KMP static void __kmp_test(const unsigned char *P, unsigned int *T) { unsigned int i = 0; unsigned len = strlen(P); printf("i:\tP[i]\tT[i]\n"); while (i < len) { printf("%d:\t%c\t%d\n", i, P[i], T[i]); i++; } } void __get_next(int next[], unsigned char *p) { int left = -1; int right = 0; next[0] = -1; int len = strlen(p); while(right < len) { if(left == -1 || p[right] == p[left]) { left++;right++; next[right] = left; } else left = next[left]; } } int __index_KMP(unsigned char *src, unsigned char *dst, int pos[]) { int i = 0, j = 0; int num = 0, search_flag = 0; int slen = strlen(src); int dlen = strlen(dst); int next[slen]; __get_next(next, src); #ifdef DEBUG __kmp_test(src, next); #endif while(i < slen /*&& j < dlen*/) { if(j == -1 || src[i] == dst[j]) { i++; j++; } else j = next[j]; //j回退 if(j >= dlen) { pos[num++] = (i - dlen); search_flag = 1; } } if (search_flag) return num; else return (-1); } int main(int argc, char const *argv[]) { int posArr[32] = {0}; unsigned char *s = "DAB"; unsigned char *str = "ABC ABCDAB ABCDABCDABDE"; // 0000123012012301230120 int num = __index_KMP(str, s, posArr); printf("have %d child\n", num); for (int i = 0; i < num; i++) { printf("child[%d] index: %d\n", i, posArr[i]); } return 0; } <file_sep>#include <stdio.h> #include <stdbool.h> #include <string.h> static int g_count = 0; int noDanger(int row, int col, int (*chess)[8]) { int i, j; //判断每一列是否有皇后 for (i = 0; i < 8; i++) { if (chess[i][col] == 1) return 0; } int plus, minus; plus = row + col;//同一条右斜线上点特点 横纵坐标和相同 minus = row - col;//同一条左斜线上点的特点 横纵坐标差相同 for (i = 0; i < 8; i++) { for (j = 0; j < 8; j++) { if ((i + j == plus || i - j == minus) && chess[i][j] == 1) return 0; } } return 1; } void EightQueen(int row, int col, int (*ppChess)[8]) { int i, j; int chess[8][8]; // 赋值上一次放置皇后的棋盘 for (i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { chess[i][j] = ppChess[i][j]; } } if (row == 8) {// 计数 g_count++; } else { for (j = 0; j < col; j++) //遍历 ROW 行的每一个元素 进行判断 if (noDanger(row, j, ppChess)) { for (i = 0; i < 8; i++) { *(*(chess + row) + i) = 0; } *(*(chess + row) + j) = 1; EightQueen(row + 1, col, chess); //向下一行遍历 } } } int main(int argc, char const *argv[]) { int i, j; int chess[8][8] = {0}; EightQueen(0, 8, chess); printf("%d\n", g_count); return 0; } <file_sep>#include <iostream> #include <memory> // std::addressof // ************************************* // class codebreaker { public: int operator&() const { // 当重载时,打印&c不能输出地址,只能通过std::addressof() return 13; } }; int test_addressof_1() { codebreaker c; std::cout << "&c: " << (&c) << '\n'; std::cout << "addressof(c): " << std::addressof(c) << '\n'; return 0; } // ************************************* // class Buffer { private: static const size_t buffer_size = 256; int bufferId; // 80x7ffdc6fcf110 -- std::addressof char buffer[buffer_size];// 80x7ffdc6fcf114 -- &this public: Buffer(int bufferId_) : bufferId(bufferId_) {} Buffer* operator&() { return reinterpret_cast<Buffer*> (&buffer); } }; template<typename T> void getAddress(T t) { std::cout << "Address returned by & operator: " << std::ios::hex << &t << "\n"; // 80x7ffdc6fcf114 std::cout << "Address returned by addressof: " << std::ios::hex << std::addressof(t) << "\n";// 80x7ffdc6fcf110 } int test_addressof_2() { int a = 3; fprintf(stderr, "a &: %p, address of: %p\n", &a, std::addressof(a));// 输出一样的地址 Buffer b(1); std::cout << "Getting the address of a Buffer type: \n"; getAddress(b); return 0; } int main(int argc, char const *argv[]) { test_addressof_2(); return 0; } <file_sep>CC = gcc CXX = g++ SRCS := $(wildcard *.c) OBJS := $(patsubst %.c, %.o, $(SRCS)) TARGETS := $(SRCS:%.c=%) INCLUDE := LIB_PATH := LIB_LINK := -ldl CFLAGS := -g -Wall all:$(TARGETS) $(TARGETS):%:%.o $(CC) $^ -o $@ $(INCLUDE) $(LIB_PATH) $(LIB_LINK) $(CFLAGS) # @rm -rf $(OBJS) %.o:%.c $(CC) -c $< -o $@ $(CFLAGS) $(INCLUDE) .PHONY: clean clean: @rm -rf $(TARGETS) $(OBJS)<file_sep>#pragma once #ifndef _QUEUE_H #define _QUEUE_H #include "huffman.h" #define TYPE htNode * #define MAX_SZ 256 //(按频率排序的)队列结点 typedef struct _pQueueNode { TYPE val; unsigned int probability; struct _pQueueNode *next; }pQueueNode; //队列 typedef struct _pQueue { unsigned int size; pQueueNode *first; }pQueue; //初始化huffman队列 void initPQueue(pQueue **queue); //二级指针*****// //增加结点到队列 void addPQueue(pQueue **queue, TYPE val, unsigned int priority); //获取队列中第一个(出现频率值probability最小的)结点 TYPE getPQueue(pQueue **queue); #endif <file_sep>#include <stdio.h> #include <stdlib.h> #include "include/uuid/uuid.h" static int test_uuid(const char * uuid, int isValid) { static const char * validStr[2] = {"invalid", "valid"}; uuid_t uuidBits; int parsedOk; parsedOk = uuid_parse(uuid, uuidBits) == 0; printf("%s is %s", uuid, validStr[isValid]); if (parsedOk != isValid) { printf(" but uuid_parse says %s\n", validStr[parsedOk]); return 1; } printf(", OK\n"); return 0; } int test_libuuid() { uuid_t uuid1, uuid2, uuid3, uuid4, uuid5; char uuid1_str[37], uuid2_str[37], uuid3_str[37], uuid4_str[37]; uuid_generate(uuid1); uuid_unparse(uuid1, uuid1_str); fprintf(stdout, "uuid1 result: %s\n", uuid1_str); uuid_generate_random(uuid2); uuid_unparse_lower(uuid2, uuid2_str); fprintf(stdout, "uuid2 result: %s\n", uuid2_str); // 字母全部大写 uuid_generate_time(uuid3); uuid_unparse_upper(uuid3, uuid3_str); fprintf(stdout, "uuid3 result: %s\n", uuid3_str); uuid_generate_time_safe(uuid4); uuid_unparse(uuid4, uuid4_str); fprintf(stdout, "uuid4 result: %s\n", uuid4_str); uuid_parse(uuid1_str, uuid5); int ret = uuid_compare(uuid1, uuid5); fprintf(stdout, "uuid1 compare uuid5: %d\n", ret); ret = uuid_is_null(uuid1); fprintf(stdout, "uuid1 is null: %d\n", ret); uuid_clear(uuid1); ret = uuid_is_null(uuid1); fprintf(stdout, "uuid1 is null: %d\n", ret); ret = uuid_type(uuid2); fprintf(stdout, "uuid2 type: %d\n", ret); ret = uuid_variant(uuid2); fprintf(stdout, "uuid2 variant: %d\n", ret); // 获取生成的详细时间日期 struct timeval tv; time_t time_reg = uuid_time(uuid3, &tv); fprintf(stdout, "uuid3 time is: (%ld, %ld): %s\n", tv.tv_sec, tv.tv_usec, ctime(&time_reg)); return 0; } int main(int argc, char *argv[]) { test_libuuid(); return 0; } <file_sep>#pragma once int module22_test(void);<file_sep>#ifndef __UUID__ #define __UUID__ #include "uuid/uuid.h" // #define DEBUG namespace Utils{ class UUID { public: static char* Generate(uuid_t *uuid = NULL); static char* GenerateLower(uuid_t *uuid = NULL); static char* GenerateUpper(uuid_t *uuid = NULL); static int Type(uuid_t &uuid); static int Variant(uuid_t &uuid); static int Compare(uuid_t &uuid1, uuid_t &uuid2); static void Clear(uuid_t &uuid); static bool isNull(uuid_t &uuid); static time_t Time(uuid_t &uuid); static int Test(const char* uuidStr, int isValid); private: UUID() {} ~UUID() {} UUID(const UUID &uuid) {}; static char *uuidStr; }; } #endif<file_sep>int module21_test(void) { return 21; } <file_sep>// observer.h #include <iostream> #include <string> #include <vector> using namespace std; typedef int State; class Subject; // 观察者抽象 class Observer { public: Observer() {} virtual ~Observer() {} virtual void update(Subject *sub) = 0; virtual void outputState(); protected: string m_name; State m_observerState; }; // 观察者A class ConcreteObserverA : public Observer { public: ConcreteObserverA(string name, State init_state) { m_name = name; m_observerState = init_state; } ~ConcreteObserverA() {} void update(Subject *sub); private: }; // 观察者B class ConcreteObserverB : public Observer { public: ConcreteObserverB(string name, State init_state) { m_name = name; m_observerState = init_state; } ~ConcreteObserverB() {} void update(Subject *sub); private: };<file_sep>#include <iostream> #include <vector> #include "boost/thread.hpp" namespace Thread{ void wait(int seconds) { boost::this_thread::sleep(boost::posix_time::seconds(seconds)); // 中断函数 } void thread() { for (int i = 0; i < 5; ++i) { wait(1); std::cout << i << std::endl; } } void test1() { boost::thread t(thread); t.interrupt();// 中断 t.join(); } void test2() { std::cout << boost::this_thread::get_id() << std::endl; // 返回基于CPU数目 std::cout << boost::thread::hardware_concurrency() << std::endl; } } namespace sync_thread{ void wait(int seconds) { boost::this_thread::sleep(boost::posix_time::seconds(seconds)); } int sum = 0; boost::mutex mutex_1; boost::timed_mutex mutex_2; boost::shared_mutex mutex_3; std::vector<int> random_numbers; void fill() { std::srand(static_cast<unsigned int>(std::time(0))); for (int i = 0; i < 3; ++i) { boost::unique_lock<boost::shared_mutex> lock(mutex_3); random_numbers.push_back(std::rand()); // 插入 lock.unlock(); wait(1); } } void print() { for (int i = 0; i < 3; ++i) { wait(1); boost::shared_lock<boost::shared_mutex> lock(mutex_3); std::cout << random_numbers.back() << std::endl; // 访问 } } void count() { for (int i = 0; i < 3; ++i) { wait(1); // boost::shared_lock 的类提供了非独占锁 boost::shared_lock<boost::shared_mutex> lock(mutex_3); sum += random_numbers.back(); } } void thread() { for (int i = 0; i < 5; ++i) { wait(1); // 1 // boost::lock_guard<boost::mutex> lock(mutex_1); // 2 // mutex_1.lock(); // std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl; // 2 // mutex_1.unlock(); // 3 // boost::unique_lock 这个所谓的独占锁意味着一个互斥量同时只能被一个线程获取 boost::unique_lock<boost::timed_mutex> lock(mutex_2, boost::try_to_lock); if (!lock.owns_lock()) {// 是否获得互斥体 lock.timed_lock(boost::get_system_time() + boost::posix_time::seconds(1)); // 等待1秒后再上锁 } std::cout << "Thread " << boost::this_thread::get_id() << ": " << i << std::endl; boost::timed_mutex *m = lock.release(); m->unlock(); } } void test1() { boost::thread t1(thread); boost::thread t2(thread); t1.join(); t2.join(); } void test2() { boost::thread t1(fill); boost::thread t2(print); boost::thread t3(count); t1.join(); t2.join(); t3.join(); std::cout << "Sum: " << sum << std::endl; } } namespace cond_thread{ boost::mutex mutex; boost::condition_variable_any cond; std::vector<int> random_numbers; void fill() { std::srand(static_cast<unsigned int>(std::time(0))); for (int i = 0; i < 3; ++i) { boost::unique_lock<boost::mutex> lock(mutex); random_numbers.push_back(std::rand()); cond.notify_all(); cond.wait(mutex); } } void print() { std::size_t next_size = 1; for (int i = 0; i < 3; ++i) { boost::unique_lock<boost::mutex> lock(mutex); while (random_numbers.size() != next_size) { cond.wait(mutex); } std::cout << random_numbers.back() << std::endl; ++next_size; cond.notify_all(); } } void test1() { boost::thread t1(fill); boost::thread t2(print); t1.join(); t2.join(); } } // 线程本地存储(TLS) namespace TLS_thread{ void init_number_generator() { #if 1 static bool done = false; if (!done) { std::cout << "111111" << std::endl; done = true; std::srand(static_cast<unsigned int>(std::time(0))); } #else static boost::thread_specific_ptr<bool> tls; // 使用 reset() 方法,可以把它的地址保存到 tls 里面。 // 在给出的例子中,会动态地分配一个 bool 型的变量,由 new 返回它的地址,并保存到 tls 里。 // 为了避免每次调用 init_number_generator() 都设置 tls , // 它会通过 get() 函数检查是否已经保存了一个地址。 if (!tls.get()) { tls.reset(new bool(false)); } if (!*tls) { std::cout << "111111" << std::endl; *tls = true; std::srand(static_cast<unsigned int>(std::time(0))); } #endif } boost::mutex mutex; void random_number_generator() { init_number_generator(); int i = std::rand(); boost::lock_guard<boost::mutex> lock(mutex); std::cout << i << std::endl; // boost::this_thread::sleep(boost::posix_time::seconds(2)); } void test1() { boost::thread t[3]; for (int i = 0; i < 3; ++i) { boost::this_thread::sleep(boost::posix_time::seconds(1)); t[i] = boost::thread(random_number_generator); } for (int i = 0; i < 3; ++i) { t[i].join(); } } } int main(int argc, char const *argv[]) { // Thread::test2(); // sync_thread::test2(); // cond_thread::test1(); TLS_thread::test1(); return 0; } <file_sep>#include <iostream> #include "boost/filesystem.hpp" void test1() { boost::filesystem::path p("/home/ysw/nfs"); // p /= "Windows"; try { boost::filesystem::file_status s = boost::filesystem::status(p); std::cout << boost::filesystem::is_directory(s) << std::endl; std::cout << p.string() << std::endl; std::cout << p.filename() << std::endl; std::cout << p.root_path() << std::endl; std::cout << p.parent_path() << std::endl; std::cout << p.stem() << std::endl; std::cout << p.extension() << std::endl; // boost::filesystem::file_size(p); std::time_t t = boost::filesystem::last_write_time(p); std::cout << std::ctime(&t) << std::endl; boost::filesystem::space_info s2 = boost::filesystem::space(p); std::cout << s2.capacity << std::endl; std::cout << s2.free << std::endl; std::cout << s2.available << std::endl; std::string name = boost::filesystem::current_path().c_str(); boost::filesystem::path p2(name + "/boost_test"); std::cout << p2.c_str() << std::endl; if (boost::filesystem::create_directory(p2)) { boost::filesystem::rename(p2, "boost_test1"); boost::filesystem::remove("boost_test1"); }else { std::cout << "create error" << std::endl; } } catch (boost::filesystem::filesystem_error &e) { std::cerr << e.what() << '\n'; } } void test2() { boost::filesystem::path p("test.txt"); boost::filesystem::ofstream ofs(p); ofs << "Hello, world!" << std::endl; } int main(int argc, char const *argv[]) { test1(); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include "huffman.h" int main(void) { htTree *codeTree = buildTree("I love FishC.com!"); //使用较多的指定字符串创建huffman树 hlTable *codeTable = buildTable(codeTree); //使用创建的huffman树创建Table表 encode(codeTable, "I love FishC.com!"); //使用Table表,对指定字符串进行编码压缩 decode(codeTree, "010101110"); //使用该huffman树,解压指定编码的字符 return 0; }<file_sep>/* Boost.Asio 异步输入输出 */ #include "asio_test.hpp" namespace Test { void handler1(const boost::system::error_code &ec) { std::cout << "2 s." << std::endl; } void handler2(const boost::system::error_code &ec) { std::cout << "4 s." << std::endl; } void test1() { boost::asio::io_service io_service; boost::asio::deadline_timer timer(io_service, boost::posix_time::seconds(2)); //计时器 timer.async_wait(handler1); // 立刻返回 // async_wait() 会启动一个异步操作并立即返回,而 run() 则是阻塞的 std::cout << "11111" << std::endl; io_service.run(); // 必须调用 std::cout << "2222" << std::endl; } void test2() { boost::asio::io_service io_service; boost::asio::deadline_timer timer1(io_service, boost::posix_time::seconds(2)); timer1.async_wait(handler1); boost::asio::deadline_timer timer2(io_service, boost::posix_time::seconds(4)); timer2.async_wait(handler2); io_service.run(); } //********************************* boost::asio::io_service io_service; void run() { io_service.run(); } void test3() { boost::asio::deadline_timer timer1(io_service, boost::posix_time::seconds(2)); timer1.async_wait(handler1); boost::asio::deadline_timer timer2(io_service, boost::posix_time::seconds(2)); timer2.async_wait(handler2); boost::thread thread1(run); boost::thread thread2(run); thread1.join(); thread2.join(); } //************************************* boost::asio::io_service io_service1; boost::asio::io_service io_service2; void run1() { io_service1.run(); } void run2() { io_service2.run(); } void test4() { boost::asio::deadline_timer timer1(io_service1, boost::posix_time::seconds(2)); timer1.async_wait(handler1); boost::asio::deadline_timer timer2(io_service2, boost::posix_time::seconds(2)); timer2.async_wait(handler2); boost::thread thread1(run1); boost::thread thread2(run2); thread1.join(); thread2.join(); } } // namespace Test int main(int argc, char const *argv[]) { test_hpp(); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/inotify.h> int main(int argc, char *argv[]) { int inotifyFd = inotify_init(); if (inotifyFd < 0) { printf("inotify_init error\n"); return -1; } int wd = inotify_add_watch(inotifyFd, "a.out", IN_ALL_EVENTS); if (wd < 0) { printf("inotify_add_watch error\n"); return -1; } #define BUF_LEN_inotify 1024 while(1) { char buf[BUF_LEN_inotify]; ssize_t numRead = read(inotifyFd, buf, BUF_LEN_inotify); if(numRead == -1) { printf("read byte -1\n"); continue; } for(char *p = buf; p < buf+numRead;) { struct inotify_event *event = (struct inotify_event *)p; switch (event->mask) { case IN_ACCESS: printf("IN_ACCESS\n"); break; case IN_MODIFY: printf("IN_MODIFY\n"); break; case IN_ATTRIB: printf("IN_ATTRIB\n"); break; case IN_CLOSE_WRITE: printf("IN_CLOSE_WRITE\n"); break; case IN_CLOSE_NOWRITE: printf("IN_CLOSE_NOWRITE\n"); break; case IN_OPEN: printf("IN_OPEN\n"); break; case IN_MOVED_FROM: printf("IN_MOVED_FROM\n"); break; case IN_MOVED_TO: printf("IN_MOVED_TO\n"); break; case IN_CREATE: printf("IN_CREATE\n"); break; case IN_DELETE: printf("IN_DELETE\n"); break; case IN_DELETE_SELF: printf("IN_DELETE_SELF\n"); break; case IN_MOVE_SELF: printf("IN_MOVE_SELF\n"); break; default: printf("default\n"); break; } p += sizeof(struct inotify_event) + event->len; } } inotify_rm_watch(inotifyFd, wd); return 0; } <file_sep>/* 智能指针 */ #include <iostream> #include <vector> #include "boost/scoped_ptr.hpp" #include "boost/scoped_array.hpp" #include "boost/shared_ptr.hpp" #include "boost/shared_array.hpp" #include "boost/weak_ptr.hpp" #include "boost/intrusive_ptr.hpp" #include "boost/ptr_container/ptr_vector.hpp" #include <thread> using namespace std; // 作用域指针 void test1() { boost::scoped_ptr<int> i(new int); *i = 2; cout << *i << endl; *i.get() = 1; cout << *i << endl; i.reset(new int); cout << *i << endl; } // 作用域数组 void test2() { boost::scoped_array<int> arr(new int[2]); *arr.get() = 1; cout << arr[0] << endl; arr[1] = 2; arr.reset(new int[3]); } // 共享指针 void test3() { std::vector< boost::shared_ptr<int> > v; v.push_back(boost::shared_ptr<int>(new int(1))); v.push_back(boost::shared_ptr<int>(new int(2))); cout << *v[0] << endl; cout << *v[1] << endl; boost::shared_ptr<int> i1(new int(1)); boost::shared_ptr<int> i2(i1); cout << *i1 << endl;// 1 cout << *i2 << endl;// 1 i1.reset(new int(2)); cout << *i1 << endl; // 2 cout << *i2 << endl; // 1 } // 共享数组 void test4() { boost::shared_array<int> i1(new int[2]); boost::shared_array<int> i2(i1); i1[0] = 1; std::cout << i2[0] << std::endl; } void reset_task(void *p) { boost::shared_ptr<int> *sh = static_cast<boost::shared_ptr<int> *>(p); sh->reset(); } void print_task(void *p) { boost::weak_ptr<int> *w = static_cast<boost::weak_ptr<int> *>(p); boost::shared_ptr<int> sh = w->lock(); if (sh) { cout << *sh << endl; }else{ cout << "sh is reset" << endl; } } // 弱指针: 只有在配合共享指针一起使用时才有意义 // 一个潜在的问题:reset() 线程在销毁对象的时候print() 线程可能正在访问它。 // 通过调用弱指针的 lock() 函数可以解决这个问题: // 如果对象存在,那么 lock() 函数返回的共享指针指向这个合法的对象。 // 否则,返回的共享指针被设置为0,这等价于标准的null指针。 void test5() { boost::shared_ptr<int> sh(new int(99)); boost::weak_ptr<int> w(sh); thread th1, th2; th1 = thread(reset_task, &sh); th2 = thread(print_task, &w); th1.join(); th2.join(); } // 介入式指针:大体上工作方式和共享指针完全一样 // COM 对象是使用 boost::intrusive_ptr 的绝佳范例,因为 COM 对象需要记录当前有多少指针引用着它。 // 通过调用 AddRef() 和 Release() 函数,内部的引用计数分别增 1 或者减 1。当引用计数为 0 时,COM 对象自动销毁 void test6() { // boost::intrusive_ptr<int> i(new int(6)); } // 指针容器 void test7() { #if 0 // 效率低,不推荐用 std::vector<boost::shared_ptr<int> > v; v.push_back(boost::shared_ptr<int>(new int(1))); v.push_back(boost::shared_ptr<int>(new int(2))); #else boost::ptr_vector<int> pv; pv.push_back(new int(6)); pv.push_back(new int(7)); cout << pv[0] << endl; cout << pv[1] << endl; #endif } int main(int argc, char const *argv[]) { test7(); return 0; } <file_sep>#include <stdio.h> #include <getopt.h> int main(int argc, char *argv[]) { // main param //******************************************************* struct option long_options[] = { {"config_file", required_argument, NULL, 'c'}, {"help", no_argument, NULL, 'h'}, {0, 0, 0, 0} }; int opt, option_index; while( (opt = getopt_long(argc, argv, "c:h:j", long_options, &option_index)) != -1) { switch(opt) { case 'c': puts(optarg);// ./stOption -c <file name> break; case 'h': printf("./stOption -c <file name>\n"); printf("ps:./stOption -c visual-ai.yaml\n"); return 0; case 'j':// information -> not register printf("1111\n"); break; } } return 0; }<file_sep># CMake 最低版本号要求 cmake_minimum_required (VERSION 2.8) # 项目信息 project(demo) # 查找当前目录下的所有源文件 # 并将名称保存到 DIR_SRCS 变量 aux_source_directory(. DIR_SRCS) # 指定生成目标rm * -cmake_minimum_required add_executable(demo ${DIR_SRCS})<file_sep>#include <iostream> #include <fstream> #include <sstream> #include "boost/archive/text_oarchive.hpp" #include "boost/archive/text_iarchive.hpp" #include <boost/serialization/string.hpp> std::stringstream ss; #if 0 void save() { // std::ofstream file("archiv.txt"); // boost::archive::text_oarchive oa(file); boost::archive::text_oarchive oa(ss); int i = 1; oa << i; } void load() { // std::ifstream file("archiv.txt"); // boost::archive::text_iarchive ia(file); boost::archive::text_iarchive ia(ss); int i = 0; ia >> i; std::cout << i << std::endl; } #else class person { public: person() { } person(int age) : age_(age) { } int age() const { return age_; } private: friend class boost::serialization::access; template <typename Archive> void serialize(Archive &ar, const unsigned int version) { ar & age_; } int age_; }; void save() { boost::archive::text_oarchive oa(ss); person p(31); oa << p; } void load() { boost::archive::text_iarchive ia(ss); person p; ia >> p; std::cout << p.age() << std::endl; } #endif int main(int argc, char const *argv[]) { save(); load(); return 0; } <file_sep>/** * 抽象工厂模式 */ #include <iostream> #include <string> using namespace std; // 卡车抽象类 class Trunk_A { public: virtual void Run() = 0; }; // 轿车抽象类 class Sedan_A { public: virtual void Run() = 0; }; // 具体的宝马卡车产品类 class BmwTrunk : public Trunk_A { public: virtual void Run() { cout << "宝马卡车" << endl; } }; // 具体的宝马轿车产品类 class BmwSedan : public Sedan_A { public: virtual void Run() { cout << "宝马轿车" << endl; } }; // 具体的奥迪卡车产品类 class AodiTrunk : public Trunk_A { public: virtual void Run() { cout << "奥迪卡车" << endl; } }; // 具体的奥迪轿车产品类 class AodiSedan : public Sedan_A { public: virtual void Run() { cout << "奥迪轿车" << endl; } }; // 抽象工厂类 class CarFactory { public: virtual Trunk_A *productTrunk() = 0; virtual Sedan_A *productSedan() = 0; }; // 宝马工厂类(一个工厂是生产一个产品族的工厂而不是生产单一的产品) class BmwFactory : public CarFactory { public: virtual Trunk_A *productTrunk() { return new BmwTrunk; } virtual Sedan_A *productSedan() { return new BmwSedan; } }; // 奥迪工厂类 class AodiFactory : public CarFactory { public: virtual Trunk_A *productTrunk() { return new AodiTrunk; } virtual Sedan_A *productSedan() { return new AodiSedan; } }; int main() { // 客户端 CarFactory *bm = new BmwFactory(); bm->productTrunk()->Run(); bm->productSedan()->Run(); return 0; } <file_sep>#include <stdio.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <zmq.h> int main() { int rc; void *context = zmq_ctx_new(); // 2.创建、绑定套接字 void *frontend = zmq_socket(context, ZMQ_ROUTER); void *backend = zmq_socket(context, ZMQ_DEALER); // ZMQ_ROUTER绑定到5559, 接收客户端的请求 rc = zmq_bind(frontend, "tcp://*:5559"); if(rc == -1) { perror("zmq_bind"); zmq_close(frontend); zmq_close(backend); zmq_ctx_destroy(context); return -1; } // ZMQ_DEALER绑定到5560, 接收服务端的回复 rc = zmq_bind(backend, "tcp://*:5560"); if(rc == -1) { perror("zmq_bind"); zmq_close(frontend); zmq_close(backend); zmq_ctx_destroy(context); return -1; } // 3.初始化轮询集合 zmq_pollitem_t items[] = { { frontend, 0, ZMQ_POLLIN, 0 }, { backend, 0, ZMQ_POLLIN, 0 } }; // 4.在套接字上切换消息 while(1) { zmq_msg_t msg; //多部分消息检测 int more; // 5.调用zmq_poll轮询消息-- -1阻塞 rc = zmq_poll(items, 2, -1); //zmq_poll出错 if(rc == -1) { perror("zmq_poll"); zmq_close(frontend); zmq_close(backend); zmq_ctx_destroy(context); return -1; } //zmq_poll超时 else if(rc == 0) { printf("timeout \n"); continue; } else { printf("data \n"); // 6.如果ROUTER套接字有数据来 if(items[0].revents & ZMQ_POLLIN) { while(1) { // 从ROUTER上接收数据, 这么数据是客户端发送过来的"Hello" zmq_msg_init(&msg); zmq_msg_recv(&msg, frontend, 0); // 查看是否是接收多部分消息, 如果后面还有数据要接收, 那么more会被置为1 size_t more_size = sizeof(more); zmq_getsockopt(frontend, ZMQ_RCVMORE, &more, &more_size); // 接收"Hello"之后, 将数据发送到DEALER上, DEALER会将"Hello"发送给服务端 zmq_msg_send(&msg, backend, more ? ZMQ_SNDMORE : 0); zmq_msg_close(&msg); // 如果没有多部分数据可以接收了, 那么退出循环 if(!more) break; } } // 7.如果DEALER套接字有数据来 if(items[1].revents & ZMQ_POLLIN) { while(1) { // 接收服务端的响应"World" zmq_msg_init(&msg); zmq_msg_recv(&msg, backend, 0); // 查看是否是接收多部分消息, 如果后面还有数据要接收, 那么more会被置为1 size_t more_size = sizeof(more); zmq_getsockopt(backend, ZMQ_RCVMORE, &more, &more_size); // 接收"World"之后, 将数据发送到ROUTER上, ROUTER会将"World"发送给客户端 zmq_msg_send(&msg, frontend, more ? ZMQ_SNDMORE : 0); zmq_msg_close(&msg); // 如果没有多部分数据可以接收了, 那么退出循环 if(!more) break; } } } } // 8.关闭套接字、销毁上下文 zmq_close(frontend); zmq_close(backend); zmq_ctx_destroy(context); return 0; }<file_sep>#include <iostream> #include "config.h" #ifdef USE_MYMATH #include "calc.h" #endif int main(int argc, char const *argv[]) { #ifdef USE_MYMATH std::cout << add(2, 3) << std::endl; #endif printf("Version %d.%d\n", VERSION_MAJOR, VERSION_MINOR); std::cout << "hello" << std::endl; return 0; } <file_sep>include ../Makefile.rc<file_sep>#include "boost/interprocess/managed_shared_memory.hpp" #include "boost/interprocess/allocators/allocator.hpp" #include "boost/interprocess/containers/string.hpp" #include "boost/bind.hpp" #include <iostream> void test1() { boost::interprocess::shared_memory_object::remove("Highscore"); boost::interprocess::managed_shared_memory managed_shm(boost::interprocess::open_or_create, "Highscore", 1024); int *i = managed_shm.construct<int>("Integer")(99); std::cout << *i << std::endl; std::pair<int *, std::size_t> p = managed_shm.find<int>("Integer"); if (p.first) std::cout << *p.first << std::endl; } void test2() { boost::interprocess::shared_memory_object::remove("Highscore"); boost::interprocess::managed_shared_memory managed_shm(boost::interprocess::open_or_create, "Highscore", 1024); int *i = managed_shm.construct<int>("Integer")[10](99); std::cout << *i << std::endl; // managed_shm.destroy<int>("Integer"); std::pair<int *, std::size_t> p = managed_shm.find<int>("Integer"); if (p.first) { std::cout << *p.first << std::endl; std::cout << p.second << std::endl; } } void test3() { boost::interprocess::shared_memory_object::remove("Highscore"); boost::interprocess::managed_shared_memory managed_shm(boost::interprocess::open_or_create, "Highscore", 1024); typedef boost::interprocess::allocator<char, boost::interprocess::managed_shared_memory::segment_manager> CharAllocator; typedef boost::interprocess::basic_string<char, std::char_traits<char>, CharAllocator> string; string *s = managed_shm.find_or_construct<string>("String")("Hello!", managed_shm.get_segment_manager()); s->insert(5, ", world"); std::cout << *s << std::endl; } // void construct_objects(boost::interprocess::managed_shared_memory &managed_shm) // { // managed_shm.construct<int>("Integer")(99); // managed_shm.construct<float>("Float")(3.14); // } // void test4() // { // boost::interprocess::shared_memory_object::remove("Highscore"); // boost::interprocess::managed_shared_memory managed_shm(boost::interprocess::open_or_create, "Highscore", 1024); // managed_shm.atomic_func(boost::bind(construct_objects, boost::ref(managed_shm))); // std::cout << *managed_shm.find<int>("Integer").first << std::endl; // std::cout << *managed_shm.find<float>("Float").first << std::endl; // } int main(int argc, char const *argv[]) { test3(); return 0; } <file_sep>#include <boost/date_time/gregorian/gregorian.hpp> #include <iostream> void test1() { boost::gregorian::date d(2010, 1, 30); std::cout << d.year() << std::endl; std::cout << d.month() << std::endl; std::cout << d.day() << std::endl; std::cout << d.day_of_week() << std::endl; std::cout << d.end_of_month() << std::endl; } void test2() { boost::gregorian::date d = boost::gregorian::day_clock::universal_day(); std::cout << d.year() << std::endl; std::cout << d.month() << std::endl; std::cout << d.day() << std::endl; d = boost::gregorian::date_from_iso_string("20100131"); std::cout << d.year() << std::endl; std::cout << d.month() << std::endl; std::cout << d.day() << std::endl; } void test3() { boost::gregorian::date d1(2008, 1, 31); boost::gregorian::date d2(2020, 8, 31); boost::gregorian::date_duration dd = d2 - d1; std::cout << dd.days() << std::endl; } void test4() { boost::gregorian::date_duration dd(4); std::cout << dd.days() << std::endl; boost::gregorian::weeks ws(4); std::cout << ws.days() << std::endl; boost::gregorian::months ms(4); std::cout << ms.number_of_months() << std::endl; boost::gregorian::years ys(4); std::cout << ys.number_of_years() << std::endl; } void test5() { // std::locale::global(std::locale("German")); std::string months[12] = {"Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"}; std::string weekdays[7] = {"Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"}; boost::gregorian::date d(2009, 1, 7); boost::gregorian::date_facet *df = new boost::gregorian::date_facet("%A, %d. %B %Y"); df->long_month_names(std::vector<std::string>(months, months + 12)); df->long_weekday_names(std::vector<std::string>(weekdays, weekdays + 7)); std::cout.imbue(std::locale(std::cout.getloc(), df)); std::cout << d << std::endl; } int main(int argc, char const *argv[]) { test5(); return 0; } <file_sep>#include <stdio.h> #include <zmq.h> #include <unistd.h> #include <string.h> int main(void) { void *ctx, *sock; int ret = 0; char data[1024]; int i = 0; ctx = zmq_ctx_new(); sock = zmq_socket(ctx, ZMQ_PUSH); ret = zmq_bind(sock, "tcp://127.0.0.1:5555"); while (1) { sprintf(data, "[%d]PUSH: Hello World", i++); ret = zmq_send(sock, data, strlen(data), 0); sleep(1); } zmq_close(sock); zmq_ctx_destroy(ctx); return 0; }<file_sep># 查找当前目录下的所有源文件 # 并将名称保存到 DIR_LIB_SRCS 变量 aux_source_directory(. DIR_LIB_SRCS) # 生成链接库 add_library (calc SHARED ${DIR_LIB_SRCS})<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <unistd.h> #include <event2/event.h> #include <event2/bufferevent.h> #include <event2/buffer.h> #include <event2/util.h> #define SERVER_IP "127.0.0.1" #define SERVER_PORT 8899 void write_cb(int fd, short events, void *arg); void read_cb(struct bufferevent *bev, void *arg); void write_over_cb(struct bufferevent *bev, void *arg); void event_cb(struct bufferevent *bev, short event, void *arg); int main(int argc, char **argv) { int ret; struct event_base *base = event_base_new(); assert(base != NULL); // 为这个客户端分配一个 bufferevent,释放时关闭套接字 struct bufferevent *bev = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE); assert(bev != NULL); // 分配并初始化一个新的event结构体,准备被添加。 struct event *ev = event_new(base, STDIN_FILENO, EV_READ|EV_PERSIST, write_cb, (void *)bev); assert(ev != NULL); // 将ev注册到event_base的I/O多路复用要监听的事件中 ret = event_add(ev, NULL); assert(ret == 0); // 配置服务器地址 struct sockaddr_in server_addr; memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(SERVER_PORT); inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr); // 连接服务器 ret = bufferevent_socket_connect(bev, (struct sockaddr *)&server_addr, sizeof(server_addr)); assert(ret == 0); // 设置读回调、事件回调 bufferevent_setcb(bev, read_cb, write_over_cb, event_cb, (void *)ev); // 默认写回调使能,这里必须使能读回调 bufferevent_enable(bev, EV_READ | EV_PERSIST); event_base_dispatch(base); printf("Finished\n"); return 0; } void write_cb(int fd, short events, void *arg) { struct bufferevent *bev = (struct bufferevent *)arg; char msg[1024]; int ret = read(fd, msg, sizeof(msg)); if (ret < 0) { perror("read fail.\n"); exit(1); } bufferevent_write(bev, msg, ret); } void read_cb(struct bufferevent *bev, void *arg) { char msg[1024]; size_t len = bufferevent_read(bev, msg, sizeof(msg)-1); msg[len] = '\0'; printf("Recv %s from server.\n", msg); } void write_over_cb(struct bufferevent *bev, void *arg) { printf("我是客户端的写回调函数,没啥用\n"); } void event_cb(struct bufferevent *bev, short event, void *arg) { if (event & BEV_EVENT_EOF) { printf("Connection closed.\n"); } else if (event & BEV_EVENT_ERROR) { printf("Some other error.\n"); } else if (event & BEV_EVENT_CONNECTED) { printf("Client has successfully cliented.\n"); return; } bufferevent_free(bev); struct event *ev = (struct event *)arg; event_free(ev); } <file_sep>// 汉诺塔 #include <stdio.h> // 将n个盘子从x借助y移动到z void move(int n, char x, char y, char z) { if ( 1 == n ) { printf("%c --> %c\n", x, z); }else{ move(n-1, x, z, y); printf("%c --> %c\n", x, z); move(n-1, y, x, z); } } int main(int argc, char const *argv[]) { move(3, 'x', 'y', 'z'); return 0; } <file_sep>#include<stdio.h> #include<time.h> #define X 8 #define Y 8 int chess[X][Y]; int nextxy(int *x,int *y,int count) { switch(count)//对于上下左右及其四周等八个情况判断 { //注意xy大小写 case 0: if(*x+2<=X-1&&*y-1>=0&&chess[*x+2][*y-1]==0)//判断是否出界和是否经过,没进过为0 { *x+=2; *y-=1; return 1;//标志可行 } break; case 1: if(*x+2<=X-1&&*y+1<=Y-1&&chess[*x+2][*y+1]==0)//判断是否出界和是否经过,没进过为0 { *x+=2; *y+=1; return 1;//标志可行 } break; case 2: if(*x+1<=X-1&&*y-2>=0&&chess[*x+1][*y-2]==0)//判断是否出界和是否经过,没进过为0 { *x+=1; *y-=2; return 1;//标志可行 } break; case 3: if(*x+1<=X-1&&*y+2<=Y-1&&chess[*x+1][*y+2]==0)//判断是否出界和是否经过,没进过为0 { *x+=1; *y+=2; return 1;//标志可行 } break; case 4: if(*x-2>=0&&*y-1>=0&&chess[*x-2][*y-1]==0)//判断是否出界和是否经过,没进过为0 { *x-=2; *y-=1; return 1;//标志可行 } break; case 5: if(*x-2>=0&&*y+1<=Y-1&&chess[*x-2][*y+1]==0)//判断是否出界和是否经过,没进过为0 { *x-=2; *y+=1; return 1;//标志可行 } break; case 6: if(*x-1>=0&&*y-2>=0&&chess[*x-1][*y-2]==0)//判断是否出界和是否经过,没进过为0 { *x-=1; *y-=2; return 1;//标志可行 } break; case 7: if(*x-1>=0&&*y+2<=Y-1&&chess[*x-1][*y+2]==0)//判断是否出界和是否经过,没进过为0 { *x-=1; *y+=2; return 1;//标志可行 } break; default: break; } return 0; } void print() { int i,j; for(i=0;i<Y;i++) { for(j=0;j<Y;j++) { printf("%2d\t",chess[i][j]); } printf("\n"); } printf("\n"); } int TravelChessBoard(int x,int y,int tag)//tag为标记变量每走一步tag+1 { int x1=x,y1=y,flag=0,count=0;//初始位置即初始化 chess[x][y]=tag; if(tag==X*Y)//完了 { print(); return 1; } //找马的下一个坐标(x1,y1),成功则flag=1否则=0 //第一次搜索 flag=nextxy(&x1,&y1,count); while(flag==0&&count<7)//已进入,进不去了 { count++; flag=nextxy(&x1,&y1,count); } while(flag) { if(TravelChessBoard(x1,y1,tag+1)) return 1; //出错则找马的下一个坐标(x1,y1),成功则flag=1否则=0 //第一次搜索错,接下来搜索 x1=x; y1=y; count++; flag=nextxy(&x1,&y1,count); while(flag==0&&count<7)//已进入,进不去了 { count++; flag=nextxy(&x1,&y1,count); } } if(flag==0) { chess[x][y]=0; } return 0; } int main() { int i,j; clock_t start,finish; start=clock(); for(i=0;i<X;i++) { for(j=0;j<Y;j++) { chess[i][j]=0; } } if(!TravelChessBoard(2,0,1)) printf("错误"); finish=clock(); printf("\n用时%f秒",(double)(finish-start)/CLOCKS_PER_SEC);//CLOCKS_PER_SEC为time 中的宏定义,每秒的数量 return 0; }<file_sep>int module22_test(void) { return 22; }<file_sep>/* 代理模式(proxy pattern):为其他对象提供一种代理以控制对这个对象的访问 代理模式的应用场景: 如果已有的方法在使用的时候需要对原有的方法进行改进,此时有两种办法: 1、修改原有的方法来适应。这样违反了“对扩展开放,对修改关闭”的原则。 2、就是采用一个代理类调用原有的方法,且对产生的结果进行控制。这种方法就是代理模式。 使用代理模式,可以将功能划分的更加清晰,有助于后期维护 代理模式最大的好处便是逻辑与实现的彻底解耦 */ #include <iostream> using namespace std; class Girl { public: Girl(char *name = "") : mName(name) {} char *getName() { return mName; } private: char *mName; }; class GiveGift // 接口 { public: virtual void GiveDolls() = 0; virtual void GiveFlowers() = 0; virtual void GiveChocolate() = 0; }; class Puisuit : public GiveGift // 送礼物实例类 { public: Puisuit(Girl mm) : mGirl(mm) {} virtual void GiveDolls() { cout << "送" << mGirl.getName() << "玩具!" << endl; } virtual void GiveFlowers() { cout << "送" << mGirl.getName() << "鲜花!" << endl; } virtual void GiveChocolate() { cout << "送" << mGirl.getName() << "巧克力!" << endl; } private: Girl mGirl; }; class Proxy : public GiveGift // 送礼物代理类 { public: Proxy(Girl mm) { mPuisuit = new Puisuit(mm); } virtual void GiveDolls() { mPuisuit->GiveDolls(); } virtual void GiveFlowers() { mPuisuit->GiveFlowers(); } virtual void GiveChocolate() { mPuisuit->GiveChocolate(); } private: Puisuit *mPuisuit; }; int main() { Girl mm("小娟"); Proxy pro(mm); pro.GiveChocolate(); pro.GiveDolls(); pro.GiveFlowers(); return 0; }<file_sep>#include "MySQL.h" MySQL::MySQL(MySQL_Info &info) : MySqlAbstract(info) { if (0 != mysql_library_init(0, NULL, NULL)) { std::cout << "mysql_library_init() failed" << std::endl; } } MySQL::~MySQL() { mysql_library_end(); } bool MySQL::connectToMysql() { //初始化数据结构 mysql_init(m_bMysql.get()); //在连接数据库之前,设置额外的连接选项 if (0 != mysql_options(m_bMysql.get(), MYSQL_SET_CHARSET_NAME, "gbk")) { std::cout << "mysql_options() failed" << std::endl; } if (m_bMysql.get() != NULL && mysql_real_connect(m_bMysql.get(), m_bInfo.host.c_str(), m_bInfo.user.c_str(), m_bInfo.pswd.c_str(), m_bInfo.database.c_str(), m_bInfo.port, NULL, 0)) { std::cout << "Connect_to_Mysql Success" << std::endl; return true; } else { std::cout << "Connect_to_Mysql Failed" << std::endl; std::cout << mysql_error(m_bMysql.get()) << std::endl; return false; } } // select 视情况封装 void MySQL::operateMysqlSelect(const char *Mysql_Sentence) { if (0 == mysql_query(m_bMysql.get(), Mysql_Sentence)) { // 返回0表示插入、更新等操作 if (mysql_field_count(m_bMysql.get()) != 0) { MYSQL_RES *result = NULL; result = mysql_store_result(m_bMysql.get()); // mysql_num_rows() 返回结果集中行的数目。此命令仅对 SELECT 语句有效。 // 要取得被 INSERT,UPDATE 或者 DELETE 查询所影响到的行的数目, // 用 mysql_affected_rows()。 // 行 unsigned int rows = (unsigned int)mysql_num_rows(result); std::cout << "总记录条数: " << rows << std::endl; // 列 unsigned int fields = mysql_num_fields(result); std::cout << "每条记录总共 " << fields << " 个字段" << std::endl; // 字段 MYSQL_FIELD *field = NULL; for (unsigned int i = 0; i < fields; i++) { field = mysql_fetch_field_direct(result, i); std::cout << field->name << "\t\t"; } std::cout << std::endl; // 一行行输出信息 MYSQL_ROW row = NULL; while ((row = mysql_fetch_row(result)) != NULL) { for (unsigned int i = 0; i < fields; ++i) { if (row[i] != NULL) { std::cout << row[i] << "\t\t"; } else { std::cout << "null" << "\t\t"; } } std::cout << std::endl; } mysql_free_result(result); } } else { std::cout << "Operate_Mysql Select Failed" << std::endl; std::cout << mysql_error(m_bMysql.get()) << std::endl; } } void MySQL::operateMysqlQuery(const char *Mysql_Sentence) { if (0 == mysql_query(m_bMysql.get(), Mysql_Sentence)) { std::cout << "Operate_Mysql Query Success" << std::endl; // std::cout << "Query:" << mysql_affected_rows(m_bMysql.get()) << std::endl; } else { std::cout << "Operate_Mysql Query Failed" << std::endl; std::cout << mysql_error(m_bMysql.get()) << std::endl; } } void MySQL::disconnectToMysql() { mysql_close(m_bMysql.get()); } void MySQL::resetConn() { mysql_reset_connection(m_bMysql.get());// 恢复到刚连接时的状态 } <file_sep>#include <iostream> #include <unistd.h> #include "zmq.hpp" #ifdef CXX_PROCESS int main(int argc, char const *argv[]) { zmq::context_t ctx(1); zmq::socket_t socket(ctx, ZMQ_REP); socket.bind("tcp://*:5555"); while (1) { zmq::message_t request; if (!socket.recv(request)) { std::cout << "REQ : zmq_recv faild" << std::endl; break; } std::printf("%s\n", request.data()); zmq::message_t msg("Recv ok\n", 7); socket.send(msg); } return 0; } #else int main(void) { void *ctx, *sock; int ret = 0; char data[1024]; ctx = zmq_ctx_new(); sock = zmq_socket(ctx, ZMQ_REP); ret = zmq_bind(sock, "tcp://127.0.0.1:5555"); while (1) { bzero(data, sizeof(data) - 1); if ((ret = zmq_recv(sock, data, sizeof(data) - 1, 0)) < 0) printf("REP : zmq_recv faild"); sleep(3); printf("REP : recv msg %s\n", data); memcpy(data, "world", 5); if ((ret = zmq_send(sock, data, 5, 0)) < 0) printf("REP : zmq_send faild"); } zmq_close(sock); zmq_ctx_destroy(ctx); return 0; } #endif<file_sep>#include <stdio.h> #include <unistd.h> void regconize() { printf("识别颜色....\n"); sleep(1); printf("识别完成...\n"); } <file_sep>#include <iostream> #include <type_traits> #include <typeinfo> using namespace std; // 元编程 template <int N, int M> struct meta_func { static const int value = N + M; }; #if 0 using one_type = std::integral_constant<int, 1>; #else template <class T> struct one_type : std::integral_constant<int, 1> { }; #endif template<typename T> struct PointerOf { using Result = T*; }; template<typename T> struct Pointer2Of { using Result = typename PointerOf<typename PointerOf<T>::Result>::Result; }; int* pi; Pointer2Of<int>::Result ppi = &pi; // #define __pointer(...) typename PointerOf<__VA_ARGS__>::Result // template<typename T> // struct Pointer2Of // { // using Result = __pointer(__pointer(T)); // }; int main(int argc, char const *argv[]) { int i = 1, j = 2; cout << meta_func<1, 2>::value << endl; cout << one_type<int>::value << endl; typedef std::conditional<true, int, float>::type A; // int typedef std::conditional<false, int, float>::type B; // float typedef std::conditional<(sizeof(long long) > sizeof(long double)), long long, long double>::type max_size_t; cout << typeid(max_size_t).name() << endl; return 0; } <file_sep>CC = gcc CXX = g++ SRCS := $(wildcard *.cpp */*.cpp) OBJS := $(patsubst %.cpp, %.o, $(SRCS)) TARGETS := $(SRCS:%.cpp=%) INCLUDE := LIB_PATH := LIB_LINK := -levent CFLAGS := -g -Wall all:$(TARGETS) $(TARGETS):%:%.o $(CXX) $^ -o $@ $(INCLUDE) $(LIB_PATH) $(LIB_LINK) $(CFLAGS) # @rm -rf $(OBJS) %.o:%.cpp $(CXX) -c $< -o $@ $(CFLAGS) $(INCLUDE) .PHONY: clean clean: @rm -rf $(TARGETS) $(OBJS)<file_sep>#pragma once int module11_test(void);<file_sep>#pragma once int driver11_test(void);<file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> #include <libxml/xmlmemory.h> #include <libxml/parser.h> void parseStory(xmlDocPtr doc, xmlNodePtr cur, const xmlChar *keyword) { /* 在当前节点下插入一个keyword子节点 */ xmlNewTextChild(cur, NULL, (const xmlChar *)"keyword", keyword); return; } xmlDocPtr parseDoc(char *docname, char *keyword) { xmlDocPtr doc; xmlNodePtr cur; doc = xmlParseFile(docname); if (doc == NULL) { fprintf(stderr, "Document not parsed successfully. \n"); return (NULL); } cur = xmlDocGetRootElement(doc); if (cur == NULL) { fprintf(stderr, "empty document\n"); xmlFreeDoc(doc); return (NULL); } if (xmlStrcmp(cur->name, (const xmlChar *)"story")) { fprintf(stderr, "document of the wrong type, root node != story"); xmlFreeDoc(doc); return (NULL); } cur = cur->xmlChildrenNode; while (cur != NULL) { if ((!xmlStrcmp(cur->name, (const xmlChar *)"storyinfo"))) { parseStory(doc, cur, (const xmlChar *)keyword); } cur = cur->next; } return (doc); } int main(int argc, char **argv) { char *docname; char *keyword; xmlDocPtr doc; if (argc <= 2) { printf("Usage: %s docname, keyword\n", argv[0]); return (0); } docname = argv[1]; keyword = argv[2]; doc = parseDoc(docname, keyword); if (doc != NULL) { xmlSaveFormatFile(docname, doc, 0); xmlFreeDoc(doc); } return (0); }<file_sep># CMake 最低版本号要求 cmake_minimum_required (VERSION 2.8) # 项目信息 project (demo) # 查找当前目录下的所有源文件 # 并将名称保存到 DIR_SRCS 变量 aux_source_directory(. DIR_SRCS) # 添加 math 子目录 add_subdirectory(math) # 指定生成目标 add_executable(demo main.cpp) # 头文件路径 include_directories(math) # 添加链接库 target_link_libraries(demo calc)<file_sep># # Configuration file for using the XML library in GNOME applications # XML2_LIBDIR="-L/home/ysw/use_lib/libxml2-2.7.2/libxml2-2.7.2/lib" XML2_LIBS="-lxml2 -lz -lm " XML2_INCLUDEDIR="-I/home/ysw/use_lib/libxml2-2.7.2/libxml2-2.7.2/include/libxml2" MODULE_VERSION="xml2-2.7.2" <file_sep>#include <iostream> #include <tinyxml2.h> //function:create a xml file //param:xmlPath:xml文件路径 //return:0,成功;非0,失败 int createXML(const char *xmlPath) { tinyxml2::XMLDocument doc; #if 0 // 手动添加 const char* declaration ="<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; doc.Parse(declaration);//会覆盖xml所有内容 #else // <?xml version="1.0" encoding="UTF-8"?> tinyxml2::XMLDeclaration *declaration = doc.NewDeclaration(); doc.InsertFirstChild(declaration); #endif tinyxml2::XMLElement *root = doc.NewElement("DBUSER"); doc.InsertEndChild(root); return doc.SaveFile(xmlPath); } // load a xml file and add node int insertXMLNode(const char *xmlPath) { tinyxml2::XMLDocument doc; int res = doc.LoadFile(xmlPath); if (res != 0) { std::cout << "load xml file failed" << std::endl; return res; } tinyxml2::XMLElement *root = doc.RootElement(); // root中插入一个node tinyxml2::XMLElement *userNode = doc.NewElement("User"); userNode->SetAttribute("Name", "root"); userNode->SetAttribute("Password", "<PASSWORD>"); root->InsertEndChild(userNode); // userNode中插入一个node tinyxml2::XMLElement *gender = doc.NewElement("Gender"); tinyxml2::XMLText *genderText = doc.NewText("22"); gender->InsertEndChild(genderText); userNode->InsertEndChild(gender); tinyxml2::XMLElement *mobile = doc.NewElement("Mobile"); mobile->InsertEndChild(doc.NewText("1234567890")); userNode->InsertEndChild(mobile); tinyxml2::XMLElement *email = doc.NewElement("Email"); email->InsertEndChild(doc.NewText("<EMAIL>")); userNode->InsertEndChild(email); return doc.SaveFile(xmlPath); } //function:根据用户名获取用户节点 //param:root:xml文件根节点;userName:用户名 //return:用户节点 tinyxml2::XMLElement *queryUserNodeByName(tinyxml2::XMLElement *root, const char *userName) { tinyxml2::XMLElement *userNode = root->FirstChildElement("User"); while (userNode != NULL) { if (!strcmp(userNode->Attribute("Name"), userName)) { break; } userNode = userNode->NextSiblingElement(); //下一个兄弟节点 } return userNode; } void select(const char *xmlPath, const char *userName) { tinyxml2::XMLDocument doc; int res = doc.LoadFile(xmlPath); if (res != 0) { std::cout << "load xml file failed" << std::endl; return; } tinyxml2::XMLElement *root = doc.RootElement(); // doc必须还在才能继续 tinyxml2::XMLElement *userNode = queryUserNodeByName(root, userName); if (userNode != NULL) { const char *Password = userNode->Attribute("Password"); if (Password) puts(Password); tinyxml2::XMLElement *genderNode = userNode->FirstChildElement("Gender"); if (genderNode) { const char *Gender = genderNode->GetText(); puts(Gender); } tinyxml2::XMLElement *mobileNode = userNode->FirstChildElement("Mobile"); if (mobileNode) { const char *Mobile = mobileNode->GetText(); puts(Mobile); } tinyxml2::XMLElement *emailNode = userNode->FirstChildElement("Email"); if (emailNode) { const char *Email = emailNode->GetText(); puts(Email); } } else { std::cout << "userNode is null" << std::endl; } std::cout << std::endl; } //function:修改指定节点内容 //param:xmlPath:xml文件路径;user:用户对象 //return:bool bool updateUser(const char *xmlPath, const char *userName) { tinyxml2::XMLDocument doc; if (doc.LoadFile(xmlPath) != 0) { std::cout << "load xml file failed" << std::endl; return false; } tinyxml2::XMLElement *root = doc.RootElement(); // 找到节点 tinyxml2::XMLElement *userNode = queryUserNodeByName(root, userName); if (userNode != NULL) { // if (password != userNode->Attribute("Password")) { userNode->SetAttribute("Password", "<PASSWORD>"); //修改属性 } tinyxml2::XMLElement *genderNode = userNode->FirstChildElement("Gender"); // if (gender != atoi(genderNode->GetText())) { genderNode->SetText("男"); //修改节点内容 } tinyxml2::XMLElement *mobileNode = userNode->FirstChildElement("Mobile"); // if (mobile != mobileNode->GetText()) { mobileNode->SetText("00000000000"); } tinyxml2::XMLElement *emailNode = userNode->FirstChildElement("Email"); // if (email != emailNode->GetText()) { emailNode->SetText("<EMAIL>"); } if (doc.SaveFile(xmlPath) == 0) return true; } return false; } //function:删除指定节点内容 //param:xmlPath:xml文件路径;userName:用户名称 //return:bool bool deleteUserByName(const char *xmlPath, const char *userName) { tinyxml2::XMLDocument doc; if (doc.LoadFile(xmlPath) != 0) { std::cout << "load xml file failed" << std::endl; return false; } tinyxml2::XMLElement *root = doc.RootElement(); //doc.DeleteNode(root);//删除xml所有节点 tinyxml2::XMLElement *userNode = queryUserNodeByName(root, userName); if (userNode != NULL) { userNode->DeleteAttribute("Password"); //删除属性 tinyxml2::XMLElement *emailNode = userNode->FirstChildElement("Email"); userNode->DeleteChild(emailNode); //删除指定节点 //userNode->DeleteChildren();//删除节点的所有孩子节点 if (doc.SaveFile(xmlPath) == 0) return true; } return false; } //function:获取xml文件申明 //param:xmlPath:xml文件路径;strDecl:xml申明 //return:bool bool getXMLDeclaration(const char *xmlPath) { tinyxml2::XMLDocument doc; if (doc.LoadFile(xmlPath) != 0) { std::cout << "load xml file failed" << std::endl; return false; } tinyxml2::XMLNode *decl = doc.FirstChild(); if (NULL != decl) { tinyxml2::XMLDeclaration *declaration = decl->ToDeclaration(); if (NULL != declaration) { std::cout << declaration->Value() << std::endl; return true; } } return false; } //function:将xml文件内容输出到标准输出 //param:xmlPath:xml文件路径 void printXML(const char *xmlPath) { tinyxml2::XMLDocument doc; if (doc.LoadFile(xmlPath) != 0) { std::cout << "load xml file failed" << std::endl; return; } doc.Print(); // tinyxml2::XMLPrinter printer; // doc.Print(&printer); } int main(int argc, char const *argv[]) { if (createXML("test.xml")) { std::cout << "createXML test.xml error" << std::endl; } else { insertXMLNode("test.xml"); select("test.xml", "root"); updateUser("test.xml", "root"); select("test.xml", "root"); deleteUserByName("test.xml", "root"); select("test.xml", "root"); getXMLDeclaration("test.xml"); printXML("test.xml"); } return 0; } <file_sep>include ../Makefile.rc <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <dlfcn.h> int main(int argc, char const *argv[]) { void *handle = dlopen(argv[1], RTLD_NOW); if (handle == NULL) { printf("打开动态库失败\n"); exit(0); } void (*func)(void); func = dlsym(handle, "regconize");// 找函数 if (func == NULL) { printf("error: %s\n", strerror(errno)); exit(0); } // 调用接口 func(); dlclose(handle); return 0; } <file_sep>#---------------------------------------------------------------- # Generated CMake target import file. #---------------------------------------------------------------- # Commands may need to know the format version. set(CMAKE_IMPORT_FILE_VERSION 1) # Import target "pugixml-static" for configuration "" set_property(TARGET pugixml-static APPEND PROPERTY IMPORTED_CONFIGURATIONS NOCONFIG) set_target_properties(pugixml-static PROPERTIES IMPORTED_LINK_INTERFACE_LANGUAGES_NOCONFIG "CXX" IMPORTED_LOCATION_NOCONFIG "${_IMPORT_PREFIX}/lib/libpugixml-static.a" ) list(APPEND _IMPORT_CHECK_TARGETS pugixml-static ) list(APPEND _IMPORT_CHECK_FILES_FOR_pugixml-static "${_IMPORT_PREFIX}/lib/libpugixml-static.a" ) # Import target "pugixml-shared" for configuration "" set_property(TARGET pugixml-shared APPEND PROPERTY IMPORTED_CONFIGURATIONS NOCONFIG) set_target_properties(pugixml-shared PROPERTIES IMPORTED_LOCATION_NOCONFIG "${_IMPORT_PREFIX}/lib/libpugixml-shared.so.1.10" IMPORTED_SONAME_NOCONFIG "libpugixml-shared.so.1" ) list(APPEND _IMPORT_CHECK_TARGETS pugixml-shared ) list(APPEND _IMPORT_CHECK_FILES_FOR_pugixml-shared "${_IMPORT_PREFIX}/lib/libpugixml-shared.so.1.10" ) # Commands beyond this point should not need to know the version. set(CMAKE_IMPORT_FILE_VERSION) <file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> // 二叉链表法 typedef struct BiTree { int data; struct BiTree *lchild, *rchild; }BiTree, *pBiTree; // 三叉链表法 typedef struct TriTree { int data; struct BiTree *lchild, *rchild; struct BiTree *parent; }TriTree, *pTriTree; // 双亲链表法 #define MAX_TREE_SIZE 100 typedef struct BPTNode { int data; int parentPosition;// 指向双亲的指针,数组下标 char LRTab;// 左右孩子标签域 }BPTNode, *pBPTNode; typedef struct BPTree { BPTNode nodes[MAX_TREE_SIZE]; int num_node;// 节点数目 int root;// 根结点数目 }BPTree, *pBPTree; int main(int argc, char const *argv[]) { #if 0 BiTree t1, t2, t3, t4, t5; t1.data = 1; t2.data = 2; t3.data = 3; t4.data = 4; t5.data = 5; t1.lchild = &t2; t1.rchild = &t3; t2.lchild = &t4; t3.lchild = &t5; #endif BPTree tree; tree.nodes[0].parentPosition = 1000; tree.nodes[1].parentPosition = 0; tree.nodes[1].data = 'B'; tree.nodes[1].LRTab = 'r'; tree.nodes[2].parentPosition = 0; tree.nodes[2].data = 'C'; tree.nodes[2].LRTab = 'r'; return 0; } <file_sep>#include <stdio.h> #include "include/libyuv.h" typedef unsigned char uint8; int libyuv_I420_to_Rgb() { const int width = 1920, height = 1080; FILE *src_file = fopen("test.yuv", "rb"); FILE *dst_file = fopen("test.rgb", "wb"); int size_src = width * height * 3 / 2; int size_dest = width * height * 4; char *buffer_src = (char *)malloc(size_src); char *buffer_dest = (char *)malloc(size_dest); if (buffer_dest == NULL || buffer_src == NULL) { printf("malloc null \n"); return -1; } while (1){ if (fread(buffer_src, 1, size_src, src_file) != size_src){ //fseek(src_file, 0, 0); //fread(buffer_src, 1, size_src, src_file); break; } //libyuv::I420ToARGB(const uint8* src_y, int src_stride_y, // const uint8* src_u, int src_stride_u, // const uint8* src_v, int src_stride_v, // uint8* dst_argb, int dst_stride_argb, // int width, int height); I420ToARGB((const uint8*)buffer_src, width, (const uint8*)(buffer_src + width * height), width / 2, (const uint8*)(buffer_src + width * height * 5 / 4), width / 2, (uint8*)buffer_dest, width * 4, width, height); fwrite(buffer_dest, 1, size_dest, dst_file); } free(buffer_src); free(buffer_dest); fclose(dst_file); fclose(src_file); return 0; } int main(int argc, char const *argv[]) { libyuv_I420_to_Rgb(); return 0; } <file_sep>/* 词汇分割器库 Boost.Tokenizer */ #include <iostream> #include <string> #include "boost/tokenizer.hpp" void test1() { typedef boost::tokenizer<boost::char_separator<char> > tokenizer; std::string s = "Boost C++ libraries1."; // tokenizer tok(s); // boost::char_separator<char> sep(" "); // tokenizer tok(s, sep); // 以sep(" ")设定的符号分割 boost::char_separator<char> sep(" ", "+"); tokenizer tok(s, sep); // 以sep(" ", "+")设定的符号分割,第二个参数指定了需要显示的分隔符 for (tokenizer::iterator it = tok.begin(); it != tok.end(); ++it) { std::cout << *it << std::endl; } } void test2() { typedef boost::tokenizer<boost::char_separator<char> > tokenizer; std::string s = "Boost C++ libraries"; // 如果连续找到两个分隔符,他们之间的部分表达式将为空。 // 在默认情况下,这些空表达式是不会显示的。第三个参数可以改变默认的行为 boost::char_separator<char> sep(" ", "+", boost::keep_empty_tokens); tokenizer tok(s, sep); for (tokenizer::iterator it = tok.begin(); it != tok.end(); ++it) { std::cout << *it << std::endl; } } void test3() { typedef boost::tokenizer<boost::char_separator<wchar_t>, std::wstring::const_iterator, std::wstring> tokenizer; std::wstring s = L"Boost C++ libraries"; boost::char_separator<wchar_t> sep(L" "); tokenizer tok(s, sep); for (tokenizer::iterator it = tok.begin(); it != tok.end(); ++it) { std::wcout << *it << std::endl; } } void test4() { // boost::escaped_list_separator 类用于读取由逗号分隔的多个值 // 它甚至还可以处理双引号以及转义序列 typedef boost::tokenizer<boost::escaped_list_separator<char> > tokenizer; std::string s = "Boost,\"C++ libraries\""; tokenizer tok(s); for (tokenizer::iterator it = tok.begin(); it != tok.end(); ++it) { std::cout << *it << std::endl; } } void test5() { typedef boost::tokenizer<boost::offset_separator> tokenizer; // 5 5 9 std::string s = "Boost C++ libraries"; // boost::offset_separator 指定了部分表达式应当在字符串中的哪个位置结束 int offsets[] = { 5, 5, 9 }; boost::offset_separator sep(offsets, offsets + 3); tokenizer tok(s, sep); for (tokenizer::iterator it = tok.begin(); it != tok.end(); ++it) { std::cout << *it << std::endl; } } int main(int argc, char const *argv[]) { test5(); return 0; } <file_sep>#pragma once #include <iostream> #include <sys/time.h> #define DEBUG class CTimer { public: /*** * @brief Timer start record */ inline void start() { gettimeofday(&startTime, NULL); } /*** * @brief Timer stop record * @return: type long, Unit Microseconds */ inline long end(std::string str = "timer") { gettimeofday(&endTime, NULL); long elapsedTime = (endTime.tv_sec - startTime.tv_sec) * 1000 * 1000 + (endTime.tv_usec - startTime.tv_usec); #ifdef DEBUG std::cout << str << ":" << elapsedTime / 1000 << "ms" << std::endl; #endif return elapsedTime; } private: struct timeval startTime, endTime; }; class Timer { public: /*** * @brief Timer start record */ inline void start() { _start = clock(); } /*** * @brief Timer stop record * @return: type long, Unit Microseconds */ inline long end(std::string str = "timer") { _end = clock(); double elapsedTime = ((double)(_end - _start)/CLOCKS_PER_SEC); #ifdef DEBUG std::cout << str << ":" << elapsedTime << "ms" << std::endl; #endif return elapsedTime; } private: clock_t _start, _end; }; <file_sep>#include <iostream> #include <gtest/gtest.h> #include <gmock/gmock.h> #include <string> using namespace std; class Parent { public: virtual ~Parent() {} virtual int getNum() const = 0; virtual void setResult(int value) = 0; virtual void print(const string &str) = 0; virtual int calc(int a, double b) = 0; }; class Target { public: Target(Parent *parent) : parent_(parent) { } int doThis() { int v = parent_->getNum(); parent_->setResult(v); while (v -- > 0) { parent_->print(to_string(v)); } return parent_->getNum(); } int doThat() { return parent_->calc(1, 2.2); } private: Parent *parent_; }; class MockParent : public Parent { public: //! MOCK_[CONST_]METHODx(方法名, 返回类型(参数类型列表)); MOCK_CONST_METHOD0(getNum, int()); //! 由于 getNum() 是 const 成员函数,所以要使用 MOCK_CONST_METHODx MOCK_METHOD1(setResult, void(int)); MOCK_METHOD1(print, void(const string &)); MOCK_METHOD2(calc, int(int, double)); }; using ::testing::Return; using ::testing::_; TEST(demo, 1) { MockParent p; Target t(&p); //! 设置 p.getNum() 方法的形为 EXPECT_CALL(p, getNum()) .Times(2) //! 期望被调两次 .WillOnce(Return(2)) //! 第一次返回值为2 .WillOnce(Return(10)); //! 第二次返回值为10 //! 设置 p.setResult(), 参数为2的调用形为 EXPECT_CALL(p, setResult(2)) .Times(1); EXPECT_CALL(p, print(_)) //! 表示任意的参数,其中 _ 就是 ::testing::_ ,如果冲突要注意 .Times(2); EXPECT_EQ(t.doThis(), 10); } TEST(demo, 2) { MockParent p; Target t(&p); EXPECT_CALL(p, calc(1, 2.2)) .Times(1) .WillOnce(Return(3)); EXPECT_EQ(t.doThat(), 3); } TEST(Codec, DecodeH264) { } TEST(main, DecodeH264) { } int main(int argc, char const *argv[]) { ::testing::GTEST_FLAG(output) = "xml:";// 输出测试结果到xml文件 ::testing::InitGoogleTest(&argc, (char **)argv); return RUN_ALL_TESTS(); } <file_sep>#include <stdio.h> int binSearch(int arr[], int len, int key) { int left = 0; int right = len - 1; int mid; while (left <= right) { mid = (left + right) / 2; if (arr[mid] == key) { return mid; }else if (arr[mid] < key) { left = mid+1; }else{ right = mid-1; } } return -1; } int main(int argc, char const *argv[]) { int arr[] = {1,2,4,5,7,9,11,23,44,56}; printf("%d\n", binSearch(arr, 10, 5)); return 0; } <file_sep>CC = gcc CXX = g++ D = SRCS += $(wildcard *.cpp) OBJS += $(patsubst %.cpp, %.o, $(SRCS)) TARGETS += $(SRCS:%.cpp=%) INCLUDE += -I$(PWD)/../../zlib-1.2.11/include LIB_PATH += -L$(PWD)/../../zlib-1.2.11/lib LIB_LINK += -lz CFLAGS += -g -Wall -std=c++11 all:$(TARGETS) $(TARGETS):%:%.o $(CXX) $^ -o $@ $(INCLUDE) $(LIB_PATH) $(LIB_LINK) $(CFLAGS) # @rm -rf $(OBJS) %.o:%.cpp $(CXX) -c $< -o $@ $(CFLAGS) $(INCLUDE) .PHONY: clean clean: @rm -rf $(TARGETS) $(OBJS) D: gcc $(demo) -o $(demo) $(INCLUDE) $(LIB_PATH) $(LIB_LINK) $(CFLAGS)<file_sep>/* 函数对象 */ #include <iostream> #include <vector> #include <algorithm> #include <boost/bind.hpp> using namespace std; namespace Boost_Bind{// Boost.Bind && Boost.Ref void printv(int num) { std::cout << num << std::endl; } // 函数对象 class Add : public std::binary_function<int, int, void>// 参1、参2、返回类型 { public: void operator()(int i, int j) const {// 仿函数 cout << i + j << endl; } }; void Add2(int i, int j) { cout << i + j << endl; } void Add3(int i, int j, std::ostream &out) { out << i + j << std::endl; } bool compare(int i, int j) { return i > j; } void test() { std::vector<int> v; v.push_back(1); v.push_back(3); v.push_back(2); std::for_each(v.begin(), v.end(), printv); std::for_each(v.begin(), v.end(), std::bind1st(Add(), 10)); std::for_each(v.begin(), v.end(), boost::bind(Add2, 10, _1));// 一元函数 // std::sort(v.begin(), v.end(), compare); std::sort(v.begin(), v.end(), boost::bind(compare, _1, _2));// 二元函数,(降序多余操作) std::sort(v.begin(), v.end(), boost::bind(compare, _2, _1));// 二元函数,(升序操作) // 要以引用方式传递常量对象,可以使用模板函数 boost::cref() std::for_each(v.begin(), v.end(), boost::bind(Add3, 10, _1, boost::ref(std::cout))); for (unsigned int i = 0; i < v.size(); i++) { std::cout << v[i] << " "; } std::cout << std::endl; } } #include "boost/function.hpp" namespace Boost_Function {// Boost.Function struct world { void Hello(std::ostream &out) { out << "Hello, world!" << std::endl; } }; void test() { boost::function<int (const char *)> FUNC = std::atoi; std::cout << FUNC("100") << std::endl; FUNC = std::strlen; std::cout << FUNC("123456") << std::endl; try { boost::function<int (const char*)> f; f(""); } catch (boost::bad_function_call &ex) { std::cout << ex.what() << std::endl; } boost::function<void (world*, std::ostream&)> f = &world::Hello; world w; f(&w, boost::ref(std::cout)); } } #include "boost/lambda/lambda.hpp" #include "boost/lambda/if.hpp" namespace Boost_Lambda{// Boost.Lambda void test() { std::vector<int> v; v.push_back(1); v.push_back(3); v.push_back(2); // 要插入换行的话,必须用 "\n" 来替代 std::endl 才能成功编译 std::for_each(v.begin(), v.end(), std::cout << boost::lambda::_1 << "\n"); // 只将大于1的元素写出到标准输出流 std::for_each(v.begin(), v.end(), boost::lambda::if_then(boost::lambda::_1 > 1, \ std::cout << boost::lambda::_1 << "\n")); } } class divide_by : public std::binary_function<int, int, int> { public: int operator()(int n, int div) const { return n / div; } }; int divide_by2(int n, int div) { return n / div; } void test() { std::vector<int> numbers; numbers.push_back(10); numbers.push_back(20); numbers.push_back(30); // std::transform(numbers.begin(), numbers.end(), numbers.begin(), std::bind2nd(divide_by(), 2)); // std::transform(numbers.begin(), numbers.end(), numbers.begin(), boost::bind(divide_by2, 2, _1)); for (std::vector<int>::iterator it = numbers.begin(); it != numbers.end(); ++it) { std::cout << *it << std::endl; } } int main(int argc, char const *argv[]) { // Boost_Bind::test(); // Boost_Function::test(); // Boost_Lambda::test(); test(); return 0; } <file_sep>#include <iostream> #include "json/json.h" void sample1() { Json::Value root; Json::Value data; root["action"] = "run"; data["number"] = 1; root["data"] = data; // constexpr bool shouldUseOldWay = true; // 过时版本 // if (shouldUseOldWay)// 去除格式化 // { // Json::FastWriter writer; // const std::string json_file = writer.write(root); // std::cout << json_file << std::endl; // } // else// 格式化 { Json::StreamWriterBuilder builder; const std::string json_file = Json::writeString(builder, root); std::cout << json_file << std::endl; } } void sample2() { Json::Value root; Json::Value data; root["action"] = "run"; data["number"] = 1; root["data"] = data; Json::StreamWriterBuilder builder; const std::string json_file = Json::writeString(builder, root); std::cout << json_file << std::endl; } void sample3() { // 构建json数组 Json::Value array; Json::Value array2; Json::Value root; Json::Value person; Json::Value data; // 添加数组1 person["name"] = "allen"; person["age"] = 10; person["sex"] = "male"; // root.append(person); array[0] = person; person["name"] = "keiv"; person["age"] = 20; person["sex"] = "female"; array[1] = person; person["name"] = "lihua"; person["age"] = 10; person["sex"] = "female"; array[2] = person; // 数组加道root root["array"] = Json::Value(array); // 添加结点 data["number"] = 1; root["data"] = data; // root添加成员 root["111"] = "111"; root["444"] = true; root["333"] = 44; root["22"] = 44.66; // 在数组1上在再添加一个数组成员 person["name"] = "lihua"; person["age"] = 10; person["sex"] = "female"; array[3] = person; root["array"] = Json::Value(array);// 必须再添加一次 // 添加第二个数组 person["name"] = "allen"; person["age"] = 10; person["sex"] = "male"; // root.append(person); array2[0] = person; root["array2"] = Json::Value(array2); #if 1 Json::String strValue = root.toStyledString(); std::cout << strValue << std::endl; #else Json::StreamWriterBuilder builder; const std::string data = Json::writeString(builder, root); std::cout << data << std::endl; #endif // 解析Json字符串 Json::Value value; Json::Value bRoot; JSONCPP_STRING err; Json::CharReaderBuilder builder; const std::unique_ptr<Json::CharReader> reader(builder.newCharReader()); if (!reader->parse(strValue.c_str(), strValue.c_str() + strValue.length(), &bRoot, &err)) { std::cout << err.data() << std::endl; return; } // 数组 Json::Value arr = bRoot["array"]; for (unsigned int i = 0; i < arr.size(); i++) { Json::String name = arr[i]["name"].asString(); int age = arr[i]["age"].asInt(); Json::String sex = arr[i]["sex"].asString(); std::cout << name << " " << age << " " << sex << std::endl; } std::cout << bRoot["111"] << std::endl; std::cout << bRoot["data"]["number"] << std::endl; } int main(int argc, char const *argv[]) { sample3(); return 0; } <file_sep>/* 事件处理 */ #include <iostream> #include <algorithm> #include <vector> #include "boost/signals2.hpp" #include "boost/function.hpp" #include "boost/lambda/lambda.hpp" #include "boost/bind.hpp" int func(int i) { std::cout << "[func ------]" << i << ":Hello world" << std::endl; return 1; } int func2(int i) { std::cout << "[func2 ++++++]" << i << ":Hello world" << std::endl; return 100; } void test1() { boost::signals2::signal<int (int)> s; // 按顺序 // s.connect(func); // s.connect(func2); // 按值 boost::signals2::connection c = s.connect(1, func);// c可以管理s s.connect(0, func2); s.disconnect(func); if (!s.empty()){ std::cout << s.num_slots() << std::endl; s(1); s.disconnect_all_slots(); } boost::function<int (int)> f; f = func; f = func2; f(2); } // 合成器(combiner) // boost::signal 要求这个合成器定义一个名为 result_type 的类型,用于说明 operator()() 操作符返回值的类型 // 返回最小的一个值 template <typename T> struct min_element { typedef T result_type; template <typename InputIterator> T operator()(InputIterator first, InputIterator last) const { return *std::min_element(first, last); } }; void test2() { boost::signals2::signal<int (int), min_element<int> > s; s.connect(func); s.connect(func2); std::cout << s(2) << std::endl;// 返回最小值,而不是最后一个 } // 保存所有返回值 template <typename T> struct element { typedef T result_type; template <typename InputIterator> T operator()(InputIterator first, InputIterator last) const { return T(first, last); } }; void test3() { boost::signals2::signal<int (int), element<std::vector<int> > > s; s.connect(1, func); s.connect(0, func2); std::vector<int> v = s(1); std::for_each(v.begin(), v.end(), std::cout << boost::lambda::_1 << " "); // std::cout << *std::min_element(v.begin(), v.end()) << std::endl; } void test4() { boost::signals2::signal<void()> s; boost::signals2::connection c = s.connect([]{ std::cout << "Hello, world!\n"; }); s(); boost::signals2::shared_connection_block b1{c, false}; b1.block();// 被 block() 调用所阻塞 std::cout << std::boolalpha << b1.blocking() << '\n';// std::boolalpha指定输出格式:false, 若无:1 s(); b1.unblock();// 被 unblock() 解除阻塞 s(); } void test5() { boost::signals2::signal<int (int)> s; { // 作用域连接:在析构时自动释放连接 boost::signals2::scoped_connection c = s.connect(func); } s(1); } class world : public boost::signals2::trackable { public: void hello() const { std::cout << "Hello, world!" << std::endl; } }; void test6() { boost::signals2::signal<void ()> s; { std::shared_ptr<world> w(new world()); s.connect(boost::bind(&world::hello, w.get())); } // 继承boost::signals2::trackable, 以确保不会试图调用已销毁对象之上的方法 std::cout << s.num_slots() << std::endl; s(); } int main(int argc, char const *argv[]) { test6(); return 0; } <file_sep>#include "MySqlAbstract.h" class MySQL : public MySqlAbstract { public: MySQL(MySQL_Info &info); virtual ~MySQL(); virtual bool connectToMysql(); virtual void operateMysqlSelect(const char *Mysql_Sentence); virtual void operateMysqlQuery(const char *Mysql_Sentence); virtual void resetConn(); virtual void disconnectToMysql(); private: }; <file_sep>#include <stdio.h> #include <string.h> #include <unistd.h> #include <assert.h> #include <sys/types.h> #include <sys/stat.h> #include <arpa/inet.h> #include <signal.h> #include <netinet/in.h> #include <sys/socket.h> #include <event2/bufferevent.h> #include <event2/buffer.h> #include <event2/listener.h> #include <event2/util.h> #include <event2/event.h> #include <event2/thread.h> #define SERVER_IP "0.0.0.0" #define SERVER_PORT 8899 void listener_cb(struct evconnlistener *listener, evutil_socket_t fd, \ struct sockaddr *sock, int socklen, void *arg); void socket_read_cb(struct bufferevent *bev, void *arg); void conn_writecb(struct bufferevent *bev, void *user_data); void socket_event_cb(struct bufferevent *bev, short events, void *arg); void signal_cb(evutil_socket_t sig, short events, void *user_data); int main(int argc, char **argv) { // 创建监听套接字、绑定、监听、等待连接 struct event_base *base = event_base_new(); assert(base != NULL); // 初始化服务器地址和端口 struct sockaddr_in sin; memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_port = htons(SERVER_PORT); inet_pton(AF_INET, SERVER_IP, &sin.sin_addr.s_addr); struct evconnlistener *listener = evconnlistener_new_bind(base, listener_cb, base, LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE, 10, (struct sockaddr *)&sin, sizeof(sin)); assert(listener != NULL); event_base_dispatch(base); struct event *signal_event; signal_event = evsignal_new(base, SIGINT, signal_cb, (void *)base); if (!signal_event || event_add(signal_event, NULL) < 0) { fprintf(stderr, "Could not create/add a signal event!\n"); return 1; } evconnlistener_free(listener); event_free(signal_event); event_base_free(base); printf("done\n"); return 0; } void listener_cb(struct evconnlistener *listener, evutil_socket_t fd, struct sockaddr *sock, int socklen, void *arg) { printf("accept a client %d\n", fd); struct event_base *base = (struct event_base *)arg; //设置socket为非阻塞 //evutil_make_socket_nonblocking(fd); // 创建一个struct bufferevent *bev,关联该sockfd,托管给event_base struct bufferevent *bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE); if (!bev) { fprintf(stderr, "Error constructing bufferevent!"); event_base_loopbreak(base); return; } // 设置读写对应的回调函数 // bufferevent_setcb(bev, socket_read_cb, conn_writecb, socket_event_cb, NULL); bufferevent_setcb(bev, socket_read_cb, NULL, socket_event_cb, NULL); //启用读写事件,其实是调用了event_add将相应读写事件加入事件监听队列 // EV_WRITE默认是使能 bufferevent_enable(bev, EV_READ | EV_PERSIST); // 写数据回去,告诉连接上了 const char *MESSAGE = "connect success."; bufferevent_write(bev, MESSAGE, strlen(MESSAGE) + 1); } void socket_read_cb(struct bufferevent *bev, void *arg) { #if 1 // 读到 char buf[1024] = {0}; size_t len = bufferevent_read(bev, buf, sizeof(buf)); printf("read = %s, len = %d\n", buf, (int)len); // 写回去 const char *MESSAGE = "data is recv ok."; bufferevent_write(bev, MESSAGE, strlen(MESSAGE) + 1); printf("send bask ok.\n"); #else struct evbuffer *input, *output; char *request_line; size_t len; input = bufferevent_get_input(bev); //其实就是取出bufferevent中的input output = bufferevent_get_output(bev); //其实就是取出bufferevent中的output size_t input_len = evbuffer_get_length(input); printf("input_len: %d\n", input_len); size_t output_len = evbuffer_get_length(output); printf("output_len: %d\n", output_len); while (1) { request_line = evbuffer_readln(input, &len, EVBUFFER_EOL_CRLF); //从evbuffer前面取出一行,用一个新分配的空字符结束 // 的字符串返回这一行,EVBUFFER_EOL_CRLF表示行尾是一个可选的回车,后随一个换行符 if (NULL == request_line) { printf("The first line has not arrived yet.\n"); free(request_line); //之所以要进行free是因为 line = mm_malloc(n_to_copy+1)),在这里进行了malloc break; } else { printf("Get one line date: %s\n", request_line); if (strstr(request_line, "over") != NULL) //用于判断是不是一条消息的结束 { char *response = "Response ok! Hello Client!\r\n"; evbuffer_add(output, response, strlen(response)); //Adds data to an event buffer printf("服务端接收一条数据完成,回复客户端一条消息: %s\n", response); free(request_line); break; } } free(request_line); } size_t input_len1 = evbuffer_get_length(input); printf("input_len1: %d\n", input_len1); size_t output_len1 = evbuffer_get_length(output); printf("output_len1: %d\n\n", output_len1); #endif } // bufferevent 写回调函数 void conn_writecb(struct bufferevent *bev, void *user_data) { // bufferevent_write(bev, MESSAGE, strlen(MESSAGE)+1);已经发出去了 struct evbuffer *output = bufferevent_get_output(bev); if (evbuffer_get_length(output) == 0) { printf("flushed answer\n"); bufferevent_free(bev); } } void socket_event_cb(struct bufferevent *bev, short events, void *arg) { if (events & BEV_EVENT_EOF) { printf("connection closed\n"); } else if (events & BEV_EVENT_ERROR) { printf("some other error\n"); } bufferevent_free(bev); } void signal_cb(evutil_socket_t sig, short events, void *user_data) { struct event_base *base = static_cast<struct event_base *>(user_data); struct timeval delay = {2, 0}; printf("Caught an interrupt signal; exiting cleanly in two seconds.\n"); // 捕捉到信号2秒后退出 event_base_loopexit(base, &delay); } <file_sep>/* 1、过滤器(Filter) - 过滤器在请求处理程序执行请求之前或之后,执行某些任务。 @ 过滤器配合责任链模式,可以实现过滤器链。 @ 过滤器链(Filter Chain) - 过滤器链带有多个过滤器,并在 Target 上按照定义的顺序执行这些过滤器。 */ #include <iostream> #include <string> #include <list> using namespace std; class Person { //被过滤的对象的类型 private: string name; string gender; string work_num; public: Person(string name, string gender, string work_num) { this->name = name; this->gender = gender; this->work_num = work_num; } string get_name() { return this->name; } string get_gender() { return this->gender; } string get_work_num() { return this->work_num; } }; class Filter { //过滤器基类 public: virtual ~Filter() {} virtual list<Person> filter(list<Person> &persons) = 0; virtual Filter *clone() = 0; }; class Name_Filter : public Filter { //名称过滤器 private: string name; public: Name_Filter(string name) { this->name = name; } list<Person> filter(list<Person> &persons) { list<Person> result_persons; for (list<Person>::iterator it = persons.begin(); it != persons.end(); ++it) { if ((*it).get_name().find_first_of(name, 0) != -1) { result_persons.push_back(*it); } } return result_persons; } Name_Filter *clone() { Name_Filter *filter = new Name_Filter(""); *filter = *this; return filter; } }; class Gender_Filter : public Filter { //性别过滤器 private: string gender; public: Gender_Filter(string gender) { this->gender = gender; } list<Person> filter(list<Person> &persons) { list<Person> result_persons; for (list<Person>::iterator it = persons.begin(); it != persons.end(); ++it) { if ((*it).get_gender() == this->gender) { result_persons.push_back(*it); } } return result_persons; } Gender_Filter *clone() { Gender_Filter *filter = new Gender_Filter(""); *filter = *this; return filter; } }; class WorkNum_Filter : public Filter { //工号过滤器 private: string work_num; public: WorkNum_Filter(string work_num) { this->work_num = work_num; } list<Person> filter(list<Person> &persons) { list<Person> result_persons; for (list<Person>::iterator it = persons.begin(); it != persons.end(); ++it) { if ((*it).get_work_num().find_first_of(work_num, 0) != -1) { result_persons.push_back(*it); } } return result_persons; } WorkNum_Filter *clone() { WorkNum_Filter *filter = new WorkNum_Filter(""); *filter = *this; return filter; } }; class List_Filter : public Filter { //过滤管道 private: list<Filter *> filters; public: List_Filter(list<Filter *> filters) { this->filters = filters; } ~List_Filter() { for (list<Filter *>::iterator filter = filters.begin(); filter != filters.end(); ++filter) { delete *filter; *filter = NULL; } } list<Person> filter(list<Person> &persons) { list<Person> result_persons = persons; for (list<Filter *>::iterator filter = filters.begin(); filter != filters.end(); ++filter) { result_persons = (*filter)->filter(result_persons); } return result_persons; } List_Filter *clone() { return NULL; } }; void print_Persons(list<Person> persons) { for (list<Person>::iterator person = persons.begin(); person != persons.end(); ++person) { cout << (*person).get_name() << " " << (*person).get_gender() << " " << (*person).get_work_num() << endl; } } int main(int argc, const char *argv[]) { list<Person> persons; persons.push_back(Person("a", "男", "1")); persons.push_back(Person("ab", "女", "66")); persons.push_back(Person("abc", "男", "166")); persons.push_back(Person("b", "男", "61")); persons.push_back(Person("bc", "女", "16")); persons.push_back(Person("bcd", "男", "21")); persons.push_back(Person("c", "女", "88")); persons.push_back(Person("cd", "男", "101")); persons.push_back(Person("cde", "女", "102")); list<Filter *> filters; // 第一个字母是a Filter *filter = new Name_Filter("a"); print_Persons(filter->filter(persons)); filters.push_back(filter->clone()); delete filter; cout << endl; // 男性 filter = new Gender_Filter("男"); print_Persons(filter->filter(persons)); filters.push_back(filter->clone()); delete filter; cout << endl; filter = new WorkNum_Filter("6"); print_Persons(filter->filter(persons)); filters.push_back(filter->clone()); delete filter; cout << endl; filter = new List_Filter(filters); print_Persons(filter->filter(persons)); delete filter; filter = NULL; return 0; } <file_sep>#pragma #include <iostream> int add(int x, int y);<file_sep>#include <iostream> #include "opencv2/opencv.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/highgui.hpp" #define RTSP_ADDR "rtsp://admin:[email protected]:554/h264/ch1/main/av_stream" int main() { cv::VideoCapture vCap(RTSP_ADDR, cv::CAP_ANY); if (!vCap.isOpened()) { std::cout << "VideoCapture is not open!" << std::endl; return 0; } // 获取视频的分辨率 int width = static_cast<int>(vCap.get(cv::CAP_PROP_FRAME_WIDTH)); int height = static_cast<int>(vCap.get(cv::CAP_PROP_FRAME_HEIGHT)); // 设置输出格式RGB // vCap.set(cv::CAP_PROP_CONVERT_RGB, 1.0); int format = static_cast<int>(vCap.get(cv::CAP_PROP_FORMAT)); std::cout << "format:" << format << std::endl; cv::Mat frame; vCap.read(frame); cv::imwrite("1.jpg", frame); vCap.release(); return 0; } <file_sep>#include <iostream> using namespace std; #if 1 template <typename T, typename U> // decltype(T() + U()) add(T t, U u) auto add(T t, U u) -> decltype(t + u) // 推荐使用 --》 返回类型后置(trailing-return-type,又称跟踪返回类型)语法 { return t + u; } #else // 考虑到 T、U 可能是没有无参构造函数的类,正确的写法应该是这样 template <typename T, typename U> decltype((*(T*)0) + (*(U*)0)) add(T t, U u) { return t + u; } #endif void operator"" _log(unsigned long long n) { cout << n << endl; } // 类型别名模板 template< typename T, typename U> class SuckType { public: T a; U b; SuckType(int value):a(value),b(value){} }; template <typename T> using NewType = SuckType<int, T>; // 合法 void test1() { 5_log; NewType<int> a(2); cout << add(10, '1') << endl; } int main(int argc, char const *argv[]) { test1(); return 0; } <file_sep>#include <boost/system/error_code.hpp> #include <boost/asio.hpp> #include <iostream> #include <string> int main() { boost::system::error_code ec; std::string hostname = boost::asio::ip::host_name(ec); std::cout << hostname << " -- " << ec.value() << std::endl; std::cout << ec.category().name() << std::endl; }<file_sep>#include <iostream> #include <thread> #include <chrono> #include <mutex> #include <unistd.h> class Thread { public: Thread() : m_bThreadExit(false) {} ~Thread() { this->stop(); } void start() { this->m_bThreadExit = false; m_runTask = std::thread(&Thread::run, this);// 创建线程并返回句柄 } void stop() { if (!this->m_bThreadExit) { this->m_bThreadExit = true; m_runTask.join(); } } private: void run() { while (!m_bThreadExit) { std::cout << "2222222222222" << std::endl; sleep(1); } } bool m_bThreadExit; std::thread m_runTask; std::mutex m_Mutex; }; int main(int argc, char const *argv[]) { Thread th; th.start(); sleep(5); th.stop(); return 0; } <file_sep>#include "calc.h" int main(int argc, char const *argv[]) { std::cout << add(2, 3) << std::endl; return 0; } <file_sep>#pragma once #include <iostream> #include <string> #include <memory> #include <mutex> #include </usr/include/mysql/mysql.h> typedef struct _MySQL_INFO { std::string user; //username std::string pswd; //password std::string host; //host address std::string database; //database unsigned int port; //server port }MySQL_Info; class MySqlAbstract { public: MySqlAbstract(MySQL_Info &info):m_bInfo(info) { m_bMysql.reset(new MYSQL()); }; virtual ~MySqlAbstract() {}; /* Connect to MYSQL */ virtual bool connectToMysql() = 0; /* select informations */ virtual void operateMysqlSelect(const char *Mysql_Sentence) = 0; /* Exec MYSQL instruction */ virtual void operateMysqlQuery(const char *Mysql_Sentence) = 0; /* reconnected */ virtual void resetConn() = 0; /* Disconnect */ virtual void disconnectToMysql() = 0; protected: std::shared_ptr<MYSQL> m_bMysql; MySQL_Info m_bInfo; }; <file_sep>/* 正则表达式 普通字符: runoo+b,可以匹配 runoob、runooob、runoooooob 等 + 号代表前面的字符必须至少出现一次(1次或多次)。 runoo*b,可以匹配 runob、runoob、runoooooob 等 * 号代表前面的字符可以不出现,也可以出现一次或者多次(0次、或1次、或多次)。 colou?r 可以匹配 color 或者 colour ? 问号代表前面的字符最多只可以出现一次(0次、或1次)。 [aeiou] 匹配字符串 匹配 aeiou 所有字符 [^aeiou] 匹配字符串 除了 e o u a 字母的所有字母 [A-Z] 表示一个区间, 匹配所有大写字母 [a-z] 表示一个区间, 表示所有小写字母。 . 匹配除换行符(\n、\r)之外的任何单个字符,相等于 [^\n\r] [\s\S] 匹配所有。\s 是匹配所有空白符,包括换行,\S 非空白符,包括换行。 \w 匹配字母、数字、下划线。等价于 [A-Za-z0-9_] 非打印字符: \cx 匹配由x指明的控制字符。例如, \cM 匹配一个 Control-M 或回车符。x 的值必须为 A-Z 或 a-z 之一。否则,将 c 视为一个原义的 'c' 字符。 \f 匹配一个换页符。等价于 \x0c 和 \cL。 \n 匹配一个换行符。等价于 \x0a 和 \cJ。 \r 匹配一个回车符。等价于 \x0d 和 \cM。 \s 匹配任何空白字符,包括空格、制表符、换页符等等。等价于 [ \f\n\r\t\v]。注意 Unicode 正则表达式会匹配全角空格符。 \S 匹配任何非空白字符。等价于 [^ \f\n\r\t\v]。 \t 匹配一个制表符。等价于 \x09 和 \cI。 \v 匹配一个垂直制表符。等价于 \x0b 和 \cK。 特殊字符: $ 匹配输入字符串的结尾位置。如果设置了 RegExp 对象的 Multiline 属性,则 $ 也匹配 '\n' 或 '\r'。要匹配 $ 字符本身,请使用 \$。 ( ) 标记一个子表达式的开始和结束位置。子表达式可以获取供以后使用。要匹配这些字符,请使用 \( 和 \)。 * 匹配前面的子表达式零次或多次。要匹配 * 字符,请使用 \*。 + 匹配前面的子表达式一次或多次。要匹配 + 字符,请使用 \+。 . 匹配除换行符 \n 之外的任何单字符。要匹配 . ,请使用 \. 。 [ 标记一个中括号表达式的开始。要匹配 [,请使用 \[。 ? 匹配前面的子表达式零次或一次,或指明一个非贪婪限定符。要匹配 ? 字符,请使用 \?。 \ 将下一个字符标记为或特殊字符、或原义字符、或向后引用、或八进制转义符。例如, 'n' 匹配字符 'n'。'\n' 匹配换行符。序列 '\\' 匹配 "\",而 '\(' 则匹配 "("。 ^ 匹配输入字符串的开始位置,除非在方括号表达式中使用,当该符号在方括号表达式中使用时,表示不接受该方括号表达式中的字符集合。要匹配 ^ 字符本身,请使用 \^。 { 标记限定符表达式的开始。要匹配 {,请使用 \{。 | 指明两项之间的一个选择。要匹配 |,请使用 \|。 限定符: * 匹配前面的子表达式零次或多次。例如,zo* 能匹配 "z" 以及 "zoo"。* 等价于{0,}。 + 匹配前面的子表达式一次或多次。例如,'zo+' 能匹配 "zo" 以及 "zoo",但不能匹配 "z"。+ 等价于 {1,}。 ? 匹配前面的子表达式零次或一次。例如,"do(es)?" 可以匹配 "do" 、 "does" 中的 "does" 、 "doxy" 中的 "do" 。? 等价于 {0,1}。 {n} n 是一个非负整数。匹配确定的 n 次。例如,'o{2}' 不能匹配 "Bob" 中的 'o',但是能匹配 "food" 中的两个 o。 {n,} n 是一个非负整数。至少匹配n 次。例如,'o{2,}' 不能匹配 "Bob" 中的 'o',但能匹配 "foooood" 中的所有 o。'o{1,}' 等价于 'o+'。'o{0,}' 则等价于 'o*'。 {n,m} m 和 n 均为非负整数,其中n <= m。最少匹配 n 次且最多匹配 m 次。例如,"o{1,3}" 将匹配 "fooooood" 中的前三个 o。'o{0,1}' 等价于 'o?'。请注意在逗号和两个数之间不能有空格。 例子: [0-9]{1,2} 或 [1-9][0-9]{0,1} ==》 0~99 <.*> ==> <h1>RUNOOB-菜鸟教程</h1> ==> 表达式匹配从开始小于符号 (<) 到关闭 h1 标记的大于符号 (>) 之间的所有内容 */ #include <iostream> #include <boost/regex.hpp> #include "boost/algorithm/string/regex.hpp" // boost::algorithm::find_regex() // boost::algorithm::replace_regex() // boost::algorithm::erase_regex() // boost::algorithm::split_regex() void test1() { std::string s = "<NAME>"; boost::regex expr("<NAME>"); std::cout << boost::regex_match(s, expr) << std::endl;// 全部匹配返回true,反之 } void test2() { std::string s = "<NAME>"; boost::regex expr("(\\w+)\\s(\\w+)"); boost::smatch what; if (boost::regex_search(s, what, expr)) { std::cout << what[0] << std::endl; // Boris Sch std::cout << what[1] << "--" << what[2] << std::endl; } } void test3() { std::string s = " <NAME> "; boost::regex expr("\\s"); // 这里找到3个空白 std::string fmt("==="); std::cout << boost::regex_replace(s, expr, fmt) << std::endl; // 将得到的结果替换成fmt : ===Boris===Schäling=== } void test4() { std::string s = "<NAME>"; boost::regex expr("(\\w+)\\s(\\w+)"); std::string fmt("\\2 \\1"); std::cout << boost::regex_replace(s, expr, fmt) << std::endl; // Sch Borisäling } void test5() { std::string s = "rtsp://admin:[email protected]/ipc"; // 172.16.100.188 boost::iterator_range<std::string::iterator> r = boost::algorithm::find_regex(s, boost::regex("((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})(\\.((2(5[0-5]|[0-4]\\d))|[0-1]?\\d{1,2})){3}")); std::cout << r << std::endl; } int main(int argc, char const *argv[]) { test5(); return 0; } <file_sep>/* 假设:有一个待检测的值:25 第一步:将25化为二进制11001 第二步:分别取奇数位和偶数位各自化成整数,比如上例:红色的奇数位:101,是5;偶数位10,是2(这两个就是生成的hashfunc) 第三步:对Bit Array总位数取模,也就是哈希运算, 5 mod1 1=5,将索引5位的数置1 2 mod1 1=2,将索引2的数置1 */ #include <stdio.h> int main(int argc, char const *argv[]) { return 0; } <file_sep>#include <iostream> #include <vector> #include <deque> using namespace std; template <typename T, template <typename Elem, typename Allocator = std::allocator<Elem>> class Container = std::vector> struct Stack { // 这个时候Container已经带参数了 Container<T> elems; }; // 数值计算,编译期得到答案,不重要,会产生时间消耗 template<int X, int Y> struct Caculate { enum // 定义成员变量 { Sum = X + Y, Dec = X - Y, Mul = X * Y, Div = X / Y }; }; // using关键字来专门定义类型别名,即代替typedef template<typename T> struct PointerOf { // typedef T* Type; using Type = T*; }; // 模板递归 template<int N> struct Factorial { enum { Value = N * Factorial<N - 1>::Value }; }; // 全特化 template<> struct Factorial<1> { enum { Value = 1 }; }; int main(int argc, char const *argv[]) { Stack<int, std::deque> intStack; intStack.elems.push_back(-1); PointerOf<const char>::Type s = "Hello world!"; clock_t start = clock(); // 分别获得10和2的加减乘除的结果 Caculate<10, 2>::Sum; Caculate<10, 2>::Dec; Caculate<10, 2>::Mul; Caculate<10, 2>::Div; Factorial<10>::Value; clock_t end = clock(); cout << (end-start) << "us"<< endl; return 0; } <file_sep>#include "MySQL.h" int main() { MySQL_Info info; info.user = "root"; info.pswd = "<PASSWORD>"; info.host = "172.16.100.147"; info.database = "test"; info.port = 3306; MySQL Mysql(info); if (Mysql.connectToMysql()) { Mysql.operateMysqlQuery("create table if not exists \ test_table(id int(4), name varchar(20) \ character set gb2312 collate gb2312_chinese_ci)"); Mysql.operateMysqlQuery("insert into test_table \ values(1, 'aaa'), (2, 'bbb'), (3, 'ccc')"); Mysql.operateMysqlQuery("insert ignore into test_table(id) values(11), (22), (33)"); Mysql.operateMysqlSelect("select * from test_table where id=22 lock in share mode"); Mysql.operateMysqlSelect("select * from test_table for update"); Mysql.operateMysqlQuery("update test_table set id=22 where name='aaa'"); Mysql.operateMysqlQuery("alter table test_table rename re_test_table"); Mysql.operateMysqlQuery("delete from re_test_table where id=2"); //删除表中的特定条件的记录 Mysql.operateMysqlQuery("truncate table re_test_table"); //删除表中的所有数据记录,清空表 // Mysql.operateMysqlQuery("delete from test_table"); //删除表中的所有数据记录,清空表 Mysql.operateMysqlQuery("drop table re_test_table"); //删除表 Mysql.resetConn(); Mysql.disconnectToMysql(); } return 0; }<file_sep>/* * Copyright (CPP) 2019-2020 ---- */ /****************************************************************************** * @file Singleton.hpp * @brief Defines Singleton APIs * @version V1.0 * @date 24. September 2020 * @usage Singleton<class_name>::Instance()->func() ******************************************************************************/ #pragma once template<class T> class Singleton { public: static T* Instance() { if (nullptr == _member) { _member = new T(); } return _member; } static void Release() { if (_member) { delete _member; _member = nullptr; } } private: Singleton() {} ~Singleton() { Release(); } Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; private: static T* _member; }; template<class T> T* Singleton<T>::_member = nullptr; <file_sep>#include <stdio.h> #include <string.h> #include <stdlib.h> // 二叉链表法 typedef struct BiTree { int data; struct BiTree *lchild, *rchild; } BiTree, *pBiTree; // 先序遍历 void preOder(BiTree *root) { if (root == NULL) { return; } printf("%d ", root->data); preOder(root->lchild); preOder(root->rchild); return; } // 中序遍历 void inOder(BiTree *root) { if (root == NULL) { return; } preOder(root->lchild); printf("%d ", root->data); preOder(root->rchild); return; } // 后序遍历 void postOder(BiTree *root) { if (root == NULL) { return; } preOder(root->lchild); preOder(root->rchild); printf("%d ", root->data); return; } // 求叶子结点 void countLeaf(BiTree *root, int *sum) { if (root) { if (!root->lchild && !root->rchild) { (*sum)++; } if (root->lchild) { countLeaf(root->lchild, sum); } if (root->rchild) { countLeaf(root->lchild, sum); } } } // 树深度 int depth(BiTree *root) { int deptLeft = 0; int deptRight = 0; int deptVal = 0; if (root == NULL) { deptVal = 0; return deptVal; } deptLeft = depth(root->lchild); deptRight = depth(root->rchild); deptVal = 1 + (deptLeft > deptRight ? deptLeft:deptRight); return deptVal; } // 树拷贝 BiTree *CopyTree(BiTree *root) { return NULL; } int main(int argc, char const *argv[]) { BiTree t1, t2, t3, t4, t5; memset(&t1, 0, sizeof(BiTree)); memset(&t2, 0, sizeof(BiTree)); memset(&t3, 0, sizeof(BiTree)); memset(&t4, 0, sizeof(BiTree)); memset(&t5, 0, sizeof(BiTree)); t1.data = 1; t2.data = 2; t3.data = 3; t4.data = 4; t5.data = 5; t1.lchild = &t2; t1.rchild = &t3; t2.lchild = &t4; t3.lchild = &t5; preOder(&t1); printf("\n"); inOder(&t1); printf("\n"); postOder(&t1); printf("\n"); int sum = 0; countLeaf(&t1, &sum); printf("sum = %d\n", sum); printf("depth = %d\n", depth(&t1)); BiTree *cp_root = CopyTree(&t1); return 0; } <file_sep>#pragma once int driver12_test(void);<file_sep>src = Glob('src/*.cpp') inc_path = ['inc'] defines = ['MODULE2_DEF'] ccflags = [] env = Environment () env.Append(CPPPATH=inc_path) env.Append(CPPDEFINES=defines) env.Append(CCCOMSTR="CC $SOURCES") SharedLibrary('module2', Glob('src/*.cpp')) obj=env.Object(src) Return('obj') <file_sep>#include "Handler.h" Beijing::Beijing() { numberList.push_back("11129812340930034"); numberList.push_back("11129812340930035"); numberList.push_back("11129812340930036"); numberList.push_back("11129812340930037"); } void Beijing::handleRequest(string number) { list<string>::iterator it; it = find(numberList.begin(), numberList.end(), number); if (it != numberList.end()) //存在 { cout << "该人在北京居住" << endl; } else { cout << "该人不在北京居住" << endl; if (NULL != myHandler) { myHandler->handleRequest(number); } } } void Beijing::setNextHandler(Handler *handler) { myHandler = handler; } Shanghai::Shanghai() { numberList.push_back("10129812340930031"); numberList.push_back("10129812340930032"); numberList.push_back("10129812340930036"); numberList.push_back("10129812340930037"); } void Shanghai::handleRequest(string number) { list<string>::iterator it; it = find(numberList.begin(), numberList.end(), number); if (it != numberList.end()) //存在 { cout << "该人在上海居住" << endl; } else { cout << "该人不在上海居住" << endl; if (NULL != myHandler) { myHandler->handleRequest(number); } } } void Shanghai::setNextHandler(Handler *handler) { myHandler = handler; } Tianjin::Tianjin() { numberList.push_back("10029812340930031"); numberList.push_back("10029812340930032"); numberList.push_back("10029812340930036"); numberList.push_back("10029812340930037"); } void Tianjin::handleRequest(string number) { list<string>::iterator it; it = find(numberList.begin(), numberList.end(), number); if (it != numberList.end()) //存在 { cout << "该人在天津居住" << endl; } else { cout << "该人不在天津居住" << endl; if (NULL != myHandler) { myHandler->handleRequest(number); } } } void Tianjin::setNextHandler(Handler *handler) { myHandler = handler; } Guangdong::Guangdong() { numberList.push_back("10029812340930088"); numberList.push_back("10029812340930089"); numberList.push_back("10029812340930090"); numberList.push_back("10029812340930091"); } void Guangdong::handleRequest(string number) { list<string>::iterator it; it = find(numberList.begin(), numberList.end(), number); if (it != numberList.end()) //存在 { cout << "该人在广东居住" << endl; } else { cout << "该人不在广东居住" << endl; if (NULL != myHandler) { myHandler->handleRequest(number); } } } void Guangdong::setNextHandler(Handler *handler) { myHandler = handler; } <file_sep>#!/bin/bash export LD_LIBRARY_PATH=$(pwd)/../../libzmq-4.3.3/lib:$LD_LIBRARY_PATH <file_sep> target_file = 'module_test1' compile_tool = 'g++' # 头文件路径 inc_path = ['inc'] inc_path += ['../module1/inc'] inc_path += ['../module2/inc'] # 源文件 src = Glob('*.cpp') src += Glob('src/*.cpp') # 宏定义 defines = ['MAIN_DEF'] # 编译附加选项 ccflags = ['-g','-O3','-Wall'] # 第三方库 lib_path = [] libs = ['pthread'] # 环境设置 env=Environment( CXX = compile_tool ) for flag in ccflags: env.AppendUnique(CPPFLAGS=[flag]) for path in inc_path: env.AppendUnique(CPPPATH=[path]) for deb in defines: env.AppendUnique(CPPDEFINES=[deb]) for path in lib_path: env.AppendUnique(LIBPATH=[path]) for lib in libs: env.AppendUnique(LIBS=[lib]) # 定义了编译时的显示格式,若不定义则编译选项非常长,冗余信息非常多,不利于查找有用的错误和警告。 env.Append(CCCOMSTR="CC $SOURCES") env.Append(LINKCOMSTR="LINK $TARGET") # duplicate=0选项是防止源文件被多余地复制到build文件夹下 objs = SConscript('../module1/SConscript',variant_dir='sdk/module1', duplicate=0) objs += SConscript('../module2/SConscript',variant_dir='sdk/module2', duplicate=0) objs += env.Object(src) env.Program(target = target_file, source=objs) <file_sep>#include <iostream> #include <vector> #include <sys/types.h> #include <dirent.h> #include <string.h> void read_pic(const char *path, std::vector<std::string> &v) { DIR *dir = opendir(path); if (dir == nullptr) { std::cout << "opendir error" << std::endl; exit(1); } std::string dst_path = path; dst_path += '/'; struct dirent *s_info; while ((s_info = readdir(dir)) != nullptr) { if (s_info->d_type == DT_DIR) { if (strcmp(s_info->d_name, ".") == 0 || strcmp(s_info->d_name, "..") == 0) { continue; } dst_path += s_info->d_name; read_pic(dst_path.c_str(), v); } if (s_info->d_type == DT_REG){ v.push_back(std::move(dst_path+s_info->d_name)); } } closedir(dir); } int main(int argc, char const *argv[]) { if (argc < 2) { return 0; } clock_t start, end; start = clock(); std::vector<std::string> v; read_pic(argv[1], v); end = clock(); std::cout << (end-start) << std::endl; for (auto str: v) { std::cout << str << std::endl; } return 0; } <file_sep>#define USE_MYMATH #define DEBUG #define VERSION_MAJOR 1 #define VERSION_MINOR 0 <file_sep>/* * Copyright (C) 2015-2017 ---- */ /****************************************************************************** * @file syslog.h * @brief Defines syslog APIs and usage * @version V1.0 * @date 24. September 2020 * @usage 0: Err; 1: Err&Warn; 2: Err&Warn&Info; 3: Err&Warn&Info&Debug * #define LOG_LEVEL 3 // before * #include <syslog.h> ******************************************************************************/ #include <stdio.h> #include <string.h> #include <time.h> #include <sys/timeb.h> #ifndef SYSLOG_H #define SYSLOG_H #ifdef __cplusplus extern "C" { #endif #ifdef LOG_LEVEL #if (LOG_LEVEL >= 3) #define LOG_ENABLE_D #endif #if (LOG_LEVEL >= 2) #define LOG_ENABLE_I #endif #if (LOG_LEVEL >= 1) #define LOG_ENABLE_W #endif #if (LOG_LEVEL >= 0) #define LOG_ENABLE_E #endif #else #define LOG_ENABLE_E #endif char LogPrefix[24]; #define LOG_COLOR_RED_YELLO_BACK "\033[1;31;43m" #define LOG_COLOR_RED "\033[2;31;49m" #define LOG_COLOR_YELLOW "\033[2;33;49m" #define LOG_COLOR_GREEN "\033[2;32;49m" #define LOG_COLOR_BLUE "\033[2;34;49m" #define LOG_COLOR_GRAY "\033[1;30m" #define LOG_COLOR_WHITE "\033[1;47;49m" #define LOG_COLOR_RESET "\033[0m" /* [LogLevel:FileName:Function:Line] */ const char *PFORMAT_D = LOG_COLOR_GRAY "[%s][%sD][%s():%d] " LOG_COLOR_RESET; const char *PFORMAT_I = LOG_COLOR_WHITE "[%s][%sI][%s():%d] " LOG_COLOR_RESET; const char *PFORMAT_W = LOG_COLOR_YELLOW "[%s][%sW][%s():%d] " LOG_COLOR_RESET; const char *PFORMAT_E = LOG_COLOR_RED "[%s][%sE][%s():%d] " LOG_COLOR_RESET; const char *PFORMAT_O = LOG_COLOR_GREEN "[%s][%sE][%s():%d] " LOG_COLOR_RESET; #define LOG_E_BASE_ARGS LogTime(), LogPrefix, __FUNCTION__, __LINE__ #define LOG_W_BASE_ARGS LogTime(), LogPrefix, __FUNCTION__, __LINE__ #define LOG_I_BASE_ARGS LogTime(), LogPrefix, __FUNCTION__, __LINE__ #define LOG_D_BASE_ARGS LogTime(), LogPrefix, __FUNCTION__, __LINE__ #define LOG_O_BASE_ARGS LogTime(), LogPrefix, __FUNCTION__, __LINE__ /* Log in freely format without prefix */ #define LOG_F(fmt, args...) printf(fmt,##args) // OK, Green color #define LOG_O(fmt, args...) \ do {printf(PFORMAT_O,LOG_O_BASE_ARGS); printf(fmt,##args);} while(0) /* Log debug */ #ifdef LOG_ENABLE_D #define LOG_D(fmt, args...) \ do {printf(PFORMAT_D,LOG_D_BASE_ARGS); printf(fmt,##args);} while(0) #else #define LOG_D(fmt, args...) #endif /* Log information */ #ifdef LOG_ENABLE_I #define LOG_I(fmt, args...) \ do {printf(PFORMAT_I ,LOG_I_BASE_ARGS); printf(fmt,##args);} while(0) #else #define LOG_I(fmt, args...) #endif /* Log warning */ #ifdef LOG_ENABLE_W #define LOG_W(fmt, args...) \ do {printf(PFORMAT_W,LOG_W_BASE_ARGS); printf(fmt,##args);} while(0) #else #define LOG_W(fmt, args...) #endif /* Log error */ #ifdef LOG_ENABLE_E #define LOG_E(fmt, args...) \ do {printf(PFORMAT_E,LOG_E_BASE_ARGS); printf(fmt,##args);} while(0) #else #define LOG_E(fmt, args...) #endif inline void SetLogPrefix(const char *prefix) { strncpy(LogPrefix, prefix, sizeof(LogPrefix)-1); LogPrefix[strlen(LogPrefix)] = ':'; } inline char* LogTime(void) { struct tm *ptm; struct timeb stTimeb; static char szTime[24]; ftime(&stTimeb); ptm = localtime(&stTimeb.time); sprintf(szTime, "%04d-%02d-%02d %02d:%02d:%02d.%03d", ptm->tm_year+1900, ptm->tm_mon+1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec, stTimeb.millitm); szTime[23] = 0; return szTime; } #define ENTER() LOG_D("Enter\n") #define EXIT_VOID() do { LOG_D("Exit\n"); return;} while(0) #define EXIT_INT(val) do { LOG_D("Exit, return val=%d\n", (int)val); return val;} while(0) #define EXIT_PTR(ptr) do { LOG_D("Exit, return ptr=%p\n", (void*)ptr); return ptr;} while(0) #ifdef __cplusplus } #endif #endif // SYSLOG_H <file_sep>#include <stdio.h> #include <getopt.h> #include <stdlib.h> #include <sys/prctl.h> #include <sys/types.h> #include <unistd.h> // 获取进程ID pid_t getProcessPidByName(const char *proc_name) { FILE *fp; char buf[100] = {0}; char cmd[200] = {'\0'}; pid_t pid = -1; sprintf(cmd, "pidof -s %s", proc_name); if((fp = popen(cmd, "r")) != NULL) { if(fgets(buf, 255, fp) != NULL) { pid = atoi(buf); } } pclose(fp); return pid; } int main(int argc, char *argv[]) { // 设置/获取进程名并根据进程名获取进程ID,不能在同个进程直接获取 //******************************************************* prctl(PR_SET_NAME, "listener_proess", NULL, NULL, NULL); // char buf[100] = {0}; // prctl(PR_GET_NAME, buf); // printf("buf = %s\n", buf); pid_t process_pid = getProcessPidByName("a.out"); printf("pid = %d\n", process_pid); //******************************************************* while (1){ sleep(1); }; return 0; } <file_sep> /* * Copyright (CPP) 2019-2020 ---- */ /****************************************************************************** * @file Singleton.hpp * @brief Defines Singleton APIs * @version V1.0 * @date 24. September 2020 * @usage Singleton<class_name>::Instance()->func() ******************************************************************************/ #ifndef _SINGLETON_HPP_ #define _SINGLETON_HPP_ /** Singleton template class ×*/ #define SINGLETON_INDEX 0 // #define DEBUG_PRINT #ifndef DEBUG_PRINT #include <iostream> #endif #if SINGLETON_INDEX == 0 #include <mutex> #include <thread> #include <chrono> #include <atomic> // C++ 11版本之后的跨平台实现 -- 线程安全 template<class T> class Singleton { private: static std::atomic<T*> m_instance; static std::mutex m_mutex; Singleton() = default; Singleton(const Singleton& s) = default; Singleton& operator=(const Singleton& s) = default; // TODO:模板嵌套模板没成功 // template<class Ty=T> // class GarbageCollector { // public: // ~GarbageCollector() { // 防止内存读写reorder不安全 // std::cout << "~GarbageCollector\n"; // Ty* tmp = m_instance.load(std::memory_order_relaxed); // if (tmp) { // std::cout << "free m_singleton: " << tmp << std::endl; // delete tmp; // } // } // }; // template<class Ty=T> // static GarbageCollector<Ty> m_gc; public: void *getSingletonAddress() { // 后续使用指针 return m_instance; } static T* getInstance() { // 第一次获取指针使用 T* tmp = m_instance.load(std::memory_order_relaxed); std::atomic_thread_fence(std::memory_order_acquire);//获取内存fence if (tmp == nullptr) { std::lock_guard<std::mutex> lock(m_mutex); tmp = m_instance.load(std::memory_order_relaxed); if (tmp == nullptr) { tmp = new T(); // 1、分配内存,2 调用构造,3 赋值操作 std::atomic_thread_fence(std::memory_order_release);//释放内存fence m_instance.store(tmp, std::memory_order_relaxed); #ifdef DEBUG_PRINT std::cout << "new m_singleton: " << tmp << std::endl; #endif } } return tmp; } static void releaseSingletonAddress() { T* tmp = m_instance.load(std::memory_order_relaxed); if (tmp) { #ifdef DEBUG_PRINT std::cout << "free m_singleton: " << tmp << std::endl; #endif delete tmp; } } }; template<class T> std::atomic<T*> Singleton<T>::m_instance; template<class T> std::mutex Singleton<T>::m_mutex; // template<class T> // Singleton<T>::GarbageCollector<Ty> Singleton<T>::m_gc; #elif SINGLETON_INDEX == 1 // 懒汉式 template<class T> class Singleton { private: Singleton() = default; // 自动生成默认构造函数 // explicit Singleton() { // 构造函数 会影响局部静态变量, 不能用隐式的构造函数 // cout << "Singleton construct\n"; // } Singleton(const Singleton& s) = delete; // 禁用拷贝构造函数 Singleton& operator=(const Singleton& s) = delete; // 禁用拷贝赋值操作符 public: static T* getInstance(){ static T s_singleton; // C++11线程安全, C++11之前不是线程安全 __cxa_guard_acquire 和 __cxa_guard_release return &s_singleton; } }; #endif #endif<file_sep>int driver12_test(void) { return 12; }<file_sep>#pragma once int module21_test(void);<file_sep> #define LOG_LEVEL 3 #include "syslog.h" int main(int argc, char const *argv[]) { LOG_I("11111111111111\n"); LOG_W("11111111111111\n"); LOG_D("11111111111111\n"); LOG_F("11111111111111\n"); LOG_O("11111111111111\n"); LOG_E("11111111111111\n"); EXIT_INT(1); return 0; } <file_sep>CC = gcc CXX = g++ D = SRCS += $(wildcard *.cpp) OBJS += $(patsubst %.cpp, %.o, $(SRCS)) TARGETS += $(SRCS:%.cpp=%) INCLUDE += -I$(PWD)/../../gflags/include \ -I$(PWD)/../../glog/include \ -I$(PWD)/../../googletest/include LIB_PATH += -L$(PWD)/../../gflags/lib \ -L$(PWD)/../../glog/lib \ -L$(PWD)/../../googletest/lib LIB_LINK += -lgflags -lgflags_nothreads -lglog -lgtest -lgmock -lgtest_main -lpthread CFLAGS += -g -Wall -std=c++11 all:$(TARGETS) $(TARGETS):%:%.o $(CXX) $^ -o $@ $(INCLUDE) $(LIB_PATH) $(LIB_LINK) $(CFLAGS) # @rm -rf $(OBJS) %.o:%.cpp $(CXX) -c $< -o $@ $(CFLAGS) $(INCLUDE) .PHONY: clean clean: @rm -rf $(TARGETS) $(OBJS) gflags_test.INFO log-* D: gcc $(demo) -o $(demo) $(INCLUDE) $(LIB_PATH) $(LIB_LINK) $(CFLAGS)<file_sep> src = Glob('src/*.cpp') inc_path = ['inc'] defines = ['MODULE1_DEF'] ccflags = [] env = Environment () env.Append(CPPPATH=inc_path) env.Append(CPPDEFINES=defines) env.Append(CCCOMSTR="CC $SOURCES") SharedLibrary('module1', Glob('src/*.cpp')) obj = env.Object(src) Return('obj') <file_sep>#include <libxml/parser.h> #include <libxml/xpath.h> /* 解析文档 */ xmlDocPtr getdoc(char *docname) { xmlDocPtr doc; doc = xmlParseFile(docname); if (doc == NULL) { fprintf(stderr, "Document not parsed successfully. \n"); return NULL; } return doc; } /* 查询节点集 */ xmlXPathObjectPtr getnodeset(xmlDocPtr doc, xmlChar *xpath) { xmlXPathContextPtr context; xmlXPathObjectPtr result; /* 存储查询结果 */ /* 创建一个xpath上下文 */ context = xmlXPathNewContext(doc); if (context == NULL) { printf("Error in xmlXPathNewContext\n"); return NULL; } /* 查询XPath表达式 */ result = xmlXPathEvalExpression(xpath, context); xmlXPathFreeContext(context); /* 释放上下文指针 */ if (result == NULL) { printf("Error in xmlXPathEvalExpression\n"); return NULL; } /* 检查结果集是否为空 */ if (xmlXPathNodeSetIsEmpty(result->nodesetval)) { xmlXPathFreeObject(result); /* 如为这空就释放 */ printf("No result\n"); return NULL; } return result; } int main(int argc, char **argv) { char *docname; xmlDocPtr doc; /* 查找所有keyword元素,而不管它们在文档中的位置 */ xmlChar *xpath = (xmlChar *)"//keyword"; xmlNodeSetPtr nodeset; xmlXPathObjectPtr result; int i; xmlChar *keyword; if (argc <= 1) { printf("Usage: %s docname\n", argv[0]); return (0); } docname = argv[1]; doc = getdoc(docname); result = getnodeset(doc, xpath); if (result) { /* 得到keyword节点集 */ nodeset = result->nodesetval; for (i = 0; i < nodeset->nodeNr; i++) { /* 打印每个节点中的内容 */ keyword = xmlNodeListGetString(doc, nodeset->nodeTab[i]->xmlChildrenNode, 1); printf("keyword: %s\n", keyword); xmlFree(keyword); } xmlXPathFreeObject(result); /* 释放结果集 */ } xmlFreeDoc(doc); /* 释放文档树 */ xmlCleanupParser(); /* 清除库内存 */ return (0); }
0a3dc276a60f982971820d4087daa86d47a9498e
[ "CMake", "Markdown", "Makefile", "Python", "C", "C++", "Shell" ]
128
C++
siweiy/learn-demo
50cba9f73f4300c3c7379f51d284541b5ff6257a
55729b6c6443e25056c906980c2e196d3c64ef83
refs/heads/master
<repo_name>mcnamarabrian/api-gw-swagger<file_sep>/README.md # api-gw-swagger This project demonstrates how to use define API Gateway APIs using swagger that incorporates dynamic values from the SAM template. # Pre-requisites * [AWS CLI version 2](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) * [AWS SAM CLI (0.41.0 or higher)](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) * [Docker](https://docs.docker.com/install/) # Deployment ## Build ```bash sam build --use-container ``` ## Deploy ## Upload swagger file to accessible S3 bucket The swagger file that contains the API definition will need to be uploaded to a S3 bucket. ```bash aws s3 cp src/apigateway/swagger.yml s3://some_bucket_you_own ``` Make note that you'll need to provide the S3 bucket when deploying the application stack. ## Deploy the serverless application Run the following command the first time the application is deployed. ```bash sam deploy --guided ``` You will be prompted to enter the S3 bucket from the previous step. Save the outputs to the file `samconfig.toml`. Subsequent runs will take advantage of the values stored in the configuration file. ```bash sam deploy ``` # Cleanup ## Destroy cloudformation stack ```bash aws cloudformation delete-stack --stack-name your_stack_name ``` <file_sep>/src/lambda/get_pet/index.py def handler(event, context): return 'get_pet' <file_sep>/src/lambda/post_pet/index.py def handler(event, context): return 'post_pet'
7093aeac8b1ec6d80e2c3cb950876959073ac036
[ "Markdown", "Python" ]
3
Markdown
mcnamarabrian/api-gw-swagger
8207f1b5f792eac3b8036a11711120f8f8dd10f4
5fe108c8a35f792a98969510949f801a820fb91a
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cassette.HtmlTemplates { public class RequireJSTmplSettings { public string PluginPrefix { get; set; } public RequireJSTmplSettings(IEnumerable<IConfiguration<RequireJSTmplSettings>> configurations) { this.PluginPrefix = string.Empty; ApplyConfigurations(configurations); } void ApplyConfigurations(IEnumerable<IConfiguration<RequireJSTmplSettings>> configurations) { configurations.OrderByConfigurationOrderAttribute().Configure(this); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Cassette.BundleProcessing; namespace Cassette.HtmlTemplates { public class RegisterTemplatesWithRequireJS : AddTransformerToAssets<HtmlTemplateBundle> { readonly RegisterTemplateWithRequireJS.Factory createAssetTransformer; readonly IJsonSerializer serializer; readonly RequireJSTmplSettings settings; public RegisterTemplatesWithRequireJS(RegisterTemplateWithRequireJS.Factory createAssetTransformer, IJsonSerializer serializer, RequireJSTmplSettings settings) { this.createAssetTransformer = createAssetTransformer; this.serializer = serializer; this.settings = settings; } protected override IAssetTransformer CreateAssetTransformer(HtmlTemplateBundle bundle) { return createAssetTransformer(bundle, this.serializer, this.settings); } } } <file_sep>using Cassette.BundleProcessing; using Cassette.TinyIoC; namespace Cassette.HtmlTemplates { [ConfigurationOrder(20)] public class RequireJSTmplServices : IConfiguration<TinyIoCContainer> { public void Configure(TinyIoCContainer container) { container.Register<RequireJSTmplSettings>().AsSingleton(); container .Register(typeof(IBundlePipeline<HtmlTemplateBundle>), typeof(RequireJSTmplPipeline)) .AsMultiInstance(); } } } <file_sep>Cassette.RequireJSTmpl ====================== HTML template compilation support for Cassette. Puts HTML templates into RequireJS modules. <file_sep>using System; using System.IO; using Cassette.Utilities; namespace Cassette.HtmlTemplates { public class RegisterTemplateWithRequireJS : IAssetTransformer { public delegate RegisterTemplateWithRequireJS Factory(HtmlTemplateBundle bundle, IJsonSerializer serializer, RequireJSTmplSettings settings); readonly HtmlTemplateBundle bundle; readonly IJsonSerializer serializer; readonly RequireJSTmplSettings settings; public RegisterTemplateWithRequireJS(HtmlTemplateBundle bundle, IJsonSerializer serializer, RequireJSTmplSettings settings) { this.bundle = bundle; this.serializer = serializer; this.settings = settings; } public Func<Stream> Transform(Func<Stream> openSourceStream, IAsset asset) { return () => { var source = openSourceStream().ReadToEnd(); var output = Module(asset.Path, source); return output.AsStream(); }; } string Module(string path, string source) { return string.Format( "define('{0}', [], function(){{ return {1}; }});", NormalizePath(path), serializer.Serialize(source) ); } string NormalizePath(string path) { var result = path.Replace("~", string.Empty); if (result.StartsWith("/")) { result = result.Remove(0, 1); } return string.Format("{0}{1}", this.settings.PluginPrefix, result); } } }
5ba2ccd56c6f3c25b47fe805472e93c29be3398c
[ "Markdown", "C#" ]
5
C#
ziflex/Cassette.RequireJSTmpl
551261d58404e876d125020473372ff585a683e1
1a0665f4bb80ff2baa6dc86f768baf8439775c52
refs/heads/master
<file_sep>#pragma once #include "Common.h" // Engine includes #include "Engine/FrameState.h" #include "Engine/RenderState.h" #include "Engine/IScript.h" class Engine { public: Engine(HINSTANCE hinst); ~Engine(); void OnPreUpdate(); bool OnRender(); void OnResize(UINT width, UINT height); void Run(); template<class T> requires std::derived_from<T, IScript> && std::default_initializable<T> void AddScript() { T* script = new T(); script->Initialize(this); _scripts.push_back(script); } private: void XInput_SetupControllers(); bool Win32_CreateApplication(); bool D2D_CreateDeviceIndependentResources(); bool D2D_CreateDeviceDependentResources(); void D2D_DiscardResources(); static LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); private: // Win32 Handles HWND _hwnd; HINSTANCE _hinst; // Direct2D Handles ID2D1Factory* _d2dFactory; ID2D1HwndRenderTarget* _renderTarget; // State keeping RenderState _stateRender; FrameState _stateFrame; std::chrono::high_resolution_clock::time_point _startTime; // Scripts std::list<IScript*> _scripts; };<file_sep>#include "../Common.h" #include "IScript.h" #include "FrameState.h" bool IScript::GetControllerButton(const FrameState& state, int user, short button) { if (state.ControllerStates[user] == nullptr) return false; return state.ControllerStates[user]->Gamepad.wButtons & button; }<file_sep>#pragma once #include "../Common.h" struct RenderState { D2D1_COLOR_F ClearColor = D2D1::ColorF(D2D1::ColorF::Black); };<file_sep>#pragma once /**** HEADER FILES ****/ // Disable lean and mean #ifdef WIN32_LEAN_AND_MEAN #undef WIN32_LEAN_AND_MEAN #endif // Windows Header Files: #include <Windows.h> #include <windowsx.h> // Direct2D Header Files: #include <d2d1_3helper.h> #include <d2d1svg.h> // DXGI Header Files: #include <dxgi1_6.h> // D2D Text Rendering Header Files: #include <dwrite_3.h> // Windows Imaging Header Files: #include <wincodecsdk.h> // XInput Header Files: #include <Xinput.h> // C/C++ Header Files: #include <cstdlib> #include <cwchar> #include <cmath> #include <chrono> #include <concepts> #include <list> /**** MACROS ****/ #include "Common/Macros.h" /**** LIBRARY FILES ****/ #pragma comment(lib, "windowscodecs.lib") #pragma comment(lib, "d2d1.lib") #pragma comment(lib, "dxgi.lib") #pragma comment(lib, "dwrite.lib") #pragma comment(lib, "xinput.lib")<file_sep>#include "VibrationScript.h" void VibrationScript::Initialize(Engine* engine) { ZeroMemory(&_vibrationState, sizeof(XINPUT_VIBRATION)); } void VibrationScript::Update(Engine* engine, const FrameState& state) { _vibrationState.wRightMotorSpeed = GetControllerButton(state, 0, XINPUT_GAMEPAD_A) ? 32000 : 0; XInputSetState(0, &_vibrationState); } void VibrationScript::Destroy(Engine* engine) { }<file_sep>#pragma once #include "../Common.h" #include "../Engine.h" class VibrationScript : public IScript { public: virtual void Initialize(Engine* engine); virtual void Update(Engine* engine, const FrameState& state); virtual void Destroy(Engine* engine); private: XINPUT_VIBRATION _vibrationState; };<file_sep>#pragma once class IScript { public: virtual void Initialize(class Engine* engine) = 0; virtual void Update(class Engine* engine, const struct FrameState& state) = 0; virtual void Destroy(class Engine* engine) = 0; protected: bool GetControllerButton(const struct FrameState& state, int user, short button); };<file_sep>#pragma once #include "../Common.h" struct FrameState { // == Storing input XINPUT_STATE** ControllerStates = nullptr; // == Keeping time double Time = 0.f; // time in seconds since start of application double DeltaTime = 0.f; // time in seconds since last frame };<file_sep>#pragma once #ifndef SafeRelease #define SafeRelease(v) if(v) { v->Release(); v = nullptr; } #endif<file_sep>#include "../Engine.h" Engine::Engine(HINSTANCE hinst) : _hinst(hinst), _hwnd(nullptr), _d2dFactory(nullptr), _renderTarget(nullptr), _stateRender(), _stateFrame(), _scripts() { // Get start time _startTime = std::chrono::high_resolution_clock::now(); XInput_SetupControllers(); D2D_CreateDeviceIndependentResources(); Win32_CreateApplication(); } Engine::~Engine() { // Destroy scripts for (IScript* script : _scripts) { script->Destroy(this); delete script; } SafeRelease(_d2dFactory); D2D_DiscardResources(); } void Engine::XInput_SetupControllers() { // Poll/allocate for controllers _stateFrame.ControllerStates = new XINPUT_STATE * [4]; XINPUT_STATE state; DWORD dwResult; for (int i = 0; i < XUSER_MAX_COUNT; ++i) { dwResult = XInputGetState(i, &state); _stateFrame.ControllerStates[i] = (dwResult == ERROR_SUCCESS) ? new XINPUT_STATE : nullptr; } } bool Engine::Win32_CreateApplication() { // Initialize Window WNDCLASSEX wcex = { sizeof(WNDCLASSEX) }; wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = Engine::WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = sizeof(LONG_PTR); wcex.hInstance = _hinst; wcex.hIcon = LoadIcon(NULL, IDI_APPLICATION); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = NULL; wcex.lpszMenuName = NULL; wcex.lpszClassName = L"BBWindow"; RegisterClassEx(&wcex); _hwnd = CreateWindow( wcex.lpszClassName, L"bruhball", // TODO: move to a settings object WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 640, // TODO: move to a settings object 480, // TODO: move to a settings object NULL, NULL, wcex.hInstance, this ); if (!_hwnd) return false; ShowWindow(_hwnd, SW_SHOWNORMAL); UpdateWindow(_hwnd); return true; } void GetControllerStates(FrameState& fstate) { // Copy states for (int i = 0; i < XUSER_MAX_COUNT; ++i) { XInputGetState(i, fstate.ControllerStates[i]); } } void Engine::OnPreUpdate() { // Set times std::chrono::duration<double, std::milli> newDuration = std::chrono::high_resolution_clock::now() - _startTime; _stateFrame.DeltaTime = newDuration.count() - _stateFrame.Time; _stateFrame.Time = newDuration.count(); // Set controller states GetControllerStates(_stateFrame); } bool Engine::OnRender() { if (!D2D_CreateDeviceDependentResources()) return false; HRESULT hr = S_OK; _renderTarget->BeginDraw(); _renderTarget->SetTransform(D2D1::Matrix3x2F::Identity()); _renderTarget->Clear(_stateRender.ClearColor); hr = _renderTarget->EndDraw(); if (hr == D2DERR_RECREATE_TARGET) { hr = S_OK; D2D_DiscardResources(); } return true; } void Engine::OnResize(UINT width, UINT height) { if (_renderTarget) { _renderTarget->Resize(D2D1::SizeU(width, height)); } } void Engine::Run() { MSG msg; msg.message = WM_NULL; while (msg.message != WM_QUIT) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { DispatchMessage(&msg); } else { // Update OnPreUpdate(); for (IScript* script : _scripts) script->Update(this, _stateFrame); // Render OnRender(); } } } bool Engine::D2D_CreateDeviceIndependentResources() { // Initialize COM if (!SUCCEEDED(CoInitializeEx(NULL, COINIT_APARTMENTTHREADED))) return false; // Initialize D2D Factory if (!SUCCEEDED(D2D1CreateFactory(D2D1_FACTORY_TYPE_SINGLE_THREADED, &_d2dFactory))) return false; return true; } bool Engine::D2D_CreateDeviceDependentResources() { if (_renderTarget) return true; RECT rc; GetClientRect(_hwnd, &rc); D2D1_SIZE_U size = D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top); HRESULT hr = _d2dFactory->CreateHwndRenderTarget( D2D1::RenderTargetProperties(), D2D1::HwndRenderTargetProperties(_hwnd, size), &_renderTarget); if (!SUCCEEDED(hr)) return false; return true; } void Engine::D2D_DiscardResources() { SafeRelease(_renderTarget); } LRESULT CALLBACK Engine::WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { // Take pointer to Engine from CreateWindow, // and move it into the WindowLongPtr // (maintain association between HWND and Engine instance) if (msg == WM_CREATE) { LPCREATESTRUCT pcs = reinterpret_cast<LPCREATESTRUCT>(lParam); Engine* engine = reinterpret_cast<Engine*>(pcs->lpCreateParams); ::SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(engine)); return 1; } // Otherwise, retrieve Engine instance from the WindowLongPtr Engine* engine = reinterpret_cast<Engine*>(::GetWindowLongPtr(hwnd, GWLP_USERDATA)); if (engine) { // WRITE MESSAGE HANDLERS HERE switch (msg) { case WM_SIZE: engine->OnResize(LOWORD(lParam), HIWORD(lParam)); return 0; case WM_DISPLAYCHANGE: InvalidateRect(hwnd, NULL, FALSE); return 0; case WM_PAINT: if (!engine->OnRender()) { PostQuitMessage(0); return 1; } ValidateRect(hwnd, NULL); return 0; case WM_DESTROY: PostQuitMessage(0); return 1; default: return DefWindowProc(hwnd, msg, wParam, lParam); } } return DefWindowProc(hwnd, msg, wParam, lParam); }<file_sep>#include "Engine.h" #include "Gameplay/VibrationScript.h" int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { Engine engine(hInstance); engine.AddScript<VibrationScript>(); engine.Run(); return 0; }
e4b313c07ed8cfa161c28e593922ac01c8f3b4e9
[ "C", "C++" ]
11
C++
jamsterwes/bruhball
3e84f2c99b030f84e33c509c708e349b667a9bd0
334509c63b6f2272596353c7eab8c40bca9eeeb1
refs/heads/master
<repo_name>paxswill/RegisterBook<file_sep>/Makefile # get uname for some simple OS detection UNAME :=$(shell sh -c 'uname -s') # If we're on Windows, assume we're on my flash drive and we need # make SQLite ifeq ($(UNAME),MINGW32_NT-5.1) MINGW_CFLAGS = MINGW_LDFLAGS = else MINGW_CFLAGS = MINGW_LDFLAGS = endif # OS X compilation flags ifeq ($(UNAME),Darwin) OSX_CFLAGS = OSX_LDFLAGS = # Prefer clang on OS X CC=clang CXX=clang else OSX_CFLAGS = OSX_LDFLAGS = CC=gcc CXX=g++ endif SYS_CFLAGS = $(MINGW_CFLAGS) $(OSX_CFLAGS) SYS_LDFLAGS = $(MINGW_LDFLAGS) $(OSX_LDFLAGS) #Compiler flags SELF_CFLAGS = -g -O0 -Wall $(CFLAGS) SELF_LDFLAGS = all: sqlite3 transaction sqlite testing #Link everything up $(CXX) $(SELF_LDFLAGS) $(SYS_LDFLAGS) ./bin/test.o ./bin/sqlite3.o ./bin/Transaction.o ./bin/SQLiteDriver.o -o ./bin/RegisterBook clean: rm -rf ./bin/* testing: transaction sqlite $(CXX) $(SELF_CFLAGS) $(SYS_CFLAGS) -c -I./src/ ./src/test.cpp -o ./bin/test.o sqlite3: $(CC) $(SELF_CFLAGS) $(SYS_CFLAGS) -c -I./sqlite3/ ./sqlite3/sqlite3.c -o ./bin/sqlite3.o transaction: $(CXX) $(SELF_CFLAGS) $(SYS_CFLAGS) -c -I./src/ ./src/Transaction.cpp -o ./bin/Transaction.o sqlite: sqlite3 transaction $(CXX) $(SELF_CFLAGS) $(SYS_CFLAGS) -c -I./src/ -I./sqlite3/ ./src/SQLiteDriver.cpp -o ./bin/SQLiteDriver.o <file_sep>/src/test.cpp /* This is just a testing file, so I can test functions as I add them */ #include "SQLDriver.h" #include "SQLiteDriver.h" #include "Transaction.h" #include "User.h" using namespace std; int main (int argc, char const *argv[]) { //testing return 0; }<file_sep>/src/Transaction.cpp #include <Transaction.h> #include "User.h" #include "UserNotFoundException.h" Transaction::Transaction(){ driver = NULL; locked = false; userID = -1; amount = 0.0; transactionStamp = time(NULL); timestamp = transactionStamp; transactionID = -1; } Transaction::Transaction(SQLDriver *driver){ } Transaction::Transaction(SQLDriver *d, std::string name, double a) throw (UserNotFoundException){ driver = d; User *user; try{ user = d->getUser(name); userID = user->getID(); }catch(UserNotFoundException e){ fprintf(stderr, "Exception: %s", e.what()); } } Transaction::~Transaction(){ //Nothing to free, yet } int Transaction::getUserID(){ return userID; } void Transaction::setUserID(int id){ if(!locked) userID = id; } double Transaction::getAmount(){ return amount; } void Transaction::setAmount(double a){ amount = a; } int Transaction::getTransactionStamp(){ return transactionStamp; } int Transaction::getTimestamp(){ return timestamp; } int Transaction::getID(){ return transactionID; } SQLDriver* Transaction::getDriver(){ return driver; } <file_sep>/src/SQLDriver.h /* This is the parent class for the SQL drivers. Forseeable subclasses are those for SQLite and later, MySQL Also, an XML export function may be tacked onto this as a child */ #ifndef SQL_DRIVER_H #define SQL_DRIVER_H #include <sqlite3.h> #include <string> #include <set> #include "UserNotFoundException.h" //Forward declarations class Transaction; class User; class SQLDriver{ public: virtual void open(std::string name) = 0; virtual void close() = 0; virtual bool saveTransaction(Transaction *t) = 0; virtual Transaction* makeTransaction() = 0; virtual User* makeUser() = 0; //Transaction access virtual std::set<Transaction*> listTransactions() = 0; virtual void setTransaction(Transaction *t) = 0; virtual int countTransactions() = 0; //User Access virtual std::set<User*> listUsers() = 0; virtual void setUser(User *u) = 0; virtual int countUsers() = 0; virtual User* getUser(std::string name) throw (UserNotFoundException) = 0; virtual User* getUser(int userID) = 0; }; #endif <file_sep>/src/SQLiteDriver.cpp #include "SQLiteDriver.h" #include "Transaction.h" #include "User.h" void SQLiteDriver::open(std::string name){ //Open a database file, creating if needed int status; char *errorMessage; status = sqlite3_open_v2(name.c_str(), &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL); if(status != SQLITE_OK){ //There was an error opening the DB const char *errorMsg = sqlite3_errmsg(db); fprintf(stderr, "%s", errorMsg); //TODO: Close out the DB and raise an exception }else{ //DB opened successfully //Turn on extended error codes sqlite3_extended_result_codes(db, 1); //Turn on foreign key support status = sqlite3_exec(db, "PRAGMA foreign_keys = ON;", NULL, NULL, &errorMessage); //Is this a new database, or an old one? //Check by retrieving the schema_version pragma. If it's 0 there's no schema sqlite3_stmt *versionStmt; //The third paramter is the length of the statement, including null terminator status = sqlite3_prepare_v2(db, "PRAGMA schema_version;", (sizeof(char) * 21), &versionStmt, NULL); int schemaVersion = 0; do{ //Step the statement status = sqlite3_step(versionStmt); //Is there data? if(status == SQLITE_ROW){ //It /should/ be an int schemaVersion = sqlite3_column_int(versionStmt, 0); } }while(status != SQLITE_DONE); sqlite3_finalize(versionStmt); //Now to check if it's a new table if(schemaVersion == 0){ //New or unintialized database //Create the schema sqlite3_stmt *schemaStmt; status = sqlite3_prepare_v2(db, "CREATE TABLE users(user_id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, name TEXT, timestamp INTEGER, comment TEXT); CREATE TABLE transactions(transaction_id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE, FOREIGN KEY(user) REFERENCES users(user_id) NOT NULL, title TEXT, amount REAL, transaction_time INTEGER, timestamp INTEGER, comment TEXT); PRAGMA user_version=?042", (sizeof(char) * 350), &schemaStmt, NULL); //Bind the schema version in status = sqlite3_bind_int(schemaStmt, 042, SCHEMA_VERSION); //Step until done do{ status = sqlite3_step(versionStmt); }while(status != SQLITE_DONE); //close out the statement sqlite3_finalize(schemaStmt); } //Buid the common statements status = sqlite3_prepare_v2(db, "UPDATE transactions SET user_id=@label_user_id, title=@label_title, amount=@label_amount, transaction_time=@label_transaction_time, timestamp=@label_timestamp, comment=@label_comment WHERE transaction_id=@label_transaction_id;", -1, &updateTransactionStmt, NULL); status = sqlite3_prepare_v2(db, "SELECT transaction_id FROM TRANSACTIONS WHERE transaction_id=@label_transaction_id LIMIT 1;", -1, &checkTransactionStmt, NULL); status = sqlite3_prepare_v2(db, "INSERT INTO transactions(transaction_id, user, title, amount, transaction_time, timestamp, comment) VALUES (@label_transaction_id, @label_user_id, @label_title, @label_amount, @label_transaction_time, @label_timestamp, @label_comment);", -1, &insertTransactionStmt, NULL); } } void SQLiteDriver::close(){ char *errorMessage; int status; //Commit status = sqlite3_exec(db, "COMMIT;", NULL, NULL, &errorMessage); //Finalize the common statements sqlite3_finalize(updateTransactionStmt); sqlite3_finalize(checkTransactionStmt); //Close the DB status = sqlite3_close(db); if(status == SQLITE_OK){ //Yay, closed }else{ //Aw hell, DB not closed yet. fprintf(stderr, "%s", errorMessage); } } Transaction* SQLiteDriver::makeTransaction(){ return new Transaction(this); } User* SQLiteDriver::makeUser(){ return new User(this); } //Transaction access std::set<Transaction*> SQLiteDriver::listTransactions(){ //Start building the statement sqlite3_stmt *transactionsStmt; int status = sqlite3_prepare_v2(db, "SELECT transaction_id, user_id, title, amount, transaction_time, timestamp, comment FROM transactions;", (sizeof(char) * 104), &transactionsStmt, NULL); //Where we're putting transactions std::set<Transaction*> transactions; do{ //Step the statement status = sqlite3_step(transactionsStmt); //Is there data? if(status == SQLITE_ROW){ //Make a transaction Transaction *temp = new Transaction(this); //Fill it in temp->locked = true; temp->transactionID = sqlite3_column_int(transactionsStmt, 0); temp->userID = sqlite3_column_int(transactionsStmt, 1); temp->title = (const char*)sqlite3_column_text(transactionsStmt, 2); temp->amount = sqlite3_column_double(transactionsStmt, 3); temp->transactionStamp = sqlite3_column_int(transactionsStmt, 4); temp->timestamp = sqlite3_column_int(transactionsStmt, 5); temp->comment = (const char*)sqlite3_column_text(transactionsStmt, 6); //Add it to the set transactions.insert(temp); } }while(status != SQLITE_DONE); sqlite3_finalize(transactionsStmt); return transactions; } void SQLiteDriver::setTransaction(Transaction *t){ int status; sqlite3_stmt *workingStatment; //Check to see if the statement exists workingStatment = checkTransactionStmt; status = bind(workingStatment, "label_transaction_id", t->transactionID); //Run the statement int checkValue = -1; do{ status = sqlite3_step(workingStatment); if(!checkError(status)){ break; } int tempCheck = sqlite3_column_int(workingStatment, 0); checkValue = tempCheck > checkValue ? tempCheck : checkValue; }while(status != SQLITE_DONE); //Reset the statement status = sqlite3_reset(workingStatment); //Are we updating or inserting? if(checkValue == -1){ //Inserting workingStatment = insertTransactionStmt; }else{ //Updating workingStatment = updateTransactionStmt; } //Bind the parameters status = bind(workingStatment, "label_user_id", t->userID); status = bind(workingStatment, "label_title", t->title); status = bind(workingStatment, "label_amount", t->amount); status = bind(workingStatment, "label_transaction_time", (int)t->transactionStamp); status = bind(workingStatment, "label_timestamp", (int)time(NULL)); status = bind(workingStatment, "label_comment", t->comment); status = bind(workingStatment, "label_transaction_id", t->transactionID); //Binding done. Now to run the statement do{ status = sqlite3_step(workingStatment); if(!checkError(status)){ break; } }while(status != SQLITE_DONE); //Reset the stement status = sqlite3_reset(updateTransactionStmt); } int SQLiteDriver::countTransactions(){ //No need for a prepared statment here int status; char **results, *errorMsg; int rows, cols; status = sqlite3_get_table(db, "SELECT COUNT(transaction_id) FROM transactions;", &results, &rows, &cols, &errorMsg); //We should ust have 1 row and 1 column, we're just getting a number, but get the last element just in case int numRecords = atoi(results[((rows + 1) * cols) - 1]); //Free the results sqlite3_free_table(results); return numRecords; } //User Access std::set<User*> SQLiteDriver::listUsers(){ //Start building the statement sqlite3_stmt *userStmt; int status = sqlite3_prepare_v2(db, "SELECT user_id, name, timestamp, comment FROM users;", (sizeof(char) * 53), &userStmt, NULL); //Where we're putting users std::set<User*> users; do{ //Step the statement status = sqlite3_step(userStmt); //Is there data? if(status == SQLITE_ROW){ //Make a user User *temp = new User(this); //Fill it in temp->id = sqlite3_column_int(userStmt, 0); temp->name = (const char*)sqlite3_column_text(userStmt, 1); temp->timestamp = sqlite3_column_int(userStmt, 2); temp->comment = (const char*)sqlite3_column_text(userStmt, 3); //Add it to the set users.insert(temp); } }while(status != SQLITE_DONE); sqlite3_finalize(userStmt); return users; } void SQLiteDriver::setUser(User *u){ } int SQLiteDriver::countUsers(){ //Almost exactly like countTransactions above. int status; char **results, *errorMsg; int rows, cols; status = sqlite3_get_table(db, "SELECT COUNT(user_id) FROM users;", &results, &rows, &cols, &errorMsg); //We should ust have 1 row and 1 column, we're just getting a number, but get the last element just in case int numRecords = atoi(results[((rows + 1) * cols) - 1]); //Free the results sqlite3_free_table(results); return numRecords; } User* SQLiteDriver::getUser(std::string name) throw (UserNotFoundException){ } User* SQLiteDriver::getUser(int userID){ } //Private Utility methods /* The bind() methods hide the SQLite3 C API for binding away. The evil parts of it are the non-overloading (which we have in C++), not binding on placeholder names, and the obtuse way of binding strings. */ int SQLiteDriver::bind(sqlite3_stmt *stmt, const char *var_name, int var){ int parameterIndex = sqlite3_bind_parameter_index(stmt, var_name); return sqlite3_bind_int(stmt, parameterIndex, var); } int SQLiteDriver::bind(sqlite3_stmt *stmt, const char *var_name, double var){ int parameterIndex = sqlite3_bind_parameter_index(stmt, var_name); return sqlite3_bind_double(stmt, parameterIndex, var); } int SQLiteDriver::bind(sqlite3_stmt *stmt, const char *var_name, std::string var){ int parameterIndex = sqlite3_bind_parameter_index(stmt, var_name); //There's some magic here, so here's an explanation //Args 1 and 2 are simple enough, 3 is a C string, 4 is the size in bytes of the string, // and 5 is a special value saying that the string passed may change in the future // (which it does, std::string.c_str() returns an internal representation that changes) return sqlite3_bind_text(stmt, parameterIndex, var.c_str(), (var.size() + 1) * sizeof(char), SQLITE_TRANSIENT); } //Easy way to check error codes //true for everything alright, false for bad things bool SQLiteDriver::checkError(int status){ if(status == SQLITE_OK || status == SQLITE_DONE){ return true; }else{ //Get the error message and log it fprintf(stderr, "%s", sqlite3_errmsg(db)); return false; } } <file_sep>/src/UserNotFoundException.h #ifndef USER_NAME_EX_H #define USER_NAME_EX_H #include <exception> class UserNotFoundException : public std::exception{ public: virtual const char* what(){ return "User not found for data supplied"; } }; #endif <file_sep>/src/SQLiteDriver.h //SQLiteDriver #ifndef SQLITE_DRIVER_H #define SQLITE_DRIVER_H //NOTE: This is the version of the schema this driver can work with natively #define SCHEMA_VERSION 1 #include <sqlite3.h> #include "SQLDriver.h" class SQLiteDriver : public SQLDriver{ public: virtual void open(std::string name); virtual void close(); virtual Transaction* makeTransaction(); virtual User* makeUser(); //Transaction access virtual std::set<Transaction*> listTransactions(); virtual void setTransaction(Transaction *t); virtual int countTransactions(); //User Access virtual std::set<User*> listUsers(); virtual void setUser(User *u); virtual int countUsers(); virtual User* getUser(std::string name) throw (UserNotFoundException); virtual User* getUser(int userID); private: sqlite3 *db; sqlite3_stmt *checkTransactionStmt; sqlite3_stmt *updateTransactionStmt; sqlite3_stmt *insertTransactionStmt; //Utility functions static int bind(sqlite3_stmt *stmt, const char *var_name, int var); static int bind(sqlite3_stmt *stmt, const char *var_name, double var); static int bind(sqlite3_stmt *stmt, const char *var_name, std::string var); bool checkError(int status); }; #endif <file_sep>/src/User.h #ifndef USER_H #define USER_H #include <string> #include <time.h> #include "SQLDriver.h" class User{ public: User(); User(SQLDriver *d); User(std::string n, int i, time_t t, SQLDriver *d); ~User(); std::string getName(); void setName(std::string n); int getID(); void setID(int i); time_t getStamp(); SQLDriver* getDriver(); friend class SQLiteDriver; private: std::string name; int id; time_t timestamp; std::string comment; SQLDriver *driver; }; #endif <file_sep>/src/Transaction.h #ifndef TRANSACTION_H #define TRANSACTION_H #include <string> #include <time.h> #include "SQLDriver.h" class Transaction{ public: Transaction(); Transaction(SQLDriver *driver); Transaction(SQLDriver *driver, std::string name, double amount) throw (UserNotFoundException); ~Transaction(); int getUserID(); void setUserID(int id); double getAmount(); void setAmount(double a); int getTransactionStamp(); int getTimestamp(); int getID(); SQLDriver* getDriver(); friend class SQLiteDriver; private: int userID; int transactionID; double amount; time_t transactionStamp; time_t timestamp; std::string title; std::string comment; SQLDriver *driver; bool locked; }; #endif
1734e2b892e9e7505ad84dadd4a4d83f46ee7e68
[ "Makefile", "C++" ]
9
Makefile
paxswill/RegisterBook
c35c29284082c07fb5e1050d88449f0ba1930e41
b2765c88fb9b4e326f657956d25c72f5c45cf0a4
refs/heads/master
<repo_name>Ben-Wunderlich/pylabyrinth<file_sep>/README.md # pylabyrinth Just a place for me to develop some algorithms I will use for a procedural labyrinth game I implemented 3 types of maze generation ## Using DFS ![dfs example](https://github.com/Ben-Wunderlich/pylabyrinth/blob/master/examples/dfspath.png) ## Using Prims algorithm ![prims example](https://github.com/Ben-Wunderlich/pylabyrinth/blob/master/examples/primspath.png) ## Using Kruskals algorithm ![Kruskals example](https://github.com/Ben-Wunderlich/pylabyrinth/blob/master/examples/kruskalpath.png) <file_sep>/visualize.py from tkinter import * master = Tk() colour = {"line":"#B5DDFF", "bg":"#7414FA"}#blue and white #colour = {"line":"#E1CC6E", "bg":"#5C532D"}#sandstone #colour = {"line":"#E17948", "bg":"#A83904"}#fire #colour = {"line":"#5A90E1", "bg":"#3C4B61"}#ocean #CIRCE_WIDTH = 4 expand=offset=line_width= half_width=-1 def makeNode(w,x,y): x+=offset y+=offset #w.create_oval(x,y,x+CIRCE_WIDTH,y+CIRCE_WIDTH, fill="#476042") def makeConnection(w, p1, p2): p1 = (p1[0]*expand+offset, p1[1]*expand+offset) p2 = (p2[0]*expand+offset, p2[1]*expand+offset) #w.create_line(p1[0]+half_width, p1[1]+half_width, p2[0], p2[1], width=line_width, fill="#B5DDFF") #it looks really cool if you use above line if(p1[0] == p2[0]): w.create_line(p1[0], p1[1]-half_width, p2[0], p2[1]+half_width, width=line_width, fill=colour["line"]) else: w.create_line(p1[0]-half_width, p1[1], p2[0]+half_width, p2[1], width=line_width, fill=colour["line"]) def updateExpand(newExpand): global expand, offset, line_width, half_width expand = newExpand offset = newExpand line_width = int(expand*0.6) half_width = line_width//2 def display(graph, x, y, newExpand): updateExpand(newExpand) canvas_width = x*expand canvas_height = y*expand w = Canvas(master, width=canvas_width+offset*2, height=canvas_height+offset*2) w.configure(bg=colour["bg"]) w.pack() allVertices = graph.get_vertices() for vertex in allVertices: makeNode(w, vertex[0]*expand, vertex[1]*expand) for connected in graph.get_vertex(vertex).get_connections(): makeConnection(w, vertex, connected.get_id()) #addedVertices.add(vertex) #y = int(canvas_height / 2) mainloop() #print(graph.get_vertices())<file_sep>/index.py ''' graph code courtesy of https://www.bogotobogo.com/python/python_graph_data_structures.php inspiration from https://en.wikipedia.org/wiki/Maze_generation_algorithm ''' from graph import Graph import visualize from disjoint import DisjointKringle from random import shuffle, randint, choice import timeit from perlin_noise import PerlinNoise #didnt work should make my own has function from math import pi def createGrid(width, height) -> int:#do more with this newGraph = Graph() for i in range(width): for j in range(height): if j != height-1: newGraph.add_edge((i,j),(i, j+1)) if i != width-1: newGraph.add_edge((i,j),(i+1, j)) return newGraph '''very fast but has lots of simple corridors and exceeds recursion depth after around 2500 nodes''' def destructiveDfs(graph, startVertex): visited = set() removed = Graph() vertex_obj = graph.get_vertex(startVertex) destructiveDfsUtil(graph, vertex_obj, visited, removed) return removed def destructiveDfsUtil(graph, nextVertex, visited, removed): visited.add(nextVertex) allNeighbors = list(nextVertex.get_connections()) shuffle(allNeighbors) for neighbor in allNeighbors: if neighbor not in visited: removed.add_edge(nextVertex.get_id(), neighbor.get_id()) destructiveDfsUtil(graph, neighbor, visited, removed) def markCount(vertex1, vertex2, marked): i=0 if vertex1.get_id() in marked: i+=1 if vertex2.get_id() in marked: i+=1 return i '''looks cool, fast, but it pretty easy to solve since it repeats a lot''' def primMaze(graph, width, height): # refer to https://en.wikipedia.org/wiki/Maze_generation_algorithm traversed = Graph() #start = (width//2,height//2) start = (width-1,height-1) marked = set([start]) startvert =graph.get_vertex(start) neighbors = graph.get_vertex(start).get_connections() while len(neighbors) > 0: #print("I run") picked = neighbors.pop() #allNeighbors = list(picked.get_connections()) #shuffle(allNeighbors) for newNeighbor in picked.get_connections(): if markCount(picked, newNeighbor, marked) == 1: traversed.add_edge(picked.get_id(), newNeighbor.get_id()) neighbors.update(picked.get_connections()) if startvert in neighbors:#XXX why does it need neighbors.remove(startvert)#bug fixing break #neighbors.update(picked.get_connections()) marked.add(picked.get_id()) return traversed '''looks cool and is hard to solve because it is fairly unpredictable, takes a while to compute''' def krisKringle(graph, use_chaos=True, chaos_chance=100): chaos_start = int(not use_chaos)#think carefully about this, its kinda wack unvisited = list(graph.get_vertices()) disj = DisjointKringle(unvisited) difference = Graph() flukeCheck = 0 while(disj.numSets() > 1): vertex = choice(unvisited) vert_ob = graph.get_vertex(vertex) for neighbor in vert_ob.get_connections(): neigh_name = neighbor.get_id() flukeIncident = randint(chaos_start,chaos_chance)==0 if not disj.areBros(neigh_name, vertex) or flukeIncident: if flukeIncident: flukeCheck+=1 difference.add_edge(neigh_name, vertex) disj.union(neigh_name, vertex) break print("there were {} flukes".format(flukeCheck)) return difference '''yet to be implemented''' def aldousBroder(graph, width, height): #also do this sometime # refer to https://en.wikipedia.org/wiki/Maze_generation_algorithm currCell = (randint(0, width-1),randint(0, height-1)) visited = set() visited.add(currCell) unvisited = set(graph.get_vertices()) while len(unvisited) > 0: pass ''' should deterministically create an exit to another section however it doesnt always give the same results. I am thinking it might be a good idea just to make a custom hash function for it ''' #this does not work as is, does not give consistent values def makeExits(graph, width, height): noisey = PerlinNoise() width = (width)/pi height = (height)/pi leftNoise = (noisey([0,height/2])) botNoise = noisey([width/2, 0]) topNoise = noisey([width/2, height]) rightNoise = noisey([width, height/2]) bigy = 100 leftNoise = int(abs(leftNoise*bigy)%height) botNoise = int(abs(botNoise*bigy)%width) topNoise = int(abs(topNoise*bigy)%width) rightNoise = int(abs(rightNoise*bigy)%height) print(leftNoise, botNoise, topNoise, rightNoise) def main(): #40x40 is pretty good WIDTH = 80 HEIGHT = 40 EXPAND = 20 aslk= createGrid(WIDTH,HEIGHT) start = timeit.default_timer() #pathes = destructiveDfs(aslk, (randint(0, WIDTH-1),randint(0, HEIGHT-1))) #pathes = primMaze(aslk, WIDTH, HEIGHT) pathes = krisKringle(aslk, False) stop = timeit.default_timer() print('Calculations took: {}s'.format(round((stop - start)*10000)/10000)) makeExits(aslk, WIDTH, HEIGHT) visualize.display(pathes, WIDTH, HEIGHT, EXPAND) if __name__ == "__main__": main() <file_sep>/disjoint.py """ This isn't my best algorithm but it has O(1) comparisons which happen a lot. Unions are O(n), but it is ok for less than 1000 sets """ class DisjointKringle: def __init__(self, startelems): self.maindict = dict() self.diffSets = len(startelems) for i, el in enumerate(startelems): self.maindict[el] = i #print(el) def areBros(self, mario, luigi): return self.maindict[mario] == self.maindict[luigi] def union(self, mario, luigi): self.diffSets -=1 marioVal = self.maindict[mario] luigiVal = self.maindict[luigi] for el in self.maindict.keys(): if self.maindict[el] == luigiVal: self.maindict[el] = marioVal def numSets(self): return self.diffSets
e7536a64c8d5819d440242935f89ee0cbb8fc312
[ "Markdown", "Python" ]
4
Markdown
Ben-Wunderlich/pylabyrinth
ec900bf19cdcff2d34bc3f80d75151430eb7682a
85e514f26f70a8e1e36cde0dacea8e4c7566aec0
refs/heads/master
<repo_name>korostenskyi/Plan-It<file_sep>/app/src/main/java/io/korostenskyi/planit/presentation/base/ui/ViewModelFragment.kt package io.korostenskyi.planit.presentation.base.ui import android.os.Bundle import android.view.View import androidx.annotation.CallSuper import androidx.annotation.LayoutRes import io.korostenskyi.planit.presentation.base.viewModel.BaseViewModel abstract class ViewModelFragment<V : BaseViewModel>( @LayoutRes layoutId: Int ) : BaseFragment(layoutId) { protected abstract val viewModel: V @CallSuper override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel.onCreate() } @CallSuper override fun onViewCreated(view: View, savedInstanceState: Bundle?) { viewModel.onViewCreated() super.onViewCreated(view, savedInstanceState) } @CallSuper override fun onDestroyView() { viewModel.onDestroyView() super.onDestroyView() } @CallSuper override fun onDestroy() { viewModel.onDestroy() super.onDestroy() } } <file_sep>/app/src/main/java/io/korostenskyi/planit/di/ApplicationModule.kt package io.korostenskyi.planit.di import org.koin.dsl.module val applicationModule = module { } <file_sep>/domain/src/main/java/io/korostenskyi/planit/domain/MyClass.kt package io.korostenskyi.planit.domain class MyClass <file_sep>/app/src/main/java/io/korostenskyi/planit/presentation/screen/home/HomeFragment.kt package io.korostenskyi.planit.presentation.screen.home import io.korostenskyi.planit.R import io.korostenskyi.planit.presentation.base.ui.BaseFragment class HomeFragment : BaseFragment(R.layout.fragment_home) <file_sep>/app/src/main/java/io/korostenskyi/planit/presentation/MainActivity.kt package io.korostenskyi.planit.presentation import androidx.appcompat.app.AppCompatActivity import io.korostenskyi.planit.R class MainActivity : AppCompatActivity(R.layout.activity_main) <file_sep>/app/src/main/java/io/korostenskyi/planit/presentation/di/PresentationModule.kt package io.korostenskyi.planit.presentation.di import org.koin.dsl.module val presentationModule = module { } <file_sep>/version.gradle ext { majorVersion = 0 minorVersion = 0 patchVersion = 1 buildCode = 1 buildName = "$majorVersion.$minorVersion.$patchVersion" } <file_sep>/app/src/main/java/io/korostenskyi/planit/App.kt package io.korostenskyi.planit import android.app.Application import io.korostenskyi.planit.di.applicationModule import io.korostenskyi.planit.presentation.di.presentationModule import org.koin.android.ext.koin.androidContext import org.koin.core.context.startKoin import timber.log.Timber import timber.log.Timber.DebugTree class App : Application() { override fun onCreate() { super.onCreate() initKoin() initTimber() } private fun initKoin() { startKoin { androidContext(this@App) modules(applicationModule + presentationModule) } } private fun initTimber() { if (BuildConfig.DEBUG) { Timber.plant(DebugTree()) } } }
b34b3a695218e5981a742d56e50c86ca204f549a
[ "Kotlin", "Gradle" ]
8
Kotlin
korostenskyi/Plan-It
6d3b7442a2c68b7f7328be09b641728b46a4b61f
b47c71af84c0ea3cf3c709d1e73b63b058b5f33a
refs/heads/master
<repo_name>golifes/commons<file_sep>/tools/utils/utils.go package utils import ( "bytes" "crypto/md5" "encoding/hex" "encoding/json" "fmt" "log" "net" "reflect" "regexp" "strings" "time" ) const ( str = `(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|(\b(select|update|and|or|delete|insert|trancate|char|chr|into|substr|ascii|declare|exec|count|master|into|drop|execute)\b)` DayFormat = "2006-01-02" ) /** pageSize:每页展示多少 pageNum:页码 defaultPageSize:默认每页展示多少 */ func Pagination(pageSize, pageNum, defaultPageSize int) (ps, pn int) { if pageNum <= 1 { pn = 1 } else { pn = pageNum } if pageSize <= 0 || pageSize >= defaultPageSize { ps = defaultPageSize } else { ps = pageSize } return } func CheckError(err error, v interface{}) bool { if err != nil { log.Printf("err is %s,%s", err, v) return false } return true } func CheckErrorArgs(v interface{}, errs ...error) bool { for _, err := range errs { if err != nil { log.Printf("err is %s,%s", err, v) return false } } return true } func FindBizStr(url string) (arr []string) { fmt.Println(url) //a := "http://mp.weixin.qq.com/s?__biz=MzU3ODE2NTMxNQ==&MID=2247485961&idx=1&sn=431af867d04efd973fd16df359365dd6&chksm=fd78c525ca0f4c334da2c677c1622f32058b7d3b89d255d5bb6e21a11a7f32407b67b13245bd&scene=27#wechat_redirect" //index := strings.Index(a, "__biz=") //fmt.Println(index) //print(a[index:]) bizIndex := strings.Index(url, "__biz=") if bizIndex == -1 { return nil } bizEnd := strings.Index(url[bizIndex:], "&") biz := url[bizIndex+6 : bizEnd+bizIndex] arr = append(arr, biz) //mid midIndex := strings.Index(url, "mid=") if midIndex == -1 { midIndex = strings.Index(url, "MID=") } if midIndex == -1 { return nil } midEnd := strings.Index(url[midIndex:], "&") mid := url[midIndex+4 : midIndex+midEnd] arr = append(arr, mid) idxIndex := strings.Index(url, "&idx=") if midIndex == -1 { idxIndex = strings.Index(url, "&idx=") } if midIndex == -1 { return nil } idxEnd := strings.Index(url[idxIndex+5:], "&") idx := url[idxIndex+5 : idxEnd+idxIndex+5] arr = append(arr, idx) return } func QueryCols(m map[string]interface{}) (query string, value []interface{}) { //待测试 这里是 value是int 和字符串时间等 count := 0 if m != nil { for k, v := range m { if count == 0 { query += k + " ? " } else { query += " and " + k + " ? " } value = append(value, v) count += 1 } } return } func EncodeMd5(value string) string { m := md5.New() m.Write([]byte(value)) return hex.EncodeToString(m.Sum(nil)) } func SqlRegex(param string) bool { re, err := regexp.Compile(str) if err != nil { log.Printf("error param error is %s", err.Error()) return true } return re.MatchString(param) } func StringJoin(a ...string) string { var buf bytes.Buffer for _, k := range a { buf.WriteString(k) } return buf.String() } func StructToMap(obj interface{}) map[string]interface{} { obj1 := reflect.TypeOf(obj) obj2 := reflect.ValueOf(obj) var data = make(map[string]interface{}) for i := 0; i < obj1.NumField(); i++ { data[obj1.Field(i).Name] = obj2.Field(i).Interface() } return data } func Time2Str(t time.Time, format string) string { //now := time.Now() //formatNow := now.Format("2006-01-02 15:04:05") formatNow := t.Format(format) fmt.Println(formatNow) return formatNow } func NowTime() time.Time { timeUnix := time.Now().Format(DayFormat) location, _ := time.ParseInLocation(DayFormat, timeUnix, time.Local) return location } func Str2Time(format, value string) time.Time { local, _ := time.LoadLocation("Local") //t, _ := time.ParseInLocation("2006-01-02 15:04:05", "2017-06-20 18:16:15", local) t, _ := time.ParseInLocation(format, value, local) fmt.Println(t) return t } //获取今天的unix时间 func StrTimeToUnix() int64 { format := time.Now().Format(DayFormat) loc, _ := time.LoadLocation("Asia/Shanghai") tt, _ := time.ParseInLocation(DayFormat, format, loc) return tt.Unix() } /** 打印es sql */ func PrintQuery(src interface{}) { data, err := json.MarshalIndent(src, "", " ") if err != nil { panic(err) } log.Printf("es sql--->%s", string(data)) } func JoinS(count int) string { s := "" for i := 0; i < count; i++ { if i < count-1 { s += " ?, " } else { s += " ? " } } return s } /** 获取本地ip地址 */ func GetClientIp() string { netInterfaces, err := net.Interfaces() if err != nil { return "" } for i := 0; i < len(netInterfaces); i++ { if (netInterfaces[i].Flags & net.FlagUp) != 0 { adders, _ := netInterfaces[i].Addrs() for _, address := range adders { if inet, ok := address.(*net.IPNet); ok && !inet.IP.IsLoopback() { if inet.IP.To4() != nil { return inet.IP.String() } } } } } return "" } <file_sep>/middleware/share.go package middleware import ( "commons/pkg/app" "commons/pkg/e" //"comadmin/pkg/app" //"comadmin/pkg/e" "github.com/gin-gonic/gin" "net/http" ) func Share() gin.HandlerFunc { return func(c app.GContext) { g := app.G{c} ip := g.ClientIP() ipList := [...]string{"127.0.0.1"} f := false for _, v := range ipList { if ip == v { f = true break } } if !f { g.Json(http.StatusOK, e.Forbid, "") g.Abort() return } g.Next() } } <file_sep>/cmd/main.go package main import ( "commons/routers/router" "flag" ) func main() { //admin.NewPath("config/config.json") path := flag.String("-c", "config/config.json", "config.conf") port := flag.Int("-p", 8080, "port") node := flag.Int64("-n", 1, "node") router.InitRouter(*port, *path, *node) } <file_sep>/middleware/spider.go package middleware import ( "commons/http/wx" "commons/pkg/app" "commons/pkg/e" "github.com/gin-gonic/gin" "net/http" ) const ( BlackListSpider = "BlackListSpider" BlackListApi = "BlackListApi" ) func Spider(m *wx.HttpWxHandler) gin.HandlerFunc { return func(c app.GContext) { g := app.G{c} ip := g.ClientIP() //ipList := [...]string{"192.168.3.11", "127.0.0.1", "172.16.58.3", "192.168.3.11"} if !m.BlackList(BlackListSpider, ip) { g.Json(http.StatusOK, e.Forbid, "") g.Abort() return } g.Next() } } <file_sep>/entiy/wx/wxv2.go package entiyWx type Page struct { Ps int `json:"ps" binding:"required"` Pn int `json:"pn" binding:"required"` } type BizContent struct { ArticleId string `json:"article_id" binding:"required"` Content string `json:"content" binding:"required"` ContentStyle string `json:"content_style" binding:"required"` NickName string `json:"nick_name"` } type RetList struct { OwId int64 `json:"ow_id"` //公号id Title string `json:"title"` //标题 ContentUrl string `json:"content_url"` //url Ptime int64 `json:"ptime"` //发布时间 } type Queue struct { Url string `json:"url"` ArticleId string `json:"article_id"` } type Id struct { Id string `json:"id" binding:"required"` } <file_sep>/logic/admin/handler.go package admin import ( "commons/dao/admin" "context" ) type LogicHandler interface { handler } type handler interface { Exist(ctx context.Context, bean interface{}) bool } type Logic struct { db admin.DbHandler } func (l Logic) Exist(ctx context.Context, bean interface{}) bool { return l.db.Exist(ctx, bean) } var _ LogicHandler = Logic{} func NewLogic(path string) LogicHandler { return &Logic{db: admin.NewDb(path)} } <file_sep>/routers/handler.go package routers import ( "commons/http/admin" "commons/http/wx" "github.com/gin-gonic/gin" ) type Engine struct { *gin.Engine *adminc.HttpAdminHandler *wx.HttpWxHandler } <file_sep>/pkg/config/config.go package config import ( "fmt" "github.com/go-redis/redis/v7" _ "github.com/go-sql-driver/mysql" "github.com/olivere/elastic/v7" "github.com/xormplus/xorm" "log" ) const sqlConn = "%s:%s@tcp(%s)/%s?charset=utf8&parseTime=True&loc=Local" type Config struct { Write struct { Addr string Port int User string Pwd string Db string } Read []struct { Addr string Port int User string Pwd string Db string } Show bool MaxOpen int MaxIdle int } type Redis struct { Dns string Pwd string PoolSize int MaxIdle int Db int } type Es struct { Host string //es host Index string // es index } func NewDb(c Config) *xorm.EngineGroup { conn := make([]string, 0) w := fmt.Sprintf(sqlConn, c.Write.User, c.Write.Pwd, c.Write.Addr, c.Write.Db) conn = append(conn, w) for _, v := range c.Read { s := fmt.Sprintf(sqlConn, v.User, v.Pwd, v.Addr, v.Db) conn = append(conn, s) } engine, err := xorm.NewEngineGroup("mysql", conn) // if err != nil { fmt.Println("err ", engine.Ping()) panic(err) } // engine.SetMaxIdleConns(c.MaxIdle) engine.SetMaxOpenConns(c.MaxOpen) engine.ShowSQL(c.Show) return engine } func LoadRedis(c Redis) (rdx *redis.Client) { rdx = redis.NewClient(&redis.Options{ Addr: c.Dns, Password: <PASSWORD>, // no password set DB: c.Db, }) if _, err := rdx.Ping().Result(); err != nil { fmt.Println("c--->", c, err) } return } func LoadElastic(s Es) (es *elastic.Client, index string) { var err error index = s.Index fmt.Println(s) es, err = elastic.NewSimpleClient(elastic.SetURL(s.Host)) if err != nil { log.Printf("elastic conn is error %s", err) } return } <file_sep>/api.md ``` GOOS=linux GOARCH=amd64 go build hello.go 获取公号biz等信息(给手机端用) uri:/api/v2/wx/phoneBiz params:{"ps":10,"pn":1,"stime":1573653933} stime:指的抓取时间,必须传递(比如可以指定三小时前没抓去的公号) method:get res: { "code": 200, "data": { "count": 2, "list": [ { "id": 2, //自定义的id "name": "艾奇SEM", //公号名称 "biz": "MzIyODA0MzUxMg==", //公号biz "wx_id": "iresearch-", //微信id "uin": "MTQxOTgxNjQwMg==", //当前uin "key": "666", // key "incr": true //知否增量抓取(手机端可以忽略) } ] }, "msg": "成功" } 更新key接口 uri:/api/v2/wx/biz params: { "id": 2, "name": "艾奇SEM", "biz": "biz", "wx_id": "iresearch-", "uin": "MTQxOTgxNjQwMg==", "key": "666", } method:post res: { "code": 200, "data": 2, //更新总数 比如更新了三条,这里就是3 "msg": "成功" } 获取列表数据 uri:/api/v2/wx/list params:{"ps":10,"pn":1} pn是页码 必须大于等于1 ps[1,10] method:get content_type:json res: { "code": 200, "data": { "count": 6242, "list": [ { "article_id": "37f476f87c078f5c6fc436e90cbf88bd", "ow_id": 2, "content_url": "http://mp.weixin.qq.com/s?__biz=MzIyODA0MzUxMg==&mid=210102625&idx=1&sn=55ffb93a30337bf9b739778346332659&chksm=6126b6f656513fe0af10241bfe38bbe0bb1c314546a60a06ad8478ef59828c7e04e75f5a1eab&scene=27#wechat_redirect", "title": "从三个方面剖析长尾理论与20/80定律", "ptime": 1441630416 } ] }, "msg": "成功" } 获取详情数据: uri:/api/v2/wx/detail params {"id":"6785562602758c135919c513c061a0d8"} method:get content_type:json res: { "code": 200, "data": "<KEY>", "msg": "成功" }<file_sep>/routers/router/wx.go package router import ( "commons/middleware" "commons/routers" ) const ( BlackListSpider = "BlackListSpider" BlackListApi = "BlackListApi" ) func weiXin(e *routers.Engine) { r := e.Group("/wx") { r.POST("/add", e.AddWx) //添加公众号 r.POST("/key", e.UpdateWxKey) //更新公众号key r.GET("/biz", e.FindWxBiz) //获取公号列表数据 r.POST("/forbid", e.ForBidWx) //禁用微信 r.GET("/list", e.WxList) r.GET("/key", e.FindBizUinKey) //r.GET("/getBiz", e.FindBizUinKey) r.POST("/list", e.AddWxList) r.POST("/detail", e.AddDetail) //r.POST("/spiderTime", e.UpdateSpiderTime) //差一个入库详情页和列表数据接口 } //自己用 v2 := e.Group("/api/v2/wx") v2.Use(middleware.Spider(e.HttpWxHandler)) { //获取biz和key等信息 这里接手一个时间,获取每个时间段的 v2.GET("/biz", e.GetWxBizList) //更新微信key 如果biz是biz,则是万能key v2.POST("/biz", e.UpdateBizKey) v2.POST("/run", e.SpiderRun) //提交列表数据 v2.POST("/queue", e.AddQueue) //提交队列任务 v2.GET("/queue", e.GetQueue) //获取队列任务 v2.POST("/errorQueue", e.ErrorQueue) v2.POST("/detail", e.UpdateBizContent) //更新详情数据 v2.GET("/list", e.GetList) //获取前端列表数据 v2.GET("/detail", e.GetOne) //获取详情数据 } //给bean的api v3 := e.Group("/api/bean/wx") v3.Use(middleware.API()) { v3.GET("/list", e.GetList) //获取前端列表数据 v3.GET("/detail", e.GetOne) //获取详情数据 } } <file_sep>/dao/wx/conf.go package wx import "commons/pkg/config" type Config struct { Db *db `json:"db"` Rdx config.Redis `json:"rdx"` Es config.Es `json:"es"` } type db struct { Admin config.Config } <file_sep>/dao/admin/handler.go package admin import "context" type DbHandler interface { Handler } type Handler interface { Exist(ctx context.Context, bean ...interface{}) bool //删除 Delete(ctx context.Context, id int64, bean interface{}) (int64, error) //单表查询 FindOne(ctx context.Context, bean interface{}, table, orderBy string, query []string, values []interface{}, ps, pn int) (interface{}, int64) //获取一条记录 GetOne(ctx context.Context, bean interface{}, cols ...string) interface{} //以结构体的方式更新 UpdateStruct(ctx context.Context, bean interface{}, cols, query []string, values []interface{}) (int64, error) //以map的方式更新 UpdateMap(ctx context.Context, table string, m map[string]interface{}, cols, query []string, values []interface{}) (int64, error) //多表查询 Join2Table(ctx context.Context, bean interface{}, table, alias, cols, orderBy string, ps, pn int, query []string, values []interface{}, join [][3]interface{}) (interface{}, int64) Insert(ctx context.Context, beans ...interface{}) error //事物 Delete2Table(beans [][2]interface{}) error //事物 } var _ DbHandler = Dao{} <file_sep>/dao/wx/handler.go package wx import "context" type DbHandler interface { MysqlHandler esHandler rexHandler } type MysqlHandler interface { Exist(ctx context.Context, bean ...interface{}) bool //删除 Delete(ctx context.Context, id int64, bean interface{}) (int64, error) //单表查询 FindOne(ctx context.Context, bean interface{}, table, orderBy string, query []string, values []interface{}, ps, pn int) (interface{}, int64) //获取一条记录 GetOne(ctx context.Context, bean interface{}, cols ...string) interface{} //以结构体的方式更新 UpdateStruct(ctx context.Context, bean interface{}, cols, query []string, values []interface{}) (int64, error) //以map的方式更新 UpdateMap(ctx context.Context, table string, m map[string]interface{}, cols, query []string, values []interface{}) (int64, error) //多表查询 Join2Table(ctx context.Context, bean interface{}, table, alias, cols, orderBy string, ps, pn int, query []string, values []interface{}, join [][3]interface{}) (interface{}, int64) Insert(ctx context.Context, beans ...interface{}) error //事物 Delete2Table(beans [][2]interface{}) error //事物 } type esHandler interface { InsertEs(id string, bean interface{}) bool UpdateEs(id string, m map[string]interface{}) bool GetOneEs(id string, cols ...string) interface{} GetListEs(ps, pn int, cols ...string) ([]interface{}, interface{}) } type rexHandler interface { Set(key string, value interface{}) bool Get(key string) []byte SAdd(members ...interface{}) (memList []string) SetQueue(key string, members ...interface{}) bool SPop(key string, ps int64) []string SisMember(key string, member interface{}) bool } var _ DbHandler = Dao{} <file_sep>/middleware/UserRecord.go package middleware import ( "commons/pkg/app" //"comadmin/pkg/app" "fmt" "github.com/gin-gonic/gin" ) /** 记录用户最后一次下载记录时间 */ func DownLoad() gin.HandlerFunc { return func(c app.GContext) { fmt.Println("download......") c.Next() } } <file_sep>/dao/admin/redis.go package admin import "commons/tools/utils" /** redis set string */ const expireTime = 60 func (d Dao) set(key string, value interface{}) bool { result, err := d.rdx.Set(key, value, expireTime).Result() if utils.CheckError(err, result) { return true } return false } func (d Dao) get(key string) string { result, err := d.rdx.Get(key).Result() if utils.CheckError(err, result) { return result } return "" } <file_sep>/http/wx/blackList.go package wx /** 白名单 */ func (h HttpWxHandler) BlackList(key string, ip string) bool { return h.logic.SisMember(key, ip) } <file_sep>/dao/admin/dao.go package admin import ( "commons/pkg/config" "context" "github.com/go-redis/redis/v7" "github.com/xormplus/xorm" ) type Dao struct { c Config engine *xorm.EngineGroup rdx *redis.Client } func (d Dao) Exist(ctx context.Context, bean ...interface{}) bool { return d.exist(bean) } func (d Dao) Delete(ctx context.Context, id int64, bean interface{}) (int64, error) { return d.delete(id, bean) } func (d Dao) FindOne(ctx context.Context, bean interface{}, table, orderBy string, query []string, values []interface{}, ps, pn int) (interface{}, int64) { return d.findOne(bean, table, orderBy, query, values, ps, pn) } func (d Dao) GetOne(ctx context.Context, bean interface{}, cols ...string) interface{} { return d.getOne(bean) } func (d Dao) UpdateStruct(ctx context.Context, bean interface{}, cols, query []string, values []interface{}) (int64, error) { return d.updateStruct(bean, cols, query, values) } func (d Dao) UpdateMap(ctx context.Context, table string, m map[string]interface{}, cols, query []string, values []interface{}) (int64, error) { return d.updateMap(table, m, cols, query, values) } func (d Dao) Join2Table(ctx context.Context, bean interface{}, table, alias, cols, orderBy string, ps, pn int, query []string, values []interface{}, join [][3]interface{}) (interface{}, int64) { return d.join2Table(bean, table, alias, cols, orderBy, ps, pn, query, values, join) } func (d Dao) Insert(ctx context.Context, beans ...interface{}) error { return d.insertMany(beans) } func (d Dao) Delete2Table(beans [][2]interface{}) error { return d.delete2Table(beans) } func NewDb(path string) *Dao { //load 结构体绑定 var c Config config.Load(path, &c) //es, index := config.LoadElastic(c.Es) return &Dao{engine: config.NewDb(c.Db.Admin), rdx: config.LoadRedis(c.Rdx)} } <file_sep>/model/wx/list.go package wx type List struct { ArticleId string `json:"article_id" xorm:"article_id"` //主键id Biz string `json:"biz"` // Mid int64 `json:"mid"` // Idx int64 `json:"idx"` // OwId int64 `json:"ow_id"` //自定义微信id Oid int64 `json:"oid" xorm:"oid"` //原始id,就是公号数据中的id AudioFileid int64 `json:"audio_fileid" xorm:"audio_fileid"` Title string `json:"title" xorm:"title"` ContentURL string `json:"content_url" xorm:"content_url"` SourceURL string `json:"source_url" xorm:"source_url"` Cover string `json:"cover" xorm:"cover"` Author string `json:"author" xorm:"author"` DelFlag int64 `json:"del_flag" xorm:"del_flag"` PlayURL string `json:"play_url" xorm:"play_url"` Content string `json:"content" xorm:"content"` ItemShowType int64 `json:"item_show_type" xorm:"item_show_type"` MaliciousTitleReasonID int64 `json:"malicious_title_reason_id" xorm:"malicious_title_reason_id"` Digest string `json:"digest" xorm:"digest"` Fileid int64 `json:"fileid" xorm:"fileid"` CopyrightStat int64 `json:"copyright_stat" xorm:"copyright_stat"` Duration int64 `json:"duration" xorm:"duration"` MaliciousContentType int64 `json:"malicious_content_type" xorm:"malicious_content_type"` Subtype int64 `json:"subtype" xorm:"subtype"` Type int64 `json:"type" xorm:"type"` Ptime int64 `json:"ptime" xorm:"ptime"` Fakeid string `json:"fakeid" xorm:"fakeid"` Status int64 `json:"status" xorm:"status"` Ctime int64 `json:"ctime" xorm:"created"` //创建时间 } //func (w WeiXinList) Deadline() (deadline time.Time, ok bool) { // panic("implement me") //} // //func (w WeiXinList) Done() <-chan struct{} { // panic("implement me") //} // //func (w WeiXinList) Err() error { // panic("implement me") //} // //func (w WeiXinList) Value(key interface{}) interface{} { // panic("implement me") //} // <file_sep>/entiy/wx/wx.go package entiyWx import "time" type WeiXin struct { Id int64 `json:"id"` //主键Id WxId string `json:"wx_id" binding:"required"` //微信id Name string `json:"name" binding:"required"` //微信名称 Url string `json:"url" binding:"required"` //微信头像 Desc string `json:"desc" binding:"required"` //公号描述 Biz string `json:"biz" binding:"required"` //公号biz Count string `json:"count"` //公号文章数量 Forbid int `json:"forbid" xorm:"default 1"` //是否被禁用 Key string `json:"key"` //公号Key Uin string `json:"uin"` //用户唯一标识 Ctime time.Time `json:"ctime" xorm:"created"` //创建时间 Mtime time.Time `json:"mtime" xorm:"updated"` //更新时间 SpiderTime time.Time `json:"spider_time"` //最后一次抓取时间 Note string `json:"note"` //备用字段 } type WeiXinParams struct { Id int `json:"id"` //查询biz Keywords string `json:"keywords"` //关键字 From string `json:"from"` //发布时间起始 To string `json:"to"` // 发布时间截止 Title string `json:"title"` //标题模糊查询 Pn int `json:"pn"` Ps int `json:"ps"` Type int `json:"type"` //导出当前页还是导出全部数据 1是导出全部 -1导出当前页 } type WeiXinKey struct { Id int64 `json:"id"` WxId string `json:"wx_id"` Biz string `json:"biz" binding:"required"` Key string `json:"key" binding:"required"` Uin string `json:"uin" binding:"required"` } type Wx struct { Id int64 `json:"id"` //通过id查询 Name string `json:"name"` //通过name模糊查询 Biz string `json:"biz"` //通过biz查询 Ps int Pn int } type WxBiz struct { Id int64 `json:"id"` Name string `json:"name"` Biz string `json:"biz"` WxId string `json:"wx_id"` Uin string `json:"uin"` Key string `json:"key"` Incr bool `json:"incr"` } type ForBidWx struct { Id string `json:"id" binding:"required"` } //获取微信文章列表数据 type WxList struct { OwId int64 `json:"ow_id"` //公号id ArticleId string `json:"article_id"` //文章id Title string `json:"title"` //标题 Forbid int `json:"forbid" xorm:"default 1"` //是否被禁用 StartTime time.Time `json:"start_time"` //发布时间 EndTime time.Time `json:"end_time"` //结束时间 Ps int `json:"ps"` //分页 Pn int `json:"pn"` //分页 OrderBy string `json:"order_by"` //排序 } type Ps struct { Ps int `json:"ps"` Pn int `json:"pn"` } type BizList struct { Ps int `json:"ps" binding:"required"` Incr bool `json:"incr"` Stime int `json:"stime" binding:"required"` } type List struct { ArticleId string `json:"article_id" xorm:"article_id"` //主键id Biz string `json:"biz"` // Mid int `json:"mid"` // Idx int `json:"idx"` // OwId int `json:"ow_id"` //自定义微信id Oid int `json:"oid" xorm:"oid"` //原始id AudioFileid int `json:"audio_fileid" xorm:"audio_fileid"` Title string `json:"title" xorm:"title"` ContentURL string `json:"content_url" xorm:"content_url"` SourceURL string `json:"source_url" xorm:"source_url"` Cover string `json:"cover" xorm:"cover"` Author string `json:"author" xorm:"author"` DelFlag int `json:"del_flag" xorm:"del_flag"` PlayUrl string `json:"play_url" xorm:"play_url"` Content string `json:"content" xorm:"content"` ItemShowType int `json:"item_show_type" xorm:"item_show_type"` MaliciousTitleReasonID int `json:"malicious_title_reason_id" xorm:"malicious_title_reason_id"` Digest string `json:"digest" xorm:"digest"` Fileid int `json:"fileid" xorm:"fileid"` CopyrightStat int `json:"copyright_stat" xorm:"copyright_stat"` Duration int `json:"duration" xorm:"duration"` MaliciousContentType int `json:"malicious_content_type" xorm:"malicious_content_type"` Subtype int `json:"subtype" xorm:"subtype"` Type int `json:"type" xorm:"type"` Ptime int64 `json:"ptime" xorm:"ptime"` Fakeid string `json:"fakeid" xorm:"fakeid"` Status int `json:"status" xorm:"status"` NickName string `json:"nick_name" xorm:"-"` ContentStyle string `json:"content_style" xorm:"-"` Ctime int64 `json:"ctime" ` Mtime int64 `json:"mtime" xorm:"-"` } type SpiderTime struct { Biz string `json:"biz" binding:"required"` Stime int64 `json:"stime" binding:"required"` Num int64 `json:"num"` Msg string `json:"msg"` } type WeiXinList struct { OwId int64 `json:"ow_id"` //公号id Biz string `json:"biz"` // ArticleId string `json:"article_id"` //文章id Title string `json:"title"` //标题 Digest string `json:"digest"` //摘要 ContentUrl string `json:"content_url"` //url SourceUrl string `json:"source_url"` //source_url Forbid int `json:"forbid" xorm:"default 1"` //是否被禁用 Ptime int64 `json:"ptim"` //发布时间 Ctime int64 `json:"ctime" xorm:"created"` //创建时间 //Mtime time.Time `json:"mtime" xorm:"updated"` //更新时间 Ps int `json:"ps,omitempty" xorm:"-"` // Pn int `json:"pn,omitempty" xorm:"-"` // } <file_sep>/model/Blacklist/back.go package Blacklist /** 白名单 */ type Blacklist struct { Id int Ip string Name string //谁的名称 Type int //是谁的标记id } <file_sep>/http/admin/handler.go package adminc import "commons/logic/admin" type HttpAdminHandler struct { logic admin.LogicHandler Node int64 } func NewAdminHttpAdminHandler(path string, node int64) *HttpAdminHandler { return &HttpAdminHandler{logic: admin.NewLogic(path), Node: node} } <file_sep>/middleware/login.go package middleware import ( "commons/pkg/app" "github.com/gin-gonic/gin" ) func Anonymous() gin.HandlerFunc { return func(c app.GContext) { g := app.G{c} //token := c.Request.Header.Get("token") //if token == "" { // g.Set("anonymous", true) //} else { // //根据实际需要设置数据 // if claims, code := webToken.ParseToken(token); code == e.Success && claims != nil { // g.Set("userName", claims.Username) // g.Set("userId", claims.Id) // g.Set("isAdmin", claims.IsAdmin) // g.Set("isRoot", claims.IsRoot) // g.Set("anonymous", false) // // } else { // g.Set("anonymous", true) // } //} g.Next() } } <file_sep>/dao/wx/dao.go package wx import ( "commons/pkg/config" "context" "github.com/go-redis/redis/v7" "github.com/olivere/elastic/v7" "github.com/xormplus/xorm" ) type Dao struct { c Config engine *xorm.EngineGroup rdx *redis.Client es *elastic.Client esIndex string } func NewDb(path string) *Dao { //load 结构体绑定 var c Config config.Load(path, &c) es, index := config.LoadElastic(c.Es) return &Dao{engine: config.NewDb(c.Db.Admin), rdx: config.LoadRedis(c.Rdx), es: es, esIndex: index} } func (d Dao) SisMember(key string, member interface{}) bool { return d.sisMember(key, member) } func (d Dao) GetListEs(ps, pn int, cols ...string) ([]interface{}, interface{}) { return d.getListEs(ps, pn, cols...) } func (d Dao) UpdateEs(id string, m map[string]interface{}) bool { return d.updateEs(id, m) } func (d Dao) GetOneEs(id string, cols ...string) interface{} { return d.getOneEs(id, cols...) } func (d Dao) SPop(key string, ps int64) []string { return d.sPop(key, ps) } func (d Dao) SetQueue(key string, members ...interface{}) bool { return d.setQueue(key, members...) } func (d Dao) SAdd(members ...interface{}) (memList []string) { return d.sAdd(members...) } func (d Dao) Set(key string, value interface{}) bool { return d.set(key, value, 7*24*60) } func (d Dao) Get(key string) []byte { return d.get(key) } func (d Dao) InsertEs(id string, bean interface{}) bool { return d.addEsOne(id, bean) } func (d Dao) Exist(ctx context.Context, bean ...interface{}) bool { return d.exist(bean) } func (d Dao) Delete(ctx context.Context, id int64, bean interface{}) (int64, error) { return d.delete(id, bean) } func (d Dao) FindOne(ctx context.Context, bean interface{}, table, orderBy string, query []string, values []interface{}, ps, pn int) (interface{}, int64) { return d.findOne(bean, table, orderBy, query, values, ps, pn) } func (d Dao) GetOne(ctx context.Context, bean interface{}, cols ...string) interface{} { return d.getOne(bean) } func (d Dao) UpdateStruct(ctx context.Context, bean interface{}, cols, query []string, values []interface{}) (int64, error) { return d.updateStruct(bean, cols, query, values) } func (d Dao) UpdateMap(ctx context.Context, table string, m map[string]interface{}, cols, query []string, values []interface{}) (int64, error) { return d.updateMap(table, m, cols, query, values) } func (d Dao) Join2Table(ctx context.Context, bean interface{}, table, alias, cols, orderBy string, ps, pn int, query []string, values []interface{}, join [][3]interface{}) (interface{}, int64) { return d.join2Table(bean, table, alias, cols, orderBy, ps, pn, query, values, join) } func (d Dao) Insert(ctx context.Context, beans ...interface{}) error { return d.insertMany(beans...) } func (d Dao) Delete2Table(beans [][2]interface{}) error { return d.delete2Table(beans) } <file_sep>/http/wx/handler.go package wx import ( "commons/logic/wx" ) type HttpWxHandler struct { logic wx.LogicHandler Node int64 } func NewWxHttpHandler(path string, node int64) *HttpWxHandler { return &HttpWxHandler{logic: wx.NewLogic(path), Node: node} } <file_sep>/dao/wx/es.go package wx import ( entiyWx "commons/entiy/wx" "commons/tools/utils" "context" "encoding/json" "github.com/olivere/elastic/v7" "strings" "time" ) /** es添加数据 */ func (d Dao) addEsOne(id string, bean interface{}) bool { if bytes, err := json.Marshal(bean); utils.CheckError(err, bytes) { do, err := d.es.Index().Index(d.esIndex).Id(id).BodyString(string(bytes)).Do(context.Background()) if utils.CheckError(err, do) { return true } return false } else { return false } } //批量入库 func (d Dao) BulkDoc() { bulk := d.es.Bulk() bulk.Add() } func (d Dao) articles(detail entiyWx.WeiXinParams, ps, pn int) (interface{}, interface{}) { /** 这里拼接es sql select a from table where forbid = 1 and ( title like "%aaa%" or text like "%bbb%") https://www.tuicool.com/articles/NFVzeqy */ //zuiwaiceng query bool query := elastic.NewBoolQuery() boolQuery := elastic.NewBoolQuery() boolQuery.Must(elastic.NewTermQuery("forbid", 1)) query.Filter(boolQuery) filter := elastic.NewBoolQuery() newBoolQuery := elastic.NewBoolQuery() queryFilter := filter.Must(newBoolQuery) if detail.Title != "" { newBoolQuery.Should(elastic.NewWildcardQuery("title", detail.Title)) } if detail.Keywords != "" { split := strings.Split(detail.Keywords, ",") for _, v := range split { newBoolQuery.Should(elastic.NewWildcardQuery("title", v)) newBoolQuery.Should(elastic.NewWildcardQuery("text", v)) } } //if detail.Id != 0 { // biz := d.findBizById(detail.Id) // if biz != "" { // query.Must(elastic.NewMatchQuery("biz", biz)) // } //} const t = "2006-01-02 15:04:05" if detail.From != "" && detail.To != "" { query.Filter(elastic.NewRangeQuery("ptime").Gte(utils.Str2Time(t, detail.From)).Lte(utils.Str2Time(t, detail.To))) } else if detail.From != "" { query.Filter(elastic.NewRangeQuery("ptime").Gte(utils.Str2Time(t, detail.From)).Lte(time.Now())) } query.Filter(queryFilter) field := elastic.NewFetchSourceContext(true) field.Include("id", "text", "text_style", "biz", "author", "original", "word_cloud", "summary", "title", "forbid") source, _ := query.Source() utils.PrintQuery(source) result, err := d.es.Search().FetchSourceContext(field).Index(d.esIndex).Query(query).Do(context.Background()) if utils.CheckError(err, result) { array := make([]interface{}, len(result.Hits.Hits)) for index, hit := range result.Hits.Hits { //var r ret //json.Unmarshal(hit.Source, &r) array[index] = hit.Source } return array, result.Hits.TotalHits.Value } return nil, 0 } func (d Dao) updateEs(id string, m map[string]interface{}) bool { do, err := d.es.Update().Index(d.esIndex).Id(id).Doc(m).Do(context.Background()) if utils.CheckErrorArgs(do, err) { return true } return false } func (d Dao) getOneEs(id string, cols ...string) interface{} { field := elastic.NewFetchSourceContext(true) //field.Include("content_style") field.Include(cols...) res, err := d.es.Get().FetchSourceContext(field).Index(d.esIndex).Id(id).Do(context.Background()) if utils.CheckErrorArgs(res, err) { bytes, _ := res.Source.MarshalJSON() return bytes } return nil } func (d Dao) getListEs(ps, pn int, cols ...string) ([]interface{}, interface{}) { field := elastic.NewFetchSourceContext(true) //field.Include("content_style") field.Include(cols...) result, err := d.es.Search().FetchSourceContext(field).Index(d.esIndex).Sort("ptime", true).From(ps * pn).Size(ps).Do(context.Background()) if utils.CheckError(err, result) { array := make([]interface{}, len(result.Hits.Hits)) for index, hit := range result.Hits.Hits { //var r ret //json.Unmarshal(hit.Source, &r) array[index] = hit.Source } return array, result.Hits.TotalHits.Value } return nil, 0 } <file_sep>/logic/wx/handler.go package wx import ( "commons/dao/wx" "context" ) type LogicHandler interface { handler esHandler rexHandler } type handler interface { Exist(ctx context.Context, bean ...interface{}) bool //删除 Delete(ctx context.Context, id int64, bean interface{}) (int64, error) //单表查询 FindOne(ctx context.Context, bean interface{}, table, orderBy string, query []string, values []interface{}, ps, pn int) (interface{}, int64) //获取一条记录 GetOne(ctx context.Context, bean interface{}, cols ...string) interface{} //以结构体的方式更新 UpdateStruct(ctx context.Context, bean interface{}, cols, query []string, values []interface{}) (int64, error) //以map的方式更新 UpdateMap(ctx context.Context, table string, m map[string]interface{}, cols, query []string, values []interface{}) (int64, error) //多表查询 Join2Table(ctx context.Context, bean interface{}, table, alias, cols, orderBy string, ps, pn int, query []string, values []interface{}, join [][3]interface{}) (interface{}, int64) Insert(ctx context.Context, beans ...interface{}) error //事物 Delete2Table(beans [][2]interface{}) error //事物 } type esHandler interface { InsertEs(id string, bean interface{}) bool UpdateEs(id string, m map[string]interface{}) bool GetOneEs(id string, cols ...string) interface{} GetListEs(ps, pn int, cols ...string) ([]interface{}, interface{}) } type rexHandler interface { Set(key string, value interface{}) bool Get(key string) []byte SAdd(members ...interface{}) (memList []string) SetQueue(key string, members ...interface{}) bool SPop(key string, ps int64) []string SisMember(key string, member interface{}) bool } type Logic struct { db wx.DbHandler } func (l Logic) SisMember(key string, member interface{}) bool { return l.db.SisMember(key, member) } func (l Logic) GetListEs(ps, pn int, cols ...string) ([]interface{}, interface{}) { return l.db.GetListEs(ps, pn, cols...) } func (l Logic) UpdateEs(id string, m map[string]interface{}) bool { return l.db.UpdateEs(id, m) } func (l Logic) GetOneEs(id string, cols ...string) interface{} { return l.db.GetOneEs(id, cols...) } func (l Logic) SPop(key string, ps int64) []string { return l.db.SPop(key, ps) } func (l Logic) SetQueue(key string, members ...interface{}) bool { return l.db.SetQueue(key, members...) } func (l Logic) SAdd(members ...interface{}) (memList []string) { return l.db.SAdd(members...) } func (l Logic) Set(key string, value interface{}) bool { return l.Set(key, value) } func (l Logic) Get(key string) []byte { return l.Get(key) } func (l Logic) InsertEs(id string, bean interface{}) bool { return l.db.InsertEs(id, bean) } func (l Logic) Exist(ctx context.Context, bean ...interface{}) bool { return l.db.Exist(ctx, bean) } func (l Logic) Delete(ctx context.Context, id int64, bean interface{}) (int64, error) { return l.db.Delete(ctx, id, bean) } func (l Logic) FindOne(ctx context.Context, bean interface{}, table, orderBy string, query []string, values []interface{}, ps, pn int) (interface{}, int64) { return l.db.FindOne(ctx, bean, table, orderBy, query, values, ps, pn) } func (l Logic) GetOne(ctx context.Context, bean interface{}, cols ...string) interface{} { return l.db.GetOne(ctx, bean, cols...) } func (l Logic) UpdateStruct(ctx context.Context, bean interface{}, cols, query []string, values []interface{}) (int64, error) { return l.db.UpdateStruct(ctx, bean, cols, query, values) } func (l Logic) UpdateMap(ctx context.Context, table string, m map[string]interface{}, cols, query []string, values []interface{}) (int64, error) { return l.db.UpdateMap(ctx, table, m, cols, query, values) } func (l Logic) Join2Table(ctx context.Context, bean interface{}, table, alias, cols, orderBy string, ps, pn int, query []string, values []interface{}, join [][3]interface{}) (interface{}, int64) { return l.db.Join2Table(ctx, bean, table, alias, cols, orderBy, ps, pn, query, values, join) } func (l Logic) Insert(ctx context.Context, beans ...interface{}) error { return l.db.Insert(ctx, beans...) } func (l Logic) Delete2Table(beans [][2]interface{}) error { return l.db.Delete2Table(beans) } var _ LogicHandler = Logic{} func NewLogic(path string) LogicHandler { return &Logic{db: wx.NewDb(path)} } <file_sep>/middleware/page.go package middleware import ( "commons/pkg/app" "commons/pkg/e" //"comadmin/pkg/app" //"comadmin/pkg/e" "github.com/gin-gonic/gin" "net/http" ) /** 匿名用户只能看前几页数据 */ func PageForBid() gin.HandlerFunc { return func(c app.GContext) { g := app.G{c} if _, ok := c.Get("userId"); ok { g.Next() } else { g.Json(http.StatusOK, e.NoLogin, "") g.Abort() } } } <file_sep>/routers/router/router.go package router import ( "commons/http/admin" "commons/http/wx" "commons/routers" "fmt" "github.com/gin-gonic/gin" ) func InitRouter(port int, path string, node int64) *routers.Engine { r := &routers.Engine{gin.New(), adminc.NewAdminHttpAdminHandler(path, node), wx.NewWxHttpHandler(path, node)} r.Use(gin.Recovery()) r.Use(gin.Logger()) weiXin(r) r.Engine.Run(fmt.Sprintf(":%d", port)) return r } <file_sep>/model/wx/wx.go package wx /** 微信公号 */ type WeiXin struct { Id int64 `json:"id"` //主键Id WxId string `json:"wx_id" binding:"required"` //微信id Name string `json:"name" binding:"required"` //微信名称 Url string `json:"url" binding:"required"` //微信头像 Desc string `json:"desc" binding:"required"` //公号描述 Biz string `json:"biz" binding:"required"` //公号biz Count int64 `json:"count"` //公号文章数量 Forbid int `json:"forbid" xorm:"default 1"` //是否被禁用 Key string `json:"key"` //公号Key Uin string `json:"uin"` //用户唯一标识 Ctime int64 `json:"ctime" xorm:"created"` //创建时间 Mtime int64 `json:"mtime" xorm:"updated"` //更新时间 Stime int64 `json:"stime" xorm:"stime"` //最后一次抓取时间 页面添加公号的时候这个时间设置成前一天时间 Note string `json:"note"` //备用字段 Num int64 `json:"num"` //总共多少页(抓取的页数) Incr bool `json:"incr"` //是否增量抓取 Run bool `json:"run"` //当前是否在运行抓取 当前运行抓取是否结束 抓取结束后更新 stime num 和finish run run从抓取进行变为未抓取 Msg string `json:"msg"` // } type WxApi struct { Id int64 `json:"id"` Url string `json:"url"` Name string `json:"name"` } //阅读历史 type Ua struct { Id int64 `json:"id"` Ua string `json:"ua"` } <file_sep>/dao/wx/rdx.go package wx import ( "commons/tools/utils" "fmt" "time" ) /** es相关的简单操作 */ const ( ArticleIdQueue = "articleIdQueue" ) func (d Dao) set(key string, value interface{}, expireTime int64) bool { res, err := d.rdx.Set(key, value, time.Duration(expireTime)).Result() if utils.CheckErrorArgs(res, err) { return true } return false } func (d Dao) get(key string) []byte { bytes, err := d.rdx.Get(key).Bytes() if utils.CheckErrorArgs("get redis task", err) { return bytes } return nil } /** set集合 */ func (d Dao) sAdd(members ...interface{}) (memList []string) { for _, member := range members { if d.rdx.SIsMember(ArticleIdQueue, member).Val() { continue } err := d.rdx.SAdd(ArticleIdQueue, members...).Err() if utils.CheckErrorArgs(fmt.Sprintf("add queue id is %s", member), err) { memList = append(memList, member.(string)) } } return } /** 判断一个元素是否属于集合 */ func (d Dao) sisMember(key string, member interface{}) bool { result, err := d.rdx.SIsMember(key, member).Result() if utils.CheckErrorArgs(result, err) && result { return true } return false } func (d Dao) setQueue(key string, members ...interface{}) bool { err := d.rdx.SAdd(key, members...).Err() if utils.CheckErrorArgs("add queue rdx", err) { return true } return false } func (d Dao) sPop(key string, ps int64) []string { result, err := d.rdx.SPopN(key, ps).Result() if utils.CheckErrorArgs(result, err) { return result } return nil } <file_sep>/http/wx/wxv2.go package wx import ( entiyWx "commons/entiy/wx" "commons/model/wx" "commons/pkg/app" "commons/pkg/e" "commons/tools/utils" "encoding/json" "fmt" "net/http" ) /** 提交到redis的任务 */ const ( StringQueue = "WxStringQueue" ) func (h HttpWxHandler) AddQueue(ctx app.GContext) { /** 接受一个列表推送 */ var p []entiyWx.List code := e.Success g, err := h.common(ctx, &p) if err != nil { return } //这里需要优化,支持批量操作 /** SetQueue支持批量操作 */ for _, v := range p { articleId := v.ArticleId //存在 if memList := h.logic.SAdd(articleId); memList == nil { continue } var queue entiyWx.Queue queue.Url = v.ContentURL queue.ArticleId = v.ArticleId marshal, _ := json.Marshal(queue) h.logic.SetQueue(StringQueue, string(marshal)) h.logic.InsertEs(articleId, v) } g.Json(http.StatusOK, code, "") } func (h HttpWxHandler) ErrorQueue(ctx app.GContext) { var p entiyWx.Queue code := e.Success g, err := h.common(ctx, &p) if err != nil { return } marshal, _ := json.Marshal(p) queue := h.logic.SetQueue(StringQueue, string(marshal)) g.Json(http.StatusOK, code, queue) } /** 从set集合队列中获取数据 params: {"ps":必填,int "pn":必填,0} */ func (h HttpWxHandler) GetQueue(ctx app.GContext) { var p entiyWx.Page code := e.Success g, err := h.common(ctx, &p) if err != nil { return } ps, _ := utils.Pagination(p.Ps, p.Pn, 10) pop := h.logic.SPop(StringQueue, int64(ps)) m := make([]entiyWx.Queue, 0) for _, v := range pop { var q entiyWx.Queue _ = json.Unmarshal([]byte(v), &q) m = append(m, q) } g.Json(http.StatusOK, code, m) return } /** 更新详情数据 */ func (h HttpWxHandler) UpdateBizContent(ctx app.GContext) { g := app.G{ctx} var p entiyWx.BizContent code := e.Success g, err := h.common(ctx, &p) if err != nil { return } toMap := utils.StructToMap(p) h.logic.UpdateEs(p.ArticleId, toMap) g.Json(http.StatusOK, code, "") } func (h HttpWxHandler) GetList(ctx app.GContext) { var p entiyWx.Page code := e.Success g, err := h.common(ctx, &p) if err != nil { return } ps, pn := utils.Pagination(p.Ps, p.Pn, 10) listEs, count := h.logic.GetListEs(ps, pn, []string{"article_id", "ow_id", "title", "content_url", "ptime"}...) m := make(map[string]interface{}) m["count"] = count m["list"] = listEs g.Json(http.StatusOK, code, m) } func (h HttpWxHandler) GetOne(ctx app.GContext) { var p entiyWx.Id code := e.Success g, err := h.common(ctx, &p) if err != nil { return } es := h.logic.GetOneEs(p.Id, []string{"content"}...) g.Json(http.StatusOK, code, es) } /** 获取抓取公号数据 每次请求返回2条数据 */ func (h HttpWxHandler) GetWxBizList(ctx app.GContext) { var p entiyWx.BizList g, err := h.common(ctx, &p) if err != nil { return } ps, pn := utils.Pagination(p.Ps, 1, 10) weiXin := make([]entiyWx.WxBiz, 0) //unix := utils.StrTimeToUnix() query := []string{} if p.Incr { query = append(query, "incr = 1 and forbid = ? and stime <= ? and run != 1 ") } else { query = append(query, " (forbid = ? and stime <= ? and run != 1 )", " or msg !='ok' ") } values := []interface{}{1, p.Stime} list, count := h.logic.FindOne(g.NewContext(ctx), &weiXin, "wei_xin", "id desc ", query, values, ps, pn) _values := []interface{}{} if count != 0 { xin := list.(*[]entiyWx.WxBiz) for _, v := range *xin { _values = append(_values, v.Biz) } //这里调用更新方法 _count := len(_values) s := utils.JoinS(_count) affect, err := h.logic.UpdateStruct(g.NewContext(ctx), wx.WeiXin{Run: true}, []string{"run"}, []string{" biz in ( " + s + ")"}, _values) fmt.Println(affect, err) } m := make(map[string]interface{}, 0) m["count"] = count m["list"] = list g.Json(http.StatusOK, e.Success, m) } func (h HttpWxHandler) UpdateBizKey(ctx app.GContext) { var p entiyWx.WeiXinKey g, err := h.common(ctx, &p) if err != nil { return } cols := []string{"key", "uin"} var query []string if p.Biz != "biz" { query = append(query, " biz = ? ") } affect, err := h.logic.UpdateStruct(g.NewContext(ctx), wx.WeiXin{Key: p.Key, Uin: p.Uin}, cols, query, []interface{}{p.Biz}) if !utils.CheckError(err, affect) { g.Json(http.StatusOK, e.UpdateWxError, p.Biz) } else { g.Json(http.StatusOK, e.Success, affect) } }
b0bd4bdce2803238567dab8416f66737f3e99310
[ "Markdown", "Go" ]
31
Go
golifes/commons
390c6c8520109e5d5c382d2f2592d6c73f242f78
44de4d0b3e428db350b8ff7bccfb37ac14cfa681
refs/heads/master
<repo_name>abugi/firebase-app<file_sep>/timeline.js $(document).ready(function(){ firebase.auth().onAuthStateChanged(function (user) { if (user) { var user = firebase.auth().currentUser; var token = user.uid; queryDatabase(token); } else { window.location = 'index.html'; } }); }); function queryDatabase(token){ firebase.database().ref('/Posts/').once('value').then(function (snapshot) { var posts = snapshot.val(); console.log(posts); var objKeys = Object.keys(posts); var currentRow; for(var i = 0; i < objKeys.length; i++){ var currentObject = posts[objKeys[i]] console.log(currentObject); if(i % 3 == 0){ currentRow = document.createElement('div'); $(currentRow).addClass('row'); $('#contentHolder').append(currentRow); } var col = document.createElement('div'); $(col).addClass('col-lg-4'); var image = document.createElement('img'); image.src = currentObject.url; $(image).addClass('contentImage'); var p = document.createElement('p'); $(p).html(currentObject.caption); $(p).addClass('contentCaption'); $(col).append(image); $(col).append(p); $(currentRow).append(col); } }); }
1669f7c6e8405620ac761ee331d2ce0df50721e6
[ "JavaScript" ]
1
JavaScript
abugi/firebase-app
eeffc852f9221204b080d36c2c6e0d43e2446b44
b2a9c45688b67c0dc2d9033033521cc4497845bc
refs/heads/master
<file_sep>First = 'Joe' Second = 'Casey' Third = 'Shore' print ("my first name is %s \nmy bffffffl's name is %s \nand his last name is %s" %(First, Second, Third))
9da6d3309b4d77c41d1854b2b7732ba5c7405dc1
[ "Python" ]
1
Python
joeoswaldhi/Python-testing
258ba9dfca51467aa6ceda6f7bc0de757ed56056
a7df96da332735877f327781224e5687a7a33396
refs/heads/master
<repo_name>h-modest/vue-oa<file_sep>/src/lib/api.js import fetch from 'isomorphic-fetch'; import _ from 'underscore'; import { timestamp, log } from './utils'; import qs from 'qs'; import Map from 'es6-map'; import XHR from './fetch-xhr'; export function ApiError(error) { this.name = 'ApiError'; this.code = error.code; this.error = error.error; this.error_description = error.error_description; } export default class APIHandler { constructor(options) { this.url = options.api_url; this.cache = new Map(); this.isPaused = false; this.stack = []; this.cacheExpires = 1000; this.requests = new Map(); } pause() { log('api:pause', this.stack.length); this.isPaused = true; } resume() { log('api:resume', this.stack.length); _.each(this.stack, callback => { callback(); }); this.stack = []; this.isPaused = false; } pushRequest(callback) { log('api:push', this.stack.length); if (this.isPaused) { this.stack.push(callback); } else { callback(); } } getCache(key) { let item = this.cache.get(key); if (item === undefined) { return undefined; } if (timestamp() > item.expires) { //console.log('cache timeout'); this.cache.delete(key); return undefined; } //console.log('cache hits:', key); return item.data; } setCache(key, data, options) { // console.log('setting cache:', key); if (typeof options === 'undefined') { options = {}; } else if (typeof options === 'number') { options = { expires: options }; } options = _.defaults(options, { expires: this.cacheExpires }); this.cache.set(key, { data: data, expires: timestamp() + this.cacheExpires }); } buildFileData(field, file) { let data = new FormData(); if (_.isArray(file)) { _.each(file, f => { data.append(field, f); }); } else { data.append(field, file); } return data; } buildFormData(field, value) { let form = new FormData(); if (_.isObject(field)) { _.each(field, (value, key) => { form.append(key, value); }); return form; } else { return this.buildFormData({[field]: value}); } } // API request // @param <url> the request url // @param <options> fetch options or HTTP method // @param <data> optional // 1. when using post/put/delete, as post data, could be javascript // object(would be converted to JSON) or FormData. // 2. when using get, as query string parameters. request(url, options, data) { let self = this; if (_.isString(options)) { if (!_.contains(['get', 'post', 'put', 'delete'], options)) { throw new Error('unsupported HTTP method: ' + options); } options = { method: options }; } options = _.defaults(options, { cache: true, }); let params = _.extend({ headers: { 'Accept': 'application/json', }, credentials: 'include' }, _.omit(options, 'cache')); params.withCredentials = true; if (options.method == 'get') { if (_.isObject(data) && !_.isEmpty(data)) { url += '?' + qs.stringify(data); } if (options.cache) { let cached = this.getCache(url); if (typeof cached !== 'undefined') { return Promise.resolve(_.clone(cached)); } } if (this.requests.has(url)) { //console.log('find existing request') return this.requests.get(url); } } let _fetch = fetch; // console.log(params); if (_.contains(['post','put','delete'], options.method) && data) { if (data instanceof FormData) { params.body = data; _fetch = XHR.fetch.bind(XHR); } else { params.headers['Content-Type'] = 'application/json'; params.body = JSON.stringify(data); } } // compose full URL: http://127.0.0.1:3000/api/route/path let fullUrl = this.url + 'api' + url; // let fullUrl = this.url + url; let promise = new Promise((resolve, reject) => { function makeRequest() { let res = undefined; // let token = self.oauth.token();; function refreshAndTryLater() { log('api:info', 'token expired, refresh it and try later...'); self.pause(); self.pushRequest(() => { log('api:info', 'token refreshed, request again!'); makeRequest(); }); } let timer = timestamp(); _fetch(fullUrl, params) .then(response => { res = response; return res.json(); }) .then(json => { self.requests.delete(url); let timeUsed = timestamp() - timer; let time = `[${timeUsed} ms]`; log('api.req', options.method.toUpperCase(), url, res.status, time); if (res.status >= 400) { let err = new ApiError(json); throw err; } if (options.method == 'get') { self.setCache(url, json); } resolve(json); }) .catch(e => { console.error(e); reject(e); }); } makeRequest(); }); if (options.method == 'get') { this.requests.set(url, promise); } return promise; } get(url, data) { return this.request(url, 'get', data); } post(url, data) { return this.request(url, 'post', data); } put(url, data) { return this.request(url, 'put', data); } delete(url, data) { return this.request(url, 'delete', data); } } <file_sep>/src/router/index.js import Vue from 'vue' import Router from 'vue-router' import Oa from '@/components/oa/routers/Oa' import Account from './account/account' Vue.use(Router) export default new Router({ linkActiveClass:'active', mode: 'history', routes: [ { path: '/', component: Oa }, Account ] }) <file_sep>/src/config.js export default { api_url: 'http://api.oa.hxq.local/', client_url: 'http://www.oa.hxq.local/', }; <file_sep>/src/lib/utils.js import _ from 'lodash'; import moment from 'moment'; export function timestamp(t) { if (t) { return +new Date(t); } else { return +new Date(); } } export function log(type, ...messages) { let t = moment(); let time = t.format('HH:mm:ss.SSS'); if (_.isUndefined(type)) { type = 'common'; } let logger; if (/err/.test(type)) { logger = 'error'; } else if (/info/.test(type)) { logger = 'info'; } else { logger = 'log'; } let params = [ '%c[' + time + '] %c' + type + '%c', 'color: blue', 'color: #999', 'color: #000', ]; if (process.env.NODE_ENV != 'production') { console[logger].apply(console, params.concat(messages)); } } log.error = (message) => { log('error', message); }; log.info = (message) => { log('info', message); }; log.log = (message) => { log('log', message); }; /** * Filter Array * * @param list array * @param filter keyword * @param filter_key array_keyword_name * * */ export function filterList(list, filter, filter_key) { return _.filter(list, item => { if (!filter) { return true; } for (let key in item) { if (filter_key.indexOf(key) >= 0){ let value = item[key]; if (typeof value === 'string') { if (value.indexOf(filter) >= 0) { return true; } } }; } return false; }); } <file_sep>/src/store/login/actions.js const mutations = { //分发状态 } const actions = { //异步操作 // loginRemote({ dispatch }, data) { // return API.post('/account/login', data); // } } export { mutations, actions } <file_sep>/src/main.js // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import createHistory from 'history/createBrowserHistory' import config from './config' import APIHandler from './lib/api' import store from './store' import Vuerify from 'vuerify' import iView from 'iview' import 'iview/dist/styles/iview.css' import './less/account.less' import './less/iview.less' Vue.use(iView) Vue.use(Vuerify) global.browserHistory = createHistory() global.API = new APIHandler(config) /* eslint-disable no-new */ new Vue({ el: '#app', router, store, template: '<App/>', components: { App }, }) <file_sep>/src/store/login/getters.js import { mutations, actions } from './actions' const state = { access_token: 0, } const getters = { access_token: state => state.access_token, } const login = { state, mutations, actions, getters } export default login <file_sep>/src/lib/i18n.js import _ from 'lodash'; const dict = { 'name': '姓名', }; let i18n = {}; i18n.translate = text => { if (_.has(dict, text)) { return dict[text]; } else { return text; } }; export const __ = i18n.translate; <file_sep>/README.md #安装 npm install
89c38a9601ee84c06a528af471a486283e9f6e8f
[ "JavaScript", "Markdown" ]
9
JavaScript
h-modest/vue-oa
7cc3de7c12ae102cd5625a5ed9e3d7fd0475965d
f2300d4aabab7400c27e8290bbcad4b64220cf01
refs/heads/master
<repo_name>spkaluzny/nyt_mini_crossword<file_sep>/analysis/nyt_mini_crossword.Rmd --- title: "New York Time Mini Crossword" author: "<NAME>" date: "`r format(Sys.time(), '%d %B, %Y')`" output: html_document: keep_md: yes theme: cerulean --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ## The Puzzle Everyday the New York Times puts out a mini crossword. A group of us have been recording our time to complete the puzzle everytime we complete a puzzle. Along with the date and time we also record the time of day that we did the puzzle. This is an analysis of that puzzle data. We look at puzzle completion time across the various players, across day of the week (are the puzzles harder later in the week?) and time of day. This is also an example data analysis done with R in a reproducible manner. As an example document for learning about R, all of the R code is shown. ## Setup We explicitly install the required R packages from CRAN if they are not already available. ```{r load_packages} if(!requireNamespace("dplyr", quietly=TRUE)) { install.packages("dplyr") } if(!requireNamespace("tidyr", quietly=TRUE)) { install.packages("tidyr") } if(!requireNamespace("ggplot2", quietly=TRUE)) { install.packages("ggplot2") } if(!requireNamespace("lubridate", quietly=TRUE)) { install.packages("lubridate") } if(!requireNamespace("hms", quietly=TRUE)) { install.packages("hms") } if(!requireNamespace("here", quietly=TRUE)) { install.packages("here") } if(!requireNamespace("assertr", quietly=TRUE)) { install.packages("assertr") } library("assertr", quietly = TRUE, warn.conflicts = FALSE) library("tidyr", quietly = TRUE, warn.conflicts = FALSE) library("dplyr", quietly = TRUE, warn.conflicts = FALSE) library("ggplot2", quietly = TRUE, warn.conflicts = FALSE) ``` ## The Data The `here` package allows us to find files (in this case the raw data file) anywhere within the project tree. ```{r read_data} d <- read.csv(here::here("data", "nyt.csv"), stringsAsFactors=FALSE) ``` The `Date` and `TimeOfDay` are combined and converted to a `POSIX` variable `DateTime`. The `WeekDay` is then computed from `DateTime`. The puzzle time (`Time`) was recorded as minutes:seconds, we convert that to a numeric `Seconds` variable. ```{r date_time} d$Date <- as.Date(d$Date) d$DateTime <- as.POSIXct(with(d, paste(Date, ifelse(is.na(TimeOfDay), "00:00", TimeOfDay)))) d$WeekDay <- lubridate::wday(d$DateTime) d$TimeOfDayOrig <- d$TimeOfDay d$TimeOfDay <- hms::parse_hm(d$TimeOfDay) d$Seconds <- with(d, as.numeric(lubridate::seconds(lubridate::ms(Time)))) ``` Compute the time interval, in days, between puzzle playing by `Player`. ```{r waiting_time} d <- d %>% group_by(Player) %>% arrange(Date) %>% mutate(WaitingTime = as.numeric(Date - lag(Date), units="days")) %>% ungroup() ``` ### Data Quality Check New data is regularly added to the CSV data file. In this section we do a quality check on the data to make sure no data entry errors have occurred. First, set some values that are expected in the data: ```{r data_verification_0} # Current list of players: players <- c("SPK", "JAK", "JIK", "BBK", "SKK", "AKK", "MBH") # Earliest date: first_date <- as.Date("2017-09-25") # Upper bound on time (10 minutes = 600 seconds): time_bound <- 700 ``` Check that Player is one of 5 possible values: ```{r data_verification_1} d %>% assert(in_set(players), Player, success_fun=success_logical, error_fun=error_logical) ``` There should be no missing values in the data: ```{r data_verification_2} d %>% assert(not_na, DateTime, WeekDay, Seconds) %>% success_logical() ``` Only one observation per player per date: ```{r data_verification_3} d %>% group_by(Date) %>% count(Player) %>% verify(n == 1) %>% success_logical() ``` Check for proper time values: ```{r data_verification_4} d %>% assertr::verify(Seconds > 0 & Seconds < time_bound, success_fun=success_logical, error_fun=error_logical) ``` Check range of dates ```{r data_verification_5} first_date <- as.Date("2017-09-25") today <- Sys.Date() d %>% assertr::verify(Date >= first_date & Date <= today, success_fun=success_logical, error_fun=error_logical) ``` ## Summary Statistics Current data set has `r nrow(d)` observations. ```{r summary} d %>% group_by(Player) %>% summarise(Mean = mean(Seconds), Median = median(Seconds), Min = min(Seconds), Max = max(Seconds), N=n()) %>% arrange(Median) ``` ## Subset the Data Subset the data by only working with observations from `SPK`, `JAK` and `JIK`. Other players do not have enough observations to analyze. ```{r subset} d <- d %>% filter(Player %in% c("SPK", "JAK", "JIK")) ``` Now have `r nrow(d)` observations. ## Plots An Initial plot of the data. ```{r plot01} d %>% ggplot(aes(x=WeekDay, y=Seconds)) + geom_jitter(position = position_jitter(width=.3)) + ggtitle("Time vs Day of the Week") ``` Same plot with player identified. ```{r plot02} d %>% ggplot(aes(x=WeekDay, y=Seconds, color=Player)) + geom_jitter(position = position_jitter(width=.3)) + ggtitle("Time vs Day of the Week") ``` The distribution of the times, summarised in a boxplot: ```{r plot03, echo=FALSE} d %>% ggplot(aes(x=WeekDay, y=Seconds, group=WeekDay)) + geom_boxplot() + ggtitle("Time vs Day of the Week") ``` ## Days Between Puzzles ```{r plot04} d %>% ggplot(aes(x=Date, y=WaitingTime, color=Player)) + geom_point() ``` ```{r plot05} d %>% ggplot(aes(x=Date, y=WaitingTime)) + geom_point() + facet_grid(Player ~ ., scales="free") ``` ## Player vs Player The function `spkjak` returns "SPKJAK" if a date contains an entry for both "SPK" and "JAK". It could also contain an entry for "JIK". The `d2` object selects the observations with "SPKJAK" set and then only keeps those where `Player` is "SPK" or "JAK". ```{r spread01} # spkjak ----- spkjak <- function(x) { m <- match(c("SPK","JAK"), x, nomatch=-1) if(all(m > 0)) { "SPKJAK" } else { NA } } d2 <- group_by(d, Date) %>% mutate(SPKJAK = spkjak(Player)) %>% ungroup() %>% filter(SPKJAK == "SPKJAK", Player %in% c("SPK", "JAK")) ``` ```{r spk_and_jak} d2 %>% filter(Player %in% c("SPK", "JAK")) %>% ggplot(aes(x=Date, y=Seconds, color=Player)) + geom_point() ``` ```{r spread02, eval=FALSE} d3 <- d2 %>% select(Date, Player, Seconds) %>% group_by(Date) %>% spread(key=Player, value=Seconds) %>% ungroup() ``` ## Appendix Knowing the versions of R and the packages used in an analysis is an important part of reproducibility. The `sessionInfo` function will show this. ```{r session_info} sessionInfo() ``` <file_sep>/README.md # Analysis of times for the New York Times Mini Crossword. A number of people are doing the New York Times Mini Crossword. Everytime they do the puzzle they text me their time and the time of day that they did the puzzle. I have been recording these observations in this repository along with code to analyze the results. Questions: - do the puzzles get harder through the week? - do individuals do better on the puzzle at particular times of the day? - how do we compare in puzzle times amongst the players? <file_sep>/analysis/nyt_mini_crossword.md --- title: "New York Time Mini Crossword" author: "<NAME>" date: "15 February, 2022" output: html_document: keep_md: yes theme: cerulean --- ## The Puzzle Everyday the New York Times puts out a mini crossword. A group of us have been recording our time to complete the puzzle everytime we complete a puzzle. Along with the date and time we also record the time of day that we did the puzzle. This is an analysis of that puzzle data. We look at puzzle completion time across the various players, across day of the week (are the puzzles harder later in the week?) and time of day. This is also an example data analysis done with R in a reproducible manner. As an example document for learning about R, all of the R code is shown. ## Setup We explicitly install the required R packages from CRAN if they are not already available. ```r if(!requireNamespace("dplyr", quietly=TRUE)) { install.packages("dplyr") } if(!requireNamespace("tidyr", quietly=TRUE)) { install.packages("tidyr") } if(!requireNamespace("ggplot2", quietly=TRUE)) { install.packages("ggplot2") } if(!requireNamespace("lubridate", quietly=TRUE)) { install.packages("lubridate") } if(!requireNamespace("hms", quietly=TRUE)) { install.packages("hms") } if(!requireNamespace("here", quietly=TRUE)) { install.packages("here") } if(!requireNamespace("assertr", quietly=TRUE)) { install.packages("assertr") } library("assertr", quietly = TRUE, warn.conflicts = FALSE) library("tidyr", quietly = TRUE, warn.conflicts = FALSE) library("dplyr", quietly = TRUE, warn.conflicts = FALSE) library("ggplot2", quietly = TRUE, warn.conflicts = FALSE) ``` ## The Data The `here` package allows us to find files (in this case the raw data file) anywhere within the project tree. ```r d <- read.csv(here::here("data", "nyt.csv"), stringsAsFactors=FALSE) ``` The `Date` and `TimeOfDay` are combined and converted to a `POSIX` variable `DateTime`. The `WeekDay` is then computed from `DateTime`. The puzzle time (`Time`) was recorded as minutes:seconds, we convert that to a numeric `Seconds` variable. ```r d$Date <- as.Date(d$Date) d$DateTime <- as.POSIXct(with(d, paste(Date, ifelse(is.na(TimeOfDay), "00:00", TimeOfDay)))) d$WeekDay <- lubridate::wday(d$DateTime) d$TimeOfDayOrig <- d$TimeOfDay d$TimeOfDay <- hms::parse_hm(d$TimeOfDay) d$Seconds <- with(d, as.numeric(lubridate::seconds(lubridate::ms(Time)))) ``` ``` ## Warning in .parse_hms(..., order = "MS", quiet = quiet): Some strings failed to ## parse, or all strings are NAs ``` Compute the time interval, in days, between puzzle playing by `Player`. ```r d <- d %>% group_by(Player) %>% arrange(Date) %>% mutate(WaitingTime = as.numeric(Date - lag(Date), units="days")) %>% ungroup() ``` ### Data Quality Check New data is regularly added to the CSV data file. In this section we do a quality check on the data to make sure no data entry errors have occurred. First, set some values that are expected in the data: ```r # Current list of players: players <- c("SPK", "JAK", "JIK", "BBK", "SKK", "AKK", "MBH") # Earliest date: first_date <- as.Date("2017-09-25") # Upper bound on time (10 minutes = 600 seconds): time_bound <- 700 ``` Check that Player is one of 5 possible values: ```r d %>% assert(in_set(players), Player, success_fun=success_logical, error_fun=error_logical) ``` ``` ## [1] TRUE ``` There should be no missing values in the data: ```r d %>% assert(not_na, DateTime, WeekDay, Seconds) %>% success_logical() ``` ``` ## [1] TRUE ``` Only one observation per player per date: ```r d %>% group_by(Date) %>% count(Player) %>% verify(n == 1) %>% success_logical() ``` ``` ## [1] TRUE ``` Check for proper time values: ```r d %>% assertr::verify(Seconds > 0 & Seconds < time_bound, success_fun=success_logical, error_fun=error_logical) ``` ``` ## [1] FALSE ``` Check range of dates ```r first_date <- as.Date("2017-09-25") today <- Sys.Date() d %>% assertr::verify(Date >= first_date & Date <= today, success_fun=success_logical, error_fun=error_logical) ``` ``` ## [1] FALSE ``` ## Summary Statistics Current data set has 1431 observations. ```r d %>% group_by(Player) %>% summarise(Mean = mean(Seconds), Median = median(Seconds), Min = min(Seconds), Max = max(Seconds), N=n()) %>% arrange(Median) ``` ``` ## # A tibble: 7 × 6 ## Player Mean Median Min Max N ## <chr> <dbl> <dbl> <dbl> <dbl> <int> ## 1 SKK 60.1 45 21 146 7 ## 2 AKK 55 55 55 55 1 ## 3 SPK 101. 83 18 455 542 ## 4 JAK 108. 87 27 818 509 ## 5 BBK 114. 102 42 350 73 ## 6 MBH 378. 362 140 770 13 ## 7 JIK NA NA NA NA 286 ``` ## Subset the Data Subset the data by only working with observations from `SPK`, `JAK` and `JIK`. Other players do not have enough observations to analyze. ```r d <- d %>% filter(Player %in% c("SPK", "JAK", "JIK")) ``` Now have 1337 observations. ## Plots An Initial plot of the data. ```r d %>% ggplot(aes(x=WeekDay, y=Seconds)) + geom_jitter(position = position_jitter(width=.3)) + ggtitle("Time vs Day of the Week") ``` ``` ## Warning: Removed 1 rows containing missing values (geom_point). ``` ![](nyt_mini_crossword_files/figure-html/plot01-1.png)<!-- --> Same plot with player identified. ```r d %>% ggplot(aes(x=WeekDay, y=Seconds, color=Player)) + geom_jitter(position = position_jitter(width=.3)) + ggtitle("Time vs Day of the Week") ``` ``` ## Warning: Removed 1 rows containing missing values (geom_point). ``` ![](nyt_mini_crossword_files/figure-html/plot02-1.png)<!-- --> The distribution of the times, summarised in a boxplot: ``` ## Warning: Removed 1 rows containing non-finite values (stat_boxplot). ``` ![](nyt_mini_crossword_files/figure-html/plot03-1.png)<!-- --> ## Days Between Puzzles ```r d %>% ggplot(aes(x=Date, y=WaitingTime, color=Player)) + geom_point() ``` ``` ## Warning: Removed 3 rows containing missing values (geom_point). ``` ![](nyt_mini_crossword_files/figure-html/plot04-1.png)<!-- --> ```r d %>% ggplot(aes(x=Date, y=WaitingTime)) + geom_point() + facet_grid(Player ~ ., scales="free") ``` ``` ## Warning: Removed 3 rows containing missing values (geom_point). ``` ![](nyt_mini_crossword_files/figure-html/plot05-1.png)<!-- --> ## Player vs Player The function `spkjak` returns "SPKJAK" if a date contains an entry for both "SPK" and "JAK". It could also contain an entry for "JIK". The `d2` object selects the observations with "SPKJAK" set and then only keeps those where `Player` is "SPK" or "JAK". ```r # spkjak ----- spkjak <- function(x) { m <- match(c("SPK","JAK"), x, nomatch=-1) if(all(m > 0)) { "SPKJAK" } else { NA } } d2 <- group_by(d, Date) %>% mutate(SPKJAK = spkjak(Player)) %>% ungroup() %>% filter(SPKJAK == "SPKJAK", Player %in% c("SPK", "JAK")) ``` ```r d2 %>% filter(Player %in% c("SPK", "JAK")) %>% ggplot(aes(x=Date, y=Seconds, color=Player)) + geom_point() ``` ![](nyt_mini_crossword_files/figure-html/spk_and_jak-1.png)<!-- --> ```r d3 <- d2 %>% select(Date, Player, Seconds) %>% group_by(Date) %>% spread(key=Player, value=Seconds) %>% ungroup() ``` ## Appendix Knowing the versions of R and the packages used in an analysis is an important part of reproducibility. The `sessionInfo` function will show this. ```r sessionInfo() ``` ``` ## R version 4.1.2 (2021-11-01) ## Platform: x86_64-pc-linux-gnu (64-bit) ## Running under: Ubuntu 20.04.3 LTS ## ## Matrix products: default ## BLAS: /home/R/R-4.1.2/lib/R/lib/libRblas.so ## LAPACK: /home/R/R-4.1.2/lib/R/lib/libRlapack.so ## ## locale: ## [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C ## [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 ## [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8 ## [7] LC_PAPER=en_US.UTF-8 LC_NAME=C ## [9] LC_ADDRESS=C LC_TELEPHONE=C ## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C ## ## attached base packages: ## [1] stats graphics grDevices utils datasets methods base ## ## other attached packages: ## [1] ggplot2_3.3.5 dplyr_1.0.8 tidyr_1.2.0 assertr_2.8 ## ## loaded via a namespace (and not attached): ## [1] highr_0.9 pillar_1.7.0 bslib_0.3.1 compiler_4.1.2 ## [5] jquerylib_0.1.4 tools_4.1.2 digest_0.6.29 lubridate_1.8.0 ## [9] jsonlite_1.7.3 evaluate_0.14 lifecycle_1.0.1 tibble_3.1.6 ## [13] gtable_0.3.0 pkgconfig_2.0.3 rlang_1.0.1 cli_3.2.0 ## [17] DBI_1.1.2 yaml_2.2.2 xfun_0.29 fastmap_1.1.0 ## [21] withr_2.4.3 stringr_1.4.0 knitr_1.37 hms_1.1.1 ## [25] generics_0.1.2 vctrs_0.3.8 sass_0.4.0 rprojroot_2.0.2 ## [29] grid_4.1.2 tidyselect_1.1.1 here_1.0.1 glue_1.6.1 ## [33] R6_2.5.1 fansi_1.0.2 rmarkdown_2.11 farver_2.1.0 ## [37] purrr_0.3.4 magrittr_2.0.2 scales_1.1.1 ellipsis_0.3.2 ## [41] htmltools_0.5.2 assertthat_0.2.1 colorspace_2.0-2 labeling_0.4.2 ## [45] utf8_1.2.2 stringi_1.7.6 munsell_0.5.0 crayon_1.5.0 ``` <file_sep>/code/reorder_cols.R # Reorder columns in the CSV, putting Player first # 2019-03-06 d <- read.csv("nyt.csv", stringsAsFactors=FALSE) d <- d[, c("Player", "Date", "Time", "TimeOfDay")] write.table(d, "nyt.csv", sep=",", row.names=FALSE, quote=FALSE) <file_sep>/analysis/nyt_quality.Rmd --- title: "Quality Check - NYT Mini Crossword Data" author: "<NAME>" date: "`r format(Sys.time(), '%d %B, %Y')`" output: html_document: theme: cerulean --- ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` We explicitly install the required R packages from CRAN if they are not already available. ```{r load_packages} library("assertr", quietly = TRUE, warn.conflicts = FALSE) library("dplyr", quietly = TRUE, warn.conflicts = FALSE) ``` ## The Data The `here` package allows us to find files (in this case the raw data file) anywhere within the project tree. ```{r read_data} d <- read.csv(here::here("data", "nyt.csv"), stringsAsFactors=FALSE) ``` The `Date` and `TimeOfDay` are combined and converted to a `POSIX` variable `DateTime`. The `WeekDay` is then computed from `DateTime`. The puzzle time (`Time`) was recorded as minutes:seconds, we convert that to a numeric `Seconds` variable. ```{r date_time} d$Date <- as.Date(d$Date) d$DateTime <- as.POSIXct(with(d, paste(Date, ifelse(is.na(TimeOfDay), "00:00", TimeOfDay)))) d$WeekDay <- lubridate::wday(d$DateTime) d$TimeOfDayOrig <- d$TimeOfDay d$TimeOfDay <- hms::parse_hm(d$TimeOfDay) d$Seconds <- with(d, as.numeric(lubridate::seconds(lubridate::ms(Time)))) ``` ### Data Quality Check New data is regularly added to the CSV data file. In this section we do a quality check on the data to make sure no data entry errors have occurred. First, set some values that are expected in the data: ```{r data_verification_0} # Current list of players: players <- c("SPK", "JAK", "JIK", "BBK", "SKK", "AKK", "MBH") # Earliest date: first_date <- as.Date("2017-09-25") # Upper bound on time (10 minutes = 600 seconds): time_bound <- 820 ``` Check that Player is one of the `r length(players)` possible values: ```{r data_verification_1} d %>% assert(in_set(players), Player, success_fun=success_logical, error_fun=error_logical) ``` There should be no missing values in the data: ```{r data_verification_2} # d %>% assert(not_na, DateTime, WeekDay, Seconds) %>% success_logical() d %>% assert(not_na, DateTime, WeekDay, Seconds, success_fun= success_logical, error_fun=error_logical) ``` Only one observation per player per date: ```{r data_verification_3} # d %>% group_by(Date) %>% count(Player) %>% verify(n == 1) %>% success_logical() d %>% group_by(Date) %>% count(Player) %>% verify(n == 1, success_fun=success_logical, error_fun=error_logical) ``` Check for proper time values: ```{r data_verification_4} d %>% assertr::verify(Seconds > 0 & Seconds < time_bound, success_fun=success_logical, error_fun=error_logical) ``` Check range of dates ```{r data_verification_5} first_date <- as.Date("2017-09-25") today <- Sys.Date() range(d$Date) d %>% assertr::verify(Date >= first_date & Date <= today, success_fun=success_logical, error_fun=error_logical) ``` <file_sep>/code/adjust_timeofday.R # Adjust TimeOfDay for JAK and JIK to their timezone time of day # 2019-03-06 d <- read.csv("nyt.csv", stringsAsFactors=FALSE) todAdj <- ifelse(d[["Player"]] %in% c("JAK", "JIK"), 2, 0) HM <- stringr::str_split_fixed(d[["TimeOfDay"]], ":", 2) HOUR <- as.numeric(HM[,1]) + todAdj MIN <- HM[,2] d[["TimeOfDay"]] <- ifelse(is.na(HOUR), NA, paste(HOUR, MIN, sep=":")) write.table(d, "nyt.csv", sep=",", row.names=FALSE, quote=FALSE) <file_sep>/code/nyttime.R library("lubridate") library("dplyr") library("ggplot2") d <- read.csv("nyt.csv", stringsAsFactors=FALSE) d <- d %>% filter(Player %in% c("SPK", "JAK", "JIK")) d$Date <- as.Date(d$Date) d$WeekDay <- lubridate::wday(d$Date) d$Seconds <- with(d, seconds(ms(Time))) d %>% ggplot(aes(x=WeekDay, y=Seconds)) + geom_point() + facet_grid(Player ~ .) <file_sep>/code/read_data.R d <- read.csv(here::here("data/nyt.csv")) d$Date <- as.Date(d$Date) d$WeekDay <- lubridate::wday(d$Date) d$Seconds <- with(d, lubridate::seconds(lubridate::ms(Time)))
cb2f257fbda23cf6f4d6bede109dc959549452a1
[ "Markdown", "R", "RMarkdown" ]
8
RMarkdown
spkaluzny/nyt_mini_crossword
612ad41017a27e1ebd538dd1946844c88c0b664f
15d96c1536bd02bcc58854ea6a1322b9f689f7ea
refs/heads/master
<file_sep>'use strict'; var util = require('util'), Base = require('./base'), errors = require('../Errors'); var Delete = function(args) { Delete.super_.call(this, args); }; util.inherits(Delete, Base); Delete.prototype.action = 'delete'; Delete.prototype.method = 'delete'; Delete.prototype.plurality = 'singular'; Delete.prototype.fetch = function(req, res, context) { var model = this.model, endpoint = this.endpoint, criteria = context.criteria || {}; endpoint.attributes.forEach(function(attribute) { criteria[attribute] = req.params[attribute]; }); return model .find({ where: criteria }) .then(function(instance) { if (!instance) { throw new errors.NotFoundError(); } context.instance = instance; return context.continue; }); }; Delete.prototype.write = function(req, res, context) { return context.instance .destroy() .then(function() { context.instance = {}; return context.continue; }); }; module.exports = Delete; <file_sep>'use strict'; var epilogue = require('../lib'), expect = require('chai').expect; describe('Epilogue', function() { it('should throw an exception when initialized without arguments', function(done) { expect(epilogue.initialize).to.throw('please specify an app'); done(); }); it('should throw an exception when initialized without a sequelize instance', function(done) { expect(epilogue.initialize.bind(epilogue, { app: {} })).to.throw('please specify a sequelize instance'); done(); }); it('should throw an exception with an invalid updateMethod', function(done) { expect(epilogue.initialize.bind(epilogue, { app: {}, sequelize: {}, updateMethod: 'dogs' })).to.throw('updateMethod must be one of PUT, POST, or PATCH'); done(); }); }); <file_sep>'use strict'; var Sequelize = require('sequelize'), http = require('http'), express = require('express'), bodyParser = require('body-parser'), restify = require('restify'), chai = require('chai'); var TestFixture = { models: {}, Sequelize: Sequelize, initializeDatabase: function(callback) { TestFixture.db .sync({ force: true }) .then(function() { callback(); }); }, initializeServer: function(callback) { if (process.env.USE_RESTIFY) { TestFixture.server = TestFixture.app = restify.createServer(); TestFixture.server.use(restify.queryParser()); TestFixture.server.use(restify.bodyParser()); } else { TestFixture.app = express(); TestFixture.app.use(bodyParser.json()); TestFixture.app.use(bodyParser.urlencoded({ extended: false })); TestFixture.server = http.createServer(TestFixture.app); } TestFixture.server.listen(0, '127.0.0.1', function() { TestFixture.baseUrl = 'http://' + TestFixture.server.address().address + ':' + TestFixture.server.address().port; callback(); }); }, clearDatabase: function(callback) { TestFixture.db .getQueryInterface() .dropAllTables() .then(function() { callback(); }); } }; before(function() { TestFixture.db = new Sequelize('main', null, null, { dialect: 'sqlite', storage: ':memory:', logging: (process.env.SEQ_LOG ? console.log : false) }); }); // always print stack traces when an error occurs chai.config.includeStack = true; module.exports = TestFixture;
fa8dea36ae6adabb8571d0fd7e22c652444da5cc
[ "JavaScript" ]
3
JavaScript
Eluinhost/epilogue
da58c8b7ec1f4243e3bda02489c71d23a926b265
80ce1746d513291879357a0085e843e2e2004468
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dominio_LibCalc { public abstract class Operacion { public double Ope2 { get; set; } public double Ope1 { get; set; } public Operacion(double op1, double op2) { this.Ope1 = op1; this.Ope2 = op2; } public abstract double ejecutar(); } } <file_sep>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; using Dominio_LibCalc; namespace WinFormCalculadora { public partial class FrmCalculadora : Form { Operacion oper = null; string operador = ""; private double _op1 = 0; private double _op2 = 0; private String[] Memory = new String[10]; private int cont = 0; private int txtSize= 14; public static Color colorFondo = Color.LightGray; public FrmCalculadora() { InitializeComponent(); } public void UpdateFrm() { this.BackColor = FrmCalculadora.colorFondo; this.Font = (new Font("Arial", txtSize)); } private void FrmCalculadora_Load(object sender, EventArgs e) { UpdateFrm(); } private void fondoToolStripMenuItem_Click(object sender, EventArgs e) { FrmColores ClrFondo = new FrmColores(); ClrFondo.SetValues(this.BackColor); ClrFondo.ShowDialog(); this.BackColor = FrmCalculadora.colorFondo; } private void ValidInput(String input) { if (LbMemory.Text != "") { LbMemory.Text = ""; txtDisplay.Text = "0"; } if (txtDisplay.Text == "0") { txtDisplay.Text = input; } else if (input == "." && txtDisplay.Text.Contains(".")) { } else { txtDisplay.Text += input; } } //botones numeros private void Btn1_Click(object sender, EventArgs e) { ValidInput("1"); } private void Btn2_Click(object sender, EventArgs e) { ValidInput("2"); } private void Btn3_Click(object sender, EventArgs e) { ValidInput("3"); } private void Btn4_Click(object sender, EventArgs e) { ValidInput("4"); } private void Btn5_Click(object sender, EventArgs e) { ValidInput("5"); } private void Btn6_Click(object sender, EventArgs e) { ValidInput("6"); } private void Btn7_Click(object sender, EventArgs e) { ValidInput("7"); } private void Btn8_Click(object sender, EventArgs e) { ValidInput("8"); } private void Btn9_Click(object sender, EventArgs e) { ValidInput("9"); } private void Btn0_Click(object sender, EventArgs e) { ValidInput("0"); } private void BtnPunto_Click(object sender, EventArgs e) { ValidInput("."); } // Operaciones igual, suma, resta, multiplicacion, division private void BtnIgual_Click(object sender, EventArgs e) { //capturamos op2 this._op2 = double.Parse(txtDisplay.Text); //instanciamos la clase de la operacion seleccionada switch (this.operador) { case "+": oper = new Suma(this._op1, this._op2); break; case "-": oper = new Resta(this._op1, this._op2); break; case "*": oper = new Multiplicacion(this._op1, this._op2); break; case "/": oper = new Division(this._op1, this._op2); break; default: operador = ""; break; } //se guarda en memoria LbMemory.Text = _op1 + " " + operador + " " + _op2 + " ="; //ejecutamos la operacion txtDisplay.Text = oper.ejecutar().ToString(); this.operador = ""; cont++; } private void BtnSuma_Click(object sender, EventArgs e) { operador = "+"; this._op1 = double.Parse(txtDisplay.Text); //limpiar display txtDisplay.Clear(); } private void BtnResta_Click(object sender, EventArgs e) { operador = "-"; this._op1 = double.Parse(txtDisplay.Text); //limpiar display txtDisplay.Clear(); } private void BtnMulti_Click(object sender, EventArgs e) { operador = "*"; this._op1 = double.Parse(txtDisplay.Text); //limpiar display txtDisplay.Clear(); } private void BtnDivision_Click(object sender, EventArgs e) { operador = "/"; this._op1 = double.Parse(txtDisplay.Text); //limpiar display txtDisplay.Clear(); } // Reset private void restartToolStripMenuItem_Click(object sender, EventArgs e) { oper = null; operador = ""; _op1 = 0; _op2 = 0; txtDisplay.Text = "0"; LbMemory.Text = ""; cont = 0; } private void btSimbolo_Click(object sender, EventArgs e) { if (!(txtDisplay.Text[0] == '-')) { txtDisplay.Text = "-" + txtDisplay.Text; } else { txtDisplay.Text = txtDisplay.Text.Remove(1, 1); } } private void btClear_Click(object sender, EventArgs e) { oper = null; operador = ""; _op1 = 0; _op2 = 0; txtDisplay.Text = "0"; LbMemory.Text = ""; cont = 0; UpdateFrm(); } } } <file_sep>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 WinFormCalculadora { public partial class FrmColores : Form { private int RedValue = 0; private int GreenValue = 0; private int BlueValue = 0; FrmCalculadora obj = new FrmCalculadora(); public FrmColores() { InitializeComponent(); } public void SetValues(Color col) { this.RedValue = col.R; this.GreenValue = col.G; this.BlueValue = col.B; } private void FrmColores_Load(object sender, EventArgs e) { this.BackColor=FrmCalculadora.DefaultBackColor; this.TBrRed.Value = this.RedValue; this.TBrGreen.Value = this.GreenValue; this.TBrBlue.Value = this.BlueValue; this.TbRed.Text = this.RedValue.ToString(); this.TbGreen.Text = this.GreenValue.ToString(); this.TbBlue.Text = this.BlueValue.ToString(); } private void BtAceptar_Click(object sender, EventArgs e) { FrmCalculadora.colorFondo=Color.FromArgb(this.RedValue, this.GreenValue, this.BlueValue); } private void BtCancel_Click(object sender, EventArgs e) { } private void TBrRed_Scroll(object sender, EventArgs e) { this.RedValue = this.TBrRed.Value; this.TbRed.Text = this.RedValue.ToString(); } private void TBrGreen_Scroll(object sender, EventArgs e) { this.GreenValue = this.TBrGreen.Value; this.TbGreen.Text = this.GreenValue.ToString(); } private void TBrBlue_Scroll(object sender, EventArgs e) { this.BlueValue = this.TBrBlue.Value; this.TbBlue.Text = this.BlueValue.ToString(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Dominio_LibCalc { public class Division : Operacion { public Division(double op1, double op2) : base(op1, op2) { } public override double ejecutar() { return this.Ope1 / this.Ope2; } } }
ca2eba79cd3d3284d15568907dce2d0f7f846012
[ "C#" ]
4
C#
DavidGarciaTIDS/WinFormCalculadora
d9c3066f127ecb169e33695063d6559f16681bd3
3ae2b16a80357222abc8869fd8e0f7605cd335e6
refs/heads/master
<file_sep>With this project, my intention was to play around with the parameters and values within an url. It basically detects the parameters (until 2) present in the url, then replaces them with the scripts from a second argument -->You should call the script like: $ python3 reflector.py https://example.com/index.php?id=43&nf=true <path_to_payloads> <file_sep>import requests import sys from urllib3.exceptions import InsecureRequestWarning import re import argparse requests.urllib3.disable_warnings() #parser = argparse.ArgumentParser() #args = parser.add_argument('--h', help='reflectorv1.py example.com?id=1&jf=true <optional_script>') #args = parser.parse_args() #print(args) url = sys.argv[1] if not '"' in url: # put the input inside " url = '"' + url + '"' print("url type: ",type(url)) if ".txt" in url: #verify if it's a list or not in the url url = open(sys.argv[1], "r") # url = open(sys.argv[1],"r") print("analyzing ", url) scripts = "\"><script>alert(1)</>" try: #if it's a list, scripts will be loaded from list. if nothing is specified, scripts is already defined in this script if ".txt" in sys.argv[2]: scripts = open(sys.argv[2], "r") else: scripts = "\"><script>alert(1)</>" except: pass regex1 = '\=[*\w]*' # all values on url result1 = re.findall(regex1, url, re.DOTALL) print(result1) if len(result1) > 1: try: print("values found in the url..", result1[0][1:], result1[1][1:]) print("analyzing",result1[0][1:]) #print the first value present in the url firstone = url.replace(result1[0][1:], scripts) #replace the first value with the script given and adjust the url print(firstone) headers = {'User-agent': 'Mozilla//10.0', } r = requests.get(url=firstone, verify=False, headers=headers) #make the request to the url adjusted print(r.status_code, "==>", r.content) #print server response to the request and the content print("analyzing", result1[1][1:]) #print the second value present in the url secondone = url.replace(result1[1][1:], scripts) secondrequest = requests.get(url=secondone,verify=False, headers=headers) print(secondrequest.content) except: print("there was only 1 value..") else: #if only 1 value is present in the url print("analyzing", result1[0][1:]) if '\"' in url: url = url.replace('"', "") #take off the " inside the url if present if ".txt" in sys.argv[2]: #check if it's a list given as second argument, in this case the scripts scripts = open(sys.argv[2], "r") #open the list of payloads for payloads in scripts: first_ = url.replace(result1[0][1:], str(payloads)) #replace the value with each of the scripts given and iterate through them headers = {'User-agent': 'Mozilla//5.0', } requester = requests.get(url=first_, verify=False, headers=headers) if requester.status_code == 403: #if forbidden, only print the response and the payload that triggered the waf print("403", "==>", first_) else: print(requester.status_code, "==>", first_) #if it's not forbidden, print the payload tested #print(requester.status_code, "==>", requester.content, "tested with: ", payloads) else: scripts = "\"><script>alert(1)</>" # if it's not a list or a txt file is not given, test with the payload by default defined in this script firstone = url.replace(result1[0][1:], str(scripts)) headers = {'User-agent': 'Mozilla//5.0', } othercondition = requests.get(url=firstone, verify=False, headers=headers) print(othercondition.status_code, "==>", othercondition.content) sys.exit() #print(url.replace(result1[1][1:], scripts)) #print(url.replace(result1[0][1:], scripts)) #print(url.replace(result1[0][1:], scripts,result1[1][1:],scripts)) #until end of 1st parameter
53944addfb40ae0c86abbd9b0bb0aa47fa73035b
[ "Markdown", "Python" ]
2
Markdown
whitehat92/reflector
b68313568504e3e59dd70cac758a840ccd0a8ac2
afcab7cb811b5aeaf2d107f2c28aa3f4686a1d55
refs/heads/master
<repo_name>nicolasbatistoni/chequer-back<file_sep>/common/models/banco.js 'use strict'; module.exports = function(Banco) { };
89091a21b4ac49f7744dde575b67b41edf2156f1
[ "JavaScript" ]
1
JavaScript
nicolasbatistoni/chequer-back
589405f4499f0b90c487c29a75cb82ea05a01aff
c1e0d0e70388f8f65c9e19b610b06d6e298e9716
refs/heads/master
<repo_name>ginnie3112x/BuLi<file_sep>/BuLi/src/loeckmann/buli/Ergebnis.java package loeckmann.buli; public class Ergebnis { private int erg1; private int erg2; public Ergebnis(int erg1, int erg2) { super(); this.erg1 = erg1; this.erg2 = erg2; } public int getErg1() { return erg1; } public void setErg1(int erg1) { this.erg1 = erg1; } public int getErg2() { return erg2; } public void setErg2(int erg2) { this.erg2 = erg2; } } <file_sep>/BuLi/src/loeckmann/buli/Main.java package loeckmann.buli; import java.util.Iterator; import java.util.Map.Entry; public class Main { public static void main(String[] args) { Spieler spieler1 = new Spieler("Spieler1"); Spieler spieler2 = new Spieler("Spieler2"); Spieler spieler3 = new Spieler("Spieler3"); Spieler spieler4 = new Spieler("Spieler4"); Spieler spieler5 = new Spieler("Spieler5"); Spieler spieler6 = new Spieler("Spieler6"); Spieler spieler7 = new Spieler("Spieler7"); Spieler spieler8 = new Spieler("Spieler8"); Spieler spieler9 = new Spieler("Spieler9"); Spieler spieler10 = new Spieler("Spieler10"); Spieler spieler11 = new Spieler("Spieler11"); Spieler spieler12 = new Spieler("Spieler12"); Spieler spieler13 = new Spieler("Spieler13"); Spieler spieler14 = new Spieler("Spieler14"); Spieler spieler15 = new Spieler("Spieler15"); Spieler spieler16 = new Spieler("Spieler16"); Mannschaft man1 = new Mannschaft("Mannschaft1"); Mannschaft man2 = new Mannschaft("Mannschaft2"); Mannschaft man3 = new Mannschaft("Mannschaft3"); Mannschaft man4 = new Mannschaft("Mannschaft4"); Mannschaft man5 = new Mannschaft("Mannschaft5"); Tabelle.getMannschaftsliste().add(man1); Tabelle.getMannschaftsliste().add(man2); Tabelle.getMannschaftsliste().add(man3); Tabelle.getMannschaftsliste().add(man4); man1.addSpieler(spieler1); man1.addSpieler(spieler2); man2.addSpieler(spieler3); man2.addSpieler(spieler4); man3.addSpieler(spieler5); man3.addSpieler(spieler6); man4.addSpieler(spieler7); man4.addSpieler(spieler8); Spieltag spieltag = new Spieltag(1); Begegnung b1 = spieltag.newBegegnung(man1, man2); Begegnung b2 = spieltag.newBegegnung(man2, man1); Begegnung b4 = spieltag.newBegegnung(man3, man4); Spieltag spieltag2 = new Spieltag(2); Begegnung b3 = spieltag2.newBegegnung(man1, man4); spieltag.addBegegnungToResulttable(b1, 2, 5); spieltag.addBegegnungToResulttable(b2, 8, 5); spieltag.addBegegnungToResulttable(b4, 1, 1); // spieltag2.addBegegnungToResulttable(b3,1,1); // spieler2.torEingeben("52",b1); // spieler2.torEingeben("53"); // man1.torEingeben(spieler1, "33");//Problem einmalwert Tabelle.printGesamttabelle(); Tabelle.printTabelleBegegnungen(); for(Mannschaft m : Tabelle.getMannschaftsliste()) System.out.println(m.getName()); System.out.println("Größe der Mannschaftsliste " + Tabelle.getMannschaftsliste().size()); System.out.println("Größe der Tabellenliste " + Tabelle.getListe().size()); System.out.println("Größe der resultliste " + spieltag.getResult().size()); System.out.println("Größe der resultliste " + spieltag2.getResult().size()); // Problemstellung: obwohle Begegnung die die gleichen Hashwerte hat, nimmt die // TreeMap diese nicht als gleich wahr. man1,man2 - man2, man1 // System.out.println(b1.equals(b2)); // System.out.println(b1.toString()); // System.out.println(b2.toString()); // System.out.println(b1.equals(b4)); // System.out.println(b4.toString()); // System.out.println("Hash " + b1.hashCode()); // System.out.println("Hash " + b2.hashCode()); // System.out.println("Hash " + b4.hashCode()); // for (Iterator<Entry<Begegnung, Ergebnis>> iterator = spieltag.getResult().entrySet().iterator(); iterator.hasNext();) { // // Entry<Begegnung, Ergebnis> n = iterator.next(); // System.out.println("Hash "+n.hashCode()); // System.out.println("K,V,"+n.getKey()+" "+n.getValue()); // System.out.println("Spiel "+n.getKey().getSpiel()); // // // } } } <file_sep>/BuLi/src/loeckmann/buli/Spieler.java package loeckmann.buli; import java.util.HashMap; public class Spieler implements Comparable<Spieler> { private String name; private Mannschaft mannschaft; private HashMap<String, String> tor; private int anzahlTore; private String karte; public Spieler(String name) { super(); this.name = name; anzahlTore = 0; tor = new HashMap<>(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public Mannschaft getMannschaft() { return mannschaft; } public void setMannschaft(Mannschaft mannschaft) { this.mannschaft = mannschaft; } public HashMap<String, String> getTor() { return tor; } public void setTor(HashMap<String, String> tor) { this.tor = tor; } public String getKarte() { return karte; } public void setKarte(String karte) { this.karte = karte; } public int getAnzahlTore() { return anzahlTore; } public void setAnzahlTore(int anzahlTore) { this.anzahlTore = anzahlTore; } public void torEingeben(String min, Begegnung b) { tor.put(min, this.getName()); System.out.println(mannschaft.getAnzahlTore() + " " + this.getAnzahlTore()); anzahlTore = anzahlTore + 1; mannschaft.setAnzahlTore(mannschaft.getAnzahlTore() + 1); if (b.getSpiel().containsKey(mannschaft)) { if (mannschaft.getSpielerliste().contains(this)) { b.getErgebnis().setErg1(b.getErgebnis().getErg1() + 1); } } else if (b.getSpiel().containsValue(mannschaft)) { b.getErgebnis().setErg2(b.getErgebnis().getErg2() + 1); } System.out.println(mannschaft.getAnzahlTore() + " " + this.getAnzahlTore()); } @Override public int compareTo(Spieler o) { Spieler spieler = (Spieler) o; return this.getName().compareTo(spieler.getName()); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((mannschaft == null) ? 0 : mannschaft.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Spieler other = (Spieler) obj; if (mannschaft == null) { if (other.mannschaft != null) return false; } else if (!mannschaft.equals(other.mannschaft)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
4da983d5bb8f875be02a9c0d23271b91640753f7
[ "Java" ]
3
Java
ginnie3112x/BuLi
093913ee32e779b80061187dbc4b1d73d994bf76
1425d572d48af28142dbef765609b261ea87c250
refs/heads/master
<file_sep>package memento; import java.io.Serializable; import java.util.ArrayList; public class CareTaker implements Serializable { private static final long serialVersionUID = -314171089120047242L; protected ArrayList<Memento> mementosource_; protected ArrayList<String> listaction_; protected ArrayList<int[]> pixellist_; protected int currentmod = 0; public ArrayList<int[]> getPixellist_() { return pixellist_; } public void setPixellist_(ArrayList<int[]> pixellist_) { this.pixellist_ = pixellist_; } public CareTaker() { mementosource_ = new ArrayList<Memento>(); listaction_ = new ArrayList<String>(); pixellist_ = new ArrayList<int[]>(); } public void add(Memento m) { mementosource_.add(m); listaction_.add(m.getStateName_()); } public void add(int[] pix) { pixellist_.add(pix); } public Memento get(int index) { return mementosource_.get(index); } public void undo() { currentmod -= 1; } public void redo() { currentmod += 1; } public int getIndex() { return currentmod; } public ArrayList<String> getListaction() { return listaction_; } public ArrayList<int[]> getAllPixel() { return pixellist_; } public int maxEl() { return mementosource_.size(); } } <file_sep>package plugin.bonus; import java.awt.image.BufferedImage; import java.awt.image.BufferedImageOp; import java.awt.image.ConvolveOp; import java.awt.image.Kernel; import plugin.IPlugin; import java.awt.Color; public class Brightness implements IPlugin { @Override public BufferedImage perform(BufferedImage img) { BufferedImage res = new BufferedImage(img.getWidth(), img.getHeight(), img.getType()); float ninth = 1.0f / 7.0f; float[] blurKernel = { ninth, ninth, ninth, ninth, ninth, ninth, ninth, ninth, ninth }; BufferedImageOp blurOp = new ConvolveOp(new Kernel(3, 3, blurKernel)); res = blurOp.filter(img, null); return res; } @Override public String getName() { return "Brightness"; } } <file_sep>package IHM; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.KeyStroke; import plugin.IPlugin; import memento.CareTaker; import memento.Memento; import memento.Originator; public class MainWindow extends JFrame implements ActionListener { private HashMap<String, Object> plugindt_; private static final long serialVersionUID = -314171089120047242L; private JButton button1; private JButton button2; private JButton button3; private JButton button4; private JPanel mainPanel_; private JFileChooser filechooser; private ImagePanel currentfile; private ImagePanel currentimg_; private JScrollPane scroll; private ProjectUtil currentproject; private int currentmodindex_; private String givenName_; public MainWindow() { super(); mainPanel_ = new JPanel(new BorderLayout()); currentmodindex_ = 0; plugindt_ = new HashMap<String, Object>(); scroll = new JScrollPane(); scroll.getVerticalScrollBar().setUnitIncrement(3); scroll.getHorizontalScrollBar().setUnitIncrement(3); build(); createMenu(); this.setVisible(true); } private void build() { setTitle("MyPhotoshop"); // titre fenetre setSize(1280,760); // taille fenetre setLocationRelativeTo(null); //centrage fenetre setResizable(true); //redimensionnement de la fenêtre interdit setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //fermeture clic sur croix } public void createMenu() { JMenuBar menuBar = new JMenuBar(); JMenu menu1 = new JMenu("File"); JMenu menu2 = new JMenu("Edit"); JMenu menu3 = new JMenu("Filters"); JMenuItem menuItem1 = new JMenuItem("Open", KeyEvent.VK_0); menuItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_0, ActionEvent.CTRL_MASK)); menuItem1.addActionListener(this); menu1.add(menuItem1); JMenuItem openproject = new JMenuItem("Open Project",KeyEvent.VK_R); openproject.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.CTRL_MASK)); openproject.addActionListener(this); menu1.add(openproject); JMenuItem menuItem2 = new JMenuItem("Save", KeyEvent.VK_S); menuItem2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK)); menuItem2.addActionListener(this); // Ici sérialization automatique de l'objet courant menu1.add(menuItem2); JMenuItem menuItem3 = new JMenuItem("Save Project", KeyEvent.VK_A); menuItem3.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK)); menuItem3.addActionListener(this); // Prendre en gestion les différentes extensions d'images // ainsi que la sérialization des .myphd menu1.add(menuItem3); JMenuItem menuItem4 = new JMenuItem("Save picture", KeyEvent.VK_P); menuItem4.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK)); // Prendre en gestion les différentes extensions d'images // ainsi que la sérialization des .myphd menu1.add(menuItem4); JMenuItem menuItem5 = new JMenuItem("New project", KeyEvent.VK_N); menuItem5.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK)); menu1.add(menuItem5); JMenuItem menuItem6 = new JMenuItem("Quit",KeyEvent.VK_Q); menuItem6.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, ActionEvent.CTRL_MASK)); menuItem6.addActionListener(this); menu1.add(menuItem6); JMenuItem menuItem7 = new JMenuItem("Undo", KeyEvent.VK_U); menuItem7.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U, ActionEvent.CTRL_MASK)); menuItem7.addActionListener(this); menu2.add(menuItem7); JMenuItem menuItem8 = new JMenuItem("Redo", KeyEvent.VK_R); menuItem8.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.CTRL_MASK)); menuItem8.addActionListener(this); menu2.add(menuItem8); menuBar.add(menu1); menuBar.add(menu2); menuBar.add(menu3); setJMenuBar(menuBar); createButton(); } public void createButton() { JPanel panel = new JPanel(new FlowLayout()); button1 = new JButton("Undo"); button1.setSize(30, 30); panel.add(button1); button2 = new JButton("Redo"); button2.setSize(30, 30); panel.add(button2); button3 = new JButton("Save"); button3.setSize(30, 30); panel.add(button3); button4 = new JButton("Open"); button4.setSize(30, 30); panel.add(button4); button1.setEnabled(false); button2.setEnabled(false); button1.addActionListener(this); button2.addActionListener(this); button3.addActionListener(this); button4.addActionListener(this); mainPanel_.add(panel, BorderLayout.NORTH); this.setContentPane(mainPanel_); } public void actionPerformed(ActionEvent e) { System.out.println(e.getActionCommand()); if (e.getActionCommand().contentEquals("Open")) { filechooser = new JFileChooser(); File f; try { f = new File(new File(".").getCanonicalPath()); filechooser.setCurrentDirectory(f); filechooser.setCurrentDirectory(null); filechooser.showOpenDialog(null); currentfile = new ImagePanel(filechooser.getSelectedFile()); currentfile.setPreferredSize(new Dimension(currentfile.getWidth(), currentfile.getHeight())); currentfile.setMinimumSize(new Dimension(currentfile.getWidth(), currentfile.getHeight())); currentfile.memento_ = new Memento(currentfile.image); currentfile.caretaker_.add(currentfile.memento_); currentfile.caretaker_.add(currentfile.pixels); currentproject = new ProjectUtil(); currentproject.setImgP(currentfile); currentproject.setCareTaker(currentfile.caretaker_); currentproject.setMemento(currentfile.memento_); currentimg_ = currentfile; scroll.getViewport().removeAll(); scroll.getViewport().add(currentfile); scroll.repaint(); mainPanel_.add(scroll); this.setContentPane(mainPanel_); mainPanel_.repaint(); currentmodindex_ = currentimg_.caretaker_.getIndex(); button1.setEnabled(false); button2.setEnabled(false); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } if (e.getActionCommand().contains("Open Project")) { File f; try { f = new File(new File(".").getCanonicalPath()); filechooser.setCurrentDirectory(f); filechooser.setCurrentDirectory(null); filechooser.showOpenDialog(null); FileInputStream fis; if (filechooser.getSelectedFile().getName().endsWith(".myPSD")) { fis = new FileInputStream(filechooser.getSelectedFile()); ObjectInputStream ois= new ObjectInputStream(fis); currentfile = (ImagePanel) ois.readObject(); scroll.getViewport().removeAll(); scroll.setViewportView(currentfile); scroll.repaint(); mainPanel_.repaint(); if (currentfile.caretaker_.getIndex() != 0) { button1.setEnabled(true); button2.setEnabled(true); } ois.close(); fis.close(); } } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } givenName_ = currentimg_.shortName; } if (e.getActionCommand().contentEquals("Save")) { File f; try { f = new File(new File(".").getCanonicalPath()); filechooser.setCurrentDirectory(f); filechooser.setCurrentDirectory(null); int x = filechooser.showSaveDialog(null); if (x == JFileChooser.APPROVE_OPTION) { FileOutputStream fos = new FileOutputStream(filechooser.getSelectedFile()); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(currentfile); oos.flush(); oos.close(); fos.close(); } } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } if (e.getActionCommand().contains("Save Project")) { File f; try { f = new File(new File(".").getCanonicalPath()); filechooser.setCurrentDirectory(f); filechooser.setCurrentDirectory(null); int x = filechooser.showSaveDialog(null); if (x == JFileChooser.APPROVE_OPTION) { FileOutputStream fos = new FileOutputStream(filechooser.getSelectedFile()+ ".myPSD"); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(currentproject); oos.flush(); oos.close(); fos.close(); } } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } if (e.getActionCommand().contains("Save picture")) { File f;//FAUX try { f = new File(new File(".").getCanonicalPath()); filechooser.setCurrentDirectory(f); filechooser.setCurrentDirectory(null); int x = filechooser.showSaveDialog(null); if (x == JFileChooser.APPROVE_OPTION) { FileOutputStream fos = new FileOutputStream(filechooser.getSelectedFile()); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(currentfile.caretaker_); oos.flush(); oos.close(); fos.close(); } else { } } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } if (e.getActionCommand().contains("Quit")) { System.exit(0); } if (e.getActionCommand().contains("Undo")) { currentfile.caretaker_.undo(); currentfile.setImage(currentfile.caretaker_.get(currentfile.caretaker_.getIndex()).getState()); currentfile.repaint(); if (currentfile.caretaker_.getIndex() == 0) { button1.setEnabled(false); } if (currentfile.caretaker_.maxEl() > 1) { button2.setEnabled(true); } } if (e.getActionCommand().contains("Redo")) { currentfile.caretaker_.redo(); currentfile.setImage(currentfile.caretaker_.get(currentfile.caretaker_.getIndex()).getState()); currentfile.repaint(); if (currentfile.caretaker_.getIndex() + 1 == currentfile.caretaker_.maxEl()) { button2.setEnabled(false); } if (currentfile.caretaker_.getIndex() >= 0) { button1.setEnabled(true); } } /*if (plugindt_.containsKey(e.getActionCommand())) { Workingfilter wf = new Workingfilter(currentfile, (IPlugin) plugindt_.get(e.getActionCommand())); wf.execute(); currentfile.caretaker_.redo(); currentfile.memento_ = new Memento(currentfile.image); currentfile.caretaker_.add(currentfile.memento_); try { doc.insertString(doc.getLength(),e.getActionCommand() + System.getProperty("line.separator"),style); } catch (BadLocationException e1){} button1.setEnabled(true); }*/ } } <file_sep>package memento; import java.awt.image.BufferedImage; import java.io.Serializable; public class Originator implements Serializable { private static final long serialVersionUID = -314171089120047242L; private BufferedImage state_; public void setMemento(Memento m) { state_ = m.getState(); } public Memento createMemento() { return new Memento(state_); } public BufferedImage restore(Memento memento) { state_ = memento.getState(); return state_; } } <file_sep>package memento; import java.awt.image.BufferedImage; import java.io.Serializable; public class Memento implements Serializable { private static final long serialVersionUID = -314171089120047242L; protected BufferedImage state_; protected String statename_; public Memento(Object state) { state_ = (BufferedImage) state; } public BufferedImage getState() { return state_; } public void setState(BufferedImage state) { state_ = state; } public String getStateName_() { return statename_; } public void setStateName_(String statename_) { this.statename_ = statename_; } }
5630ad0c8ca370877cadf49dbeeff1232f03fbe1
[ "Java" ]
5
Java
Linuviel/MPH_axcel
aeb0b6db60b9a8339f52fee414521541d7e9feda
d00745e0716e29d10491df03a828e283fbf5c88b
refs/heads/master
<repo_name>annakviese/Tax-Calculator<file_sep>/README.md # TFSA vs RRSP Calculator This calculator was created to compare TFSA and RRSP contributions. A "user" will have to manually input the values in order to get the result. ## Technology Used Since it is my first independent Angular 2 app, I've used the angular quickstart suggested by CodeSchool (https://github.com/angular/quickstart) * Angular 2 * TypeScript * HTML5 ## To run the app * Download the zip file * Unzip the file and access it via your Git * run "npm install" (to install the necessary node modules) * run "npm start" (to load the file in a separate window) ## Improvements Due to time constrains the app does not provide the best user experience and requires some improvements: * Allow users to enter full numbers and convert to the percentages automatically * Provide a select option values for some entries * Apply additional form validation (max.rate, max.deposit etc.) * Add styles to emphasize results * Change screens when getting results <file_sep>/app/input-form.component.ts import { Component } from '@angular/core'; import { Input } from './input'; @Component({ moduleId: module.id, selector: 'input-form', styleUrls: ['css/style.css'], templateUrl: 'input-form.component.html', }) export class InputFormComponent { MarginalTaxRate = [0.36]; model = new Input(); submitted = false; onSubmit() { this.submitted = true; //calculates After Tax Value this.model.tsfaAfterTax = this.model.DepositAmount * (1 - this.model.MarginalTaxRate); this.model.rrspAfterTax = this.model.DepositAmount; //calculates Future Value in Todays Dollars this.model.rateOfReturn = ((1 + this.model.ROI)/ (1 + this.model.Inflation)) - 1; this.model.tsfaFutureValue = Math.round(this.model.tsfaAfterTax * Math.pow((1 + this.model.rateOfReturn),this.model.Years)); this.model.rrspFutureValue = Math.round(this.model.rrspAfterTax * Math.pow((1 + this.model.rateOfReturn),this.model.Years)); //calculates Tax Paid Upon Withdrawal this.model.tsfaTaxPaid = 0; this.model.rrspTaxPaid = Math.round(this.model.rrspFutureValue) * this.model.AvRetirenmentTax; //calculates Future Value at the End of the period this.model.tsfaEndValue = Math.round(this.model.tsfaFutureValue); this.model.rrspEndValue = Math.round(this.model.rrspFutureValue - this.model.rrspTaxPaid); } } <file_sep>/app/input.ts export class Input { public MarginalTaxRate: number; public AvRetirenmentTax: number; public DepositAmount: number; public Years: number; public ROI: number; public Inflation: number; public rateOfReturn: number; public tsfaAfterTax: number; public rrspAfterTax: number; public tsfaFutureValue: number; public rrspFutureValue: number; public tsfaTaxPaid: number; public rrspTaxPaid : number; public tsfaEndValue: number; public rrspEndValue : number; }<file_sep>/app/app.component.ts import { Component } from '@angular/core'; import { InputFormComponent } from './input-form.component'; @Component ({ selector: 'my-app', template: '<input-form> </input-form>' }) export class AppComponent { } <file_sep>/app/main.ts import { NgModule, Component } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { ReactiveFormsModule } from '@angular/forms'; import { SelectModule } from 'angular2-select'; import { AppComponent } from './app.component'; import { AppModule } from './app.module'; import { InputFormComponent } from './input-form.component'; platformBrowserDynamic() .bootstrapModule(AppModule);
ec53891510026605e8132805b990349ae3601b03
[ "Markdown", "TypeScript" ]
5
Markdown
annakviese/Tax-Calculator
b06c3ff944f4e6cd970ba71622d531e9c1525bf1
04c14fcf27f92a037925ee40128d630373825f83
refs/heads/master
<file_sep>import React from "react"; import Head from "next/head"; import Global from "./_global.js"; import Navigation from "../components/navigation"; import Board from "../components/board"; import styles from "./index.scss"; export default class extends React.Component { render() { return ( <Global> <Head> <title>DEV Board</title> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.1/semantic.min.css"></link> </Head> <Board /> <style jsx>{styles}</style> </Global> ); } }
fe1390fef0ee6b43aef73297288029bdf7798f96
[ "JavaScript" ]
1
JavaScript
nayayan/dev-board
8e00f640c12075ec52913d529c9a14e9ca23b6e1
fe5c494c5a12d9739c88345e89388a164249f166
refs/heads/main
<repo_name>andrewkup/python_learning<file_sep>/cat.py from classcat import Pets cats = [ { 'name': 'baron', 'gender': 'male', 'age': '2' }, { 'name': 'sam', 'gender': 'male', 'age': '2' } ] for cat in cats: c = Pets(name=cat.get('name'), gender=cat.get('gender'), age=cat.get('age')) print(c.name) print(c.gender) print(c.age)
8772b0a137ab3229e6a96678e3da8275781d36d7
[ "Python" ]
1
Python
andrewkup/python_learning
c8cb866d514844cf7c68371e88c636885645c7b3
3a6d20ce66fed9a884f765f6bdc4594af1a7199a
refs/heads/master
<repo_name>renosyah/Proyek-paw-php<file_sep>/pelanggan.php <?php include "header.php"; ?> <table width="90%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.5);border-radius:5px;margin-top:15px;margin-bottom:15px"> <tr> <td style="text-align:center"><h2>Daftar Pelanggan</h2><hr></td> </tr> <tr> <td height="300" style="vertical-align:top"> <table width="90%" border="1" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.5);border-radius:5px;margin-top:15px;margin-bottom:15px;"> <tr style="text-align:center"> <td><h3>No</h3></td> <td><h3>Nama</h3></td> <td><h3>username</h3></td> <td width="150"><h3>Jumlah buku disewa</h3></td> <td><h3>Gold dimiliki</h3></td> <td><h3>Opsi</h3></td> </tr> <?php $hasil_pelanggan = mysqli_query($konek,"select *,(select count(*) from sewa_buku where sewa_buku.username = pelanggan.username) as buku_disewa from pelanggan"); if (!$hasil_pelanggan) die("gagal memilih data karena : ".mysql_error($konek)); $no_p=1; while ($data_p = mysqli_fetch_assoc($hasil_pelanggan)) { include "isi_daftar_pelanggan.php"; $no_p++; } ?> </table> </td> </tr> </table> <?php include "footer.php"; ?><file_sep>/index_user.php <html> <head> <style type="text/css"> @import url(data/set1.css); </style> <title>Penyewaan E-book</title> </head> <script src="data/my_jquerry.js"></script> <script> function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#blah') .attr('src', e.target.result) .width(400) .height(400); }; reader.readAsDataURL(input.files[0]); } } function readURL2(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#blah') .attr('src', e.target.result) .width(300) .height(330); }; reader.readAsDataURL(input.files[0]); } } function tema_set(form,option){ var form = document.getElementById(form); document.getElementById(option).addEventListener("click", function () { form.submit();}); } </script> <body> <table width="100%" id="head" border="0"> <tr> <td height="190" style="text-align:center"><h1>Penyewaan E-Book</h1></td> </tr> </table> <!---------------> <table width="95%" border="0" style="margin-left:auto;margin-right:auto;margin-top:15px;margin-bottom:15px;"> <tr> <td style="display:none" id="aturan" width="90%"> <table width="100%" style=";background-color:rgba(0, 0, 0, 0.3);border-radius:5px;margin-top:15px;margin-bottom:15px"> <tr> <td style="text-align:center"><h2>Peraturan Wajib</h2><hr></td> </tr> <tr> <td> <table width="90%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.5);border-radius:5px;margin-top:15px;margin-bottom:15px;"> <tr> <td height="10" colspan="2"></td> </tr> <tr style="vertical-align:top"> <td> </td><td> Dengan menjadi bagian dari komunitas ini maka anda telah menyetujui semua aturan yg ada, dengan aturan-aturan yg wajib dipatuhi, adapun aturannya adalah sebagai berikut : <br><br></td> </tr> <tr style="vertical-align:top"> <td>1. </td><td>saling menghormati satu sama lain sebagai user, user yang melanggar akan dikenai sanksi teguran dan juga peringatan, hingga banned akun secara permanen.</td> </tr> <tr> <td height="10" colspan="2"></td> </tr> <tr style="vertical-align:top"> <td>2. </td><td>segala bentuk buku atau gambar tidak boleh berbau sara,porno, dan mengandung konten terlarang lainya, jika ada user yang melanggar dan mengupload konten berbau pornografi, maka akan dikenai pasal Undang-Undang No. 44 Tahun 2008 Tentang Pornografi ("UU Pornografi").</td> </tr> <tr> <td height="10" colspan="2"></td> </tr> <tr style="vertical-align:top"> <td>3. </td><td>website ini masih dalam tahap pengembangan, apabila ada yg berusaha atau telah mengacak, meretas dan merusak website ini maka akan dikenai sanksi berupa pidana,silahkan dilihat di Undang-Undang Nomor 11 Tahun 2008 Tentang Internet & Transaksi Elektronik (ITE)</td> </tr> <tr> <td height="10" colspan="2"></td> </tr> <tr style="vertical-align:top"> <td>4. </td><td>setiap buku yg diposting adalah asli buatan user sendiri, dilarang mengupload buku yang bukan milik sendiri tanpa meminta ijin kepada sang penulis buku tersebut.</td> </tr> <tr> <td height="10" colspan="2"></td> </tr> <tr style="vertical-align:top"> <td>5. </td><td> jika ada pemberitahuan tetang pelanggaran hak cipta buku, maka user yg bersangkutanlah yg harus menerima sanksi tersebut, Undang-Undang Republik Indonesia Nomor 28 Tahun 2014 tentang Hak Cipta sanksi bisa berupa pidana.</td> </tr> <tr> <td height="10" colspan="2"></td> </tr> <tr style="vertical-align:top"> <td></td><td>sekian dulu (maaf, sebelumnya admin bukan dari jurusan hukum,ngga terlalu mengerti soal pasal dan udang-undang).<br><br></td> </tr> </table> </td> </tr> </table> <table width="100%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.3);border-radius:5px;margin-top:15px;margin-bottom:15px"> <tr> <td style="text-align:center"><h2>Peraturan Umum</h2><hr></td> </tr> <tr> <td> <table width="90%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.5);border-radius:5px;margin-top:15px;margin-bottom:15px"> <tr> <td height="10" colspan="2"></td> </tr> <tr style="vertical-align:top"> <td>1. </td><td>setiap user wajib mengupdate isi file buku, agar pelanggan yg menyewa buku tidak merasa bosan, dan ini juga dapat menambah minat baca setiap orang agar terus menyewa buku yg anda posting.</td> </tr> <tr> <td height="10" colspan="2"></td> </tr> <tr style="vertical-align:top"> <td>2. </td><td>untuk setiap penyewaan buku, user yg memposting buku dan bukunya tersebut disewa oleh pelanggan,user yg bersangkutan berhak mendapat gold sesuai banyaknya durasi waktu atau buku yg disewa,Untuk gold bisa ditukar dengan uang sungguhan, silahkan hubungi admin untuk informasi ini, data tentang penyewaan buku bisa dilihat di menu pelanggan. </td> </tr> <tr> <td height="10" colspan="2"></td> </tr> <tr style="vertical-align:top"> <td>3. </td><td>website ini tidak menyediakan ruangan untuk menyimpan konten yg dibutuhkan buku anda,seperti konten gambar,video,suara dan lain-lain, usahakan untuk konten-konten tersebut diletakan di website lain.</td> </tr> <tr> <td height="10" colspan="2"></td> </tr> <tr style="vertical-align:top"> <td>4. </td><td>semua aturan tersebut tidak berlaku untuk admin, karena admin bebas dari segala tuntutan,dan juga semua aturan tidak berlaku jika aplikasi belum sah.<br></td> </tr> </table> </td> </tr> </table> </td> <td width="30%"> <script> $(document).ready( function(){ $('#button').click( function(){ $('#aturan').toggle(); $('#apk').toggle(); $('#pelanggan').toggle(); $('#menu_daftar').toggle(); $('#login').toggle(); } ); $('#button2').click( function(){ $('#aturan').toggle(); $('#apk').toggle(); $('#pelanggan').toggle(); $('#menu_daftar').toggle(); $('#login').toggle(); } ); }); </script> <table id="login" width="30%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.3);border-radius:5px;margin-top:15px;margin-bottom:15px"> <tr> <td style="text-align:center;"><h2 style="margin-top:15px">Login Sebagai User</h2><hr></td> </tr> <tr> <td style="text-align:center;padding-right:10px;padding-left:10px"> <form action="service/mau_login.php" method="post"> <input type="text" name="username" placeholder="Username" style="width:150px"><br><br> <input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" style="width:150px"><br><br> <input type="submit" value="Login" style="width:150px"> <br><br><button type="button" id="button">Daftar Baru</button> <button type="button" onclick=" window.location.href = 'index.php'">Kembali</button><br> </form> </td> </tr> <tr> <td colspan="2" style="text-align:center"><?php if (isset($_GET['msg'])) { echo "<div style='color:red'>".$_GET['msg']."</div>"; } ?> </td> </tr> </table> <table id="menu_daftar" width="400" style="display:none;margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.3);border-radius:5px;margin-top:15px;margin-bottom:15px;"> <tr> <td style="text-align:center;"><h2>Daftar User Baru</h2><hr></td> </tr> <tr> <td> </tr> <tr> <td height="513" style="vertical-align:top"> <table width="90%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.3);border-radius:5px"> <tr> <td style="text-align:center"><h2>Masukkan Data Diri Anda</h2><hr></td> </tr> <form action="service/mau_daftar_user.php" method="post" enctype="multipart/form-data"> <td style="padding-left:10px"> <table style="vetical-align:bottom"> <tr> <td> Nama Lengkap :</td><td width="60%"> <input type="text" name="nama" style="width:70%" required> </td> </tr> <tr> <td> Email :</td><td> <input type="email" name="email" style="width:70%" required> </td> </tr> <tr> <td> No telp :</td><td> <input type="number" name="telp" style="width:70%" required> </td> </tr> <tr> <td> Jenis kelamin :</td><td><input type="radio" name="jk" value="pria" required> Pria <input type="radio" name="jk" value="wanita" required> Wanita </td> </tr> <tr> <td> Alamat :</td><td><textarea name="alamat" style="width:70%" required></textarea> </td> </tr> <tr> <td> Pekerjaan :</td><td><input type="text" name="pekerjaan" style="width:70%" required> </td> </tr> <tr> <td> Status :</td><td><input type="radio" name="status" value="lajang" required> Lajang <input type="radio" name="status" value="menikah" required> Menikah </td> </tr> <tr> <td> Username :</td><td><input type="text" name="username" style="width:70%" required> </td> </tr> <tr> <td> Password :</td><td><input type="text" name="password" style="width:70%" required> </td> </tr> <tr> <td> Konfirmasi Password :</td><td><input type="text" name="password_konfir" style="width:70%" required> </td> </tr> <tr> <td> Foto Profil :</td><td><input type="file" name="gambar" style="width:80%" required><br><br> </td> </tr> <tr> <td style="text-align:center" colspan="2"> <button type="submit">Mendaftar</button> <button id="button2" type="button">Batal</button></td> </td> </tr> <tr> <td colspan="2"><br> <p style="font-size:12px">*pembuatan akun tidak gratis, akun anda tidak bisa dibuat jika admin tidak menyetujui formulir yang anda inputkan. beberapa hari berikutnya, admin akan mengirimkan pesan email persetujuan atau mungkin wawancara singkat.<br><p> </td> </tr> </table> </td> </form> </tr> </table> </td> </tr> <tr> <td style="text-align:center"><h2>Daftar sebagai Pelanggan</h2><hr></td> </tr> <td colspan="2" style="text-align:center;background-color:rgba(0, 0, 0, 0.3);border-radius:10px;" > <h2>Download Apk<h2> <a href="index.php#apk"><img id="img" width="90%" height="30%" src="https://raw.githubusercontent.com/renosyah/proyek-web-php/master/apk/android.png"></img></a> </td> </table> </td> </tr> </table> <div style="margin-top:200px"> </div> </body> </html><file_sep>/list_user.php <?php include "header.php"; ?> <table width="90%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.5);border-radius:5px;margin-top:15px;margin-bottom:15px;"> <tr style="vertical-align:top"> <td style="text-align:center" colspan="7"><h2>Daftar User</h2><hr></td> </tr> <tr> <td> <table width="90%" border="1" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.5);border-radius:5px;margin-top:15px;margin-bottom:15px;"> <tr style="vertical-align:top;text-align:center"> <td>No</td> <td>Nama Lengkap</td> <td>Username</td> <td>Gold</td> <td>Nomor</td> <td>Email</td> <td>Status</td> <td>Opsi</td> </tr> <?php $no = 1; $sql_user = "select u.*,du.* from user u left join detail_user du on du.username = u.username"; $data_user = mysqli_query($konek,$sql_user); if (!$data_user) die("gagal memilih data karena : ".mysql_error($konek)); while ($dt = mysqli_fetch_assoc($data_user)) { include "isi_list_user.php"; $no++; } ?> </table> </td> </tr> </table> <?php include "footer.php"; ?><file_sep>/footer_client.php <table width="100%" style="text-align:center;margin-top:500px;background-color:rgba(0, 0, 0, 0.3);background-repeat:no-repeat; background-size:cover; box-shadow: 12px 12px 12px black; border-radius:20px; max-width:auto;"> <tr> <td height="80">Copyright &copy;2017 by <NAME></td> </tr> </table> </body> </html><file_sep>/service/simpan_perubahan_akun_pelanggan.php <?php session_start(); include "koneksi.php"; $user_edit = $_POST['user_edit']; $nama_baru = $_POST['edit_nama']; $password_baru = $_POST['edit_password']; $konfirmasi_password_baru = $_POST['konfirmasi_password']; $email_baru = $_POST['edit_email']; $nomor_baru = $_POST['edit_nomor']; if (strlen(trim($nama_baru)) > 0){ $sql = "update pelanggan set nama = '$nama_baru' where username = '$user_edit'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan nama baru anda!');self.history.back();</script>"; exit; } $_SESSION['nama_user_login'] = $nama_baru; } if (strlen(trim($password_baru)) > 0){ if ($password_baru != $konfirmasi_password_baru){ echo "<script>alert('password tidak cocok dengan konfirmasi!');self.history.back();</script>"; exit; } $sql = "update pelanggan set password = '$<PASSWORD>' where username = '$user_edit'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan password baru anda!');self.history.back();</script>"; exit; } } if (strlen(trim($email_baru)) > 0){ $sql = "update pelanggan set email = '$email_baru' where username = '$user_edit'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan email baru anda!');self.history.back();</script>"; exit; } } if ($nomor_baru != ""){ $sql = "update pelanggan set nomor_telp = '$nomor_baru' where username = '$user_edit'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan nomor baru anda!');self.history.back();</script>"; exit; } } header("location:../halaman_pengaturan_client.php"); ?><file_sep>/mobile/mau_daftar_pelanggan_mobile.php <?php include "../service/koneksi.php"; $nama = $_POST['nama']; $email = $_POST['email']; $no = $_POST['telp']; $username = $_POST['username']; $password = $_POST['password']; $password_konfirmasi = $_POST['password_konfir']; if (strlen(trim($nama)) < 0){ $pesan = array("Pesan" => "nama tidak boleh kosong","Respon" => false); echo json_encode($pesan); exit; } if (strlen(trim($email)) < 0){ $pesan = array("Pesan" => "email tidak boleh kosong","Respon" => false); echo json_encode($pesan); exit; } if (strlen(trim($no)) < 0){ $pesan = array("Pesan" => "nomor tidak boleh kosong","Respon" => false); echo json_encode($pesan); exit; } if (strlen(trim($username)) < 0){ $pesan = array("Pesan" => "username tidak boleh kosong","Respon" => false); echo json_encode($pesan); exit; } if (strlen(trim($password)) < 0){ $pesan = array("Pesan" => "password tidak boleh kosong","Respon" => false); echo json_encode($pesan); exit; } if ($password_konfirmasi != $password){ $pesan = array("Pesan" => "password dan konfirmasi tidak cocok","Respon" => false); echo json_encode($pesan); exit; } $sql_pelanggan = "insert into pelanggan (username,password,email,nomor_telp,nama,gold) values ('$username','$password','$email','$no','$nama',100)"; $insert_data = mysqli_query($konek,$sql_pelanggan); if (!$insert_data){ $pesan = array("Pesan" => "gagal mendaftarkan, username telah digunakan orang lain","Respon" => false); echo json_encode($pesan); exit; } $pesan = array("Pesan" => "selamat bergabung","Respon" => true); echo json_encode($pesan); ?><file_sep>/mobile/mau_beli_gold.php <html> <head> <title>Konfirmasi Pembelian</title> <style type="text/css"> label { cursor: pointer; } #bukti_gambar { opacity: 0; position: absolute; z-index: -1; } </style> </head> <script src="../data/my_jquerry.js"></script> <script> function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#blah') .attr('src', e.target.result) .width(440) .height(480); }; reader.readAsDataURL(input.files[0]); } } </script> <body style="background-image:url(https://raw.githubusercontent.com/renosyah/Proyek-BasisData/master/server%20admin/data/bg.jpg); background-attachment:fixed; zoom:reset; color:white; font-family:tahoma,verdana,arial; background-repeat:no-repeat; background-size:cover;"> <table width="100%"> <tr> <td> <?php include "../service/koneksi.php"; $kd_gold = $_GET['kd_gold']; $username = $_GET['username']; ?> <table width="90%" border="1" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.3);border-radius:5px;margin-top:114px;margin-bottom:85px;font-size:28px"> <tr> <td colspan="5" style="text-align:center"><h2>Konfirmasi Pembelian Gold</h2></td> </tr> <tr style="vertical-align:top;text-align:center"> <td>Nama</td><td>Username</td><td>Harga</td><td>Jumlah</td><td>Gambar</td> </tr> <tr style="vertical-align:top;text-align:center"> <?php $hasil_gold = mysqli_query($konek,"select * from gold_kategori where kd_gold = '$kd_gold'"); if (!$hasil_gold) die("gagal memilih data karena : ".mysql_error($konek)); $hasil_pelanggan = mysqli_query($konek,"select * from pelanggan where username = '$username'"); if (!$hasil_gold) die("gagal memilih data karena : ".mysql_error($konek)); $data_gold = mysqli_fetch_assoc($hasil_gold); $data_pelanggan = mysqli_fetch_assoc($hasil_pelanggan); echo "<td>".$data_pelanggan['nama']."</td> <td>".$data_pelanggan['username']."</td> <td style='color:LawnGreen;font-size:24px;text-shadow: 1px 1px white'> Rp ".number_format($data_gold['harga'])."</td> <td style='color:orange;font-size:28px;text-shadow: 1px 1px white;'> Gold ".number_format($data_gold['jumlah'])."</td> <td><img src='../data/gold/".$data_gold['kd_gold']."/".$data_gold['gambar']."'></img></td>"; ?> </tr> </table> <table id="ok" width="90%" border="1" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.3);border-radius:5px;margin-top:18px;margin-bottom:85px"> <tr> <td colspan="5" style="text-align:center"><h2>Upload Bukti Transaksi</h2></td> </tr> <td style="vertical-align:top;text-align:center"> <form action="terima_transaksi.php" method="post" enctype="multipart/form-data"> <input type="hidden" name="username" value="<?php echo $username;?>"> <input type="hidden" name="kd_gold" value="<?php echo $kd_gold;?>"><br> <label for="bukti_gambar"> <img id="blah" src="../data/plus.png" width="440" height="480"> </label><br> <input type="file" name="bukti_gambar" id="bukti_gambar" accept="image/*" style="width:120px;" onchange="readURL(this)" required> <br> <br> <input type="submit" value="Kirim Bukti" style="font-size:28px;width:90%;height:40px"> </form> </td> </tr> </table> </body> <script> $(document).ready( function(){ $('#ya').click( function(){ $('#ok').toggle(); } ); }); </script> </html> <file_sep>/service/terima_pesan_gold.php <?php include "koneksi.php"; $kd_tansaksi = $_POST['jual']; $username_pelanggan = $_POST['pelanggan']; $jumlah_gold = $_POST['gold']; $sql = "update pelanggan set gold = gold+'$jumlah_gold' where username = '$username_pelanggan'"; $pesanan_gold = mysqli_query($konek,$sql); if (!$pesanan_gold) die("gagal mengambil data"); $delete_transaksi = "delete from jual_gold where kd_jual_gold = '$kd_tansaksi'"; $pesanan_gold_delete = mysqli_query($konek,$delete_transaksi); if (!$pesanan_gold_delete) die("gagal menghapus data"); $folder = "../data/transaksi/$username_pelanggan/"; rmdir_recursive($folder); header("location:../jual_gold.php"); ?><file_sep>/service/simpan_perubahan_buku.php <?php include "koneksi.php"; $kd_buku = $_POST['kd_buku']; $judul_buku = $_POST['judul_buku']; $penulis = $_POST['penulis_buku']; $harga_buku = $_POST['harga_buku']; $potongan = $_POST['potongan_harga']; $kategori = $_POST['kategori']; $gambar_lama = $_POST['gambar_lama']; $file_lama = $_POST['file_lama']; $name_sampul = $_FILES['gambar']['name']; $tmp_name_sampul = $_FILES['gambar']['tmp_name']; $type_sampul = $_FILES['gambar']['type']; $size_sampul = $_FILES['gambar']['size']; $name_buku = $_FILES['buku']['name']; $tmp_name_buku = $_FILES['buku']['tmp_name']; $type_buku = $_FILES['buku']['type']; $size_buku = $_FILES['buku']['size']; if (strlen(trim($judul_buku)) > 0){ $sql = "update buku set judul = '$judul_buku' where kd_buku = '$kd_buku'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan judul!');self.history.back();</script>"; exit; } } if (strlen(trim($penulis)) > 0){ $sql = "update buku set penulis = '$penulis' where kd_buku = '$kd_buku'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan penulis!');self.history.back();</script>"; exit; } } if (strlen(trim($harga_buku)) > 0){ if ((int)$harga_buku > 500){ echo "<script>alert('gagal simpan!, harga tidak boleh lebih dari 500');self.history.back();</script>"; exit; } $sql = "update buku set harga = '$harga_buku' where kd_buku = '$kd_buku'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan harga!');self.history.back();</script>"; exit; } } if (strlen(trim($potongan)) > 0){ $sql = "update buku set potongan = '$potongan' where kd_buku = '$kd_buku'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan potongan!');self.history.back();</script>"; exit; } } if (strlen(trim($kategori)) > 0){ $sql = "update buku set kd_kategori = '$kategori' where kd_buku = '$kd_buku'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan kategori!');self.history.back();</script>"; exit; } } $maxsize_sampul = 1000000; $allowed_sampul = array('image/png', 'image/jpg','image/jpeg'); $maxsize_file = 1000000; $allowed_file = array('text/html'); $folder = "../data/gambar/$kd_buku"; $dir_foto = $folder."/".$name_sampul; $dir_file = $folder."/".$name_buku; if ($size_sampul > 0){ if (!in_array($type_sampul, $allowed_sampul)) { echo "<script>alert('gagal simpan!, tipe hanya bisa jpg dan png');self.history.back();</script>"; exit; } if ($size_sampul > $maxsize_sampul) { echo "<script>alert('gagal simpan!, ukuran sampul terlalu besar');self.history.back();</script>"; exit; } unlink($folder."/".$gambar_lama); $sql = "update buku set gambar = '$name_sampul' where kd_buku = '$kd_buku'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan sampul!');self.history.back();</script>"; exit; } move_uploaded_file($tmp_name_sampul, $dir_foto); } if ($size_buku > 0){ if (!in_array($type_buku, $allowed_file)) { echo "<script>alert('gagal simpan!, tipe buku hanya bisa html');self.history.back();</script>"; exit; } if ($size_buku > $maxsize_file) { echo "<script>alert('gagal simpan!, ukuran buku terlalu besar');self.history.back();</script>"; exit; } unlink($folder."/".$file_lama); $sql = "update buku set direktori = '$name_buku' where kd_buku = '$kd_buku'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan file buku!');self.history.back();</script>"; exit; } move_uploaded_file($tmp_name_buku, $dir_file); } header("location:../daftar.php"); ?><file_sep>/isi_daftar_buku.php <tr style="text-align:center"> <td><?php echo $no; ?></td> <td><?php echo $data['kd_buku']; ?></td> <td><?php echo $data['judul']; ?></td> <td><?php echo $data['penulis']; ?></td> <td><?php echo $data['harga']; ?> Gold</td> <td><?php echo $data['potongan']; ?> %</td> <td style="color:orange"><?php echo $data['harga_total']; ?> Gold</td> <td><img height="60" width="50" src="data/gambar/<?php echo $data['kd_buku']."/". $data['gambar']; ?>"></img></td> <td><a href="data/gambar/<?php echo $data['kd_buku']."/".$data['direktori']; ?>">file</a></td> <td><?php echo $data['nama_kategori']; ?></td> <td><button style="width:50px" id="b0<?php echo $data['kd_buku']; ?>">Edit</button></td> <form action="service/hapus_buku.php" method="post"> <td> <button name="hapus" value="<?php echo $data['kd_buku']; ?>" onclick="return confirm('anda yakin ingin menghapus <?php echo $data['judul']; ?>')">Hapus</button> </td> </form> </tr> <tr id="edit<?php echo $data['kd_buku']; ?>" style="display:none"> <td colspan="12" height="400" style="text-align:center;vertical-align:top"> <!--------edit buku-----> <br> <h2>Edit Data Buku <?php echo $data['judul']; ?></h2><hr> <form action="service/simpan_perubahan_buku.php" method="post" enctype="multipart/form-data"> <table width="80%" border="0" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.5);border-radius:15px;margin-top:5px;margin-bottom:25px;padding-top:25px;padding-bottom:25px;padding-right:30px"> <tr> <td></td><td></td><td colspan="2" style="text-align:center">Gambar sampul</td> </tr> <tr> <td height="10" width="30%" style="text-align:right">Kode Buku : </td><td><?php echo $data['kd_buku']; ?></td><td rowspan="9" width="40%"> <label for="gambar"> <img width="100%" id="blah" height="400" src="data/gambar/<?php echo $data['kd_buku']."/".$data['gambar']; ?>"></img></td> </label> </tr> <tr> <td height="10" style="text-align:right">Judul Buku : </td><td><input type="text" name="judul_buku" placeholder="<?php echo $data['judul']; ?>"></td> </tr> <tr> <td height="10" style="text-align:right">Nama Penulis : </td><td><input type="text" name="penulis_buku" placeholder="<?php echo $data['penulis']; ?>"></td> </tr> <tr> <td height="10" style="text-align:right">Harga : </td><td><input type="number" name="harga_buku" style="width:70px" placeholder="<?php echo $data['harga']; ?>"></td> </tr> <tr> <td height="10" style="text-align:right">Potongan : </td><td><input type="number" name="potongan_harga" style="width:50px" placeholder="<?php echo $data['potongan']; ?>"> %</td> </tr> <tr> <td height="10" style="vertical-align:top;text-align:right" >Kategori : </td> <td style="vertical-align:top"> <select name="kategori"> <option value=""> --pilih kategori-- </option> <?php $hasil_kategori = mysqli_query($konek,"select * from kategori"); if (!$hasil_kategori) die("gagal memilih data karena : ".mysql_error($konek)); while ($data_k = mysqli_fetch_assoc($hasil_kategori)) { echo "<option value='".$data_k['kd_kategori']."'>".$data_k['nama_kategori']."</option>"; } ?> </select> </td> </tr> <tr> <td style="text-align:right">gambar sampul : </td><td><input type="file" accept="image/*" name="gambar" onchange="readURL(this);"></td> </tr> <tr> <td style="text-align:right">file buku : </td><td><input type="file" name="buku" accept="text/html"></td> </tr> <tr> <td height="140" colspan="3"> <input type="hidden" name="gambar_lama" value="<?php echo $data['gambar']; ?>"> <input type="hidden" name="file_lama" value="<?php echo $data['direktori']; ?>"></td> </tr> <tr> <td style="text-align:center;" colspan="3"><br><button type="submit" value="<?php echo $data['kd_buku']; ?>" style="width:30%;height:40px" name="kd_buku">Simpan Perubahan</button></td> </tr> </table> </form> <!--------edit buku-----> </td> </tr> <script> $(document).ready(function(){ $('#b0<?php echo $data['kd_buku']; ?>').click(function(){ $('#edit<?php echo $data['kd_buku']; ?>').toggle();});}); </script><file_sep>/service/mau_beli_gold.php <?php include "koneksi.php"; $kd_gold = $_POST['kd_gold']; $username = $_POST['username']; $name_bukti = $_FILES['bukti_gambar']['name']; $tmp_name_bukti = $_FILES['bukti_gambar']['tmp_name']; $type_bukti = $_FILES['bukti_gambar']['type']; $size_bukti = $_FILES['bukti_gambar']['size']; $image = "../data/transaksi/".$username; mkdir($image, 0755, true); $image_bukti = $image."/image.jpg"; $slip_bukti = $image."/slip.txt"; $myfile = fopen($slip_bukti, "w") or die("Unable to open file!"); $txt = "$nama_gambar\n$kd_gold\n$username"; fwrite($myfile, $txt); fclose($myfile); $sql = "insert into jual_gold (username,kd_gold,bukti_gambar,tgl_pesan_gold) values ('$username','$kd_gold','image.jpg',curdate())"; $hasil = mysqli_query($konek,$sql); if (!$hasil) die("gagal query pelanggan"); move_uploaded_file($tmp_name_bukti, $image_bukti); header("location:../halaman_buku_client.php"); ?><file_sep>/README.md # Proyek Pengembangan Aplikasi web : aplikasi penyewaan E-book aplikasi penyewaan buku elektronik berbasis web dan android dengan menggunakan php sebagai backend dan mysql sebagai database, terdapat apliasi android sebagai user interface untuk pelanggan, sedangkan alamat web untuk proyek ini ada di link ini : http://www.penyewaanebook.16mb.com untuk aplikasi mobile android app-nya sendiri bisa diunduh di link ini : https://github.com/renosyah/proyek-web-php/raw/master/apk/Mari Membaca E-book.zip ## fitur bagi pelanggan * Pelanggan dapat dengan mudah menyewa buku * terdapat banyak buku tersedia * mudah digunakan ## fitur bagi user * mudah pengoperasian * dapat menjadi peluang bisnis ## fitur web * tampilan yang menawan * mudah digunakan ## fitur android app * mendukung mobilitas * data internet yang digunakan sedikit ## gambar * tampilan pelanggan web dan di android app ![GitHub Logo](/image/1.png) * tampilan pada ranah penulis ![GitHub Logo](/image/2.png) sekian terimakasih, semoga bermanfaat...<file_sep>/pengaturan_akun_anggota.php <?php include "header.php"; ?> <form action="service/simpan_perubahan_akun.php" method="post" enctype="multipart/form-data"> <table width="90%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.5);border-radius:5px;margin-top:15px;margin-bottom:15px"> <tr> <td style="text-align:center" colspan="5"><h2>Edit Data Akun Anda</h2><hr></td> </tr> <tr> <td> <?php $sql_data_user = "select * from detail_user where username = '$user'"; $hasil_data_user = mysqli_query($konek,$sql_data_user); if (!$hasil_data_user) die("gagal query user"); $dt_user = mysqli_fetch_assoc($hasil_data_user); $email = $dt_user['email']; $nomor = $dt_user['no_telp']; $alamat = $dt_user['alamat']; $pekerjaan = $dt_user['pekerjaan']; $status = $dt_user['status_hubungan']; $jenis_kelamin = $dt_user['jenis_kelamin']; ?> <table width="60%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.5);border-radius:5px;margin-top:15px;margin-bottom:15px;padding-left:10px"> <tr> <td colspan="2" style="text-align:center"><h2>Data Lengkap Untuk user <?php echo $user;?></h2></td> </tr> <tr> <td width="60%">Edit Nama Lengkap : </td><td><input type="text" name="edit_nama" placeholder="<?php echo $_SESSION['nama_user_login']?>"></td> </tr> <tr> <td width="60%">Edit Password : </td><td><input type="password" name="edit_password"></td> </tr> <tr> <td width="60%">Konfirmasi Password baru : </td><td><input type="password" name="konfirmasi_password"><br></td> </tr> <tr> <td><br><br></td> </tr> <tr> <td>Edit Email : </td><td><input type="email" name="edit_email" placeholder="<?php echo $email?>"></td> </tr> <tr> <td>Edit Nomor Telephone : </td><td><input type="number" name="edit_nomor" placeholder="<?php echo $nomor?>"></td> </tr> <tr> <td>Edit jenis kelamin : </td><td><input type="radio" name="edit_jk" value="pria" <?php echo ($jenis_kelamin=="pria")?"checked":"";?>> Pria<br><input type="radio" name="edit_jk" value="wanita" <?php echo ($jenis_kelamin=="wanita")?"checked":"";?>> Wanita </tr> <tr> <td><br><br></td> </tr> <tr> <td>Edit Alamat : </td><td><textarea name="edit_alamat" placeholder="<?php echo $alamat?>"></textarea></td> </tr> <tr> <td>Edit Pekerjaan : </td><td><input type="text" name="edit_pekerjaan" placeholder="<?php echo $pekerjaan?>"></td> </tr> <tr> <td>Edit Status Hubungan : </td><td><input type="radio" name="edit_status" value="lajang" <?php echo ($status=="lajang")?"checked":"";?>> Lajang<br><input type="radio" name="edit_status" value="menikah" <?php echo ($status=="menikah")?"checked":"";?>> Menikah</td> </tr> <tr> <td><br><br></td> </tr> <tr> <td>Edit Foto : </td><td><input type="file" name="edit_foto"></td> </tr> <tr> <td></td><td><input type="hidden" name="foto_lama" value="<?php echo $_SESSION['gambar_login'];?>"></td> </tr> <tr> <td></td><td><br><br><br><button type="submit" value="<?php echo $user;?>" name="user_edit">Simpan Perubahan</button><br><br></td> </tr> </table> </form> </td> </tr> <tr> <td><br><br></td> </tr> </table> <?php include "footer.php"; ?><file_sep>/mobile/terima_transaksi.php <?php include "../service/koneksi.php"; $kd_gold = $_POST['kd_gold']; $username = $_POST['username']; $name_bukti = $_FILES['bukti_gambar']['name']; $tmp_name_bukti = $_FILES['bukti_gambar']['tmp_name']; $type_bukti = $_FILES['bukti_gambar']['type']; $size_bukti = $_FILES['bukti_gambar']['size']; $image = "../data/transaksi/".$username; mkdir($image, 0755, true); $image_bukti = $image."/".$name_bukti; $slip_bukti = $image."/slip.txt"; $myfile = fopen($slip_bukti, "w") or die("Unable to open file!"); $txt = "$nama_gambar\n$kd_gold\n$username"; fwrite($myfile, $txt); fclose($myfile); $sql = "insert into jual_gold (username,kd_gold,bukti_gambar,tgl_pesan_gold) values ('$username','$kd_gold','$name_bukti',curdate())"; $hasil = mysqli_query($konek,$sql); if (!$hasil) die("gagal query pelanggan"); move_uploaded_file($tmp_name_bukti, $image_bukti); ?> <html> <head> <title>Konfirmasi Pembelian</title> </head> <body style="background-image:url(https://raw.githubusercontent.com/renosyah/Proyek-BasisData/master/server%20admin/data/bg.jpg); background-attachment:fixed; zoom:reset; color:white; font-family:tahoma,verdana,arial; background-repeat:no-repeat; background-size:cover;"> <table width="90%" border="1" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.3);border-radius:5px;margin-top:114px;margin-bottom:85px;"> <tr> <td colspan="5" style="text-align:center"><h2>Konfirmasi Pembelian Gold</h2></td> </tr> <tr style="vertical-align:top;text-align:center"> <td>Terima kasih Telah Membeli Gold, Transaksi anda sedang diproses<br><a href="../halaman_beli_gold_client.php">Kembali</a></td> </tr> </table> </body> </html> <file_sep>/halaman_informasi_client.php <?php include "header_client.php"; ?> <table width="90%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.3);border-radius:5px;margin-top:15px;margin-bottom:15px"> <tr> <td style="text-align:center" colspan="5"><h2>Daftar Info</h2><hr></td> </tr> <tr> <td> <table width="80%" border="0" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.4);border-radius:5px;margin-top:15px;margin-bottom:15px"> <tr style="text-align:center"> <td>No</td> <td>Judul</td> <td>Isi</td> <td>Gambar</td> </tr> <?php $hasil = mysqli_query($konek,"select * from info_buku_terbaru"); if (!$hasil) die("gagal memilih data karena : ".mysql_error($konek)); $no=1; if (mysqli_num_rows($hasil) == 0) { echo "<td style='text-align:center' colspan='5' height='100'>Belum ada info terbaru saat ini.</td>"; }else{ while ($data = mysqli_fetch_assoc($hasil)) { echo "<tr style='text-align:center;vertical-align:top'>"; echo "<td>$no</td>"; echo "<td>".$data['judul']."</td>"; echo "<td>".$data['isi']."</td>"; echo "<td><img width='200' height=250' src='data/info/".$data['judul']."/".$data['gambar']."'></img></td>"; echo "</tr>"; $no++; } } ?> </table> </td> </tr> </table> <?php include "footer_client.php"; ?><file_sep>/mobile/url.php <?php $url_web = "http://penyewaanebook.16mb.com/"; ?><file_sep>/mobile/daftar_buku.php <?php include "../service/koneksi.php"; include "url.php"; $cari = $_POST['cari']; $hasil = mysqli_query($konek,"select *,potongan+0 as diskon from buku where judul like '%$cari%' or penulis like '%$cari%' ORDER BY RAND()"); if (!$hasil) die("gagal memilih data karena : ".mysql_error($konek)); while ($data = mysqli_fetch_assoc($hasil)) { $data_dikirim[] = array("Kd_buku" => $data['kd_buku'],"Judul" => $data['judul']." Oleh ".$data['penulis'],"Harga" => $data['harga'],"Potongan" => $data['diskon'],"Gambar" => $url_web."data/gambar/".$data['kd_buku']."/".$data['gambar'],"Username" => $data['username']); } $buku = array("Buku" => $data_dikirim); echo json_encode($buku,JSON_UNESCAPED_SLASHES); ?><file_sep>/daftar.php <?php include "header.php"; ?> <!------------------------tambah buku----------------------> <table width="90%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.5);border-radius:5px;margin-top:15px;margin-bottom:85px;"> <tr> <td height="50" style="text-align:center"><h2>Menu Tambah Buku</h2><hr></td> </tr> <tr> <td style="vertical-align:top;"> <form action="service/daftar_buku.php" method="post" enctype="multipart/form-data"> <table width="80%" border="0" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.5);border-radius:15px;margin-top:5px;margin-bottom:25px;padding-top:25px;padding-bottom:25px;padding-right:30px"> <tr> <td></td><td></td><td colspan="2" style="text-align:center">Gambar sampul</td> </tr> <tr> <td height="10" width="20%" style="text-align:right">Kode Buku : </td><td><input type="text" name="kd_buku" style="width:80px" required></td><td rowspan="9" width="40%"> <label for="gambar" > <img width="100%" id="blah" style="background-color:rgba(0, 0, 0, 0.3);border-radius:15px" height="400" src="data/book.png"></img></td> </label> </tr> <tr> <td height="10" style="text-align:right">Judul Buku : </td><td><input type="text" name="judul_buku" required></td> </tr> <tr> <td height="10" style="text-align:right">Nama Penulis : </td><td><input type="text" name="penulis_buku" required></td> </tr> <tr> <td height="10" style="text-align:right">Harga : </td><td><input type="number" name="harga_buku" style="width:70px" required></td> </tr> <tr> <td height="10" style="text-align:right">Potongan : </td><td><input type="number" name="potongan_harga" style="width:50px" required> %</td> </tr> <tr> <td height="10" style="vertical-align:top;text-align:right" >Kategori : </td> <td style="vertical-align:top"> <select name="kategori" required> <option value=""> --pilih kategori-- </option> <?php $hasil = mysqli_query($konek,"select * from kategori"); if (!$hasil) die("gagal memilih data karena : ".mysql_error($konek)); while ($data = mysqli_fetch_assoc($hasil)) { echo "<option value='".$data['kd_kategori']."'>".$data['nama_kategori']."</option>"; } ?> </select> </td> </tr> <tr> <td style="text-align:right">gambar sampul : </td><td><input type="file" accept="image/*" name="gambar" onchange="readURL(this);" required></td> </tr> <tr> <td style="text-align:right">file buku : </td><td><input type="file" name="buku" accept="text/html" required></td> </tr> <tr> <td height="140" colspan="3"></td> </tr> <tr> <td style="text-align:center;" colspan="3"><br><input type="submit" value="Daftarkan Buku" style="width:30%;height:40px"></td> </tr> </table> </form> </td> </tr> </table> <table width="90%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.5);border-radius:5px;margin-top:15px;margin-bottom:15px"> <tr> <td height="50" style="text-align:center"><h2>Daftar Buku Dari <?php echo $_SESSION['nama_user_login'];?></h2><hr></td> </tr> <tr> <td style="vertical-align:top"> <table width="95%" border="1" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.3);border-radius:5px;margin-top:15px;margin-bottom:15px"> <tr style="text-align:center"> <td><h3>No</h3></td> <td><h3>Kode buku</h3></td> <td><h3>Judul</h3></td> <td><h3>Nama Penulis</h3></td> <td><h3>Harga Sewa</h3></td> <td><h3>Potongan</h3></td> <td><h3>Harga Total</h3></td> <td><h3>Gambar</h3></td> <td width="100"><h3>file</h3></td> <td><h3>Kategori</h3></td> <td colspan="2"><h3>Opsi</h3></td> </tr> <?php $hasil = mysqli_query($konek,"select b.*,k.*,format(b.harga-(b.harga*(b.potongan/100)),'##,###') as harga_total from buku b left join kategori k on k.kd_kategori = b.kd_kategori where b.username = '$user'"); if (!$hasil) die("gagal memilih data karena : ".mysql_error($konek)); if (mysqli_num_rows($hasil) > 0) { $no = 1; while ($data = mysqli_fetch_assoc($hasil)) { include "isi_daftar_buku.php"; $no++; } }else{ echo "<tr><td colspan='11' height='90' style='text-align:center'>Data Tidak Ditemukan</td></tr>"; } ?> </table> </td> </tr> </table> <?php include "footer.php"; ?><file_sep>/service/mau_login.php <?php include "koneksi.php"; session_start(); $username = htmlentities($_POST['username']); $password = htmlentities($_POST['password']); $sql = "select * from user where username = '$username'"; $hasil = mysqli_query($konek,$sql); if (!$hasil) die("gagal query user"); if (mysqli_num_rows($hasil) > 0) { $dt = mysqli_fetch_assoc($hasil); if ($dt['password'] == $password){ $_SESSION['nama_user_login'] = $dt['nama_user']; $_SESSION['username_login'] = $dt['username']; $_SESSION['gambar_login'] = $dt['gambar']; $_SESSION['tema_login'] = $dt['tema']; $_SESSION['akses_user_login'] = $dt['status']; $_SESSION['akses'] = "anggota"; header("location:../daftar.php"); }else { header("location:../index_user.php?msg=password salah!"); } }else{ header("location:../index_user.php?msg=username dan password salah!"); } ?><file_sep>/halaman_pengaturan_client.php <?php include "header_client.php"; ?> <form action="service/simpan_perubahan_akun_pelanggan.php" method="post"> <table width="90%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.3);border-radius:5px;margin-top:15px;margin-bottom:15px"> <tr> <td style="text-align:center" colspan="5"><h2>Edit Data Akun Anda</h2><hr></td> </tr> <tr> <td> <?php $sql_data_user = "select * from pelanggan where username = '$user'"; $hasil_data_user = mysqli_query($konek,$sql_data_user); if (!$hasil_data_user) die("gagal query user"); $dt_user = mysqli_fetch_assoc($hasil_data_user); $email = $dt_user['email']; $nomor = $dt_user['nomor_telp']; ?> <table width="60%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.4);border-radius:5px;margin-top:15px;margin-bottom:15px;padding-left:10px"> <tr> <td colspan="2" style="text-align:center"><h2>Data Lengkap Untuk user <?php echo $user;?></h2></td> </tr> <tr> <td width="60%">Edit Nama Lengkap : </td><td><input type="text" name="edit_nama" placeholder="<?php echo $_SESSION['nama_user_login']?>"></td> </tr> <tr> <td width="60%">Edit Password : </td><td><input type="<PASSWORD>" name="edit_password"></td> </tr> <tr> <td width="60%">Konfirmasi Password baru : </td><td><input type="<PASSWORD>" name="konfirmasi_password"><br></td> </tr> <tr> <td><br><br></td> </tr> <tr> <td>Edit Email : </td><td><input type="email" name="edit_email" placeholder="<?php echo $email?>"></td> </tr> <tr> <td>Edit Nomor Telephone : </td><td><input type="number" name="edit_nomor" placeholder="<?php echo $nomor?>"></td> </tr> <tr> <td><br><br></td> </tr> <tr> <td></td><td><br><br><br><button type="submit" value="<?php echo $user;?>" name="user_edit">Simpan Perubahan</button><br><br></td> </tr> </table> </form> </td> </tr> <tr> <td><br><br></td> </tr> </table> <?php include "footer_client.php"; ?><file_sep>/sql/proyek_web.sql -- MySQL dump 10.16 Distrib 10.1.16-MariaDB, for Win32 (AMD64) -- -- Host: localhost Database: proyek_web -- ------------------------------------------------------ -- Server version 10.1.16-MariaDB /*!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 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `buku` -- DROP TABLE IF EXISTS `buku`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `buku` ( `kd_buku` char(10) NOT NULL, `judul` varchar(100) DEFAULT NULL, `penulis` varchar(100) DEFAULT NULL, `harga` int(11) DEFAULT NULL, `potongan` int(11) DEFAULT NULL, `kd_kategori` char(10) DEFAULT NULL, `gambar` varchar(200) DEFAULT NULL, `direktori` varchar(200) DEFAULT NULL, `username` varchar(100) DEFAULT NULL, PRIMARY KEY (`kd_buku`), KEY `kd_kategori` (`kd_kategori`), KEY `username` (`username`), CONSTRAINT `buku_ibfk_1` FOREIGN KEY (`kd_kategori`) REFERENCES `kategori` (`kd_kategori`), CONSTRAINT `buku_ibfk_2` FOREIGN KEY (`username`) REFERENCES `user` (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `buku` -- LOCK TABLES `buku` WRITE; /*!40000 ALTER TABLE `buku` DISABLE KEYS */; INSERT INTO `buku` VALUES ('b001','laskar pelangi','mr asa',80,10,'k02','220px-Laskar_Pelangi_film.jpg','a.html','renosyah'),('b002','perjuangan','mr b',70,10,'k02','IMG.jpg','b.html','rikka'),('b003','si alan','mr k',50,10,'k01','ALAN_comic.jpg','b.html','renosyah'),('b004','caillou','mr c',50,10,'k02','sam.jpg','a.html','rikka'),('b005','digi charat nyo','mr j',70,10,'k01','57015.jpg','b.html','renosyah'),('b006','doraemon','mr l',40,10,'k01','6131733.jpg','b.html','rikka'),('b007','mari belajar masak','mrs z',80,10,'k02','masak.jpg','a.html','renosyah'),('b008','learn golang','mr c',60,10,'k06','go.png','b.html','rikka'),('b009','belajar php','mr php',100,10,'k06','cepat-mudah-small.png','b.html','renosyah'),('b010','belajar web node.js','mr node',105,10,'k06','pengenalan-nodejs.jpg','a.html','rikka'),('b011','sinchan','mr s',60,10,'k01','download.jpg','b.html','rikka'),('b012','belajar node','<NAME>',120,10,'k06','9781783287314.png','a.html','renosyah'); /*!40000 ALTER TABLE `buku` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `detail_user` -- DROP TABLE IF EXISTS `detail_user`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `detail_user` ( `username` varchar(100) DEFAULT NULL, `email` varchar(100) DEFAULT NULL, `jenis_kelamin` enum('pria','wanita') DEFAULT NULL, `alamat` varchar(100) DEFAULT NULL, `pekerjaan` varchar(100) DEFAULT NULL, `status_hubungan` enum('lajang','menikah') DEFAULT NULL, `no_telp` varchar(25) DEFAULT NULL, KEY `username` (`username`), CONSTRAINT `detail_user_ibfk_1` FOREIGN KEY (`username`) REFERENCES `user` (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `detail_user` -- LOCK TABLES `detail_user` WRITE; /*!40000 ALTER TABLE `detail_user` DISABLE KEYS */; INSERT INTO `detail_user` VALUES ('renosyah','<EMAIL>','pria','jl janti','mahasiswa','lajang','081214038236'),('rikka','<EMAIL>','wanita','jl kenangan','mahasiswa','lajang','081214038236'); /*!40000 ALTER TABLE `detail_user` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `gold_kategori` -- DROP TABLE IF EXISTS `gold_kategori`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `gold_kategori` ( `kd_gold` char(10) NOT NULL, `nama_gold` varchar(100) DEFAULT NULL, `jumlah` int(11) DEFAULT NULL, `deskripsi` varchar(100) DEFAULT NULL, `gambar` varchar(100) DEFAULT NULL, `harga` int(11) DEFAULT NULL, PRIMARY KEY (`kd_gold`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `gold_kategori` -- LOCK TABLES `gold_kategori` WRITE; /*!40000 ALTER TABLE `gold_kategori` DISABLE KEYS */; INSERT INTO `gold_kategori` VALUES ('g001','kantung penuh gold',8000,'Rp 10.000 untuk 8000 Gold','gold1.png',10000),('g002','tas penuh gold',16000,'Rp 20.000 untuk 16000 Gold','gold2.png',20000),('g003','karung penuh gold',32000,'Rp 35.000 untuk 32.000 Gold','gold3.png',35000),('g004','tumpukan penuh gold',64000,'Rp 68.000 untuk 64.000 Gold','gold4.png',68000),('g005','kotak penuh gold',78000,'Rp 82.000 untuk 78.000 Gold','gold5.png',81000),('g006','peti besar penuh gold',95000,'Rp 100.000 untuk 95.000 Gold','gold6.png',100000); /*!40000 ALTER TABLE `gold_kategori` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `info_buku_terbaru` -- DROP TABLE IF EXISTS `info_buku_terbaru`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `info_buku_terbaru` ( `judul` varchar(200) DEFAULT NULL, `isi` text, `gambar` varchar(200) DEFAULT NULL, `username` varchar(100) DEFAULT NULL, `tanggal_kadarluasa` date DEFAULT NULL, KEY `username` (`username`), CONSTRAINT `info_buku_terbaru_ibfk_1` FOREIGN KEY (`username`) REFERENCES `user` (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `info_buku_terbaru` -- LOCK TABLES `info_buku_terbaru` WRITE; /*!40000 ALTER TABLE `info_buku_terbaru` DISABLE KEYS */; /*!40000 ALTER TABLE `info_buku_terbaru` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `jual_gold` -- DROP TABLE IF EXISTS `jual_gold`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `jual_gold` ( `username` varchar(100) DEFAULT NULL, `kd_gold` char(10) DEFAULT NULL, `bukti_gambar` varchar(100) DEFAULT NULL, `tgl_pesan_gold` date DEFAULT NULL, `kd_jual_gold` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`kd_jual_gold`), KEY `username` (`username`), KEY `kd_gold` (`kd_gold`), CONSTRAINT `jual_gold_ibfk_1` FOREIGN KEY (`username`) REFERENCES `pelanggan` (`username`), CONSTRAINT `jual_gold_ibfk_2` FOREIGN KEY (`username`) REFERENCES `pelanggan` (`username`), CONSTRAINT `jual_gold_ibfk_3` FOREIGN KEY (`kd_gold`) REFERENCES `gold_kategori` (`kd_gold`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `jual_gold` -- LOCK TABLES `jual_gold` WRITE; /*!40000 ALTER TABLE `jual_gold` DISABLE KEYS */; /*!40000 ALTER TABLE `jual_gold` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `kategori` -- DROP TABLE IF EXISTS `kategori`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `kategori` ( `kd_kategori` char(10) NOT NULL, `nama_kategori` char(10) DEFAULT NULL, `ranting` int(11) DEFAULT NULL, PRIMARY KEY (`kd_kategori`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `kategori` -- LOCK TABLES `kategori` WRITE; /*!40000 ALTER TABLE `kategori` DISABLE KEYS */; INSERT INTO `kategori` VALUES ('k01','Komik',5),('k02','Edukasi',5),('k03','Cerpen',5),('k04','Cerpan',5),('k05','Artikel',5),('k06','Teknologi',5); /*!40000 ALTER TABLE `kategori` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `pelanggan` -- DROP TABLE IF EXISTS `pelanggan`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `pelanggan` ( `username` varchar(100) NOT NULL, `password` varchar(100) DEFAULT NULL, `nama` varchar(100) DEFAULT NULL, `gold` int(11) DEFAULT NULL, `email` varchar(100) DEFAULT NULL, `nomor_telp` varchar(25) DEFAULT NULL, PRIMARY KEY (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `pelanggan` -- LOCK TABLES `pelanggan` WRITE; /*!40000 ALTER TABLE `pelanggan` DISABLE KEYS */; INSERT INTO `pelanggan` VALUES ('renosyah','12345','<NAME>',100,'<EMAIL>','081214038236'),('rikka','12345','<NAME>',100,'<EMAIL>','081214038235'); /*!40000 ALTER TABLE `pelanggan` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `sewa_buku` -- DROP TABLE IF EXISTS `sewa_buku`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `sewa_buku` ( `kd_sewa_buku` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(100) DEFAULT NULL, `kd_buku` char(10) DEFAULT NULL, `durasi_hari_sewa` int(11) DEFAULT NULL, `tgl_sewa` date DEFAULT NULL, `tgl_berakhir` date DEFAULT NULL, `gold_sewa` int(11) DEFAULT NULL, PRIMARY KEY (`kd_sewa_buku`), KEY `username` (`username`), KEY `kd_buku` (`kd_buku`), CONSTRAINT `sewa_buku_ibfk_1` FOREIGN KEY (`username`) REFERENCES `pelanggan` (`username`), CONSTRAINT `sewa_buku_ibfk_2` FOREIGN KEY (`kd_buku`) REFERENCES `buku` (`kd_buku`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `sewa_buku` -- LOCK TABLES `sewa_buku` WRITE; /*!40000 ALTER TABLE `sewa_buku` DISABLE KEYS */; /*!40000 ALTER TABLE `sewa_buku` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `user` -- DROP TABLE IF EXISTS `user`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `user` ( `username` varchar(100) NOT NULL, `password` varchar(100) DEFAULT NULL, `nama_user` varchar(100) DEFAULT NULL, `gambar` varchar(100) DEFAULT NULL, `tema` varchar(100) DEFAULT NULL, `gaji_gold` int(11) DEFAULT NULL, `status` varchar(20) DEFAULT NULL, PRIMARY KEY (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `user` -- LOCK TABLES `user` WRITE; /*!40000 ALTER TABLE `user` DISABLE KEYS */; INSERT INTO `user` VALUES ('renosyah','12345','Reno Syahputra','reno.jpg','set1.css',0,'admin'),('rikka','12345','<NAME>','rikka.jpg','set1.css',0,'user'); /*!40000 ALTER TABLE `user` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!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 */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2017-05-14 12:59:29 <file_sep>/service/mau_login_pelanggan.php <?php include "koneksi.php"; session_start(); $username = htmlentities($_POST['username']); $password = htmlentities($_POST['password']); $sql = "select * from pelanggan where username = '$username'"; $hasil = mysqli_query($konek,$sql); if (!$hasil) die("gagal query user"); if (mysqli_num_rows($hasil) > 0) { $dt = mysqli_fetch_assoc($hasil); if ($dt['password'] == $password){ $_SESSION['nama_user_login'] = $dt['nama']; $_SESSION['username_login'] = $dt['username']; $_SESSION['akses'] = "pelanggan"; header("location:../halaman_buku_client.php"); }else { header("location:../index.php?msg=password salah!"); } }else{ header("location:../index.php?msg=username dan password salah!"); } ?><file_sep>/service/simpan_perubahan_akun.php <?php session_start(); include "koneksi.php"; $user_edit = $_POST['user_edit']; $nama_baru = $_POST['edit_nama']; $password_baru = $_POST['edit_password']; $konfirmasi_password_baru = $_POST['konfirmasi_password']; $email_baru = $_POST['edit_email']; $nomor_baru = $_POST['edit_nomor']; $jk_baru = $_POST['edit_jk']; $alamat_baru = $_POST['edit_alamat']; $pekerjaan_baru = $_POST['edit_pekerjaan']; $status_baru = $_POST['edit_status']; $name_foto_baru = $_FILES['edit_foto']['name']; $tmp_name_foto_baru = $_FILES['edit_foto']['tmp_name']; $type_foto_baru = $_FILES['edit_foto']['type']; $size_foto_baru = $_FILES['edit_foto']['size']; $foto_lama = $_POST['foto_lama']; if (strlen(trim($nama_baru)) > 0){ $sql = "update user set nama_user = '$nama_baru' where username = '$user_edit'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan nama baru anda!');self.history.back();</script>"; exit; } $_SESSION['nama_user_login'] = $nama_baru; } if (strlen(trim($password_baru)) > 0){ if ($password_baru != $konfirmasi_password_baru){ echo "<script>alert('password tidak cocok dengan konfirmasi!');self.history.back();</script>"; exit; } $sql = "update user set password = '$<PASSWORD>' where username = '$user_edit'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan password baru anda!');self.history.back();</script>"; exit; } } if (strlen(trim($email_baru)) > 0){ $sql = "update detail_user set email = '$email_baru' where username = '$user_edit'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan email baru anda!');self.history.back();</script>"; exit; } } if ($jk_baru != ""){ $sql = "update detail_user set jenis_kelamin = '$jk_baru' where username = '$user_edit'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan jenis kelamin baru anda!');self.history.back();</script>"; exit; } } if (strlen(trim($nomor_baru)) > 0){ $sql = "update detail_user set no_telp = '$nomor_baru' where username = '$user_edit'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan nomor baru anda!');self.history.back();</script>"; exit; } } if (strlen(trim($alamat_baru)) > 0){ $sql = "update detail_user set alamat = '$alamat_baru' where username = '$user_edit'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan alamat baru anda!');self.history.back();</script>"; exit; } } if (strlen(trim($pekerjaan_baru)) > 0){ $sql = "update detail_user set pekerjaan = '$pekerjaan_baru' where username = '$user_edit'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan pekerjaan baru anda!');self.history.back();</script>"; exit; } } if ($status_baru != ""){ $sql = "update detail_user set status_hubungan = '$status_baru' where username = '$user_edit'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan status baru anda!');self.history.back();</script>"; exit; } } $maxsize_foto = 1000000; $allowed_foto = array('image/png', 'image/jpg','image/jpeg'); $folder = "../data/user/$user_edit"; $dir_foto = $folder."/".$name_foto_baru; if ($size_foto_baru != 0){ if (!in_array($type_foto_baru, $allowed_foto)) { echo "<script>alert('gagal simpan!, tipe foto hanya bisa file gambar jpg dan png');self.history.back();</script>"; exit; } if ($size_foto_baru > $maxsize_foto) { echo "<script>alert('gagal simpan!, ukuran foto terlalu besar');self.history.back();</script>"; exit; } unlink($folder."/".$foto_lama); $sql = "update user set gambar = '$name_foto_baru' where username = '$user_edit'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan foto baru anda!');self.history.back();</script>"; exit; } $_SESSION['gambar_login'] = "$name_foto_baru"; move_uploaded_file($tmp_name_foto_baru, $dir_foto); } header("location:../pengaturan_akun_anggota.php"); ?><file_sep>/isi_halaman_buku_dipinjam.php <script src="data/w3.js"></script> <table border="0" width="90%" style="margin-left:auto;margin-right:auto;;border-radius:5px;margin-top:15px;margin-bottom:15px"> <?php $lihat_daftar_sewa = mysqli_query($konek,"select b.*,s.*,datediff(s.tgl_berakhir,curdate())+1 as hari_sisa from sewa_buku s left join buku b on b.kd_buku = s.kd_buku where s.username = '$user'"); if (!$lihat_daftar_sewa) die("gagal memilih data karena : ".mysql_error($konek)); if (mysqli_num_rows($lihat_daftar_sewa) == 0) { echo "<tr><td style='text-align:center'>Data tidak ditemukan, anda belum menyewa buku.<br><br> <a href='halaman_buku_client.php'>sewa sekarang</a></td></tr>"; } while ($data_disewa = mysqli_fetch_assoc($lihat_daftar_sewa)) { if ((int)$data_disewa['hari_sisa'] <= 0){ //biarin kosong } else { ?> <tr><td> <table border="0" id ="<?php echo $data_disewa['kd_buku']; ?>" width="80%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.5);border-radius:5px;margin-top:15px;margin-bottom:15px;"> <tr> <td style="text-align:center" colspan="2"><h2><?php echo $data_disewa['judul']." Oleh ".$data_disewa['penulis']; ?></h2><hr></td> </tr> <tr> <td style="text-align:center;vertical-align:top;color:orange" width="30%"><img width="100%" src="data/gambar/<?php echo $data_disewa['kd_buku']."/".$data_disewa['gambar'];?>"></img><br><?php echo "Durasi tersisa : ".$data_disewa['hari_sisa']." hari"; ?></td> <td rowspan="2" id="konten" width="70%" height="420" style="vertical-align:top;"> <div style="position:relative;overflow:auto;max-height:420px;" w3-include-html="data/gambar/<?php echo $data_disewa['kd_buku']."/".$data_disewa['direktori'];?>"></div><br> </td> </tr> <tr> <td style="text-align:center;"> </td> </tr> </table> <?php } } ?> </td> </tr> </table> <script> w3IncludeHTML(); </script> <file_sep>/mobile/daftar_buku_disewa.php <?php include "../service/koneksi.php"; include "url.php"; $cari = $_POST['username']; $hasil = mysqli_query($konek,"select b.*,s.*,datediff(s.tgl_berakhir,curdate())+1 as hari_sisa from sewa_buku s left join buku b on b.kd_buku = s.kd_buku where s.username = '$cari'"); if (!$hasil) die("gagal memilih data karena : ".mysql_error($konek)); while ($data = mysqli_fetch_assoc($hasil)) { if ((int)$data['hari_sisa'] <= 0){ }else { $data_dikirim[] = array("Kd_sewa" => $data['kd_sewa_buku'],"Judul" => $data['judul']." Oleh ".$data['penulis'],"Hari" => $data['hari_sisa'],"Url" => $url_web."data/gambar/".$data['kd_buku']."/".$data['direktori'],"Url_gambar" => $url_web."/data/gambar/".$data['kd_buku']."/".$data['gambar']); } } $buku = array("Daftar" => $data_dikirim); echo json_encode($buku,JSON_UNESCAPED_SLASHES); ?><file_sep>/isi_daftar_pelanggan.php <tr style="text-align:center"> <td height="50"><?php echo $no_p; ?></td> <td height="50"><?php echo $data_p['nama']; ?></td> <td height="50"><?php echo $data_p['username']; ?></td> <td height="50"><?php echo $data_p['buku_disewa']; ?></td> <td height="50" style="color:orange"><?php echo $data_p['gold']; ?> Gold</td> <td><button type="button" id="<?php echo $data_p['username']; ?>">Detail</button></td> </tr> <tr style="display:none;vertical-align:top" id="button<?php echo $data_p['username']; ?>"> <td colspan="6"> <table width="70%" border="0" style="padding-left:15px;padding-right:15px;margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.3);border-radius:5px;margin-top:15px;margin-bottom:15px"> <tr> <td colspan="2" style="text-align:center"><h2>keterangan Buku-Buku anda yang disewa Oleh <?php echo $data_p['nama']; ?><hr></h2></td> </tr> <?php $username_pelanggan = $data_p['username']; $hasil_disewa = mysqli_query($konek,"select s.kd_sewa_buku as kd_sewa_buku,s.kd_buku as kd_buku, b.gambar as gambar,b.judul as judul,b.penulis as penulis,b.harga as harga,b.potongan as potongan,format(b.harga*s.durasi_hari_sewa-((b.harga*s.durasi_hari_sewa) * (b.potongan/100)),'###,##') as total,datediff(s.tgl_berakhir,curdate())+1 as hari_sewa from sewa_buku s left join buku b on b.kd_buku = s.kd_buku where s.username = '$username_pelanggan' and b.username = '$user'"); if (!$hasil_disewa) die("gagal memilih data karena : ".mysql_error($konek)); if (mysqli_num_rows($hasil_disewa) > 0) { $no_disewa=1; while ($data_disewa = mysqli_fetch_assoc($hasil_disewa)) { if ((int)$data_disewa['hari_sewa'] <= 0){ echo "<tr>"; echo "<tr><td>Judul Buku : ".$data_disewa['judul']."</td><td rowspan='7'><img width='200' height='300' src='data/gambar/".$data_disewa['kd_buku']."/".$data_disewa['gambar']."'></img></td></tr>"; echo "<tr><td>Nama Penulis :".$data_disewa['penulis']."</td></tr>"; echo "<tr><td>Harga sewa : ".$data_disewa['harga']." Gold</td></tr>"; echo "<tr><td>Potongan harga : ".$data_disewa['potongan']." %</td></tr>"; echo "<tr><td>Durasi Hari Sewa : <a style='color:red'>Waktu sewa Telah Habis</a></td></tr>"; echo "<tr><td>Total Harga sewa : ".$data_disewa['total']." Gold</td></tr>"; echo "<tr><td height='200'></td></tr>"; echo "<tr><form action='service/hapus_sewa_buku.php' method='post'><td style='text-align:center'><button style='width:30%' name='kd_sewa' value='".$data_disewa['kd_sewa_buku']."'>Hapus</button></td></tr>"; echo "<tr><td colspan='2'><hr></td></tr>"; echo "</tr>"; } else{ echo "<tr>"; echo "<tr><td>Judul Buku : ".$data_disewa['judul']."</td><td rowspan='7'><img width='200' height='300' src='data/gambar/".$data_disewa['kd_buku']."/".$data_disewa['gambar']."'></img></td></tr>"; echo "<tr><td>Nama Penulis :".$data_disewa['penulis']."</td></tr>"; echo "<tr><td>Harga sewa : ".$data_disewa['harga']." Gold</td></tr>"; echo "<tr><td>Potongan harga : ".$data_disewa['potongan']." %</td></tr>"; echo "<tr><td>Durasi Hari Sewa : ".$data_disewa['hari_sewa']." Hari</td></tr>"; echo "<tr><td>Total Harga sewa : ".$data_disewa['total']." Gold</td></tr>"; echo "<tr><td height='200'></td></tr>"; echo "<tr><td colspan='2'><hr></td></tr>"; echo "</tr>"; } $no_disewa++; } }else{ echo "<tr>"; echo "<td style='text-align:center;padding-bottom:5px' height='90'>data tidak ditemukan, pelanggan belum menyewa buku anda.</td>"; echo "</tr>"; } ?> </table> </td> </tr> <script> $(document).ready(function(){ $('#<?php echo $data_p['username']; ?>').click(function(){ $('#button<?php echo $data_p['username']; ?>').toggle();});}); </script><file_sep>/service/mau_daftar_pelanggan.php <?php include "koneksi.php"; session_start(); $nama = $_POST['nama']; $email = $_POST['email']; $no = $_POST['telp']; $username = $_POST['username']; $password = $_POST['password']; $password_konfirmasi = $_POST['password_konfir']; if (strlen(trim($nama)) < 0){ echo "<script>alert('gagal simpan!, nama harap diisi');self.history.back();</script>"; exit; } if (strlen(trim($email)) < 0){ echo "<script>alert('gagal simpan!, email harap diisi');self.history.back();</script>"; exit; } if (strlen(trim($no)) < 0){ echo "<script>alert('gagal simpan!, nomor telephone harap diisi,untuk kepentingan transaksi');self.history.back();</script>"; exit; } if (strlen(trim($username)) < 0){ echo "<script>alert('gagal simpan!, harap username harap diisi');self.history.back();</script>"; exit; } if (strlen(trim($password)) < 0){ echo "<script>alert('gagal simpan!, password harap diisi');self.history.back();</script>"; exit; } if ($password_konfirmasi != $password){ echo "<script>alert('gagal simpan!, password dan konfirmasi password tidak sama');self.history.back();</script>"; exit; } $sql_pelanggan = "insert into pelanggan (username,password,email,nomor_telp,nama,gold) values ('$username','$password','$email','$no','$nama',100)"; $insert_data = mysqli_query($konek,$sql_pelanggan); if (!$insert_data){ echo "<script>alert('gagal simpan pelanggan baru!,username telah digunakan orang lain');self.history.back();</script>"; exit; } $_SESSION['nama_user_login'] = $nama; $_SESSION['username_login'] = $username; $_SESSION['akses'] = "pelanggan"; header("location:../halaman_buku_client.php"); ?><file_sep>/aturan_umum.php <?php include "header.php"; ?> <table width="90%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.5);border-radius:5px;margin-top:15px;margin-bottom:15px"> <tr> <td style="text-align:center" colspan="5"><h2>Daftar Info</h2><hr></td> </tr> <tr> <td> <table width="80%" border="1" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.5);border-radius:5px;margin-top:15px;margin-bottom:15px"> <tr style="text-align:center"> <td>No</td> <td>Oleh User</td> <td>Judul</td> <td>Isi</td> <td>Gambar</td> </tr> <?php $hasil = mysqli_query($konek,"select * from info_buku_terbaru"); if (!$hasil) die("gagal memilih data karena : ".mysql_error($konek)); $no=1; if (mysqli_num_rows($hasil) == 0) { echo "<td style='text-align:center' colspan='5' height='100'>Belum ada info terbaru saat ini.</td>"; }else{ while ($data = mysqli_fetch_assoc($hasil)) { echo "<tr style='text-align:center;vertical-align:top'>"; echo "<td>$no</td>"; echo "<td>".$data['username']."</td>"; echo "<td>".$data['judul']."</td>"; echo "<td>".$data['isi']."</td>"; echo "<td><img width='200' height=250' src='data/info/".$data['judul']."/".$data['gambar']."'></img></td>"; echo "</tr>"; $no++; } } ?> </table> </td> </tr> </table> <table width="90%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.5);border-radius:5px;margin-top:105px;margin-bottom:15px"> <tr> <td style="text-align:center"><h2>Menu input Informasi</h2><hr></td> </tr> <tr> <td> <form action="service/input_info.php" method="post" enctype="multipart/form-data"> <table width="80%" border="0" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.5);border-radius:5px;margin-top:15px;margin-bottom:15px"> <tr> <td style="text-align:center" colspan="4" height="50"></td> </tr> <tr> <td width="5%"></td><td>Judul :</td><td><input type="text" name="judul" required></td></td><td width="40%" rowspan="5" style="text-align:center;vertical-align:top"><label for="gambar"><img width="90%" height="330" src="data/book.png" id="blah" style="background-color:rgba(0, 0, 0, 0.3);margin-right:50px"></label></td> </tr> <tr> <td></td><td>isi :</td><td><textarea name="isi" required style="width:300px;height:200px;"></textarea> </tr> <tr> <td width="15"></td><td>gambar :</td><td><input type="file" name="gambar" onchange="readURL2(this);" required></td> </tr> <tr> <td></td><td colspan="2" style="text-align:center"><input type="submit" value="kirimkan"></td> </tr> <tr> <td width="15"></td><td height="200" colspan="2"><p>harap memasukkan info yg berguna dan menarik bagi pelanggan, jangan memberi janji yang tidak bisa anda penuhi atau buku anda tidak akan disewa dan dibaca oleh pelanggan</p></td> </tr> <tr> <td width="15"></td><td colspan="4" height="30"></td> </tr> </table> </form> </td> </tr> </table> <?php include "footer.php"; ?><file_sep>/service/koneksi.php <?php $host = "mysql.idhostinger.com"; $username = "u246284403_renos"; $password = "<PASSWORD>"; $dbname = "u246284403_paw"; $konek = @mysqli_connect($host,$username,$password,$dbname); if (!$konek) { die("gagal koneksi karena : ".mysqli_connect_error()); } function rmdir_recursive($dir) { foreach(scandir($dir) as $file) { if ('.' === $file || '..' === $file) continue; if (is_dir("$dir/$file")) rmdir_recursive("$dir/$file"); else unlink("$dir/$file"); } rmdir($dir); } ?><file_sep>/mobile/daftar_gold.php <?php include "../service/koneksi.php"; include "url.php"; $username = $_POST['username']; $sql_cek = "select * from jual_gold where username = '$username'"; $hasil_cek = mysqli_query($konek,$sql_cek); if (!$hasil_cek) die("gagal query pelanggan"); if (mysqli_num_rows($hasil_cek) > 0) { $sql2 = "select * from pelanggan where username = '$username'"; $hasil_goldku2 = mysqli_query($konek,$sql2); if (!$hasil_goldku2) die("gagal query pelanggan"); $dt2 = mysqli_fetch_assoc($hasil_goldku2); $buku = array("Goldku" => $dt2['gold'],"Gold" => null); echo json_encode($buku,JSON_UNESCAPED_SLASHES); }else{ $sql = "select * from pelanggan where username = '$username'"; $hasil_goldku = mysqli_query($konek,$sql); if (!$hasil_goldku) die("gagal query pelanggan"); $dt = mysqli_fetch_assoc($hasil_goldku); $hasil = mysqli_query($konek,"select *,format(harga,'###,##') as harga_f,format(jumlah,'###,##') as jumlah_f from gold_kategori"); if (!$hasil) die("gagal memilih data karena : ".mysql_error($konek)); while ($data = mysqli_fetch_assoc($hasil)) { $data_dikirim[] = array("Kd_gold" => $data['kd_gold'],"Nama_gold" => $data['nama_gold'],"Harga" => "Rp ".$data['harga_f'],"Potongan" => "","Gambar" => $url_web."data/gold/".$data['kd_gold']."/".$data['gambar'],"Deskripsi" => $data['deskripsi'],"Jumlah" => "Gold ".$data['jumlah_f']); } $buku = array("Goldku" => $dt['gold'],"Gold" => $data_dikirim); echo json_encode($buku,JSON_UNESCAPED_SLASHES); } ?><file_sep>/mobile/simpan_perubahan_akun_pelanggan.php <?php include "../service/koneksi.php"; $user_edit = $_POST['user_edit']; $nama_baru = $_POST['edit_nama']; $password_baru = $_POST['edit_password']; $email_baru = $_POST['edit_email']; $nomor_baru = $_POST['edit_nomor']; if (strlen(trim($nama_baru)) > 0){ $sql = "update pelanggan set nama = '$nama_baru' where username = '$user_edit'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ $respon = array("Respon" => false); echo json_encode($respon); exit; } $_SESSION['nama_user_login'] = $nama_baru; } if (strlen(trim($password_baru)) > 0){ $sql = "update pelanggan set password = '$<PASSWORD>' where username = '$user_edit'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ $respon = array("Respon" => false); echo json_encode($respon); exit; } } if (strlen(trim($email_baru)) > 0){ $sql = "update pelanggan set email = '$email_baru' where username = '$user_edit'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ $respon = array("Respon" => false); echo json_encode($respon); exit; } } if ($nomor_baru != ""){ $sql = "update pelanggan set nomor_telp = '$nomor_baru' where username = '$user_edit'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ $respon = array("Respon" => false); echo json_encode($respon); exit; } } $respon = array("Respon" => true); echo json_encode($respon); ?><file_sep>/mobile/detail_mausewa.php <?php include "../service/koneksi.php"; $username = $_POST['username']; $sql = "select * from pelanggan where username = '$username'"; $hasil = mysqli_query($konek,$sql); if (!$hasil) die("gagal query pelanggan"); if (mysqli_num_rows($hasil) > 0) { $dt = mysqli_fetch_assoc($hasil); $data = array("Username" => $dt['username'],"Gold" => $dt['gold']); echo json_encode($data); } ?> <file_sep>/isi_halaman_buku_client.php <form action="service/mau_sewa_buku.php" method="post"> <div style="background-image:url(data/gambar/<?php echo $data['kd_buku']; ?>/<?php echo $data['gambar']; ?>);<?php echo $ukuran; ?>;margin-left:auto;margin-right:auto;margin-top:15px;margin-bottom:15px;background-repeat:no-repeat;background-size:cover;height:40%;padding-bottom:-10px;padding-top:150px;border-radius:15px;background-size: 100% 100%"> <table width="100%" border="0" style="background-color:rgba(0, 0, 0, 0.6);border-radius:15px"> <tr> <td style="text-align:center;"> <h3 style=";border-radius:15px;"><?php echo $data['judul']; ?></h3> Penulis : <?php echo $data['penulis']; ?><br> Kategori : <?php echo $data['kategori']; ?><br> Harga : <a style="color:orange;text-shadow: 1px 1px white">Gold <?php echo $data['harga_baru']; ?></a><br> <strike style="color:grey">Harga : Gold <?php echo $data['harga']; ?></strike><br><br> <br>Durasi hari sewa :<br><br>Durasi <input type="number" name="hari" style="width:50px;text-align:center" value="1"> Hari<br> <input type="hidden" name="kd_buku" value="<?php echo $data['kd_buku']; ?>"> <input type="hidden" value="<?php echo $user; ?>" name="username"> <input type="hidden" value="<?php echo $data['harga_baru']; ?>" name="gold"> <input type="hidden" value="<?php echo $data['username']; ?>" name="username_pemilik"><br> <button type="submit" onclick="return confirm('apakah anda yakin ingin menyewa buku <?php echo $data['judul']; ?>?')">Sewa Sekarang!</button><br><br> </td> </tr> </table> </div> </form> <file_sep>/mobile/login.php <?php include "../service/koneksi.php"; $username = htmlentities($_POST['username']); $password = htmlentities($_POST['password']); $sql = "select * from pelanggan where username = '$username'"; $hasil = mysqli_query($konek,$sql); if (!$hasil) die("gagal query pelanggan"); if (mysqli_num_rows($hasil) > 0) { $dt = mysqli_fetch_assoc($hasil); if ($dt['password'] == $password) { $ijin = array("Username" => $dt['username'],"Name" => $dt['nama'],"Ijin" => true); echo json_encode($ijin); } else { $ijin_gagal = array("Username" => "","Name" => "","Ijin" => false); echo json_encode($ijin_gagal); } } else { $ijin_gagal = array("Username" => "","Name" => "","Ijin" => false); echo json_encode($ijin_gagal); } ?><file_sep>/service/daftar_buku.php <?php include "koneksi.php"; session_start(); $user = $_SESSION['username_login']; $kd_buku = $_POST['kd_buku']; $judul_buku = $_POST['judul_buku']; $penulis = $_POST['penulis_buku']; $harga_buku = $_POST['harga_buku']; $potongan = $_POST['potongan_harga']; $kategori = $_POST['kategori']; $name_sampul = $_FILES['gambar']['name']; $tmp_name_sampul = $_FILES['gambar']['tmp_name']; $type_sampul = $_FILES['gambar']['type']; $size_sampul = $_FILES['gambar']['size']; $name_buku = $_FILES['buku']['name']; $tmp_name_buku = $_FILES['buku']['tmp_name']; $type_buku = $_FILES['buku']['type']; $size_buku = $_FILES['buku']['size']; //---------------------------------------------validasi-------------------------------------------------------- if (strlen(trim($judul_buku)) < 0){ echo "<script>alert('gagal simpan!, judul buku harap diisi');self.history.back();</script>"; exit; } if (strlen(trim($penulis)) < 0){ echo "<script>alert('gagal simpan!, penulis buku harap diisi');self.history.back();</script>"; exit; } if (strlen(trim($harga_buku)) < 0){ echo "<script>alert('gagal simpan!,harga buku harap diisi');self.history.back();</script>"; exit; } if ((int)$harga_buku > 500){ echo "<script>alert('gagal simpan!, harga tidak boleh lebih dari 500');self.history.back();</script>"; exit; } if (strlen(trim($potongan)) < 0){ echo "<script>alert('gagal simpan!, potongan buku harap diisi, setidaknya 0 aja');self.history.back();</script>"; exit; } if (strlen(trim($kategori)) < 0){ echo "<script>alert('gagal simpan!,kategori buku harap dipilih');self.history.back();</script>"; exit; } $maxsize_sampul = 1000000; $allowed_sampul = array('image/png', 'image/jpg','image/jpeg'); $maxsize_file = 1000000; $allowed_file = array('text/html'); if (!in_array($type_sampul, $allowed_sampul)) { echo "<script>alert('gagal simpan!, tipe hanya bisa jpg dan png');self.history.back();</script>"; exit; } if ($size_sampul > $maxsize_sampul) { echo "<script>alert('gagal simpan!, ukuran sampul terlalu besar');self.history.back();</script>"; exit; } if (!in_array($type_buku, $allowed_file)) { echo "<script>alert('gagal simpan!, tipe buku hanya bisa html');self.history.back();</script>"; exit; } if ($size_buku > $maxsize_file) { echo "<script>alert('gagal simpan!, ukuran buku terlalu besar');self.history.back();</script>"; exit; } //---------------------------------------------validasi-------------------------------------------------------- $buat_folder = "../data/gambar/$kd_buku"; mkdir($buat_folder, 0755, true); $sql = "insert into buku values ('$kd_buku','$judul_buku','$penulis','$harga_buku','$potongan','$kategori','$name_sampul','$name_buku','$user')"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan!');self.history.back();</script>"; exit; } $dir_foto = $buat_folder."/".$name_sampul; $dir_file = $buat_folder."/".$name_buku; move_uploaded_file($tmp_name_sampul, $dir_foto); move_uploaded_file($tmp_name_buku, $dir_file); $myfile = fopen("$buat_folder/index.php", "w") or die("Unable to open file!"); $txt = "<?php header('location:../../../daftar.php') ?>;"; fwrite($myfile, $txt); fclose($myfile); header("location:../daftar.php"); ?><file_sep>/header_client.php <html> <?php include "service/koneksi.php"; session_start(); if (!$_SESSION['nama_user_login']){ header("location:index.php?msg=anda harus login!"); } if ($_SESSION['akses'] == "anggota"){ header("location:index.php?msg=ini ranah pelanggan"); } $user = $_SESSION['username_login']; $sql = "select * from pelanggan where username = '$user'"; $hasil = mysqli_query($konek,$sql); if (!$hasil) die("gagal query user"); $dt = mysqli_fetch_assoc($hasil); ?> <head> <style type="text/css"> @import url(data/set1.css); </style> <title>Penyewaan E-book</title> </head> <script src="data/my_jquerry.js"></script> <body> <table width="100%" id="head" border="0"> <tr> <td width="25%"></td><td height="190" style="text-align:center"><h1>Penyewaan E-Book</h1></td> <td style="text-align:right;padding-right:10px"> </td> <td width="20%" style="text-align:left"> Nama : <?php echo $_SESSION['nama_user_login'];?><br> Username : <?php echo $_SESSION['username_login'];?><br> <a style="color:orange;text-shadow: 1px 1px white">Gold : <?php echo number_format($dt['gold']);?></a><br> <a style="font-size:18px" href="service/logout.php">Logout</a> </td> </tr> </table> <table width="100%" id="tabelku" style="text-align:center;margin-top:20px;background-color:rgba(0, 0, 0, 0.5);border-radius: 10px;"> <tr> <td width="5%"></td> <td height="40"><a href="halaman_buku_client.php">Daftar Buku Tersedia</a></td> <td><a href="halaman_buku_dipinjam_client.php">Buku Disewa</a></td> <td><a href="halaman_beli_gold_client.php">Beli Gold</a></td> <td><a href="halaman_informasi_client.php">Info Buku Terbaru</a></td> <td><a href="halaman_pengaturan_client.php">Pengaturan akun</a></td> <td width="5%"></td> </tr> </table> <file_sep>/isi_list_user.php <tr style="text-align:center"> <td height="50"><?php echo $no;?></td> <td><?php echo $dt['nama_user'];?></td> <td><?php echo $dt['username'];?></td> <td style="color:orange"><?php echo $dt['gaji_gold']?> Gold</td> <td><?php echo $dt['no_telp']?></td> <td><?php echo $dt['email']?></td> <td><?php echo $dt['status']?></td> <td><button type="button" id="tombol_detail_user_<?php echo $dt['username'];?>">Detail</button></td> </tr> <tr id="detail_user_<?php echo $dt['username'];?>" style="display:none"> <td colspan="8" height="400"> <table width="80%" border="0" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.5);border-radius:5px;margin-top:15px;margin-bottom:15px;"> <tr style="vertical-align:top;text-align:center"> <td colspan="2"><h2>Detail User untuk user <?php echo $dt['username'];?></h2><hr></td> </tr> <tr style="vertical-align:top;text-align:center"> <td rowspan="10" height="370" width="40%">Foto Profil<br> <img src="data/user/<?php echo $dt['username'];?>/<?php echo $dt['gambar'];?>" height="80%" width="80%"></img> </td> </tr> <tr> <td>Nama Lengkap : <?php echo $dt['nama_user'];?></td> </tr> <tr> <td>Username : <?php echo $dt['username'];?></td> </tr> <tr> <td>Nomor : <?php echo $dt['no_telp'];?></td> </tr> <tr> <td>Email : <?php echo $dt['email'];?></td> </tr> <tr> <td>Jenis Kelamin : <?php echo $dt['jenis_kelamin'];?></td> </tr> <tr> <td>Alamat : <?php echo $dt['alamat'];?></td> </tr> <tr> <td>Pekerjaan : <?php echo $dt['pekerjaan'];?></td> </tr> <tr> <td>Status Hubungan : <?php echo $dt['status_hubungan'];?></td> </tr> <tr> <td height="20%"></td> </tr> </table> </td> </tr> <script> $(document).ready(function(){ $('#tombol_detail_user_<?php echo $dt['username'];?>').click(function(){ $('#detail_user_<?php echo $dt['username'];?>').toggle();});}); </script><file_sep>/service/hapus_pesan_gold.php <?php include "koneksi.php"; $kd_tansaksi = $_POST['hapus']; $username_pelanggan = $_POST['username_pelanggan']; $delete_transaksi = "delete from jual_gold where kd_jual_gold = '$kd_tansaksi'"; $pesanan_gold_delete = mysqli_query($konek,$delete_transaksi); if (!$pesanan_gold_delete) die("gagal menghapus data"); $folder_transaksi = "../data/transaksi/$username_pelanggan"; rmdir_recursive($folder_transaksi); header("location:../jual_gold.php"); ?><file_sep>/halaman_beli_gold_client.php <?php include "header_client.php"; ?> <table width="98%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.3);border-radius:5px;margin-bottom:15px;margin-top:-4px"> <tr> <td style="text-align:center" colspan="3"><h2>Beli Gold</h2><hr></td> </tr> <tr> <br> <?php $sql_cek = "select * from jual_gold where username = '$user'"; $hasil_cek = mysqli_query($konek,$sql_cek); if (!$hasil_cek) die("gagal query pelanggan"); if (mysqli_num_rows($hasil_cek) > 0) { echo "<td style='text-align:center'>"; echo "maaf, anda tidak dapat membeli gold karena transaksi untuk gold anda sebelumnya masih diproses."; echo "</td>"; }else { $no_gold = 0; $hasil = mysqli_query($konek,"select * from gold_kategori"); if (!$hasil) die("gagal memilih data karena : ".mysql_error($konek)); while ($data = mysqli_fetch_assoc($hasil)) { $no_gold++; echo "<td style='vertical-align:top' width='30%'>"; include "isi_halaman_beli_gold_client.php"; echo "</td>"; if ($no_gold % 3 == 0){ echo "</tr>"; echo "<tr>"; }else { } } } ?> </tr> </table> <?php include "footer_client.php"; ?><file_sep>/service/hapus_sewa_buku.php <?php include "koneksi.php"; $kd_sewa = $_POST['kd_sewa']; $sql = "delete from sewa_buku where kd_sewa_buku = '$kd_sewa'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal menghapus daftar sewa buku yg dipilih!');self.history.back();</script>"; exit; } header("location:../pelanggan.php"); ?><file_sep>/service/input_info.php <?php include "koneksi.php"; session_start(); $user = $_SESSION['username_login']; $judul = $_POST['judul']; $isi = $_POST['isi']; $name_gambar = $_FILES['gambar']['name']; $tmp_name_gambar = $_FILES['gambar']['tmp_name']; $type_gambar = $_FILES['gambar']['type']; $size_gambar = $_FILES['gambar']['size']; $buat_folder = "../data/info/$judul"; mkdir($buat_folder, 0755,true); $sql = "insert into info_buku_terbaru values ('$judul','$isi','$name_gambar','$user',curdate() + interval 5 day)"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan!');self.history.back();</script>"; exit; } $dir_foto = $buat_folder."/".$name_gambar; move_uploaded_file($tmp_name_gambar, $dir_foto); header("location:../aturan_umum.php"); ?><file_sep>/mobile/info_buku.php <?php include "../service/koneksi.php"; include "url.php"; $hasil = mysqli_query($konek,"select * from info_buku_terbaru"); if (!$hasil) die("gagal memilih data karena : ".mysql_error($konek)); while ($data = mysqli_fetch_assoc($hasil)) { $data_array[] = array("Judul" => $data['judul'],"Isi" => $data['isi'],"Gambar" => $url_web."data/info/".rawurlencode($data['judul'])."/".$data['gambar']); } $data_array = array("Info" => $data_array); echo json_encode($data_array,JSON_UNESCAPED_SLASHES); ?><file_sep>/service/hapus_buku.php <?php include "koneksi.php"; $kd_buku = $_POST['hapus']; $folder = "../data/gambar/$kd_buku"; $sql = "delete from buku where kd_buku = '$kd_buku'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal menghapus buku!, buku sedang disewa oleh pelanggan.');self.history.back();</script>"; exit; } else { rmdir_recursive($folder); } header("location:../daftar.php"); ?><file_sep>/halaman_buku_dipinjam_client.php <?php include "header_client.php"; ?> <table width="90%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.3);border-radius:5px;margin-top:15px;margin-bottom:15px"> <tr> <td style="text-align:center"><h2>Daftar Buku Disewa</h2><hr></td> </tr> <tr> <td style="text-align:center"> <?php include "isi_halaman_buku_dipinjam.php"; ?> </td> </tr> </table> <?php include "footer_client.php"; ?><file_sep>/mobile/data_akun_pelanggan.php <?php include "../service/koneksi.php"; $username = $_POST['username']; $sql = "select * from pelanggan where username = '$username'"; $hasil = mysqli_query($konek,$sql); if (!$hasil) die("gagal query pelanggan"); $dt = mysqli_fetch_assoc($hasil); $ijin = array("Nama" => $dt['nama'],"Email" => $dt['email'],"Nomor" => $dt['nomor_telp']); echo json_encode($ijin); ?><file_sep>/header.php <html> <?php include "service/koneksi.php"; session_start(); if (!$_SESSION['nama_user_login']) { header("location:index_user.php?msg=anda harus login!"); } if ($_SESSION['akses'] == "pelanggan"){ echo "<script>self.history.back();</script>"; header("location:index.php?msg=anda harus login sebagai user!"); } $user = $_SESSION['username_login']; $sql = "select * from user where username = '$user'"; $hasil = mysqli_query($konek,$sql); if (!$hasil) die("gagal query user"); $dt = mysqli_fetch_assoc($hasil); ?> <head> <style type="text/css"> @import url(data/<?php echo $dt['tema'];?>); </style> <title>Penyewaan E-book</title> </head> <script src="data/my_jquerry.js"></script> <script> function readURL(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#blah') .attr('src', e.target.result) .width(400) .height(400); }; reader.readAsDataURL(input.files[0]); } } function readURL2(input) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $('#blah') .attr('src', e.target.result) .width(300) .height(330); }; reader.readAsDataURL(input.files[0]); } } function tema_set(form,option){ var form = document.getElementById(form); document.getElementById(option).addEventListener("click", function () { form.submit();}); } </script> <script> //document.addEventListener('contextmenu', event => event.preventDefault()); </script> <body> <table width="100%" id="head" border="0"> <tr> <td width="25%"></td><td height="190" style="text-align:center"><h1>Penyewaan E-Book</h1></td> <td style="text-align:right;padding-right:10px"> <img width="55" height="60" style="border-radius:30px;margin-bottom:40px" src="data/user/<?php echo $_SESSION['username_login']."/".$_SESSION['gambar_login'];?>"></img></td> <td width="20%" style="text-align:left"> Nama : <?php echo $_SESSION['nama_user_login'];?><br> Username : <?php echo $_SESSION['username_login'];?><br> Status : <?php echo $_SESSION['akses_user_login'];?><br> <a style="color:orange;text-shadow: 1px 1px white">Gold didapat : <?php echo number_format($dt['gaji_gold']);?></a><br> <form action="service/ubah_tema.php" method="post" id="tema_form"> <select id="tema" name="tema" onclick="tema_set('tema_form','tema')"> <option value="set1.css" disabled selected>Pilih Tema</option> <option value="set1.css">Glossy Blue</option> <option value="set2.css">Beach</option> <option value="set3.css">Lake</option> <option value="set4.css">Mountain</option> </select> </form> <a style="font-size:18px" href="service/logout_user.php">Logout</a> </td> </tr> </table> <table width="100%" id="tabelku" style="text-align:center;margin-top:20px;background-color:rgba(0, 0, 0, 0.5);border-radius: 10px;"> <tr> <td width="5%"></td> <td height="40"><a href="daftar.php">Daftar Buku</a></td> <td><a href="pelanggan.php">Pelanggan</a></td> <td><a href="aturan_umum.php">Input Informasi</a></td> <td><a href="jual_gold.php" style="<?php echo ($_SESSION['akses_user_login']!="admin")?"display:none":"";?>">Pesanan Gold</a></td> <td><a href="list_user.php" >User & Penulis</a></td> <td><a href="pengaturan_akun_anggota.php">Pengaturan akun</a></td> <td width="5%"></td> </tr> </table> <file_sep>/service/mau_sewa_buku.php <?php include "koneksi.php"; $kd_buku = $_POST['kd_buku']; $username_pelanggan = $_POST['username']; $hari_sewa = $_POST['hari']; $gold = $_POST['gold']; $username_pemilik = $_POST['username_pemilik']; if ((int) $hari_sewa <= 0) { echo "<script>alert('harap memasukkan data hari dengan benar!');self.history.back();</script>"; exit; } $sql_validasi_gold = "select gold-($gold * $hari_sewa) as valid_gold from pelanggan where username = '$username_pelanggan'"; $validasi_gold = mysqli_query($konek,$sql_validasi_gold); if (!$validasi_gold) die("gagal query gold pelanggan"); $dt = mysqli_fetch_assoc($validasi_gold); if ((int)$dt['valid_gold'] < 0 ){ echo "<script>alert('maaf, gold anda tidak cukup untuk menyewa buku ini!');self.history.back();</script>"; exit; } //------------------------- $sql = ""; $sql_lihat_buku_sblmnya = "select * ,datediff(tgl_berakhir,curdate())+1 as hari_sisa from sewa_buku where username = '$username_pelanggan' and kd_buku = '$kd_buku'"; $lihat_histori = mysqli_query($konek,$sql_lihat_buku_sblmnya); if (!$lihat_histori) die("gagal query buku disewa"); if (mysqli_num_rows($lihat_histori) > 0){ $hasil_kode_sewa = mysqli_fetch_assoc($lihat_histori); $hasil_kd_sewa_buku = $hasil_kode_sewa['kd_sewa_buku']; $hari_sisa = $hasil_kode_sewa['hari_sisa']; if ((int)$hari_sisa <= 0){ $sql = "update sewa_buku set durasi_hari_sewa = durasi_hari_sewa + $hari_sewa,tgl_berakhir = curdate() + interval $hari_sewa day,gold_sewa = gold_sewa + ($gold * $hari_sewa) where kd_sewa_buku = '$hasil_kd_sewa_buku'"; } else { $sql = "update sewa_buku set durasi_hari_sewa = durasi_hari_sewa + $hari_sewa,tgl_berakhir = tgl_berakhir + interval $hari_sewa day,gold_sewa = gold_sewa + ($gold * $hari_sewa) where kd_sewa_buku = '$hasil_kd_sewa_buku'"; } } else { $sql = "insert into sewa_buku (username,kd_buku,durasi_hari_sewa,tgl_sewa,tgl_berakhir,gold_sewa) values ('$username_pelanggan','$kd_buku','$hari_sewa',curdate(),curdate() + interval $hari_sewa day, $gold * $hari_sewa)"; } //------------------------- $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal menyewa buku ini!');self.history.back();</script>"; exit; }else{ $sql_2 = "update pelanggan set gold = gold-($gold * $hari_sewa) where username = '$username_pelanggan'"; $update_gold = mysqli_query($konek,$sql_2); if (!$update_gold) { echo "<script>alert('gagal mengupdate gold anda!');self.history.back();</script>"; exit; } $sql_3 = "update user set gaji_gold = gaji_gold + ($gold * $hari_sewa) where username = '$username_pemilik'"; $update_gold_user = mysqli_query($konek,$sql_3); if (!$update_gold_user) { echo "<script>alert('gagal mengupdate gold user!');self.history.back();</script>"; exit; } echo "<script>alert('terimakasih telah menyewa buku ini.');</script>"; header("location:../halaman_buku_dipinjam_client.php#$kd_buku"); } ?><file_sep>/service/mau_daftar_user.php <?php session_start(); include "koneksi.php"; $nama = $_POST['nama']; $email = $_POST['email']; $no = $_POST['telp']; $jk = $_POST['jk']; $alamat = $_POST['alamat']; $pekerjaan = $_POST['pekerjaan']; $status = $_POST['status']; $username = $_POST['username']; $password = $_POST['password']; $password_konfirmasi = $_POST['password_konfir']; $name_profil = $_FILES['gambar']['name']; $tmp_name_profil = $_FILES['gambar']['tmp_name']; $type_profil = $_FILES['gambar']['type']; $size_profil = $_FILES['gambar']['size']; //------------------------------------------------validasi------------------------------------------- //data diri if (strlen(trim($nama)) < 0){ echo "<script>alert('gagal simpan!, nama harap diisi');self.history.back();</script>"; exit; } if (strlen(trim($email)) < 0){ echo "<script>alert('gagal simpan!, email harap diisi,untuk kepentingan transaksi');self.history.back();</script>"; exit; } if (strlen(trim($no)) < 0){ echo "<script>alert('gagal simpan!, nomor telephone harap diisi,untuk kepentingan transaksi');self.history.back();</script>"; exit; } //jenis kelamin if (strlen(trim($jk)) < 0){ echo "<script>alert('gagal simpan!, jenis kelamin harap diisi');self.history.back();</script>"; exit; } //data diri 2 if (strlen(trim($alamat)) < 0){ echo "<script>alert('gagal simpan!, alamat harap diisi');self.history.back();</script>"; exit; } if (strlen(trim($pekerjaan)) < 0){ echo "<script>alert('gagal simpan!, pekerjaan harap diisi');self.history.back();</script>"; exit; } if (strlen(trim($status)) < 0){ echo "<script>alert('gagal simpan!, status harap diisi');self.history.back();</script>"; exit; } //akses if (strlen(trim($username)) < 0){ echo "<script>alert('gagal simpan!, harap username harap diisi');self.history.back();</script>"; exit; } if (strlen(trim($password)) < 0){ echo "<script>alert('gagal simpan!, password harap diisi');self.history.back();</script>"; exit; } if ($password_konfirmasi != $password){ echo "<script>alert('gagal simpan!, password dan konfirmasi password tidak sama');self.history.back();</script>"; exit; } $maxsize_foto = 1000000; $allowed_foto = array('image/png', 'image/jpg','image/jpeg'); if (!in_array($type_profil, $allowed_foto)) { echo "<script>alert('gagal simpan!, tipe hanya bisa jpg dan png');self.history.back();</script>"; exit; } if ($size_profil > $maxsize_foto) { echo "<script>alert('gagal simpan!, ukuran sampul terlalu besar');self.history.back();</script>"; exit; } //------------------------------------------------validasi------------------------------------------- $buat_folder = "../data/user/$username"; mkdir($buat_folder, 0755, true); $sql = "insert into user (username,password,nama_user,gambar,tema,gaji_gold,status) values ('$username','$password','$nama','$name_profil','set1.css',0,'user')"; $sql_detail_user = "insert into detail_user (username,email,no_telp,jenis_kelamin,alamat,pekerjaan,status_hubungan) values ('$username','$email','$no','$jk','$alamat','$pekerjaan','$status')"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan user baru!');self.history.back();</script>"; exit; } $insert_data_detail = mysqli_query($konek,$sql_detail_user); if (!$insert_data_detail){ echo "<script>alert('gagal simpan detail user baru!');self.history.back();</script>"; exit; } $dir_file = $buat_folder."/".$name_profil; move_uploaded_file($tmp_name_profil, $dir_file); $_SESSION['nama_user_login'] = $nama; $_SESSION['username_login'] = $username; $_SESSION['gambar_login'] = $name_profil; $_SESSION['tema_login'] = "set1.css"; $_SESSION['akses_user_login'] = "user"; $_SESSION['akses'] = "anggota"; echo "<script>alert('berhasil mendaftarkan user baru!,selamat bergabung');</script>"; header("location:../daftar.php"); ?><file_sep>/index.php <html> <head> <style type="text/css"> @import url(data/set1.css); </style> <title>Penyewaan E-book</title> </head> <script src="data/my_jquerry.js"></script> <body> <table width="100%" id="head" border="0"> <tr> <td height="190" style="text-align:center"><h1>Penyewaan E-Book</h1></td> </tr> </table> <!---------------> <table width="95%" border="0" style="margin-left:auto;margin-right:auto;margin-top:15px;margin-bottom:15px"> <tr> <td width="70%" style="vertical-align:top"> <div id="apk" style="text-align:center;background-color:rgba(0, 0, 0, 0.3);border-radius:10px;width:90%;margin-left:auto;margin-right:auto;margin-top:55px;padding-top:1px;"> <h2>Download App</h2><hr><br> <a href="https://github.com/renosyah/proyek-web-php/raw/master/apk/Mari%20Membaca%20E-book.zip"><img id="img" width="100%" height="60%" src="https://raw.githubusercontent.com/renosyah/proyek-web-php/master/apk/android.png"></img></a> </div> </td> <td style="text-align:center;vertical-align:top;" id="pelanggan"> <div id="apk" style="background-color:rgba(0, 0, 0, 0.3);border-radius:10px;width:100%;margin-left:auto;margin-right:auto;margin-bottom:5px;margin-top:55px;padding-top:15px"> <h2 style="margin-top:10px">Login sebagai Pelanggan</h2><hr> <form action="service/mau_login_pelanggan.php" method="post"> <input type="text" name="username" placeholder="Username" style="width:150px"><br><br> <input type="<PASSWORD>" name="password" placeholder="<PASSWORD>" style="width:150px"><br><br> <input type="submit" value="Login" style="width:150px"> <br> <?php if (isset($_GET['msg'])) { echo "<div style='color:red'>".$_GET['msg']."</div>"; } ?> <br> <button id="daftar" type="button">Daftar baru</button><br><br> </form> </div> <table id="daftar_form" border="0" width="100%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.3);border-radius:5px;display:none;"> <tr> <td style="text-align:center"><h2>Masukkan Data Diri Anda</h2><hr></td> </tr> <form action="service/mau_daftar_pelanggan.php" method="post"> <td style="padding-left:10px"> <table style="vetical-align:bottom"> <tr> <td width="40%"> Nama Lengkap :</td><td> <input type="text" name="nama" style="width:90%" required> </td> </tr> <tr> <td> Email :</td><td> <input type="email" name="email" style="width:80%" required> </td> </tr> <tr> <td> No telp :</td><td> <input type="number" name="telp" style="width:70%" required> </td> </tr> <tr> <td> <br><br><br> Username :</td><td><br><br><br><input type="text" name="username" style="width:70%" required> </td> </tr> <tr> <td> Password :</td><td><input type="text" name="password" style="width:60%" required> </td> </tr> <tr> <td> Konfirmasi Password :</td><td><input type="text" name="password_konfir" style="width:60%" required> </td> <tr> <td colspan="2" style="text-align:center"><br><br>Pelanggan baru, mendaftarlah sekarang dan dapatkan gratis 100 gold</td> </tr> </tr> <tr> <td colspan="2" style="text-align:center"> <br><button type="submit">Mendaftar</button> <button type="button" id="batal">Batal</button><br><br></td> </td> </tr> </table> </td> </tr> <tr> <td></td> <td> </td> </tr> </table> <div style="background-color:rgba(0, 0, 0, 0.3);height:50px;border-radius:10px;width:100%;margin-left:auto;margin-right:auto;margin-bottom:5px;margin-top:55px"><br> <a href="index_user.php">Ingin bergabung sebagai anggota?</a> </div> <div style="margin-top:350px"> </div> </body> <script> $(document).ready( function(){ $('#daftar').click( function(){ $('#daftar_form').toggle(); } ); $('#batal').click( function(){ $('#daftar_form').toggle(); } ); }); </script> </html><file_sep>/service/ubah_tema.php <?php include "koneksi.php"; session_start(); if (!$_SESSION['nama_user_login']){ header("location:index.php?msg=anda harus login!"); } if (isset($_POST['tema'])) { $tema = $_POST['tema']; $username = $_SESSION['username_login']; $sql = "update user set tema = '$tema' where username = '$username'"; $insert_data = mysqli_query($konek,$sql); if (!$insert_data){ echo "<script>alert('gagal simpan!');self.history.back();</script>"; exit; } } echo "<script>self.history.back();</script>"; ?><file_sep>/jual_gold.php <?php include "header.php"; if ($_SESSION['akses_user_login']!="admin"){ echo "<script>self.history.back();</script>"; } ?> <table width="90%" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.5);border-radius:5px;margin-top:15px;margin-bottom:15px;"> <tr style="vertical-align:top"> <td style="text-align:center"><h2>Daftar Pemesanan Gold</h2><hr></td> </tr> <tr style="vertical-align:top"> <td> <table width="90%" border="1" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.5);border-radius:5px;margin-top:15px;margin-bottom:15px;"> <tr style="vertical-align:top;text-align:center"> <td>No</td> <td>Nama</td> <td>Username Pelanggan</td> <td>Jumlah Gold</td> <td>Harga</td> <td>Tanggal Pesan</td> <td>Gambar</td> <td colspan="2">Opsi</td> </tr> <?php $sql = "select j.kd_jual_gold as kd ,p.nama as nama,j.username as username,g.jumlah as gold,g.harga as harga,j.tgl_pesan_gold as tanggal,j.bukti_gambar as gambar from jual_gold j left join pelanggan p on p.username = j.username left join gold_kategori g on g.kd_gold = j.kd_gold"; $pesanan_gold = mysqli_query($konek,$sql); if (!$pesanan_gold) die("gagal mengambil data"); $no = 1; if (mysqli_num_rows($pesanan_gold) == 0) { echo "<td style='text-align:center' colspan='9' height='70'>Belum ada pesanan gold untuk hari ini.</td>"; } while ($data = mysqli_fetch_assoc($pesanan_gold)) { echo "<tr style='vertical-align:top;text-align:center'>"; echo "<td>$no</td>"; echo "<td>".$data['nama']."</td>"; echo "<td>".$data['username']."</td>"; echo "<td>Gold ".$data['gold']."</td>"; echo "<td>Rp ".number_format($data['harga'])."</td>"; echo "<td>".$data['tanggal']."</td>"; echo "<td><img width='200' height='230' src='data/transaksi/".$data['username']."/".$data['gambar']."'></img></td>"; echo "<form action='service/terima_pesan_gold.php' method='post'>"; echo "<td><input type='hidden' name='pelanggan' value='".$data['username']."'><input type='hidden' name='gold' value='".$data['gold']."'><button type='submit' name='jual' value='".$data['kd']."'>Jual Gold</button></td>"; echo "</form>"; echo "<form action='service/hapus_pesan_gold.php' method='post'>"; echo "<td><input type='hidden' value='".$data['username']."' name='username_pelanggan'><button type='submit' name='hapus' value='".$data['kd']."'>Hapus</button></td>"; echo "</form>"; echo "</tr>"; $no++; } ?> </table> </td> </tr> </table> <?php include "footer.php"; ?><file_sep>/data/gambar/b012/index.php <?php header('location:../../../daftar.php') ?>;<file_sep>/halaman_buku_client.php <?php include "header_client.php"; $cari = ""; $ukuran = "width:100%"; $text_tombol_cari = "Cari Buku"; $cari_text = "masukkan kata kunci"; if (isset($_GET['cari'])) { $cari = $_GET['cari']; if ($cari != ""){ $ukuran = "width:30%"; $cari_text = "Hasil Pencarian Untuk ".$cari; } } ?> <table width="98%" border="0" style="margin-left:auto;margin-right:auto;background-color:rgba(0, 0, 0, 0.3);border-radius:5px;;margin-top:-4px;margin-bottom:85px;"> <tr> <td height="50" colspan="4" style="text-align:center"><h2>Daftar Buku Tersedia</h2><hr></td> </tr> <tr> <td style="text-align:center" colspan="4"><form>Kata Kunci : <input style="border-radius:10px;width:20%" type="text" name="cari" placeholder="<?php echo $cari_text; ?>" > <input type="submit" value="<?php echo $text_tombol_cari;?>" style="border-radius:10px"></form></td> </tr> <tr> <br> <?php $no_buku = 0; $hasil = mysqli_query($konek,"select *,format(harga - (harga*potongan/100),'##,###') as harga_baru,k.nama_kategori as kategori from buku left join kategori k on k.kd_kategori = buku.kd_kategori where judul like '%$cari%' or penulis like '%$cari%' ORDER BY RAND()"); if (!$hasil) die("gagal memilih data karena : ".mysql_error($konek)); //penentu ukuran jika hasilnya berjumlah if (mysqli_num_rows($hasil) == 0) { echo "<td style='text-align:center;padding:5px'>"; echo "Data Buku untuk kata kunci ''$cari'' tidak ditemukan, coba cari lagi."; echo "</td>"; }else if (mysqli_num_rows($hasil) == 2) { $ukuran = "width:50%"; }else if (mysqli_num_rows($hasil) == 3) { $ukuran = "width:80%"; }else if (mysqli_num_rows($hasil) >= 4){ $ukuran = "width:100%"; } while ($data = mysqli_fetch_assoc($hasil)) { $no_buku++; echo "<td style='vertical-align:top;padding-left:5px;padding-right:5px;width:20%;'>"; include "isi_halaman_buku_client.php"; echo "</td>"; if ($no_buku % 4 == 0){ echo "</tr>"; echo "<tr>"; }else { } } ?> </tr> </table> <?php include "footer_client.php"; ?><file_sep>/isi_halaman_beli_gold_client.php <form action="mobile/mau_beli_gold.php" target="_blank" method="get" style="background-color:rgba(0, 0, 0, 0.4);border-radius:15px;width:95%;margin-left:auto;margin-right:auto;"> <div style="background-image:url(data/gold/<?php echo $data['kd_gold']; ?>/<?php echo $data['gambar']; ?>);width:100%;margin-left:auto;margin-right:auto;margin-top:15px;margin-bottom:15px;background-repeat:no-repeat;background-size:cover;height:40%;padding-bottom:-10px;padding-top:150px;border-radius:15px;background-size: 100% 100%"> <table width="100%" border="0" style="background-color:rgba(0, 0, 0, 0.7);border-radius:15px"> <tr> <td style="text-align:center;"> <h2 style=";border-radius:15px;text-shadow: 5px 5px solid-black;"><?php echo $data['nama_gold']; ?></h2> <a style="color:orange;font-size:28px;text-shadow: 1px 1px white;">Gold <?php echo number_format($data['jumlah']); ?></a><br> <a style="color:LawnGreen;font-size:24px;text-shadow: 1px 1px white">Rp <?php echo number_format($data['harga']); ?></a><br> </td> </tr> <tr> <td style="text-align:center"> <input type="hidden" name="kd_gold" value="<?php echo $data['kd_gold']; ?>"> <input type="hidden" value="<?php echo $user; ?>" name="username"> <input type="hidden" value="<?php echo $data['jumlah']; ?>" name="jumlah"> <input type="hidden" value="<?php echo $data['harga']; ?>" name="harga"><br><br><br> <button type="submit">Beli Gold!</button><br><br><br> </td> </tr> </table> </div> </form>
3deebdfda90bbaae6be94ed65e63ff22c5bbfca0
[ "Markdown", "SQL", "PHP" ]
54
PHP
renosyah/Proyek-paw-php
b4851963197adbe643eb48ffe0c4d1d308ef8063
a1fae9d6acd811489ddc669995f5f7b6313c9924
refs/heads/master
<repo_name>maciekpastuszka/sw_challenge_newest<file_sep>/pre/js/concat/nivo-lightbox.min.js /* * Nivo Lightbox v1.2.0 * http://dev7studios.com/nivo-lightbox * * Copyright 2013, Dev7studios * Free to use and abuse under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ (function (e, t, n, r) { function o(t, n) { this.el = t; this.$el = e(this.el); this.options = e.extend({}, s, n); this._defaults = s; this._name = i; this.init() } var i = "nivoLightbox", s = { effect: "fade", theme: "default", keyboardNav: true, clickOverlayToClose: true, onInit: function () {}, beforeShowLightbox: function () {}, afterShowLightbox: function (e) {}, beforeHideLightbox: function () {}, afterHideLightbox: function () {}, onPrev: function (e) {}, onNext: function (e) {}, errorMessage: "The requested content cannot be loaded. Please try again later." }; o.prototype = { init: function () { var t = this; if (!e("html").hasClass("nivo-lightbox-notouch")) e("html").addClass("nivo-lightbox-notouch"); if ("ontouchstart" in n) e("html").removeClass("nivo-lightbox-notouch"); this.$el.on("click", function (e) { t.showLightbox(e) }); if (this.options.keyboardNav) { e("body").off("keyup").on("keyup", function (n) { var r = n.keyCode ? n.keyCode : n.which; if (r == 27) t.destructLightbox(); if (r == 37) e(".nivo-lightbox-prev").trigger("click"); if (r == 39) e(".nivo-lightbox-next").trigger("click") }) } this.options.onInit.call(this) }, showLightbox: function (t) { var n = this, r = this.$el; var i = this.checkContent(r); if (!i) return; t.preventDefault(); this.options.beforeShowLightbox.call(this); var s = this.constructLightbox(); if (!s) return; var o = s.find(".nivo-lightbox-content"); if (!o) return; e("body").addClass("nivo-lightbox-body-effect-" + this.options.effect); this.processContent(o, r); if (this.$el.attr("data-lightbox-gallery")) { var u = e('[data-lightbox-gallery="' + this.$el.attr("data-lightbox-gallery") + '"]'); e(".nivo-lightbox-nav").show(); e(".nivo-lightbox-prev").off("click").on("click", function (t) { t.preventDefault(); var i = u.index(r); r = u.eq(i - 1); if (!e(r).length) r = u.last(); n.processContent(o, r); n.options.onPrev.call(this, [r]) }); e(".nivo-lightbox-next").off("click").on("click", function (t) { t.preventDefault(); var i = u.index(r); r = u.eq(i + 1); if (!e(r).length) r = u.first(); n.processContent(o, r); n.options.onNext.call(this, [r]) }) } setTimeout(function () { s.addClass("nivo-lightbox-open"); n.options.afterShowLightbox.call(this, [s]) }, 1) }, checkContent: function (e) { var t = this, n = e.attr("href"), r = n.match(/(youtube|youtu|vimeo)\.(com|be)\/(watch\?v=([\w-]+)|([\w-]+))/); if (n.match(/\.(jpeg|jpg|gif|png)$/i) !== null) { return true } else if (r) { return true } else if (e.attr("data-lightbox-type") == "ajax") { return true } else if (n.substring(0, 1) == "#" && e.attr("data-lightbox-type") == "inline") { return true } else if (e.attr("data-lightbox-type") == "iframe") { return true } return false }, processContent: function (n, r) { var i = this, s = r.attr("href"), o = s.match(/(youtube|youtu|vimeo)\.(com|be)\/(watch\?v=([\w-]+)|([\w-]+))/); n.html("").addClass("nivo-lightbox-loading"); if (this.isHidpi() && r.attr("data-lightbox-hidpi")) { s = r.attr("data-lightbox-hidpi") } if (s.match(/\.(jpeg|jpg|gif|png)$/i) !== null) { var u = e("<img>", { src: s }); u.one("load", function () { var r = e('<div class="nivo-lightbox-image" />'); r.append(u); n.html(r).removeClass("nivo-lightbox-loading"); r.css({ "line-height": e(".nivo-lightbox-content").height() + "px", height: e(".nivo-lightbox-content").height() + "px" }); e(t).resize(function () { r.css({ "line-height": e(".nivo-lightbox-content").height() + "px", height: e(".nivo-lightbox-content").height() + "px" }) }) }).each(function () { if (this.complete) e(this).load() }); u.error(function () { var t = e('<div class="nivo-lightbox-error"><p>' + i.options.errorMessage + "</p></div>"); n.html(t).removeClass("nivo-lightbox-loading") }) } else if (o) { var a = "", f = "nivo-lightbox-video"; if (o[1] == "youtube") { a = "//www.youtube.com/embed/" + o[4]; f = "nivo-lightbox-youtube" } if (o[1] == "youtu") { a = "//www.youtube.com/embed/" + o[3]; f = "nivo-lightbox-youtube" } if (o[1] == "vimeo") { a = "//player.vimeo.com/video/" + o[3]; f = "nivo-lightbox-vimeo" } if (a) { var l = e("<iframe>", { src: a, "class": f, frameborder: 0, vspace: 0, hspace: 0, scrolling: "auto" }); n.html(l); l.load(function () { n.removeClass("nivo-lightbox-loading") }) } } else if (r.attr("data-lightbox-type") == "ajax") { e.ajax({ url: s, cache: false, success: function (r) { var i = e('<div class="nivo-lightbox-ajax" />'); i.append(r); n.html(i).removeClass("nivo-lightbox-loading"); if (i.outerHeight() < n.height()) { i.css({ position: "relative", top: "50%", "margin-top": -(i.outerHeight() / 2) + "px" }) } e(t).resize(function () { if (i.outerHeight() < n.height()) { i.css({ position: "relative", top: "50%", "margin-top": -(i.outerHeight() / 2) + "px" }) } }) }, error: function () { var t = e('<div class="nivo-lightbox-error"><p>' + i.options.errorMessage + "</p></div>"); n.html(t).removeClass("nivo-lightbox-loading") } }) } else if (s.substring(0, 1) == "#" && r.attr("data-lightbox-type") == "inline") { if (e(s).length) { var c = e('<div class="nivo-lightbox-inline" />'); c.append(e(s).clone().show()); n.html(c).removeClass("nivo-lightbox-loading"); if (c.outerHeight() < n.height()) { c.css({ position: "relative", top: "50%", "margin-top": -(c.outerHeight() / 2) + "px" }) } e(t).resize(function () { if (c.outerHeight() < n.height()) { c.css({ position: "relative", top: "50%", "margin-top": -(c.outerHeight() / 2) + "px" }) } }) } else { var h = e('<div class="nivo-lightbox-error"><p>' + i.options.errorMessage + "</p></div>"); n.html(h).removeClass("nivo-lightbox-loading") } } else if (r.attr("data-lightbox-type") == "iframe") { var p = e("<iframe>", { src: s, "class": "nivo-lightbox-item", frameborder: 0, vspace: 0, hspace: 0, scrolling: "auto" }); n.html(p); p.load(function () { n.removeClass("nivo-lightbox-loading") }) } else { return false } if (r.attr("title")) { var d = e("<span>", { "class": "nivo-lightbox-title" }); d.text(r.attr("title")); e(".nivo-lightbox-title-wrap").html(d) } else { e(".nivo-lightbox-title-wrap").html("") } }, constructLightbox: function () { if (e(".nivo-lightbox-overlay").length) return e(".nivo-lightbox-overlay"); var t = e("<div>", { "class": "nivo-lightbox-overlay nivo-lightbox-theme-" + this.options.theme + " nivo-lightbox-effect-" + this.options.effect }); var n = e("<div>", { "class": "nivo-lightbox-wrap" }); var r = e("<div>", { "class": "nivo-lightbox-content" }); var i = e('<a href="#" class="nivo-lightbox-nav nivo-lightbox-prev">Previous</a><a href="#" class="nivo-lightbox-nav nivo-lightbox-next">Next</a>'); var s = e('<a href="#" class="nivo-lightbox-close" title="Close">Close</a>'); var o = e("<div>", { "class": "nivo-lightbox-title-wrap" }); var u = 0; if (u) t.addClass("nivo-lightbox-ie"); n.append(r); n.append(o); t.append(n); t.append(i); t.append(s); e("body").append(t); var a = this; if (a.options.clickOverlayToClose) { t.on("click", function (t) { if (t.target === this || e(t.target).hasClass("nivo-lightbox-content") || e(t.target).hasClass("nivo-lightbox-image")) { a.destructLightbox() } }) } s.on("click", function (e) { e.preventDefault(); a.destructLightbox() }); return t }, destructLightbox: function () { var t = this; this.options.beforeHideLightbox.call(this); e(".nivo-lightbox-overlay").removeClass("nivo-lightbox-open"); e(".nivo-lightbox-nav").hide(); e("body").removeClass("nivo-lightbox-body-effect-" + t.options.effect); var n = 0; if (n) { e(".nivo-lightbox-overlay iframe").attr("src", " "); e(".nivo-lightbox-overlay iframe").remove() } e(".nivo-lightbox-prev").off("click"); e(".nivo-lightbox-next").off("click"); e(".nivo-lightbox-content").empty(); this.options.afterHideLightbox.call(this) }, isHidpi: function () { var e = "(-webkit-min-device-pixel-ratio: 1.5), (min--moz-device-pixel-ratio: 1.5), (-o-min-device-pixel-ratio: 3/2), (min-resolution: 1.5dppx)"; if (t.devicePixelRatio > 1) return true; if (t.matchMedia && t.matchMedia(e).matches) return true; return false } }; e.fn[i] = function (t) { return this.each(function () { if (!e.data(this, i)) { e.data(this, i, new o(this, t)) } }) } })(jQuery, window, document) var rlArgs = { "script": "nivo", "selector": "lightbox", "customEvents": "", "activeGalleries": "1", "effect": "fade", "clickOverlayToClose": "1", "keyboardNav": "1", "errorMessage": "The requested content cannot be loaded. Please try again later." }; (function ($) { $(document).on('ready' + rlArgs.customEvents, function () { // initialise event $.event.trigger({ type: 'doResponsiveLightbox', script: rlArgs.script, selector: rlArgs.selector, args: rlArgs }); }); // this is similar to the WP function add_action(); $(document).on('doResponsiveLightbox', function (event) { var script = event.script, selector = event.selector args = event.args; if (typeof script === 'undefined' || typeof selector === 'undefined') { return false; } switch (script) { case 'swipebox': $('a[rel*="' + rlArgs.selector + '"], a[data-rel*="' + rlArgs.selector + '"]').swipebox({ useCSS: (rlArgs.animation === '1' ? true : false), useSVG: (rlArgs.useSVG === '1' ? true : false), hideCloseButtonOnMobile: (rlArgs.hideCloseButtonOnMobile === '1' ? true : false), removeBarsOnMobile: (rlArgs.removeBarsOnMobile === '1' ? true : false), hideBarsDelay: (rlArgs.hideBars === '1' ? parseInt(rlArgs.hideBarsDelay) : 0), videoMaxWidth: parseInt(rlArgs.videoMaxWidth), loopAtEnd: (rlArgs.loopAtEnd === '1' ? true : false) }); break; case 'prettyphoto': $('a[rel*="' + rlArgs.selector + '"], a[data-rel*="' + rlArgs.selector + '"]').prettyPhoto({ hook: 'data-rel', animation_speed: rlArgs.animationSpeed, slideshow: (rlArgs.slideshow === '1' ? parseInt(rlArgs.slideshowDelay) : false), autoplay_slideshow: (rlArgs.slideshowAutoplay === '1' ? true : false), opacity: rlArgs.opacity, show_title: (rlArgs.showTitle === '1' ? true : false), allow_resize: (rlArgs.allowResize === '1' ? true : false), allow_expand: (rlArgs.allowExpand === '1' ? true : false), default_width: parseInt(rlArgs.width), default_height: parseInt(rlArgs.height), counter_separator_label: rlArgs.separator, theme: rlArgs.theme, horizontal_padding: parseInt(rlArgs.horizontalPadding), hideflash: (rlArgs.hideFlash === '1' ? true : false), wmode: rlArgs.wmode, autoplay: (rlArgs.videoAutoplay === '1' ? true : false), modal: (rlArgs.modal === '1' ? true : false), deeplinking: (rlArgs.deeplinking === '1' ? true : false), overlay_gallery: (rlArgs.overlayGallery === '1' ? true : false), keyboard_shortcuts: (rlArgs.keyboardShortcuts === '1' ? true : false), social_tools: (rlArgs.social === '1' ? '<div class="pp_social"><div class="twitter"><a href="//twitter.com/share" class="twitter-share-button" data-count="none">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script></div><div class="facebook"><iframe src="//www.facebook.com/plugins/like.php?locale=en_US&href=' + location.href + '&amp;layout=button_count&amp;show_faces=true&amp;width=500&amp;action=like&amp;font&amp;colorscheme=light&amp;height=23" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:500px; height:23px;" allowTransparency="true"></iframe></div></div>' : ''), changepicturecallback: function () {}, callback: function () {}, ie6_fallback: true }); break; case 'fancybox': $('a[rel*="' + rlArgs.selector + '"], a[data-rel*="' + rlArgs.selector + '"]').fancybox({ modal: (rlArgs.modal === '1' ? true : false), overlayShow: (rlArgs.showOverlay === '1' ? true : false), showCloseButton: (rlArgs.showCloseButton === '1' ? true : false), enableEscapeButton: (rlArgs.enableEscapeButton === '1' ? true : false), hideOnOverlayClick: (rlArgs.hideOnOverlayClick === '1' ? true : false), hideOnContentClick: (rlArgs.hideOnContentClick === '1' ? true : false), cyclic: (rlArgs.cyclic === '1' ? true : false), showNavArrows: (rlArgs.showNavArrows === '1' ? true : false), autoScale: (rlArgs.autoScale === '1' ? true : false), scrolling: rlArgs.scrolling, centerOnScroll: (rlArgs.centerOnScroll === '1' ? true : false), opacity: (rlArgs.opacity === '1' ? true : false), overlayOpacity: parseFloat(rlArgs.overlayOpacity / 100), overlayColor: rlArgs.overlayColor, titleShow: (rlArgs.titleShow === '1' ? true : false), titlePosition: rlArgs.titlePosition, transitionIn: rlArgs.transitions, transitionOut: rlArgs.transitions, easingIn: rlArgs.easings, easingOut: rlArgs.easings, speedIn: parseInt(rlArgs.speeds), speedOut: parseInt(rlArgs.speeds), changeSpeed: parseInt(rlArgs.changeSpeed), changeFade: parseInt(rlArgs.changeFade), padding: parseInt(rlArgs.padding), margin: parseInt(rlArgs.margin), width: parseInt(rlArgs.videoWidth), height: parseInt(rlArgs.videoHeight) }); break; case 'nivo': $.each($('a[rel*="' + rlArgs.selector + '"], a[data-rel*="' + rlArgs.selector + '"]'), function () { var attr = $(this).attr('data-rel'); // check data-rel attribute first if (typeof attr === 'undefined' || attr == false) { // if not found then try to check rel attribute for backward compatibility attr = $(this).attr('rel'); } // for some browsers, `attr` is undefined; for others, `attr` is false. Check for both. if (typeof attr !== 'undefined' && attr !== false) { var match = attr.match(new RegExp(rlArgs.selector + '\\-(gallery\\-(?:[\\da-z]{1,4}))', 'ig')); if (match !== null) { $(this).attr('data-lightbox-gallery', match[0]); } } }); $('a[rel*="' + rlArgs.selector + '"], a[data-rel*="' + rlArgs.selector + '"]').nivoLightbox({ effect: rlArgs.effect, clickOverlayToClose: (rlArgs.clickOverlayToClose === '1' ? true : false), keyboardNav: (rlArgs.keyboardNav === '1' ? true : false), errorMessage: rlArgs.errorMessage }); break; case 'imagelightbox': var selectors = []; $('a[rel*="' + rlArgs.selector + '"], a[data-rel*="' + rlArgs.selector + '"]').each(function (i, item) { var attr = $(item).attr('data-rel'); // check data-rel attribute first if (typeof attr !== 'undefined' && attr !== false && attr !== 'norl') selectors.push(attr); // if not found then try to check rel attribute for backward compatibility else { attr = $(item).attr('rel'); if (typeof attr !== 'undefined' && attr !== false && attr !== 'norl') selectors.push(attr); } }); if (selectors.length > 0) { // make unique selectors = $.unique(selectors); $(selectors).each(function (i, item) { $('a[data-rel="' + item + '"], a[rel="' + item + '"]').imageLightbox({ animationSpeed: parseInt(rlArgs.animationSpeed), preloadNext: (rlArgs.preloadNext === '1' ? true : false), enableKeyboard: (rlArgs.enableKeyboard === '1' ? true : false), quitOnEnd: (rlArgs.quitOnEnd === '1' ? true : false), quitOnImgClick: (rlArgs.quitOnImageClick === '1' ? true : false), quitOnDocClick: (rlArgs.quitOnDocumentClick === '1' ? true : false) }); }); } break; case 'tosrus': var selectors = []; $('a[rel*="' + rlArgs.selector + '"], a[data-rel*="' + rlArgs.selector + '"]').each(function (i, item) { var attr = $(item).attr('data-rel'); // check data-rel attribute first if (typeof attr !== 'undefined' && attr !== false && attr !== 'norl') selectors.push(attr); // if not found then try to check rel attribute for backward compatibility else { attr = $(item).attr('rel'); if (typeof attr !== 'undefined' && attr !== false && attr !== 'norl') selectors.push(attr); } }); if (selectors.length > 0) { // make unique selectors = $.unique(selectors); $(selectors).each(function (i, item) { $('a[data-rel="' + item + '"], a[rel="' + item + '"]').tosrus({ infinite: (rlArgs.infinite === '1' ? true : false), autoplay: { play: (rlArgs.autoplay === '1' ? true : false), pauseOnHover: (rlArgs.pauseOnHover === '1' ? true : false), timeout: rlArgs.timeout }, effect: rlArgs.effect, keys: { prev: (rlArgs.keys === '1' ? true : false), next: (rlArgs.keys === '1' ? true : false), close: (rlArgs.keys === '1' ? true : false) }, pagination: { add: (rlArgs.pagination === '1' ? true : false), type: rlArgs.paginationType }, // forced show: false, buttons: true, caption: { add: true, attributes: ["title"] } }); }); } break; } }); })(jQuery);<file_sep>/pre/js/formularz.js (function () { function ajax(options) { options = { type: options.type || "POST", url: options.url || "", data: options.data, onComplete: options.onComplete || function () {}, onError: options.onError || function () {}, onSuccess: options.onSuccess || function () {}, dataType: options.dataType || "text" }; var xhr = new XMLHttpRequest(); xhr.open(options.type, options.url, true); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (httpSuccess(xhr)) { var returnData = (options.dataType == "xml") ? xhr.responseXML : xhr.responseText options.onSuccess(returnData); } else { options.onError(); } options.onComplete(); xhr = null; } }; xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(options.data); function httpSuccess(r) { try { return (r.status >= 200 && r.status < 300 || r.status == 304 || navigator.userAgent.indexOf("Safari") >= 0 && typeof r.status == "undefined") } catch (e) { return false; } } } var newsletter = { source: document.getElementById("source").value, sent: false, form: [], validateForm: function () { var form = document.getElementById("form"); var inputs = form.querySelectorAll("input.required"); var radio = []; for (var i = 0; i < inputs.length; i++) { var input = inputs[i]; switch (input.type) { case "text": if (input.value) { input.classList.remove("error"); } else { input.classList.add("error"); } if (input.classList.contains('email')) { if (input.value.indexOf("@") > 0 && input.value.indexOf(".") > 0) { input.classList.remove("error"); } else { input.classList.add("error"); } } break; case "checkbox": if (input.checked) { input.parentElement.classList.remove("error"); } else { input.parentElement.classList.add("error"); } break; case "radio": if (!radio[input.name]) { if (input.checked) { radio[input.name] = true; input.parentElement.parentElement.classList.remove("error"); } else { input.parentElement.parentElement.classList.add("error"); } } break; } } var error = form.querySelectorAll(".error"); if (error.length === 0) { return true; } }, serialize: function () { var s = []; var form = document.getElementById("form"); var inputs = form.querySelectorAll("input"); for (var i = 0; i < inputs.length; i++) { var input = inputs[i]; switch (input.type) { case "text": var pole = { name: input.name, value: input.value } s.push(pole); break; case "radio": if (input.checked) { var pole = { name: input.name, value: input.value } s.push(pole); } break; } } return s; }, send: function () { this.sent = true; this.form = this.serialize(); var dane = JSON.stringify(this); var wynik = document.getElementById("success"); var v_form = this.validateForm(); // console.log(dane); if (v_form === true) { console.log("data ok"); ajax({ type: "POST", data: 'json=' + dane, url: "../mail.php", dataType: "text", onError: function (msg) { console.warn(msg); wynik.innerHTML = "<div class=\"alert warning\">Coś poszło nie tak.</div>"; }, onSuccess: function (msg) { console.log(msg); wynik.innerHTML = "<div class=\"alert success\">" + msg + "</div>"; } }); } else { console.log("incorrect data"); } } }; var form = document.getElementById("form"); var inputs = document.querySelectorAll("input"); var cities = document.querySelectorAll(".city"); var schedule = document.getElementById("schedule"); for (var i = 0; i < inputs.length; i++) { switch (inputs[i].type) { case "checkbox": inputs[i].addEventListener("click", function () { if (newsletter.sent === true) { newsletter.validateForm(); } }); break; case "radio": inputs[i].addEventListener("click", function () { if (newsletter.sent === true) { newsletter.validateForm(); } }); break; case "text": inputs[i].addEventListener("keyup", function () { if (newsletter.sent === true) { newsletter.validateForm(); } }); break; } } form.addEventListener("submit", function (event) { event.preventDefault(); newsletter.send(); }); for (var i = 0; i < cities.length; i++) { var city = cities[i]; city.addEventListener("change", function () { if (this.value == "wroclaw") { schedule.innerHTML = "<label><input type=\"radio\" name=\"termin\" value=\"poniedziałek 18:20\" checked> poniedziałek 18:20</label><label><input type=\"radio\" name=\"termin\" value=\"środa 18:20\" > środa 18:20 </label><label><input type=\"radio\" name=\"termin\" value=\"piątek 19:10\"> piątek 19:10</label><label><input type=\"radio\" name=\"termin\" value=\"piątek 20:00\"> piątek 20:00</label>"; } else { schedule.innerHTML = "<label><input type=\"radio\" name=\"termin\" value=\"wtorek 18:00\"> wtorek 18:00</label><label><input type=\"radio\" name=\"termin\" value=\"czwartek 18:00\">czwartek 18:00</label>"; } }); } }());
c7f3c04b86dbe2c3707c91528542b2391d0835b2
[ "JavaScript" ]
2
JavaScript
maciekpastuszka/sw_challenge_newest
e7477cdd6b3a12bcf6796ea10f6223748636c479
a7680968e3636616961615e9fd56567b6f8b1294
refs/heads/main
<file_sep># questionnaire_test_task ## Prerequsites Developed and tested in Linux (Ubuntu) environment only. Requires `git` and `docker` to be installed. ## Project setup and dev server ``` git clone cd ./questionnaire_test_task docker-compose -f dc-start.yml build docker-compose -f dc-start.yml up ``` ## API reference API reference is available at `/swagger` ## Django admin Django admin is available at `/admin`<file_sep>from rest_framework import serializers from questionnaire.models import Questionnaire, Question, Answer class QuestionsSerializer(serializers.ModelSerializer): class Meta: model = Question fields = ('id', 'question_body', 'question_type',) class ActualQuestionnairesSerializer(serializers.ModelSerializer): question = QuestionsSerializer(many=True) class Meta: model = Questionnaire fields = ('id', 'name', 'start_date', 'end_date', 'description', 'question',) class AnswersSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = '__all__' <file_sep>from django.contrib import admin from django.urls import path from questionnaire.views import GetActiveQuestionnaires, GetUserCompletedQuestionnaires, AnswerQuestionnaire from rest_framework import permissions from drf_yasg2.views import get_schema_view from drf_yasg2 import openapi schema_view = get_schema_view( openapi.Info( title="API references", default_version='v1', ), public=True, permission_classes=[permissions.AllowAny], ) urlpatterns = [ path('admin/', admin.site.urls), path('questionnaires/', GetActiveQuestionnaires.as_view()), path('answers/', GetUserCompletedQuestionnaires.as_view()), path('make_answers/', AnswerQuestionnaire.as_view()), #drf-yasg part path('swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), ] <file_sep>from django.contrib import admin from questionnaire.models import Questionnaire, Question, Answer class QuestionInLine(admin.TabularInline): model = Question.questionnaire.through class QuestionnaireAdmin(admin.ModelAdmin): model = Questionnaire inlines = [QuestionInLine] list_display = ('name', 'end_date', 'description') def get_readonly_fields(self, request, obj=None): if obj: return ('start_date',) + self.readonly_fields return self.readonly_fields admin.site.register(Questionnaire, QuestionnaireAdmin) admin.site.register(Question) admin.site.register(Answer) <file_sep>from enum import Enum from django.contrib.auth.models import User from django.db import models class QuestionTypeEnum(Enum): text = "text" choose_one = "choose_one" choose_many = "choose_many" class Questionnaire(models.Model): name = models.CharField( verbose_name="Наименование", max_length=255, blank=False, null=False ) start_date = models.DateTimeField(verbose_name="Дата начала", blank=False, null=False) end_date = models.DateTimeField(verbose_name="Дата окончания", blank=False, null=False) description = models.TextField(verbose_name="Описание", blank=True, null=True) def __str__(self): return self.name class Question(models.Model): question_body = models.CharField(verbose_name="Текст вопроса", max_length=255, blank=False, null=False) question_type = models.CharField( verbose_name="Тип вопроса", max_length=20, choices=[(tag.name, tag.value) for tag in QuestionTypeEnum], blank=False, null=False, ) questionnaire = models.ManyToManyField(Questionnaire, related_name='question') def __str__(self): return self.question_body class Answer(models.Model): user = models.IntegerField(verbose_name="Идентификатор пользователя", blank=True, null=True) answer_body = models.TextField(verbose_name="Ответ", blank=True, null=True) question = models.ForeignKey(Question, on_delete=models.CASCADE) questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE) def __str__(self): return self.answer_body <file_sep>import datetime import logging from django.http import JsonResponse from django.utils import timezone from drf_yasg2 import openapi from drf_yasg2.utils import swagger_auto_schema from rest_framework import status from rest_framework.decorators import action from rest_framework.views import APIView from questionnaire.models import Questionnaire, Answer, Question from questionnaire.serializers import ActualQuestionnairesSerializer, AnswersSerializer class GetActiveQuestionnaires(APIView): @swagger_auto_schema( method="get", manual_parameters=[ openapi.Parameter( in_="query", name="date", type="string", description="optional date to specify actual questionnaries. Default is datetime.datetime.now(tz=timezone.utc).", ) ], responses={status.HTTP_200_OK: ActualQuestionnairesSerializer,}, ) @action(detail=False, methods=["GET"]) def get(self, request): try: target_date = request.GET["date"] except KeyError: target_date = datetime.datetime.now(tz=timezone.utc) actual_questionnaires = Questionnaire.objects.prefetch_related( "question" ).filter(start_date__lte=target_date, end_date__gte=target_date) serialized_data = ActualQuestionnairesSerializer( actual_questionnaires, many=True ).data return JsonResponse({"active_questionnaires": serialized_data}, status=200) class GetUserCompletedQuestionnaires(APIView): @swagger_auto_schema( method="get", manual_parameters=[ openapi.Parameter( in_="query", name="user_id", type="number", description="special id to identify anonymous or actual user.", ) ], responses={ status.HTTP_200_OK: openapi.Schema( type=openapi.TYPE_OBJECT, properties={ "answered_questionnaires": openapi.Schema( type=openapi.TYPE_OBJECT, description="Json with questionnaires", properties={ "questionnaire": openapi.Schema( type=openapi.TYPE_OBJECT, description="questionnaire name", additional_properties=openapi.Schema( type=openapi.TYPE_STRING, description="Mapped questions and answers", ), ), }, ), }, ), }, ) @action(detail=False, methods=["GET"]) def get(self, request): try: target_user_id = request.GET["user_id"] except KeyError: return JsonResponse( {"error": "missing or invalid user_id in request querystring"}, status=400, ) user_answers_raw = Answer.objects.select_related( "questionnaire", "question" ).filter(user=target_user_id) if not user_answers_raw: return JsonResponse( {"answers": f"no answers found for user_id {target_user_id}"}, status=200, ) result_dict = {} for answer in user_answers_raw: try: result_dict[answer.questionnaire.name][ answer.question.question_body ] = answer.answer_body except KeyError: result_dict.update( { answer.questionnaire.name: { answer.question.question_body: answer.answer_body } } ) return JsonResponse({"answered_questionnaires": result_dict}, status=200) answer_questionnaire_schema = openapi.Schema( type=openapi.TYPE_OBJECT, required=["user_id", "answers_data"], properties={ "user_id": openapi.Schema( type=openapi.TYPE_NUMBER, description="numeric user id" ), "answers_data": openapi.Schema( type=openapi.TYPE_OBJECT, description="Json with questions and questionnaire data", properties={ "questionnaire": openapi.Schema( type=openapi.TYPE_NUMBER, description="questionnaire id", ), }, additional_properties=openapi.Schema( type=openapi.TYPE_STRING, description="mapped question id to answer string", ), ), }, ) class AnswerQuestionnaire(APIView): @swagger_auto_schema( method="post", request_body=answer_questionnaire_schema, responses={status.HTTP_200_OK: AnswersSerializer,}, ) @action(detail=False, methods=["POST"]) def post(self, request): try: user_id = request.data["user_id"] except KeyError: return JsonResponse( {"error": "missing or invalid user_id in request json"}, status=400 ) try: answers_data = request.data["answers_data"] except KeyError: return JsonResponse( {"error": "missing or invalid answers_data in request json"}, status=400 ) questionnaire_id = answers_data["questionnaire"] try: questionnaire = Questionnaire.objects.get(pk=questionnaire_id) except Questionnaire.DoesNotExist: return JsonResponse( {"error": f"no such questionnaire with id {questionnaire_id}"}, status=400, ) questions = Question.objects.filter(questionnaire=questionnaire_id) answers_list = [] for question in questions: try: answer_str = answers_data[str(question.id)] except KeyError: return JsonResponse( {"error": f"missing answered question with id {question.id} "}, status=400, ) answer = Answer( user=user_id, answer_body=answer_str, questionnaire=questionnaire, question=question, ) answers_list.append(answer) self.save_models(answers_list) serialized_data = AnswersSerializer(answers_list, many=True).data return JsonResponse({"answered_questionnaire": serialized_data}, status=200) def save_models(self, model_list): for model in model_list: model.save() <file_sep># Generated by Django 2.2.10 on 2021-08-13 16:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('questionnaire', '0001_initial'), ] operations = [ migrations.AlterField( model_name='answer', name='user', field=models.IntegerField(blank=True, null=True, verbose_name='Идентификатор пользователя'), ), migrations.AlterField( model_name='question', name='questionnaire', field=models.ManyToManyField(related_name='questionnaire', to='questionnaire.Questionnaire'), ), ]
304d0d925e3470ffcfa8db9fe6fd5b5efc9a8206
[ "Markdown", "Python" ]
7
Markdown
Tchocorpse/questionnaire_test_task
2ddb8c35381a0c1348e18f530020f59fc150cf05
f26a09a369378a2f360be0b3ee55589a1c36d3e8