code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
#include <bits/stdc++.h> using namespace std; #define sd(x) scanf("%d",&x) #define su(x) scanf("%u",&x) #define slld(x) scanf("%lld",&x) #define sc(x) scanf("%c",&x) #define ss(x) scanf("%s",x) #define sf(x) scanf("%f",&x) #define slf(x) scanf("%lf",&x) #define ll long long int #define mod(x,n) (x+n)%n #define pb push_back #define mp make_pair #define pii pair<int,int> #define vi vector<int> #define all(a) (a).begin(),(a).end() #define F first #define S second #define sz(x) (int)x.size() #define Mod 1000000007 char St[1007][1007]; bool Stck[1007][1007]; int Calc[1007][1007]; int n,m; bool flag = false; bool isEdge(int i,int j,int x,int y) { return ( St[i][j]==&#39;D&#39; && St[x][y]==&#39;I&#39; ) || ( St[i][j]==&#39;I&#39; && St[x][y]==&#39;M&#39; ) || ( St[i][j]==&#39;M&#39; && St[x][y]==&#39;A&#39; ) || ( St[i][j]==&#39;A&#39; && St[x][y]==&#39;D&#39; ); } void CalcFun(int i,int j) { if(Stck[i][j]) flag = true; if(flag) return; if(Calc[i][j]) return; Stck[i][j] = true; int cur = 1; if(i+1<n && isEdge(i,j,i+1,j)) { CalcFun(i+1,j); cur = max(cur,1+Calc[i+1][j]); } if(i-1>=0 && isEdge(i,j,i-1,j)) { CalcFun(i-1,j); cur = max(cur,1+Calc[i-1][j]); } if(j+1<m && isEdge(i,j,i,j+1)) { CalcFun(i,j+1); cur = max(cur,1+Calc[i][j+1]); } if(j-1>=0 && isEdge(i,j,i,j-1)) { CalcFun(i,j-1); cur = max(cur,1+Calc[i][j-1]); } Stck[i][j] = false; Calc[i][j] = cur; } int main() { // freopen("input_file_name.in","r",stdin); // freopen("output_file_name.out","w",stdout); int i,j,k,l,x,y,z,a,b,r,ans=0; // ll i,j,k,l,m,n,x,y,z,a,b,r; sd(n); sd(m); for(i=0;i<n;i++) ss(St[i]); for(i=0;i<n;i++) { for(j=0;j<m;j++) { if(Calc[i][j]==0) { CalcFun(i,j); } if(flag) break; } if(flag) break; } if(flag) { printf("Poor Inna!\n"); } else { for(i=0;i<n;i++) { for(j=0;j<m;j++) { if(St[i][j]==&#39;D&#39;) { ans = max(ans, Calc[i][j]/4 ); } } } if(ans==0) printf("Poor Dima!\n"); else printf("%d\n", ans ); } return 0; }
mejanvijay/codeforces-jvj_iit-submissions
374/C[ Inna and Dima ].cpp
C++
mit
2,165
import { browser, element, by } from 'protractor'; describe('Form Component', function () { var _modelName: string, _modelDesc: string, _modelStatus: string; beforeEach(function () { }); it('should display: the correct url', function(){ browser.get('addTicket'); browser.getCurrentUrl().then(function (url) { expect(url).toEqual(browser.baseUrl + 'addTicket'); }); }); it('should display: Title', function () { expect(element(by.css('h1')).getText()).toEqual('Novo Ticket'); }); it('should display: Subtitle', function () { expect(element(by.css('p')).getText()).toEqual('Formulário para adição de um novo ticket.'); }); it('should display: form', function () { var _form = element.all(by.tagName('label')); expect(_form.get(0).getText()).toEqual('Nome:'); expect(_form.get(1).getText()).toEqual('Descrição:'); expect(_form.get(2).getText()).toEqual('Status:'); }); it('should display: input name', function () { var _name = browser.findElement(by.name('nome')); _name.sendKeys('A'); var _model = browser.findElement(by.name('nome')); _model.getAttribute('value').then(function (value) { _modelName = value; expect(value).toEqual('A'); }); }); it('should display: input description', function () { var _desc = browser.findElement(by.name('descrição')); _desc.sendKeys('Primeira letra do alfabeto'); var _model = browser.findElement(by.name('descrição')); _model.getAttribute('value').then(function (value) { _modelDesc = value; expect(value).toEqual('Primeira letra do alfabeto'); }); }); it('should display: input status', function () { var _sta = browser.findElement(by.name('status')); _sta.sendKeys('TO DO'); var _model = browser.findElement(by.name('status')); _model.getAttribute('value').then(function (value) { _modelStatus = value; expect(value).toEqual('TO DO'); }); }); it('should display: add ticket', function () { var _button = browser.findElement(by.name('salvar')); _button.click().then(function () { var el = element.all(by.css('.table tbody tr')); el.count().then(function (count){ expect(count === 1).toBeTruthy();; }); }); }); it('should display: edit ticket', function () { var _button = browser.findElement(by.name('editar')); _button.click().then(function () { expect(_modelStatus).toEqual('TO DO'); }); }); it('should display: delete ticket', function () { var _button = browser.findElement(by.name('remover')); _button.click().then(function () { var el = element.all(by.css('.table tbody tr')); el.count().then(function (count){ expect(count === 0).toBeTruthy(); }); }); }); it('should display: titles of table', function () { var _elementTable = element.all(by.css('.table th')); expect(_elementTable.get(0).getText()).toEqual('Id'); expect(_elementTable.get(1).getText()).toEqual('Nome'); expect(_elementTable.get(2).getText()).toEqual('Descrição'); expect(_elementTable.get(3).getText()).toEqual('Status'); }); });
camposmandy/Tickets
e2e/form.component/cenario1/form.e2e-spec.ts
TypeScript
mit
3,191
const ADD_TODO = 'ADD_TODO'; const TOGGLE_TODO = 'TOGGLE_TODO'; const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER'; const SHOW_ALL = 'SHOW_ALL'; const todo = (state = {}, action) => { switch (action.type) { case ADD_TODO: return { id: action.id, text: action.text, completed: false }; case TOGGLE_TODO: if (state.id !== action.id) { return state; } return { ...state, completed: !state.completed }; default: return state; } }; const initialState = { todos: [], filter: SHOW_ALL }; export default function reducer(state = initialState, action) { let todos; switch (action.type) { case ADD_TODO: todos = [todo(undefined, action), ...state.todos]; return { ...state, filter: SHOW_ALL, todos }; case TOGGLE_TODO: todos = state.todos.map(td => todo(td, action) ); return { ...state, todos }; case SET_VISIBILITY_FILTER: return { ...state, filter: action.filter, todos: [...state.todos] }; default: return state; } } export function addTodo(id, text) { return { type: ADD_TODO, id, text }; } export function toggleTodo(id) { return { type: TOGGLE_TODO, id }; } export function setVisibilityFilter(filter) { return { type: SET_VISIBILITY_FILTER, filter }; }
yogakurniawan/cerebral-app
src/redux/modules/todo.js
JavaScript
mit
1,465
#include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "util.h" #include "init.h" #include "base58.h" #include <QString> #include <QDateTime> #include <QDoubleValidator> #include <QFont> #include <QLineEdit> #include <QUrl> #include <QTextDocument> // For Qt::escape #include <QAbstractItemView> #include <QApplication> #include <QClipboard> #include <QFileDialog> #include <QDesktopServices> #include <QThread> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shlwapi.h" #include "shlobj.h" #include "shellapi.h" #endif namespace GUIUtil { QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); font.setStyleHint(QFont::TypeWriter); return font; } void setupAddressWidget(QLineEdit *widget, QWidget *parent) { widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength); widget->setValidator(new BitcoinAddressValidator(parent)); widget->setFont(bitcoinAddressFont()); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { if(uri.scheme() != QString("litebar")) return false; // check if the address is valid CBitcoinAddress addressFromUri(uri.path().toStdString()); if (!addressFromUri.IsValid()) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; QList<QPair<QString, QString> > items = uri.queryItems(); for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert litebar:// to litebar: // // Cannot handle this later, because litebar:// will cause Qt to see the part after // as host, // which will lowercase it (and thus invalidate the address). if(uri.startsWith("litebar://")) { uri.replace(0, 11, "litebar:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString HtmlEscape(const QString& str, bool fMultiLine) { QString escaped = Qt::escape(str); if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item QApplication::clipboard()->setText(selection.at(0).data(role).toString()); } } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); } else { myDir = dir; } QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != QCoreApplication::instance()->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = qApp->widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (boost::filesystem::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string()))); } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) : QObject(parent), size_threshold(size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt) { if(evt->type() == QEvent::ToolTipChange) { QWidget *widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip)) { // Prefix <qt/> to make sure Qt detects this as rich text // Escape the current message as HTML and replace \n by <br> tooltip = "<qt/>" + HtmlEscape(tooltip, true); widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } #ifdef WIN32 boost::filesystem::path static StartupShortcutPath() { return GetSpecialFolderPath(CSIDL_STARTUP) / "LiteBar.lnk"; } bool GetStartOnSystemStartup() { // check for LiteBar.lnk return boost::filesystem::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating boost::filesystem::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(NULL); // Get a pointer to the IShellLink interface. IShellLink* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); TCHAR pszArgs[5] = TEXT("-min"); // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); psl->SetArguments(pszArgs); // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html boost::filesystem::path static GetAutostartDir() { namespace fs = boost::filesystem; char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } boost::filesystem::path static GetAutostartFilePath() { return GetAutostartDir() / "litebar.desktop"; } bool GetStartOnSystemStartup() { boost::filesystem::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) boost::filesystem::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH+1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1) return false; boost::filesystem::create_directories(GetAutostartDir()); boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; // Write a litebar.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; optionFile << "Name=LiteBar\n"; optionFile << "Exec=" << pszExePath << " -min\n"; optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #else // TODO: OSX startup stuff; see: // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif HelpMessageBox::HelpMessageBox(QWidget *parent) : QMessageBox(parent) { header = tr("LiteBar-Qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " litebar-qt [" + tr("command-line options") + "] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n"; setWindowTitle(tr("LiteBar-Qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in nonbreaking spaces to make it wider. setText(header + QString(QChar(0x2003)).repeated(50)); setDetailedText(coreOptions + "\n" + uiOptions); } void HelpMessageBox::printToConsole() { // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stderr, "%s", strUsage.toStdString().c_str()); } void HelpMessageBox::showOrPrint() { #if defined(WIN32) // On windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } } // namespace GUIUtil
digiwhite/litebar
src/qt/guiutil.cpp
C++
mit
13,477
<?php /* @WebProfiler/Profiler/base_js.html.twig */ class __TwigTemplate_ae056cb8a330276cc4561a2e713ee0f5489318f7ac1443c94398f9f61fbbd02e extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "<script>/*<![CDATA[*/ Sfjs = (function() { \"use strict\"; var noop = function() {}, profilerStorageKey = 'sf2/profiler/', request = function(url, onSuccess, onError, payload, options) { var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); options = options || {}; xhr.open(options.method || 'GET', url, true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onreadystatechange = function(state) { if (4 === xhr.readyState && 200 === xhr.status) { (onSuccess || noop)(xhr); } else if (4 === xhr.readyState && xhr.status != 200) { (onError || noop)(xhr); } }; xhr.send(payload || ''); }, hasClass = function(el, klass) { return el.className.match(new RegExp('\\\\b' + klass + '\\\\b')); }, removeClass = function(el, klass) { el.className = el.className.replace(new RegExp('\\\\b' + klass + '\\\\b'), ' '); }, addClass = function(el, klass) { if (!hasClass(el, klass)) { el.className += \" \" + klass; } }, getPreference = function(name) { if (!window.localStorage) { return null; } return localStorage.getItem(profilerStorageKey + name); }, setPreference = function(name, value) { if (!window.localStorage) { return null; } localStorage.setItem(profilerStorageKey + name, value); }; return { hasClass: hasClass, removeClass: removeClass, addClass: addClass, getPreference: getPreference, setPreference: setPreference, request: request, load: function(selector, url, onSuccess, onError, options) { var el = document.getElementById(selector); if (el && el.getAttribute('data-sfurl') !== url) { request( url, function(xhr) { el.innerHTML = xhr.responseText; el.setAttribute('data-sfurl', url); removeClass(el, 'loading'); (onSuccess || noop)(xhr, el); }, function(xhr) { (onError || noop)(xhr, el); }, options ); } return this; }, toggle: function(selector, elOn, elOff) { var i, style, tmp = elOn.style.display, el = document.getElementById(selector); elOn.style.display = elOff.style.display; elOff.style.display = tmp; if (el) { el.style.display = 'none' === tmp ? 'none' : 'block'; } return this; } } })(); /*]]>*/</script> "; } public function getTemplateName() { return "@WebProfiler/Profiler/base_js.html.twig"; } public function getDebugInfo() { return array ( 91 => 35, 83 => 30, 79 => 29, 75 => 28, 70 => 26, 66 => 25, 62 => 24, 50 => 15, 26 => 3, 24 => 2, 19 => 1, 98 => 40, 93 => 9, 46 => 14, 44 => 9, 40 => 8, 32 => 6, 27 => 4, 22 => 1, 120 => 20, 117 => 19, 110 => 22, 108 => 19, 105 => 18, 102 => 17, 94 => 34, 90 => 32, 88 => 6, 84 => 29, 82 => 28, 78 => 40, 73 => 16, 64 => 13, 61 => 12, 56 => 11, 53 => 10, 47 => 8, 41 => 5, 33 => 3, 158 => 79, 139 => 63, 135 => 62, 131 => 61, 127 => 28, 123 => 59, 106 => 45, 101 => 43, 97 => 41, 85 => 32, 80 => 41, 76 => 17, 74 => 27, 63 => 19, 58 => 17, 48 => 9, 45 => 8, 42 => 12, 36 => 7, 30 => 5,); } }
NewRehtse/GastosTallerSf
app/cache/dev/twig/ae/05/6cb8a330276cc4561a2e713ee0f5489318f7ac1443c94398f9f61fbbd02e.php
PHP
mit
4,632
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DuplicateFileManager { class Class1 { } }
kellycoinguy/DuplicateFileManager
DuplicateFileManager/Class1.cs
C#
mit
184
require "spec_helper" module Orion module RSpec describe Delete do let(:just_delete) { Orion::Delete.send(:just_delete, found_files(name_hash ".txt")) } let(:delete_files) { Orion::Delete.send(:delete_files, found_files(name_hash ".txt")) } shared_examples_for "a normal deleter" do it "should return nil if the files array is empty" do deleted = Orion::Delete.send(method, found_files(name_hash rare_query)) deleted.should be_nil end end describe "#just_delete" do # The files array comes from the Orion::Search class it_should_behave_like "any normal finder" do let(:search_method) { invalid_search.search(name_hash) } end it_should_behave_like "a normal deleter" do let(:method) { :just_delete } end it "should return true if could delete the files" do create_files(".txt") just_delete.should be_true end it "should delete the files it found" do create_files(".txt") just_delete found_files(name_hash ".txt").should be_empty end end describe "#delete_files" do it_should_behave_like "any normal finder" do let(:search_method) { invalid_search.search(name_hash) } end it_should_behave_like "a normal deleter" do let(:method) { :delete_files } end it "should return an array if the files are found" do create_files(".txt") delete_files.should be_instance_of Array end it "should return an array with the deleted files" do create_files(".txt") deleted = Orion::Delete.send(:delete_files, found_files(name_hash "remove")) deleted.each do |deleted_file| deleted_file.should be_instance_of String deleted_file.should_not be_a_valid_file end end end end end end
bismark64/orion
spec/orion/delete_spec.rb
Ruby
mit
1,975
#include <vector> #include <iostream> #include <unordered_set> #include <unordered_map> #include <map> #include <sstream> #include <algorithm> #include <queue> #include <set> #include <functional> #include <stdio.h> #include <stdlib.h> using namespace std; #if 0 This algorithm's idea is: to iteratively determine what would be each bit of the final result from left to right. And it narrows down the candidate group iteration by iteration. e.g.assume input are a, b, c, d, ...z, 26 integers in total. In first iteration, if you found that a, d, e, h, u differs on the MSB(most significant bit), so you are sure your final result's MSB is set. Now in second iteration, you try to see if among a, d, e, h, u there are at least two numbers make the 2nd MSB differs, if yes, then definitely, the 2nd MSB will be set in the final result. And maybe at this point the candidate group shinks from a,d,e,h,u to a, e, h. Implicitly, every iteration, you are narrowing down the candidate group, but you don't need to track how the group is shrinking, you only cares about the final result. #endif class Solution { public: int findMaximumXOR(vector<int>& nums) { int max = 0, mask = 0; unordered_set<int> t; #if 0 search from left to right, find out for each bit is there two numbers that has different value #endif for (int i = 31; i >= 0; i--){ /* mask contains the bits considered so far */ mask |= (1 << i); t.clear(); /* store prefix of all number with right i bits discarded */ for (int n : nums){ t.insert(mask & n); } #if 0 now find out if there are two prefix with different i-th bit if there is, the new max should be current max with one 1 bit at i-th position, which is candidate and the two prefix, say A and B, satisfies: A ^ B = candidate so we also have A ^ candidate = B or B ^ candidate = A thus we can use this method to find out if such A and B exists in the set #endif int candidate = max | (1 << i); for (int prefix : t){ if (t.find(prefix ^ candidate) != t.end()){ max = candidate; break; } } } return max; } }; int main() { { vector<int> nums = { 3, 10, 5, 25, 2, 8 }; cout << Solution().findMaximumXOR(nums) << endl; // 28 } cin.get(); return EXIT_SUCCESS; }
wonghoifung/tips
leetcode/medium_maximum_xor_of_two_numbers_in_an_array.cpp
C++
mit
2,278
/* eslint-disable security/detect-object-injection */ const path = require("path").posix; const { calculateInstability, metricsAreCalculable } = require("../module-utl"); const { getAfferentCouplings, getEfferentCouplings, getParentFolders, object2Array, } = require("./utl"); function upsertCouplings(pAllDependents, pNewDependents) { pNewDependents.forEach((pNewDependent) => { pAllDependents[pNewDependent] = pAllDependents[pNewDependent] || { count: 0, }; pAllDependents[pNewDependent].count += 1; }); } function upsertFolderAttributes(pAllMetrics, pModule, pDirname) { pAllMetrics[pDirname] = pAllMetrics[pDirname] || { dependencies: {}, dependents: {}, moduleCount: 0, }; upsertCouplings( pAllMetrics[pDirname].dependents, getAfferentCouplings(pModule, pDirname) ); upsertCouplings( pAllMetrics[pDirname].dependencies, getEfferentCouplings(pModule, pDirname).map( (pDependency) => pDependency.resolved ) ); pAllMetrics[pDirname].moduleCount += 1; return pAllMetrics; } function aggregateToFolder(pAllFolders, pModule) { getParentFolders(path.dirname(pModule.source)).forEach((pParentDirectory) => upsertFolderAttributes(pAllFolders, pModule, pParentDirectory) ); return pAllFolders; } function sumCounts(pAll, pCurrent) { return pAll + pCurrent.count; } function getFolderLevelCouplings(pCouplingArray) { return Array.from( new Set( pCouplingArray.map((pCoupling) => path.dirname(pCoupling.name) === "." ? pCoupling.name : path.dirname(pCoupling.name) ) ) ).map((pCoupling) => ({ name: pCoupling })); } function calculateFolderMetrics(pFolder) { const lModuleDependents = object2Array(pFolder.dependents); const lModuleDependencies = object2Array(pFolder.dependencies); // this calculation might look superfluous (why not just .length the dependents // and dependencies?), but it isn't because there can be > 1 relation between // two folders const lAfferentCouplings = lModuleDependents.reduce(sumCounts, 0); const lEfferentCouplings = lModuleDependencies.reduce(sumCounts, 0); return { ...pFolder, afferentCouplings: lAfferentCouplings, efferentCouplings: lEfferentCouplings, instability: calculateInstability(lEfferentCouplings, lAfferentCouplings), dependents: getFolderLevelCouplings(lModuleDependents), dependencies: getFolderLevelCouplings(lModuleDependencies), }; } function findFolderByName(pAllFolders, pName) { return pAllFolders.find((pFolder) => pFolder.name === pName); } function denormalizeInstability(pFolder, _, pAllFolders) { return { ...pFolder, dependencies: pFolder.dependencies.map((pDependency) => { const lFolder = findFolderByName(pAllFolders, pDependency.name) || {}; return { ...pDependency, instability: lFolder.instability >= 0 ? lFolder.instability : 0, }; }), }; } module.exports = function aggregateToFolders(pModules) { const lFolders = object2Array( pModules.filter(metricsAreCalculable).reduce(aggregateToFolder, {}) ).map(calculateFolderMetrics); return lFolders.map(denormalizeInstability); };
sverweij/dependency-cruiser
src/enrich/derive/folders/aggregate-to-folders.js
JavaScript
mit
3,202
import datetime import MySQLdb from os import sys class DBLogger: def __init__(self, loc='default-location'): self.usr = '<user>' self.pwd = '<password>' self.dbase = '<database>' self.location = loc self.conn = MySQLdb.connect(host="localhost", user=self.usr, passwd=self.pwd, db=self.dbase) self.cursor = self.conn.cursor() def cleanUp(self): self.conn.close() self.cursor.close()
georgetown-analytics/classroom-occupancy
SensorDataCollection/Sensors/DBLogger.py
Python
mit
421
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::ApiManagement::Mgmt::V2019_01_01 module Models # # Paged Operation list representation. # class OperationCollection include MsRestAzure include MsRest::JSONable # @return [Array<OperationContract>] Page values. attr_accessor :value # @return [String] Next page link if any. attr_accessor :next_link # return [Proc] with next page method call. attr_accessor :next_method # # Gets the rest of the items for the request, enabling auto-pagination. # # @return [Array<OperationContract>] operation results. # def get_all_items items = @value page = self while page.next_link != nil && !page.next_link.strip.empty? do page = page.get_next_page items.concat(page.value) end items end # # Gets the next page of results. # # @return [OperationCollection] with next page content. # def get_next_page response = @next_method.call(@next_link).value! unless @next_method.nil? unless response.nil? @next_link = response.body.next_link @value = response.body.value self end end # # Mapper for OperationCollection class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'OperationCollection', type: { name: 'Composite', class_name: 'OperationCollection', model_properties: { value: { client_side_validation: true, required: false, read_only: true, serialized_name: 'value', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'OperationContractElementType', type: { name: 'Composite', class_name: 'OperationContract' } } } }, next_link: { client_side_validation: true, required: false, read_only: true, serialized_name: 'nextLink', type: { name: 'String' } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_api_management/lib/2019-01-01/generated/azure_mgmt_api_management/models/operation_collection.rb
Ruby
mit
2,802
using System.Data.SQLite; using System.IO; namespace FunWithSQLite.Db { public class Database { public const string CREATE_TABLE_SQL = @" CREATE TABLE MyTable ( Id integer NOT NULL PRIMARY KEY AUTOINCREMENT, Created varchar(28), LastModified varchar(28), MyColumn varchar(256) NOT NULL ); "; public const string INSERT_SQL = @"insert into MyTable (Created, LastModified, MyColumn) values ('2015-05-05-12:12:12', '2015-05-05-12:12:12', 'My value')"; public const string READ_SQL = @"select count('x') from MyTable"; public Database(string fullPath, string connectionString) : this(fullPath, connectionString, "Mr. Database") { } public Database(string fullPath, string connectionString, string name) { Name = name; FullPath = fullPath; ConnectionString = connectionString; } public string ConnectionString { get; } public string FullPath { get; } public string Name { get; } public void BackupTo(Database dstDb) { using (var src = new SQLiteConnection(this.ConnectionString)) using (var dst = new SQLiteConnection(dstDb.ConnectionString)) { src.Open(); dst.Open(); src.BackupDatabase(dst, "main", "main", -1, null, 0); } } public void CreateDb(string tableCreate = CREATE_TABLE_SQL) { if (File.Exists(FullPath)) File.Delete(FullPath); Directory.CreateDirectory(new FileInfo(FullPath).Directory.FullName); SQLiteConnection.CreateFile(FullPath); using (var con = new SQLiteConnection(ConnectionString)) using (var cmd = new SQLiteCommand(tableCreate, con)) { con.Open(); cmd.ExecuteNonQuery(); } } public void ExecuteNonQuery(string sql = INSERT_SQL) { using (var con = new SQLiteConnection(ConnectionString)) using (var cmd = new SQLiteCommand(sql, con)) { con.Open(); cmd.ExecuteNonQuery(); } } public T ExecuteScalarQuery<T>(string sql = READ_SQL) { using (var con = new SQLiteConnection(ConnectionString)) using (var cmd = new SQLiteCommand(sql, con)) { con.Open(); var result = cmd.ExecuteScalar(); return (T)result; } } } }
jquintus/spikes
ConsoleApps/FunWithSQLite/FunWithSQLite/Db/Database.cs
C#
mit
2,604
class WikiHouse::DoorPanelOuterSide < WikiHouse::WallPanelOuterSide def initialize(parent_part: nil, sheet: nil, group: nil, origin: nil, label: label) part_init(origin: origin, sheet: sheet, label: label, parent_part: parent_part) @length_method = :length @width_method = :depth init_board(right_connector: WikiHouse::TabConnector.new(count: 2, thickness: thickness), top_connector: WikiHouse::SlotConnector.new(count: 1, thickness: thickness), bottom_connector: WikiHouse::SlotConnector.new(count: 1, thickness: thickness, length_in_t: 2), left_connector: WikiHouse::TabConnector.new(count: 2, thickness: thickness), face_connector: [ WikiHouse::UPegPassThruConnector.new(thickness: thickness, count: parent_part.number_of_side_column_supports), WikiHouse::UPegEndPassThruConnector.new(thickness: thickness), WikiHouse::PocketConnector.new(count: parent_part.number_of_side_column_supports)] ) end def build_left_side super #add a tab at the top for the top section last_point = @left_side_points.pop connector = WikiHouse::TabConnector.new(count: 1, thickness: thickness) tab_points = connector.points(bounding_start: bounding_c4, bounding_end: nil, start_pt: [last_point.x, last_point.y - parent_part.top_column_length, last_point.z], end_pt: last_point, orientation: :left, starting_thickness: 0, total_length: parent_part.top_column_length) # tab_points.shift new_left_side = [] new_left_side.concat(@left_side_points) new_left_side.concat(tab_points) # new_left_side << last_point #new_left_side.concat(tab_points) @left_side_points = new_left_side return(@left_side_points) end def build_right_side super #add a tab at the top for the top section first_point = @right_side_points.shift connector = WikiHouse::TabConnector.new(count: 1, thickness: thickness) tab_points = connector.points(bounding_start: bounding_c2, bounding_end: nil, start_pt: first_point, end_pt: [first_point.x, first_point.y - parent_part.top_column_length, first_point.z], orientation: :right, starting_thickness: 0, total_length: parent_part.top_column_length) tab_points.shift new_right_side = [first_point] new_right_side.concat(tab_points) new_right_side.concat(@right_side_points) @right_side_points = new_right_side return(@right_side_points) end def draw_non_groove_faces super connector = WikiHouse::PocketConnector.new(length_in_t: 2, thickness: thickness, count: 1) connector.draw!(bounding_origin: [origin.x, origin.y, origin.z], part_length: parent_part.top_column_length * 2, part_width: width) end end
WikiHouseSATX/WikiHouseSATXSketchUpPlugin
models/parts/door_panel_outer_side.rb
Ruby
mit
3,182
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "db.h" #include "init.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; // Return average network hashes per second based on the last 'lookup' blocks, // or from the last difficulty change if 'lookup' is nonpositive. // If 'height' is nonnegative, compute the estimate at the time when a given block was found. Value GetNetworkHashPS(int lookup, int height) { CBlockIndex *pb = pindexBest; if (height >= 0 && height < nBestHeight) pb = FindBlockByHeight(height); if (pb == NULL || !pb->nHeight) return 0; // If lookup is -1, then use blocks since last difficulty change. if (lookup <= 0) lookup = pb->nHeight % 2016 + 1; // If lookup is larger than chain, then set it to chain length. if (lookup > pb->nHeight) lookup = pb->nHeight; CBlockIndex *pb0 = pb; int64 minTime = pb0->GetBlockTime(); int64 maxTime = minTime; for (int i = 0; i < lookup; i++) { pb0 = pb0->pprev; int64 time = pb0->GetBlockTime(); minTime = std::min(time, minTime); maxTime = std::max(time, maxTime); } // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception. if (minTime == maxTime) return 0; uint256 workDiff = pb->nChainWork - pb0->nChainWork; int64 timeDiff = maxTime - minTime; return (boost::int64_t)(workDiff.getdouble() / timeDiff); } Value getnetworkhashps(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getnetworkhashps [blocks] [height]\n" "Returns the estimated network hashes per second based on the last 120 blocks.\n" "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n" "Pass in [height] to estimate the network speed at the time when a certain block was found."); return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1); } // Key used by getwork/getblocktemplate miners. // Allocated in InitRPCMining, free'd in ShutdownRPCMining static CReserveKey* pMiningKey = NULL; void InitRPCMining() { if (!pwalletMain) return; // getwork/getblocktemplate mining rewards paid here: pMiningKey = new CReserveKey(pwalletMain); } void ShutdownRPCMining() { if (!pMiningKey) return; delete pMiningKey; pMiningKey = NULL; } Value getgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getgenerate\n" "Returns true or false."); if (!pMiningKey) return false; return GetBoolArg("-gen"); } Value setgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setgenerate <generate> [genproclimit]\n" "<generate> is true or false to turn generation on or off.\n" "Generation is limited to [genproclimit] processors, -1 is unlimited."); bool fGenerate = true; if (params.size() > 0) fGenerate = params[0].get_bool(); if (params.size() > 1) { int nGenProcLimit = params[1].get_int(); mapArgs["-genproclimit"] = itostr(nGenProcLimit); if (nGenProcLimit == 0) fGenerate = false; } mapArgs["-gen"] = (fGenerate ? "1" : "0"); assert(pwalletMain != NULL); GenerateBitcoins(fGenerate, pwalletMain); return Value::null; } Value gethashespersec(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "gethashespersec\n" "Returns a recent hashes per second performance measurement while generating."); if (GetTimeMillis() - nHPSTimerStart > 8000) return (boost::int64_t)0; return (boost::int64_t)dHashesPerSec; } Value getmininginfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmininginfo\n" "Returns an object containing mining-related information."); Object obj; obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx)); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("generate", GetBoolArg("-gen"))); obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1))); obj.push_back(Pair("hashespersec", gethashespersec(params, false))); obj.push_back(Pair("networkhashps", getnetworkhashps(params, false))); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); obj.push_back(Pair("testnet", fTestNet)); return obj; } Value getworkex(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getworkex [data, coinbase]\n" "If [data, coinbase] is not specified, returns extended work data.\n" ); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Corecoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Corecoin is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlockTemplate*> vNewBlockTemplate; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate) delete pblocktemplate; vNewBlockTemplate.clear(); } // Clear pindexPrev so future getworks make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block pblocktemplate = CreateNewBlockWithKey(*pMiningKey); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); vNewBlockTemplate.push_back(pblocktemplate); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Pre-build hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); CTransaction coinbaseTx = pblock->vtx[0]; std::vector<uint256> merkle = pblock->GetMerkleBranch(0); Object result; result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << coinbaseTx; result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end()))); Array merkle_arr; BOOST_FOREACH(uint256 merkleh, merkle) { printf("%s\n", merkleh.ToString().c_str()); merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh))); } result.push_back(Pair("merkle", merkle_arr)); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); vector<unsigned char> coinbase; if(params.size() == 2) coinbase = ParseHex(params[1].get_str()); if (vchData.size() != 128) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; if(coinbase.size() == 0) pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; else CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); return CheckWork(pblock, *pwalletMain, reservekey); } } Value getwork(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getwork [data]\n" "If [data] is not specified, returns formatted hash data to work on:\n" " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated " \"data\" : block data\n" " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated " \"target\" : little endian hash target\n" "If [data] is specified, tries to solve the block and returns true if it was successful."); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Corecoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Corecoin is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlockTemplate*> vNewBlockTemplate; if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate) delete pblocktemplate; vNewBlockTemplate.clear(); } // Clear pindexPrev so future getworks make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block pblocktemplate = CreateNewBlockWithKey(*pMiningKey); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); vNewBlockTemplate.push_back(pblocktemplate); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Pre-build hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); Object result; result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); if (vchData.size() != 128) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); assert(pwalletMain != NULL); return CheckWork(pblock, *pwalletMain, *pMiningKey); } } Value getblocktemplate(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getblocktemplate [params]\n" "Returns data needed to construct a block to work on:\n" " \"version\" : block version\n" " \"previousblockhash\" : hash of current highest block\n" " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n" " \"coinbaseaux\" : data that should be included in coinbase\n" " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n" " \"target\" : hash target\n" " \"mintime\" : minimum timestamp appropriate for next block\n" " \"curtime\" : current timestamp\n" " \"mutable\" : list of ways the block template may be changed\n" " \"noncerange\" : range of valid nonces\n" " \"sigoplimit\" : limit of sigops in blocks\n" " \"sizelimit\" : limit of block size\n" " \"bits\" : compressed target of next block\n" " \"height\" : height of the next block\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); std::string strMode = "template"; if (params.size() > 0) { const Object& oparam = params[0].get_obj(); const Value& modeval = find_value(oparam, "mode"); if (modeval.type() == str_type) strMode = modeval.get_str(); else if (modeval.type() == null_type) { /* Do nothing */ } else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); } if (strMode != "template") throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Corecoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Corecoin is downloading blocks..."); // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { // Clear pindexPrev so future calls make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block if(pblocktemplate) { delete pblocktemplate; pblocktemplate = NULL; } CScript scriptDummy = CScript() << OP_TRUE; pblocktemplate = CreateNewBlock(scriptDummy); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; Array transactions; map<uint256, int64_t> setTxIndex; int i = 0; BOOST_FOREACH (CTransaction& tx, pblock->vtx) { uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; if (tx.IsCoinBase()) continue; Object entry; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end()))); entry.push_back(Pair("hash", txHash.GetHex())); Array deps; BOOST_FOREACH (const CTxIn &in, tx.vin) { if (setTxIndex.count(in.prevout.hash)) deps.push_back(setTxIndex[in.prevout.hash]); } entry.push_back(Pair("depends", deps)); int index_in_template = i - 1; entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template])); entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template])); transactions.push_back(entry); } Object aux; aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end()))); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); static Array aMutable; if (aMutable.empty()) { aMutable.push_back("time"); aMutable.push_back("transactions"); aMutable.push_back("prevblock"); } Object result; result.push_back(Pair("version", pblock->nVersion)); result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex())); result.push_back(Pair("transactions", transactions)); result.push_back(Pair("coinbaseaux", aux)); result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue)); result.push_back(Pair("target", hashTarget.GetHex())); result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1)); result.push_back(Pair("mutable", aMutable)); result.push_back(Pair("noncerange", "00000000ffffffff")); result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS)); result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE)); result.push_back(Pair("curtime", (int64_t)pblock->nTime)); result.push_back(Pair("bits", HexBits(pblock->nBits))); result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); return result; } Value submitblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "submitblock <hex data> [optional-params-obj]\n" "[optional-params-obj] parameter is currently ignored.\n" "Attempts to submit new block to network.\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); vector<unsigned char> blockData(ParseHex(params[0].get_str())); CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION); CBlock pblock; try { ssBlock >> pblock; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); } CValidationState state; bool fAccepted = ProcessBlock(state, NULL, &pblock); if (!fAccepted) return "rejected"; // TODO: report validation state return Value::null; }
TimMaylon/corecoin
src/rpcmining.cpp
C++
mit
21,099
/* * grunt-tankipas * https://github.com/Leny/grunt-tankipas * * Copyright (c) 2014 Leny * Licensed under the MIT license. */ "use strict"; var chalk, error, spinner, tankipas; tankipas = require("tankipas"); chalk = require("chalk"); error = chalk.bold.red; (spinner = require("simple-spinner")).change_sequence(["◓", "◑", "◒", "◐"]); module.exports = function(grunt) { var tankipasTask; tankipasTask = function() { var fNext, oOptions; fNext = this.async(); oOptions = this.options({ system: null, gap: 120, user: null, branch: null, commit: null, raw: false }); spinner.start(50); return tankipas(process.cwd(), oOptions, function(oError, iTotal) { var iHours, iMinutes, sUserString; spinner.stop(); if (oError) { grunt.log.error(oError); fNext(false); } if (oOptions.raw) { grunt.log.writeln(iTotal); } else { iTotal /= 1000; iMinutes = (iMinutes = Math.floor(iTotal / 60)) > 60 ? iMinutes % 60 : iMinutes; iHours = Math.floor(iTotal / 3600); sUserString = oOptions.user ? " (for " + (chalk.cyan(oOptions.user)) + ")" : ""; grunt.log.writeln("Time spent on project" + sUserString + ": ±" + (chalk.yellow(iHours)) + " hours & " + (chalk.yellow(iMinutes)) + " minutes."); } return fNext(); }); }; if (grunt.config.data.tankipas) { return grunt.registerMultiTask("tankipas", "Compute approximate development time spent on a project, using logs from version control system.", tankipasTask); } else { return grunt.registerTask("tankipas", "Compute approximate development time spent on a project, using logs from version control system.", tankipasTask); } };
leny/grunt-tankipas
tasks/tankipas.js
JavaScript
mit
1,775
<?php use CoRex\Support\System\Session; use CoRex\Support\System\Token; use PHPUnit\Framework\TestCase; class TokenTest extends TestCase { private $test1 = 'test 1'; private $test2 = 'test 2'; /** * Setup. */ protected function setUp() { parent::setUp(); Token::clear(); } /** * Test create. */ public function testCreate() { $token1 = Token::create($this->test1); $token2 = Token::create($this->test2); $this->assertGreaterThan(30, strlen($token1)); $this->assertGreaterThan(30, strlen($token2)); $this->assertNotEquals($token1, $token2); } /** * Test get. */ public function testGet() { // Test if tokens exists. $this->assertFalse(Token::has($this->test1)); $this->assertFalse(Token::has($this->test2)); // Create tokens. $token1 = Token::create($this->test1); $token2 = Token::create($this->test2); // Check tokens. $this->assertEquals($token1, Token::get($this->test1)); $this->assertEquals($token2, Token::get($this->test2)); $this->assertNull(Token::get('unknown')); } /** * Test has. */ public function testHas() { // Check if tokens exists. $this->assertFalse(Token::has($this->test1)); $this->assertFalse(Token::has($this->test2)); // Create tokens. Token::create($this->test1); Token::create($this->test2); // Check if tokens exists. $this->assertTrue(Token::has($this->test1)); $this->assertTrue(Token::has($this->test2)); } /** * Test is valid. */ public function testIsValid() { // Get and test standard token. $token1 = Token::create($this->test1); // Set and test older token. Token::create($this->test2); $tokenData = Session::get($this->test2, null, Token::$namespace); $tokenData['time'] -= 500; Session::set($this->test2, $tokenData, Token::$namespace); $token2 = Token::get($this->test2); // Validate tokens. $this->assertTrue(Token::isValid($this->test1, $token1)); $this->assertFalse(Token::isValid($this->test2, $token2)); $this->assertFalse(Token::isValid('unknown', 'unknown')); } /** * Test delete. */ public function testDelete() { // Test if tokens exists. $this->assertFalse(Token::has($this->test1)); $this->assertFalse(Token::has($this->test2)); // Create test tokens. Token::create($this->test1); Token::create($this->test2); // Test if tokens exists. $this->assertTrue(Token::has($this->test1)); $this->assertTrue(Token::has($this->test2)); // Delete tokens. Token::delete($this->test1); Token::delete($this->test2); // Test if tokens exists. $this->assertFalse(Token::has($this->test1)); $this->assertFalse(Token::has($this->test2)); } }
corex/support
tests/System/TokenTest.php
PHP
mit
3,080
// test: indent_only const foo = 1 + 2 ; const foo = [1, 2]; const foo = [ 1, 2]; const foo = {a, b}; const foo = { a, b}; someMethod(foo, [ 0, 1, 2,], bar); someMethod( foo, [0, 1, 2,], bar); someMethod(foo, [ 0, 1, 2, ], bar); someMethod( foo, [ 1, 2],); someMethod( foo, [1, 2], ); someMethod(foo, { a: 1, b: 2,}, bar); someMethod( foo, {a: 1, b: 2,}, bar); someMethod(foo, { a: 1, b: 2 }, bar); someMethod( foo, { a: 1, b: 2},); someMethod( foo, {a: 1, b: 2}, ); someMethod(a => a*2 ); someMethod(a => { a*2} ); foo() .bar(a => a*2); foo().bar(a => a*2); foo = function() { }; foo = function() { }; switch (foo) { case 1: return b;} switch (foo) { case 1: return b;} class Foo { } class Foo { bar( ) {} } class Foo { bar() { } } if (x) { statement; more; }
codemirror/google-modes
test/js/indent.js
JavaScript
mit
995
/* * Snapshot multiple pages using arrays. * * Use an array to snapshot specific urls. * Use per-page selectors. * Use per-page output paths. * Remove all script tags from output. * Use javascript arrays. */ var path = require("path"); var util = require("util"); var assert = require("assert"); var htmlSnapshots = require("html-snapshots"); // a data structure with snapshot input var sites = [ { label: "html5rocks", url: "http://html5rocks.com", selector: ".latest-articles" }, { label: "updates.html5rocks", url: "http://updates.html5rocks.com", selector: ".articles-list" } ]; htmlSnapshots.run({ // input source is the array of urls to snapshot input: "array", source: sites.map(function(site) { return site.url; }), // setup and manage the output outputDir: path.join(__dirname, "./tmp"), outputDirClean: true, // per url output paths, { url: outputpath [, url: outputpath] } outputPath: sites.reduce(function(prev, curr) { prev[curr.url] = curr.label; // use the label to differentiate '/index.html' from both sites return prev; }, {}), // per url selectors, { url: selector [, url: selector] } selector: sites.reduce(function(prev, curr) { prev[curr.url] = curr.selector; return prev; }, {}), // remove all script tags from the output snapshotScript: { script: "removeScripts" } }, function(err, completed) { console.log("completed snapshots:"); console.log(util.inspect(completed)); // throw if there was an error assert.ifError(err); });
open-grabhouse/html-snapshots
examples/html5rocks/snapshot.js
JavaScript
mit
1,558
get '/decks' do @decks = Deck.order(:topic) erb :'/decks/index' end get '/decks/:deck_id/cards/:card_id' do @deck = Deck.find(params[:deck_id]) @card = @deck.cards.find(params[:card_id]) erb :'cards/show' end #if answer is true. Update Guess.correct to true #remove card from deck #show answer is correct onpage button to go tonext question #if wrong display wrong. put card in back. display correc submit button question post '/decks/:deck_id/cards/:card_id' do @deck = Deck.find(params([:deck_id])) @card = deck.cards.find(params[:card_id]) if params[:user_guess] == @card.answer card.guess.correct = true else thigns are false end end
MiniGiraffe23/Happy_with_Whatevs
app/controllers/decks.rb
Ruby
mit
673
import * as React from "react"; import { connect } from 'react-redux' import { searchSubTitle } from '../actions' function natcmp(a, b) { var ra = a.match(/\D+|\d+/g); var rb = b.match(/\D+|\d+/g); var r = 0; while (!r && ra.length && rb.length) { var x = ra.shift(), y = rb.shift(), nx = parseInt(x), ny = parseInt(y); if (isNaN(nx) || isNaN(ny)) r = x > y ? 1 : (x < y ? -1 : 0); else r = nx - ny; } return r || ra.length - rb.length; } class MediaTable extends React.Component<{ dispatch: Function, files: Array<MediaFileObject>, setting: any, filterWrods: string }, undefined> { clickDownloadHandler(mediaObj) { this.props.dispatch(searchSubTitle(mediaObj)) } renderMediaFilesList() { let {mediaPath} = this.props.setting; let resultHtml = []; // console.log(this.props.files) let files = this.props.files.sort((a, b) => { if (a.subs.length === 0 || b.subs.length === 0) { return a.subs.length - b.subs.length; } else { return natcmp(a.name, b.name); } }); files.forEach((mediaObj) => { let path = mediaObj.path.replace(mediaPath, ''); if (this.props.filterWrods && path.toLowerCase().indexOf(this.props.filterWrods.toLowerCase()) < 0) { return true; } path = path.substr(0, path.indexOf(mediaObj.name)); resultHtml.push( <tr key={mediaObj.name}> <td> <b>{mediaObj.name}</b> <p className="media-table__path">所在路径:{path}</p> </td> <td>{(mediaObj.subs && mediaObj.subs.length) || <span style={{ color: '#cc4b37' }}>0</span>}</td> <td> <a onClick={() => { this.clickDownloadHandler(mediaObj) }} href="javascript:;">搜索</a> </td> </tr> ) }) return resultHtml; } render() { return ( <table className="hover"> <thead> <tr> <th>视频名称</th> <th width="60">字幕</th> <th width="60">操作</th> </tr> </thead> <tbody> {this.renderMediaFilesList()} </tbody> </table> ); } } function mapStateToProps(state) { return { files: state.common.files || [], setting: state.common.setting || {}, filterWrods: state.common.mediaFilter } } export default connect(mapStateToProps)(MediaTable);
zqjimlove/subox
app/ts/modules/MediaTable.tsx
TypeScript
mit
2,815
import * as express from "express"; import { GameDashboardController } from "../controllers/GameDashboardController"; import { GameLobbyController } from "../controllers/GameLobbyController"; var router = express.Router(); export class GameRoutes { private gameDashboardController: GameDashboardController; private gameLobbyController: GameLobbyController; constructor() { this.gameDashboardController = new GameDashboardController(); this.gameLobbyController = new GameLobbyController(); } get routes() { router.get("/games", this.gameDashboardController.retrieve); router.post("/games", this.gameDashboardController.create); router.get("/games/:id", this.gameDashboardController.findById); router.put("/games/:id/join", this.gameLobbyController.joinGameLobby); router.put("/games/:id/leave", this.gameLobbyController.leaveGameLobby); router.get('/games/:id/start', this.gameLobbyController.startGame); return router; } } Object.seal(GameRoutes);
atomicham/defiance
src/server/web/routes/GameRoutes.ts
TypeScript
mit
1,049
package hashcat3 type Dictionary struct { Name string Path string } type Dictionaries []Dictionary func (d Dictionaries) Len() int { return len(d) } func (d Dictionaries) Swap(i, j int) { d[i], d[j] = d[j], d[i] } func (d Dictionaries) Less(i, j int) bool { return d[i].Name < d[j].Name }
jmmcatee/cracklord
plugins/tools/hashcat3/dictionaries.go
GO
mit
299
/*! * Office for Experience Design v1.0.0 (http://ing-experience-design.com/) * Copyright 2016 ING, Office for Experience Design * Licensed under MIT (https://spdx.org/licenses/MIT) */
designing-experiences/designing-experiences.github.io
assets/js/ing-experience-design.min.js
JavaScript
mit
190
var async = require('async'), fs = require('graceful-fs'), path = require('path'), colors = require('colors'), swig = require('swig'), spawn = require('child_process').spawn, util = require('../../util'), file = util.file2, commitMessage = require('./util').commitMessage; // http://git-scm.com/docs/git-clone var rRepo = /(:|\/)([^\/]+)\/([^\/]+)\.git\/?$/; module.exports = function(args, callback){ var baseDir = hexo.base_dir, deployDir = path.join(baseDir, '.deploy'), publicDir = hexo.public_dir; if (!args.repo && !args.repository){ var help = ''; help += 'You should configure deployment settings in _config.yml first!\n\n'; help += 'Example:\n'; help += ' deploy:\n'; help += ' type: github\n'; help += ' repo: <repository url>\n'; help += ' branch: [branch]\n'; help += ' message: [message]\n\n'; help += 'For more help, you can check the docs: ' + 'http://hexo.io/docs/deployment.html'.underline; console.log(help); return callback(); } var url = args.repo || args.repository; if (!rRepo.test(url)){ hexo.log.e(url + ' is not a valid repository URL!'); return callback(); } var branch = args.branch; if (!branch){ var match = url.match(rRepo), username = match[2], repo = match[3], rGh = new RegExp('^' + username + '\\.github\\.[io|com]', 'i'); // https://help.github.com/articles/user-organization-and-project-pages if (repo.match(rGh)){ branch = 'master'; } else { branch = 'gh-pages'; } } var run = function(command, args, callback){ var cp = spawn(command, args, {cwd: deployDir}); cp.stdout.on('data', function(data){ process.stdout.write(data); }); cp.stderr.on('data', function(data){ process.stderr.write(data); }); cp.on('close', callback); }; async.series([ // Set up function(next){ fs.exists(deployDir, function(exist){ if (exist && !args.setup) return next(); hexo.log.i('Setting up GitHub deployment...'); var commands = [ ['init'], ['add', '-A', '.'], ['commit', '-m', 'First commit'] ]; if (branch !== 'master') commands.push(['branch', '-M', branch]); commands.push(['remote', 'add', 'github', url]); file.writeFile(path.join(deployDir, 'placeholder'), '', function(err){ if (err) callback(err); async.eachSeries(commands, function(item, next){ run('git', item, function(code){ if (code === 0) next(); }); }, function(){ if (!args.setup) next(); }); }); }); }, function(next){ hexo.log.i('Clearing .deploy folder...'); file.emptyDir(deployDir, next); }, function(next){ hexo.log.i('Copying files from public folder...'); file.copyDir(publicDir, deployDir, next); }, function(next){ var commands = [ ['add', '-A'], ['commit', '-m', commitMessage(args)], ['push', '-u', 'github', branch, '--force'] ]; async.eachSeries(commands, function(item, next){ run('git', item, function(){ next(); }); }, next); } ], callback); };
007slm/hexo
lib/plugins/deployer/github.js
JavaScript
mit
3,302
require 'socket' ''' The API to this is very simple GET / - returns all keys GET /key - returns value of key "key" GET /key/value - sets value of key "key" to value ''' class SocketListen def initialize port=8181 @data = { 'apache' => 'apache', 'bsd' => 'mit', 'chef' => 'apache' } @port = port || 8181 @server = TCPServer.new @port loop { client = @server.accept request = client.gets puts request client.puts handle request client.close } end def handle arg verb = arg.split()[0] arg=arg.split()[1..-1].join(" ") if verb == 'GET' return handle_get arg else return "NOT IMPLEMENTED" end end def handle_get arg path = (arg.split[0]).split('/')[1..-1] if path.nil? keys=[] @data.each do |key,value| keys << key end puts keys return keys else puts path[0] + " => " + @data[path[0]] return @data[path[0]] + " " end end end SocketListen.new()
dsklopp/ruby_class_2015_samples
day_3/rest_5b.rb
Ruby
mit
1,010
module Pundit class PolicyFinder private alias :original_find :find def find if object.is_a?(ActiveRecord::Associations::CollectionProxy) "#{object.klass}Policy" else original_find end end end end
archan937/directiveadmin
lib/directive_admin/gem_ext/pundit/policy_finder.rb
Ruby
mit
253
@extends('common') @section('title'){{ $article->title }} - @parent @stop @section('meta') <meta name="keywords" content="{{ $article->keywords }}"> <meta name="description" content="{{ $article->description }}"> <meta name="author" content="chongyi@xopns.com"> @stop @section('body') <!-- 面包屑导航 --> <nav> <ul class="am-breadcrumb"> <li><a title="首页" href="/">首页</a></li> <li class="am-active">{{ $article->title }}</li> </ul> </nav> <!-- 最新最热文章聚合展示区 --> <div class="am-g"> <!-- 文章列表区 --> <div class="am-u-md-8"> <article class="insp-d-article"> <header> <h1 class="insp-d-title">{{ $article->title }}</h1> <div class="insp-d-article-info"> </div> </header> <div class="insp-d-article-body"> {!! \App\Inspirer\ArticleProcess::getContent($article->content) !!} </div> <footer> <div class="insp-d-article-footer-notice-list"> </div> </footer> </article> </div> @include('widget') </div> @stop
chongyi/inspirer
resources/views/page/page.blade.php
PHP
mit
1,293
require 'spec_helper' describe SupportEngine do it "should be valid" do SupportEngine.should be_a(Module) end end
sparrovv/support_engine
spec/support_engine_spec.rb
Ruby
mit
122
// config.pro.spec.js import config from '../../../src/constants/config.pro' describe('Config PRO constants', function () { test('exist', () => { expect(config).toMatchSnapshot() }) })
ToniChaz/react-redux
test/unit/constants/config.pro.spec.js
JavaScript
mit
194
const DrawCard = require('../../drawcard.js'); class VaesTolorro extends DrawCard { setupCardAbilities(ability) { this.interrupt({ when: { onCharacterKilled: event => event.card.getPower() >= 1 }, cost: ability.costs.kneelSelf(), handler: context => { let pendingCard = context.event.card; let power = pendingCard.getPower() >= 2 && pendingCard.getStrength() === 0 ? 2 : 1; pendingCard.modifyPower(-power); this.modifyPower(power); this.game.addMessage('{0} kneels {1} to move {2} power from {3} to {1}', this.controller, this, power, pendingCard); } }); } } VaesTolorro.code = '04074'; module.exports = VaesTolorro;
cryogen/gameteki
server/game/cards/04.4-TIMC/VaesTolorro.js
JavaScript
mit
821
package app import ( "time" "github.com/urfave/cli" ) type innerContext interface { Args() cli.Args Bool(name string) bool BoolT(name string) bool Duration(name string) time.Duration FlagNames() (names []string) Float64(name string) float64 Generic(name string) interface{} GlobalBool(name string) bool GlobalBoolT(name string) bool GlobalDuration(name string) time.Duration GlobalFlagNames() (names []string) GlobalFloat64(name string) float64 GlobalGeneric(name string) interface{} GlobalInt(name string) int GlobalInt64(name string) int64 GlobalInt64Slice(name string) []int64 GlobalIntSlice(name string) []int GlobalIsSet(name string) bool GlobalSet(name, value string) error GlobalString(name string) string GlobalStringSlice(name string) []string GlobalUint(name string) uint GlobalUint64(name string) uint64 Int(name string) int Int64(name string) int64 Int64Slice(name string) []int64 IntSlice(name string) []int IsSet(name string) bool NArg() int NumFlags() int Parent() *cli.Context Set(name, value string) error String(name string) string StringSlice(name string) []string Uint(name string) uint Uint64(name string) uint64 App() *cli.App Command() cli.Command } // CliContextWrapper is a struct which embeds cli.Context and is used to ensure that the entirety of innerContext is implemented on it. This allows for making mocks of cli.Contexts. App() and Command() are the methods unique to innerContext that are not in cli.Context type CliContextWrapper struct { *cli.Context } // App returns the app for this Context func (ctx CliContextWrapper) App() *cli.App { return ctx.Context.App } // Command returns the Command that was run to create this Context func (ctx CliContextWrapper) Command() cli.Command { return ctx.Context.Command }
BytemarkHosting/bytemark-client
cmd/bytemark/app/clicontext.go
GO
mit
1,799
# A subscription has moved from the Active status to the Past Due status. This will only be triggered when the initial transaction in a billing cycle is declined. Once the status moves to past due, it will not be triggered again in that billing cycle. module Pay module Braintree module Webhooks class SubscriptionWentPastDue def call(event) subscription = event.subscription return if subscription.nil? pay_subscription = Pay.subscription_model.find_by(processor: :braintree, processor_id: subscription.id) return unless pay_subscription.present? pay_subscription.update!(status: :past_due) end end end end end
jasoncharnes/pay
lib/pay/braintree/webhooks/subscription_went_past_due.rb
Ruby
mit
705
package com.zoinks.waterreporting.model; import android.util.Log; import com.github.mikephil.charting.data.Entry; import com.google.gson.Gson; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.List; /** * Facade for the model for users and water reports * * Created by Nancy on 03/24/2017. */ public class Facade { public final static String USER_JSON = "users.json"; public final static String REPORT_JSON = "reports.json"; // required model classes private UserSvcProvider usp; private WaterReportSvcProvider wrsp; // singleton private static Facade instance = new Facade(); private Facade() { usp = new UserSvcProvider(); wrsp = new WaterReportSvcProvider(); } /** * Accessor for singleton instance of Facade * * @return Facade singleton instance */ public static Facade getInstance() { return instance; } /** * Loads data from saved json * * @param userFile the file from which to load the user json * @param reportsFile the file from which to load the reports json * @return true if successful */ public boolean loadData(File userFile, File reportsFile) { try { // first load up the users BufferedReader input = new BufferedReader(new FileReader(userFile)); // Since we saved the json as a string, we just read in the string normally String inString = input.readLine(); Log.d("DEBUG", "JSON: " + inString); // use the Gson library to recreate the object references and links Gson gson = new Gson(); usp = gson.fromJson(inString, UserSvcProvider.class); input.close(); } catch (IOException e) { Log.e("Facade", "Failed to open/read the buffered reader for user json"); return false; } try { // next load up the water reports BufferedReader input = new BufferedReader(new FileReader(reportsFile)); // Since we saved the json as a string, we just read in the string normally String inString = input.readLine(); Log.d("DEBUG", "JSON: " + inString); // use the Gson library to recreate the object references and links Gson gson = new Gson(); wrsp = gson.fromJson(inString, WaterReportSvcProvider.class); input.close(); } catch (IOException e) { Log.e("Facade", "Failed to open/read the buffered reader for reports json"); return false; } return true; } /** * Saves data to json * * @param userFile the json file to which to save the user * @param reportsFile the json file to which to save the reports * @return true if successful */ public boolean saveData(File userFile, File reportsFile) { try { PrintWriter writer = new PrintWriter(userFile); Gson gson = new Gson(); // convert our objects to a string for output String outString = gson.toJson(usp); Log.d("DEBUG", "JSON Saved: " + outString); // then just write the string writer.println(outString); writer.close(); } catch (FileNotFoundException e) { Log.e("Facade", "Failed to open json file for output"); return false; } try { PrintWriter writer = new PrintWriter(reportsFile); Gson gson = new Gson(); // convert our objects to a string for output String outString = gson.toJson(wrsp); Log.d("DEBUG", "JSON Saved: " + outString); // then just write the string writer.println(outString); writer.close(); } catch (FileNotFoundException e) { Log.e("Facade", "Failed to open json file for output"); return false; } return true; } /** * Returns the currently logged in user, if any * * @return the currently logged in user, if any */ public User getCurrentUser() { return usp.getCurrentUser(); } /** * Gets all of the users currently registered * @return a List of all of the Users currently registered */ public List<User> getAllUsers() { return usp.getAllUsers(); } /** * Attempts to register a new user * * @param firstName first name of the new user * @param lastName last name of the new user * @param username username of the new user * @param password un-hashed password of new user * @param privilege type of new user, used for privilege * @return True if the new user was registered, False if the user was not registered (ie username taken) */ public boolean registerUser(String firstName, String lastName, String username, String password, UserType privilege) { return usp.register(firstName, lastName, username, password, privilege); } /** * Delete user's account * * @param username username of the user to delete */ public void deleteUser(String username) { usp.deleteUser(username); } /** * Gets the User by username * @param username of User to get * @return User with associated username */ public User getUserByUsername(String username) { return usp.getUserByUsername(username); } /** * Updates attributes passed in to update profile of current user * * @param oldUsername username from current user * @param newUsername username from edit text * @param firstName new or old firstName * @param lastName new or old lastName * @param password "" if password was unchanged, otherwise old hashed password * @return boolean true if profile was updated */ public boolean updateUser(String oldUsername, String newUsername, String firstName, String lastName, String password, String email, String address, String phone) { return usp.update(oldUsername, newUsername, firstName, lastName, password, email, address, phone); } /** * Attempts login * * @param username username of profile trying to login as * @param password to be checked for a match * @return True only if user exists and password matches * False if password incorrect, user does not exist, or user blocked */ public boolean login(String username, String password) { return usp.login(username, password); } /** * Logs user out of application and resets current user */ public void logout() { usp.logout(); } /** * Get the list of water reports * * @return the list of water reports */ public List<WaterReport> getReports() { return wrsp.getReports(); } /** * Get the list of water source reports * * @return the list of water source reports */ public List<WaterReport> getSourceReports() { return wrsp.getSourceReports(); } /** * Get the list of water quality reports for managers to view * * @return the list of water quality reports */ public List<WaterReport> getQualityReports() { return wrsp.getQualityReports(); } /** * Adds a water source report where time is current time and author is current user * * @param latitude latitude of the water report * @param longitude longitude of the water report * @param type type of water at the water source * @param condition condition of water at the water source */ public void addSourceReport(double latitude, double longitude, WaterSourceType type, WaterSourceCondition condition) { wrsp.addSourceReport(latitude, longitude, type, condition, usp.getCurrentUser()); } /** * Adds a water quality report where time is current time and author is current user * * @param latitude latitude of the water report * @param longitude longitude of the water report * @param condition condition of water at the water source * @param virusPPM virus concentration measured in PPM at the water source * @param contaminantPPM contaminant concentration measured in PPM at the water source */ public void addQualityReport(double latitude, double longitude, WaterQualityCondition condition, double virusPPM, double contaminantPPM) { wrsp.addQualityReport(latitude, longitude, condition, virusPPM, contaminantPPM, usp.getCurrentUser()); } /** * Returns the data for the year requested, 12 points, one for each month for the location requested * * @param year the year from which data is requested * @param latitude the latitude of the reports to get * @param longitude the longitude of the reports to get * @param virus true if the manager wishes to graph virus PPM, false to graph contaminant PPM */ public List<Entry> getYearsData(int year, double latitude, double longitude, boolean virus) { return wrsp.getYearsData(year, latitude, longitude, virus); } }
seantitus/WaterReporting
app/src/main/java/com/zoinks/waterreporting/model/Facade.java
Java
mit
9,500
<?php namespace MessageContext\Domain\Event; class DomainEvents { const MESSAGE_PUBLISHED_ON_CHANNEL = "message_context.message.published"; }
danieledangeli/symfony-microservice-bounded-context-example
src/MessageContext/Domain/Event/DomainEvents.php
PHP
mit
148
<!doctype html> <html class="no-js" lang=""> <head> <title>Zabuun - Learn Egyptian Arabic for English speakers</title> <meta name="description" content=""> <?php include $_SERVER['DOCUMENT_ROOT'].'/layout/head.php';?> </head> <body> <?php include $_SERVER['DOCUMENT_ROOT'].'/layout/ie8.php';?> <?php include $_SERVER['DOCUMENT_ROOT'].'/layout/header.php';?> <div class="content"> <?php include $_SERVER['DOCUMENT_ROOT'].'/layout/side.php';?> <div class="main"> <div class="location"> <p class="breadcrumbs">Essays > Passion for Pizza</p> <p class="expandcollapse"> <a href="">Expand All</a> | <a href="">Collapse All</a> </p> </div> <!-- begin essay --> <h1>Passion for Pizza</h1> <p> Clark graduated from college with a degree in chemistry. His parents were so excited for his future. "You're going to make a great doctor!" they always said. Clark did not want to be a doctor. All he wanted was to open up his own pizza place. "That's ridiculous," said his mother. "Think about how much money you could make as a doctor!" Clark did not care about money. All he wanted was to spend every day making, smelling, and eating pizzas. </p> <!-- end essay --> </div> </div> <?php include $_SERVER['DOCUMENT_ROOT'].'/layout/footer.php';?> <?php include $_SERVER['DOCUMENT_ROOT'].'/layout/scripts.php';?> </body> </html>
javanigus/zabuun
essay/0805-passion-for-pizza.php
PHP
mit
1,392
module DropletKit class KubernetesClusterResource < ResourceKit::Resource include ErrorHandlingResourcable resources do action :all, 'GET /v2/kubernetes/clusters' do query_keys :per_page, :page, :tag_name handler(200) { |response| KubernetesClusterMapping.extract_collection(response.body, :read) } end action :find, 'GET /v2/kubernetes/clusters/:id' do handler(200) { |response| KubernetesClusterMapping.extract_single(response.body, :read) } end action :create, 'POST /v2/kubernetes/clusters' do body { |object| KubernetesClusterMapping.representation_for(:create, object) } handler(201) { |response, cluster| KubernetesClusterMapping.extract_into_object(cluster, response.body, :read) } handler(422) { |response| ErrorMapping.fail_with(FailedCreate, response.body) } end action :kubeconfig, 'GET /v2/kubernetes/clusters/:id/kubeconfig' do handler(200) { |response| response.body } end action :update, 'PUT /v2/kubernetes/clusters/:id' do body { |cluster| KubernetesClusterMapping.representation_for(:update, cluster) } handler(202) { |response| KubernetesClusterMapping.extract_single(response.body, :read) } handler(422) { |response| ErrorMapping.fail_with(FailedUpdate, response.body) } end action :delete, 'DELETE /v2/kubernetes/clusters/:id' do handler(202) { |response| true } end action :node_pools, 'GET /v2/kubernetes/clusters/:id/node_pools' do handler(200) { |response| KubernetesNodePoolMapping.extract_collection(response.body, :read) } end action :find_node_pool, 'GET /v2/kubernetes/clusters/:id/node_pools/:pool_id' do handler(200) { |response| KubernetesNodePoolMapping.extract_single(response.body, :read) } end action :create_node_pool, 'POST /v2/kubernetes/clusters/:id/node_pools' do body { |node_pool| KubernetesNodePoolMapping.representation_for(:create, node_pool) } handler(201) { |response| KubernetesNodePoolMapping.extract_single(response.body, :read) } handler(422) { |response| ErrorMapping.fail_with(FailedCreate, response.body) } end action :update_node_pool, 'PUT /v2/kubernetes/clusters/:id/node_pools/:pool_id' do body { |node_pool| KubernetesNodePoolMapping.representation_for(:update, node_pool) } handler(202) { |response| KubernetesNodePoolMapping.extract_single(response.body, :read) } handler(404) { |response| ErrorMapping.fail_with(FailedUpdate, response.body) } end action :delete_node_pool, 'DELETE /v2/kubernetes/clusters/:id/node_pools/:pool_id' do handler(202) { |response| true } end action :recycle_node_pool, 'POST /v2/kubernetes/clusters/:id/node_pools/:pool_id/recycle' do body { |node_ids| { nodes: node_ids }.to_json } handler(202) { |response| true } handler(404) { |response| ErrorMapping.fail_with(FailedUpdate, response.body) } end end def all(*args) PaginatedResource.new(action(:all), self, *args) end end end
andrewsomething/droplet_kit
lib/droplet_kit/resources/kubernetes_cluster_resource.rb
Ruby
mit
3,144
// ImGui Win32 + DirectX11 binding // Implemented features: // [X] User texture binding. Use 'ID3D11ShaderResourceView*' as ImTextureID. Read the FAQ about ImTextureID in imgui.cpp. // You can copy and use unmodified imgui_impl_* files in your project. See main.cpp for an example of using this. // If you use this binding you'll need to call 4 functions: ImGui_ImplXXXX_Init(), ImGui_ImplXXXX_NewFrame(), ImGui::Render() and ImGui_ImplXXXX_Shutdown(). // If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp. // https://github.com/ocornut/imgui // CHANGELOG // (minor and older changes stripped away, please see git history for details) // 2018-02-20: Inputs: Added support for mouse cursors (ImGui::GetMouseCursor() value and WM_SETCURSOR message handling). // 2018-02-16: Misc: Obsoleted the io.RenderDrawListsFn callback and exposed ImGui_ImplDX11_RenderDrawData() in the .h file so you can call it yourself. // 2018-02-06: Misc: Removed call to ImGui::Shutdown() which is not available from 1.60 WIP, user needs to call CreateContext/DestroyContext themselves. // 2018-02-06: Inputs: Added mapping for ImGuiKey_Space. // 2018-02-06: Inputs: Honoring the io.WantMoveMouse by repositioning the mouse (when using navigation and ImGuiConfigFlags_NavMoveMouse is set). // 2018-01-20: Inputs: Added Horizontal Mouse Wheel support. // 2018-01-08: Inputs: Added mapping for ImGuiKey_Insert. // 2018-01-05: Inputs: Added WM_LBUTTONDBLCLK double-click handlers for window classes with the CS_DBLCLKS flag. // 2017-10-23: Inputs: Added WM_SYSKEYDOWN / WM_SYSKEYUP handlers so e.g. the VK_MENU key can be read. // 2017-10-23: Inputs: Using Win32 ::SetCapture/::GetCapture() to retrieve mouse positions outside the client area when dragging. // 2016-11-12: Inputs: Only call Win32 ::SetCursor(NULL) when io.MouseDrawCursor is set. // 2016-05-07: DirectX11: Disabling depth-write. #include "imgui.h" #include "imgui_impl_dx11.h" // DirectX #include <d3d11.h> #include <d3dcompiler.h> #define DIRECTINPUT_VERSION 0x0800 #include <dinput.h> // Win32 data static HWND g_hWnd = 0; static INT64 g_Time = 0; static INT64 g_TicksPerSecond = 0; static ImGuiMouseCursor g_LastMouseCursor = ImGuiMouseCursor_Count_; // DirectX data static ID3D11Device* g_pd3dDevice = NULL; static ID3D11DeviceContext* g_pd3dDeviceContext = NULL; static ID3D11Buffer* g_pVB = NULL; static ID3D11Buffer* g_pIB = NULL; static ID3D10Blob * g_pVertexShaderBlob = NULL; static ID3D11VertexShader* g_pVertexShader = NULL; static ID3D11InputLayout* g_pInputLayout = NULL; static ID3D11Buffer* g_pVertexConstantBuffer = NULL; static ID3D10Blob * g_pPixelShaderBlob = NULL; static ID3D11PixelShader* g_pPixelShader = NULL; static ID3D11SamplerState* g_pFontSampler = NULL; static ID3D11ShaderResourceView*g_pFontTextureView = NULL; static ID3D11RasterizerState* g_pRasterizerState = NULL; static ID3D11BlendState* g_pBlendState = NULL; static ID3D11DepthStencilState* g_pDepthStencilState = NULL; static int g_VertexBufferSize = 5000, g_IndexBufferSize = 10000; struct VERTEX_CONSTANT_BUFFER { float mvp[4][4]; }; // Render function // (this used to be set in io.RenderDrawListsFn and called by ImGui::Render(), but you can now call this directly from your main loop) void ImGui_ImplDX11_RenderDrawData(ImDrawData* draw_data) { ID3D11DeviceContext* ctx = g_pd3dDeviceContext; // Create and grow vertex/index buffers if needed if (!g_pVB || g_VertexBufferSize < draw_data->TotalVtxCount) { if (g_pVB) { g_pVB->Release(); g_pVB = NULL; } g_VertexBufferSize = draw_data->TotalVtxCount + 5000; D3D11_BUFFER_DESC desc; memset(&desc, 0, sizeof(D3D11_BUFFER_DESC)); desc.Usage = D3D11_USAGE_DYNAMIC; desc.ByteWidth = g_VertexBufferSize * sizeof(ImDrawVert); desc.BindFlags = D3D11_BIND_VERTEX_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; desc.MiscFlags = 0; if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVB) < 0) return; } if (!g_pIB || g_IndexBufferSize < draw_data->TotalIdxCount) { if (g_pIB) { g_pIB->Release(); g_pIB = NULL; } g_IndexBufferSize = draw_data->TotalIdxCount + 10000; D3D11_BUFFER_DESC desc; memset(&desc, 0, sizeof(D3D11_BUFFER_DESC)); desc.Usage = D3D11_USAGE_DYNAMIC; desc.ByteWidth = g_IndexBufferSize * sizeof(ImDrawIdx); desc.BindFlags = D3D11_BIND_INDEX_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; if (g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pIB) < 0) return; } // Copy and convert all vertices into a single contiguous buffer D3D11_MAPPED_SUBRESOURCE vtx_resource, idx_resource; if (ctx->Map(g_pVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &vtx_resource) != S_OK) return; if (ctx->Map(g_pIB, 0, D3D11_MAP_WRITE_DISCARD, 0, &idx_resource) != S_OK) return; ImDrawVert* vtx_dst = (ImDrawVert*)vtx_resource.pData; ImDrawIdx* idx_dst = (ImDrawIdx*)idx_resource.pData; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; memcpy(vtx_dst, cmd_list->VtxBuffer.Data, cmd_list->VtxBuffer.Size * sizeof(ImDrawVert)); memcpy(idx_dst, cmd_list->IdxBuffer.Data, cmd_list->IdxBuffer.Size * sizeof(ImDrawIdx)); vtx_dst += cmd_list->VtxBuffer.Size; idx_dst += cmd_list->IdxBuffer.Size; } ctx->Unmap(g_pVB, 0); ctx->Unmap(g_pIB, 0); // Setup orthographic projection matrix into our constant buffer { D3D11_MAPPED_SUBRESOURCE mapped_resource; if (ctx->Map(g_pVertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mapped_resource) != S_OK) return; VERTEX_CONSTANT_BUFFER* constant_buffer = (VERTEX_CONSTANT_BUFFER*)mapped_resource.pData; float L = 0.0f; float R = ImGui::GetIO().DisplaySize.x; float B = ImGui::GetIO().DisplaySize.y; float T = 0.0f; float mvp[4][4] = { { 2.0f/(R-L), 0.0f, 0.0f, 0.0f }, { 0.0f, 2.0f/(T-B), 0.0f, 0.0f }, { 0.0f, 0.0f, 0.5f, 0.0f }, { (R+L)/(L-R), (T+B)/(B-T), 0.5f, 1.0f }, }; memcpy(&constant_buffer->mvp, mvp, sizeof(mvp)); ctx->Unmap(g_pVertexConstantBuffer, 0); } // Backup DX state that will be modified to restore it afterwards (unfortunately this is very ugly looking and verbose. Close your eyes!) struct BACKUP_DX11_STATE { UINT ScissorRectsCount, ViewportsCount; D3D11_RECT ScissorRects[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE]; D3D11_VIEWPORT Viewports[D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE]; ID3D11RasterizerState* RS; ID3D11BlendState* BlendState; FLOAT BlendFactor[4]; UINT SampleMask; UINT StencilRef; ID3D11DepthStencilState* DepthStencilState; ID3D11ShaderResourceView* PSShaderResource; ID3D11SamplerState* PSSampler; ID3D11PixelShader* PS; ID3D11VertexShader* VS; UINT PSInstancesCount, VSInstancesCount; ID3D11ClassInstance* PSInstances[256], *VSInstances[256]; // 256 is max according to PSSetShader documentation D3D11_PRIMITIVE_TOPOLOGY PrimitiveTopology; ID3D11Buffer* IndexBuffer, *VertexBuffer, *VSConstantBuffer; UINT IndexBufferOffset, VertexBufferStride, VertexBufferOffset; DXGI_FORMAT IndexBufferFormat; ID3D11InputLayout* InputLayout; }; BACKUP_DX11_STATE old; old.ScissorRectsCount = old.ViewportsCount = D3D11_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE; ctx->RSGetScissorRects(&old.ScissorRectsCount, old.ScissorRects); ctx->RSGetViewports(&old.ViewportsCount, old.Viewports); ctx->RSGetState(&old.RS); ctx->OMGetBlendState(&old.BlendState, old.BlendFactor, &old.SampleMask); ctx->OMGetDepthStencilState(&old.DepthStencilState, &old.StencilRef); ctx->PSGetShaderResources(0, 1, &old.PSShaderResource); ctx->PSGetSamplers(0, 1, &old.PSSampler); old.PSInstancesCount = old.VSInstancesCount = 256; ctx->PSGetShader(&old.PS, old.PSInstances, &old.PSInstancesCount); ctx->VSGetShader(&old.VS, old.VSInstances, &old.VSInstancesCount); ctx->VSGetConstantBuffers(0, 1, &old.VSConstantBuffer); ctx->IAGetPrimitiveTopology(&old.PrimitiveTopology); ctx->IAGetIndexBuffer(&old.IndexBuffer, &old.IndexBufferFormat, &old.IndexBufferOffset); ctx->IAGetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); ctx->IAGetInputLayout(&old.InputLayout); // Setup viewport D3D11_VIEWPORT vp; memset(&vp, 0, sizeof(D3D11_VIEWPORT)); vp.Width = ImGui::GetIO().DisplaySize.x; vp.Height = ImGui::GetIO().DisplaySize.y; vp.MinDepth = 0.0f; vp.MaxDepth = 1.0f; vp.TopLeftX = vp.TopLeftY = 0.0f; ctx->RSSetViewports(1, &vp); // Bind shader and vertex buffers unsigned int stride = sizeof(ImDrawVert); unsigned int offset = 0; ctx->IASetInputLayout(g_pInputLayout); ctx->IASetVertexBuffers(0, 1, &g_pVB, &stride, &offset); ctx->IASetIndexBuffer(g_pIB, sizeof(ImDrawIdx) == 2 ? DXGI_FORMAT_R16_UINT : DXGI_FORMAT_R32_UINT, 0); ctx->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); ctx->VSSetShader(g_pVertexShader, NULL, 0); ctx->VSSetConstantBuffers(0, 1, &g_pVertexConstantBuffer); ctx->PSSetShader(g_pPixelShader, NULL, 0); ctx->PSSetSamplers(0, 1, &g_pFontSampler); // Setup render state const float blend_factor[4] = { 0.f, 0.f, 0.f, 0.f }; ctx->OMSetBlendState(g_pBlendState, blend_factor, 0xffffffff); ctx->OMSetDepthStencilState(g_pDepthStencilState, 0); ctx->RSSetState(g_pRasterizerState); // Render command lists int vtx_offset = 0; int idx_offset = 0; for (int n = 0; n < draw_data->CmdListsCount; n++) { const ImDrawList* cmd_list = draw_data->CmdLists[n]; for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) { const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; if (pcmd->UserCallback) { pcmd->UserCallback(cmd_list, pcmd); } else { const D3D11_RECT r = { (LONG)pcmd->ClipRect.x, (LONG)pcmd->ClipRect.y, (LONG)pcmd->ClipRect.z, (LONG)pcmd->ClipRect.w }; ctx->PSSetShaderResources(0, 1, (ID3D11ShaderResourceView**)&pcmd->TextureId); ctx->RSSetScissorRects(1, &r); ctx->DrawIndexed(pcmd->ElemCount, idx_offset, vtx_offset); } idx_offset += pcmd->ElemCount; } vtx_offset += cmd_list->VtxBuffer.Size; } // Restore modified DX state ctx->RSSetScissorRects(old.ScissorRectsCount, old.ScissorRects); ctx->RSSetViewports(old.ViewportsCount, old.Viewports); ctx->RSSetState(old.RS); if (old.RS) old.RS->Release(); ctx->OMSetBlendState(old.BlendState, old.BlendFactor, old.SampleMask); if (old.BlendState) old.BlendState->Release(); ctx->OMSetDepthStencilState(old.DepthStencilState, old.StencilRef); if (old.DepthStencilState) old.DepthStencilState->Release(); ctx->PSSetShaderResources(0, 1, &old.PSShaderResource); if (old.PSShaderResource) old.PSShaderResource->Release(); ctx->PSSetSamplers(0, 1, &old.PSSampler); if (old.PSSampler) old.PSSampler->Release(); ctx->PSSetShader(old.PS, old.PSInstances, old.PSInstancesCount); if (old.PS) old.PS->Release(); for (UINT i = 0; i < old.PSInstancesCount; i++) if (old.PSInstances[i]) old.PSInstances[i]->Release(); ctx->VSSetShader(old.VS, old.VSInstances, old.VSInstancesCount); if (old.VS) old.VS->Release(); ctx->VSSetConstantBuffers(0, 1, &old.VSConstantBuffer); if (old.VSConstantBuffer) old.VSConstantBuffer->Release(); for (UINT i = 0; i < old.VSInstancesCount; i++) if (old.VSInstances[i]) old.VSInstances[i]->Release(); ctx->IASetPrimitiveTopology(old.PrimitiveTopology); ctx->IASetIndexBuffer(old.IndexBuffer, old.IndexBufferFormat, old.IndexBufferOffset); if (old.IndexBuffer) old.IndexBuffer->Release(); ctx->IASetVertexBuffers(0, 1, &old.VertexBuffer, &old.VertexBufferStride, &old.VertexBufferOffset); if (old.VertexBuffer) old.VertexBuffer->Release(); ctx->IASetInputLayout(old.InputLayout); if (old.InputLayout) old.InputLayout->Release(); } static void ImGui_ImplWin32_UpdateMouseCursor() { ImGuiIO& io = ImGui::GetIO(); ImGuiMouseCursor imgui_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor(); if (imgui_cursor == ImGuiMouseCursor_None) { // Hide OS mouse cursor if imgui is drawing it or if it wants no cursor ::SetCursor(NULL); } else { // Hardware cursor type LPTSTR win32_cursor = IDC_ARROW; switch (imgui_cursor) { case ImGuiMouseCursor_Arrow: win32_cursor = IDC_ARROW; break; case ImGuiMouseCursor_TextInput: win32_cursor = IDC_IBEAM; break; case ImGuiMouseCursor_ResizeAll: win32_cursor = IDC_SIZEALL; break; case ImGuiMouseCursor_ResizeEW: win32_cursor = IDC_SIZEWE; break; case ImGuiMouseCursor_ResizeNS: win32_cursor = IDC_SIZENS; break; case ImGuiMouseCursor_ResizeNESW: win32_cursor = IDC_SIZENESW; break; case ImGuiMouseCursor_ResizeNWSE: win32_cursor = IDC_SIZENWSE; break; } ::SetCursor(::LoadCursor(NULL, win32_cursor)); } } // Process Win32 mouse/keyboard inputs. // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs. // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application. // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application. // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags. // PS: In this Win32 handler, we use the capture API (GetCapture/SetCapture/ReleaseCapture) to be able to read mouse coordinations when dragging mouse outside of our window bounds. // PS: We treat DBLCLK messages as regular mouse down messages, so this code will work on windows classes that have the CS_DBLCLKS flag set. Our own example app code doesn't set this flag. IMGUI_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (ImGui::GetCurrentContext() == NULL) return 0; ImGuiIO& io = ImGui::GetIO(); switch (msg) { case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: case WM_RBUTTONDOWN: case WM_RBUTTONDBLCLK: case WM_MBUTTONDOWN: case WM_MBUTTONDBLCLK: { int button = 0; if (msg == WM_LBUTTONDOWN || msg == WM_LBUTTONDBLCLK) button = 0; if (msg == WM_RBUTTONDOWN || msg == WM_RBUTTONDBLCLK) button = 1; if (msg == WM_MBUTTONDOWN || msg == WM_MBUTTONDBLCLK) button = 2; if (!ImGui::IsAnyMouseDown() && ::GetCapture() == NULL) ::SetCapture(hwnd); io.MouseDown[button] = true; return 0; } case WM_LBUTTONUP: case WM_RBUTTONUP: case WM_MBUTTONUP: { int button = 0; if (msg == WM_LBUTTONUP) button = 0; if (msg == WM_RBUTTONUP) button = 1; if (msg == WM_MBUTTONUP) button = 2; io.MouseDown[button] = false; if (!ImGui::IsAnyMouseDown() && ::GetCapture() == hwnd) ::ReleaseCapture(); return 0; } case WM_MOUSEWHEEL: io.MouseWheel += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f; return 0; case WM_MOUSEHWHEEL: io.MouseWheelH += GET_WHEEL_DELTA_WPARAM(wParam) > 0 ? +1.0f : -1.0f; return 0; case WM_MOUSEMOVE: io.MousePos.x = (signed short)(lParam); io.MousePos.y = (signed short)(lParam >> 16); return 0; case WM_KEYDOWN: case WM_SYSKEYDOWN: if (wParam < 256) io.KeysDown[wParam] = 1; return 0; case WM_KEYUP: case WM_SYSKEYUP: if (wParam < 256) io.KeysDown[wParam] = 0; return 0; case WM_CHAR: // You can also use ToAscii()+GetKeyboardState() to retrieve characters. if (wParam > 0 && wParam < 0x10000) io.AddInputCharacter((unsigned short)wParam); return 0; case WM_SETCURSOR: if (LOWORD(lParam) == HTCLIENT) { ImGui_ImplWin32_UpdateMouseCursor(); return 1; } return 0; } return 0; } static void ImGui_ImplDX11_CreateFontsTexture() { // Build texture atlas ImGuiIO& io = ImGui::GetIO(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // Upload texture to graphics system { D3D11_TEXTURE2D_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Width = width; desc.Height = height; desc.MipLevels = 1; desc.ArraySize = 1; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; desc.SampleDesc.Count = 1; desc.Usage = D3D11_USAGE_DEFAULT; desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; desc.CPUAccessFlags = 0; ID3D11Texture2D *pTexture = NULL; D3D11_SUBRESOURCE_DATA subResource; subResource.pSysMem = pixels; subResource.SysMemPitch = desc.Width * 4; subResource.SysMemSlicePitch = 0; g_pd3dDevice->CreateTexture2D(&desc, &subResource, &pTexture); // Create texture view D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc; ZeroMemory(&srvDesc, sizeof(srvDesc)); srvDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MipLevels = desc.MipLevels; srvDesc.Texture2D.MostDetailedMip = 0; g_pd3dDevice->CreateShaderResourceView(pTexture, &srvDesc, &g_pFontTextureView); pTexture->Release(); } // Store our identifier io.Fonts->TexID = (void *)g_pFontTextureView; // Create texture sampler { D3D11_SAMPLER_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR; desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; desc.MipLODBias = 0.f; desc.ComparisonFunc = D3D11_COMPARISON_ALWAYS; desc.MinLOD = 0.f; desc.MaxLOD = 0.f; g_pd3dDevice->CreateSamplerState(&desc, &g_pFontSampler); } } bool ImGui_ImplDX11_CreateDeviceObjects() { if (!g_pd3dDevice) return false; if (g_pFontSampler) ImGui_ImplDX11_InvalidateDeviceObjects(); // By using D3DCompile() from <d3dcompiler.h> / d3dcompiler.lib, we introduce a dependency to a given version of d3dcompiler_XX.dll (see D3DCOMPILER_DLL_A) // If you would like to use this DX11 sample code but remove this dependency you can: // 1) compile once, save the compiled shader blobs into a file or source code and pass them to CreateVertexShader()/CreatePixelShader() [preferred solution] // 2) use code to detect any version of the DLL and grab a pointer to D3DCompile from the DLL. // See https://github.com/ocornut/imgui/pull/638 for sources and details. // Create the vertex shader { static const char* vertexShader = "cbuffer vertexBuffer : register(b0) \ {\ float4x4 ProjectionMatrix; \ };\ struct VS_INPUT\ {\ float2 pos : POSITION;\ float4 col : COLOR0;\ float2 uv : TEXCOORD0;\ };\ \ struct PS_INPUT\ {\ float4 pos : SV_POSITION;\ float4 col : COLOR0;\ float2 uv : TEXCOORD0;\ };\ \ PS_INPUT main(VS_INPUT input)\ {\ PS_INPUT output;\ output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\ output.col = input.col;\ output.uv = input.uv;\ return output;\ }"; D3DCompile(vertexShader, strlen(vertexShader), NULL, NULL, NULL, "main", "vs_4_0", 0, 0, &g_pVertexShaderBlob, NULL); if (g_pVertexShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! return false; if (g_pd3dDevice->CreateVertexShader((DWORD*)g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), NULL, &g_pVertexShader) != S_OK) return false; // Create the input layout D3D11_INPUT_ELEMENT_DESC local_layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->pos), D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, (size_t)(&((ImDrawVert*)0)->uv), D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R8G8B8A8_UNORM, 0, (size_t)(&((ImDrawVert*)0)->col), D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; if (g_pd3dDevice->CreateInputLayout(local_layout, 3, g_pVertexShaderBlob->GetBufferPointer(), g_pVertexShaderBlob->GetBufferSize(), &g_pInputLayout) != S_OK) return false; // Create the constant buffer { D3D11_BUFFER_DESC desc; desc.ByteWidth = sizeof(VERTEX_CONSTANT_BUFFER); desc.Usage = D3D11_USAGE_DYNAMIC; desc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; desc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; desc.MiscFlags = 0; g_pd3dDevice->CreateBuffer(&desc, NULL, &g_pVertexConstantBuffer); } } // Create the pixel shader { static const char* pixelShader = "struct PS_INPUT\ {\ float4 pos : SV_POSITION;\ float4 col : COLOR0;\ float2 uv : TEXCOORD0;\ };\ sampler sampler0;\ Texture2D texture0;\ \ float4 main(PS_INPUT input) : SV_Target\ {\ float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \ return out_col; \ }"; D3DCompile(pixelShader, strlen(pixelShader), NULL, NULL, NULL, "main", "ps_4_0", 0, 0, &g_pPixelShaderBlob, NULL); if (g_pPixelShaderBlob == NULL) // NB: Pass ID3D10Blob* pErrorBlob to D3DCompile() to get error showing in (const char*)pErrorBlob->GetBufferPointer(). Make sure to Release() the blob! return false; if (g_pd3dDevice->CreatePixelShader((DWORD*)g_pPixelShaderBlob->GetBufferPointer(), g_pPixelShaderBlob->GetBufferSize(), NULL, &g_pPixelShader) != S_OK) return false; } // Create the blending setup { D3D11_BLEND_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.AlphaToCoverageEnable = false; desc.RenderTarget[0].BlendEnable = true; desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA; desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA; desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; g_pd3dDevice->CreateBlendState(&desc, &g_pBlendState); } // Create the rasterizer state { D3D11_RASTERIZER_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.FillMode = D3D11_FILL_SOLID; desc.CullMode = D3D11_CULL_NONE; desc.ScissorEnable = true; desc.DepthClipEnable = true; g_pd3dDevice->CreateRasterizerState(&desc, &g_pRasterizerState); } // Create depth-stencil State { D3D11_DEPTH_STENCIL_DESC desc; ZeroMemory(&desc, sizeof(desc)); desc.DepthEnable = false; desc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; desc.DepthFunc = D3D11_COMPARISON_ALWAYS; desc.StencilEnable = false; desc.FrontFace.StencilFailOp = desc.FrontFace.StencilDepthFailOp = desc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; desc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; desc.BackFace = desc.FrontFace; g_pd3dDevice->CreateDepthStencilState(&desc, &g_pDepthStencilState); } ImGui_ImplDX11_CreateFontsTexture(); return true; } void ImGui_ImplDX11_InvalidateDeviceObjects() { if (!g_pd3dDevice) return; if (g_pFontSampler) { g_pFontSampler->Release(); g_pFontSampler = NULL; } if (g_pFontTextureView) { g_pFontTextureView->Release(); g_pFontTextureView = NULL; ImGui::GetIO().Fonts->TexID = NULL; } // We copied g_pFontTextureView to io.Fonts->TexID so let's clear that as well. if (g_pIB) { g_pIB->Release(); g_pIB = NULL; } if (g_pVB) { g_pVB->Release(); g_pVB = NULL; } if (g_pBlendState) { g_pBlendState->Release(); g_pBlendState = NULL; } if (g_pDepthStencilState) { g_pDepthStencilState->Release(); g_pDepthStencilState = NULL; } if (g_pRasterizerState) { g_pRasterizerState->Release(); g_pRasterizerState = NULL; } if (g_pPixelShader) { g_pPixelShader->Release(); g_pPixelShader = NULL; } if (g_pPixelShaderBlob) { g_pPixelShaderBlob->Release(); g_pPixelShaderBlob = NULL; } if (g_pVertexConstantBuffer) { g_pVertexConstantBuffer->Release(); g_pVertexConstantBuffer = NULL; } if (g_pInputLayout) { g_pInputLayout->Release(); g_pInputLayout = NULL; } if (g_pVertexShader) { g_pVertexShader->Release(); g_pVertexShader = NULL; } if (g_pVertexShaderBlob) { g_pVertexShaderBlob->Release(); g_pVertexShaderBlob = NULL; } } bool ImGui_ImplDX11_Init(void* hwnd, ID3D11Device* device, ID3D11DeviceContext* device_context) { g_hWnd = (HWND)hwnd; g_pd3dDevice = device; g_pd3dDeviceContext = device_context; if (!QueryPerformanceFrequency((LARGE_INTEGER *)&g_TicksPerSecond)) return false; if (!QueryPerformanceCounter((LARGE_INTEGER *)&g_Time)) return false; ImGuiIO& io = ImGui::GetIO(); io.KeyMap[ImGuiKey_Tab] = VK_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array that we will update during the application lifetime. io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT; io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = VK_UP; io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN; io.KeyMap[ImGuiKey_PageUp] = VK_PRIOR; io.KeyMap[ImGuiKey_PageDown] = VK_NEXT; io.KeyMap[ImGuiKey_Home] = VK_HOME; io.KeyMap[ImGuiKey_End] = VK_END; io.KeyMap[ImGuiKey_Insert] = VK_INSERT; io.KeyMap[ImGuiKey_Delete] = VK_DELETE; io.KeyMap[ImGuiKey_Backspace] = VK_BACK; io.KeyMap[ImGuiKey_Space] = VK_SPACE; io.KeyMap[ImGuiKey_Enter] = VK_RETURN; io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE; io.KeyMap[ImGuiKey_A] = 'A'; io.KeyMap[ImGuiKey_C] = 'C'; io.KeyMap[ImGuiKey_V] = 'V'; io.KeyMap[ImGuiKey_X] = 'X'; io.KeyMap[ImGuiKey_Y] = 'Y'; io.KeyMap[ImGuiKey_Z] = 'Z'; io.ImeWindowHandle = g_hWnd; return true; } void ImGui_ImplDX11_Shutdown() { ImGui_ImplDX11_InvalidateDeviceObjects(); g_pd3dDevice = NULL; g_pd3dDeviceContext = NULL; g_hWnd = (HWND)0; } void ImGui_ImplDX11_NewFrame() { if (!g_pFontSampler) ImGui_ImplDX11_CreateDeviceObjects(); ImGuiIO& io = ImGui::GetIO(); // Setup display size (every frame to accommodate for window resizing) RECT rect; GetClientRect(g_hWnd, &rect); io.DisplaySize = ImVec2((float)(rect.right - rect.left), (float)(rect.bottom - rect.top)); // Setup time step INT64 current_time; QueryPerformanceCounter((LARGE_INTEGER *)&current_time); io.DeltaTime = (float)(current_time - g_Time) / g_TicksPerSecond; g_Time = current_time; // Read keyboard modifiers inputs io.KeyCtrl = (GetKeyState(VK_CONTROL) & 0x8000) != 0; io.KeyShift = (GetKeyState(VK_SHIFT) & 0x8000) != 0; io.KeyAlt = (GetKeyState(VK_MENU) & 0x8000) != 0; io.KeySuper = false; // io.KeysDown : filled by WM_KEYDOWN/WM_KEYUP events // io.MousePos : filled by WM_MOUSEMOVE events // io.MouseDown : filled by WM_*BUTTON* events // io.MouseWheel : filled by WM_MOUSEWHEEL events // Set OS mouse position if requested last frame by io.WantMoveMouse flag (used when io.NavMovesTrue is enabled by user and using directional navigation) if (io.WantMoveMouse) { POINT pos = { (int)io.MousePos.x, (int)io.MousePos.y }; ClientToScreen(g_hWnd, &pos); SetCursorPos(pos.x, pos.y); } // Update OS mouse cursor with the cursor requested by imgui ImGuiMouseCursor mouse_cursor = io.MouseDrawCursor ? ImGuiMouseCursor_None : ImGui::GetMouseCursor(); if (g_LastMouseCursor != mouse_cursor) { g_LastMouseCursor = mouse_cursor; ImGui_ImplWin32_UpdateMouseCursor(); } // Start the frame. This call will update the io.WantCaptureMouse, io.WantCaptureKeyboard flag that you can use to dispatch inputs (or not) to your application. ImGui::NewFrame(); }
ThisIsNotRocketScience/Eurorack-KDS
VIsualStudio_EuroRackSimulator/libs/imgui-master/examples/directx11_example/imgui_impl_dx11.cpp
C++
mit
30,064
import IError from './error'; interface IAlertMessage { id?: number; status?: number; message?: string; errors?: IError[]; alertType: string; } export default IAlertMessage;
borkovskij/scheduleGrsu
src/app/models/alertMessage.ts
TypeScript
mit
186
<?php $name='OpenSansEmoji-Regular'; $type='TTF'; $desc=array ( 'Ascent' => 960, 'Descent' => -240, 'CapHeight' => 714, 'Flags' => 4, 'FontBBox' => '[-550 -271 1335 1065]', 'ItalicAngle' => 0, 'StemV' => 87, 'MissingWidth' => 600, ); $up=-37; $ut=24; $ttffile='/var/www/web10/html/wp-content/plugins/zawiw-chat/mpdf/MPDF57/ttfonts/OpenSansEmoji.ttf'; $TTCfontID='0'; $originalsize=561512; $sip=false; $smp=true; $BMPselected=false; $fontkey='emoji'; $panose=' 0 0 0 0 5 0 0 0 0 0 0 0'; $haskerninfo=false; $unAGlyphs=false; ?>
swinkelhofer/zawiw-chat
mpdf/MPDF57/ttfontdata/emoji.mtx.php
PHP
mit
542
using System; using FluentNHibernate.Mapping; namespace Logic.Customers { public class PurchasedMovieMap : ClassMap<PurchasedMovie> { public PurchasedMovieMap() { Id(x => x.Id); Map(x => x.Price).CustomType<decimal>().Access.CamelCaseField(Prefix.Underscore); Map(x => x.PurchaseDate); Map(x => x.ExpirationDate).CustomType<DateTime?>().Access.CamelCaseField(Prefix.Underscore).Nullable(); References(x => x.Movie); References(x => x.Customer); } } }
vkhorikov/AnemicDomainModel
After/src/Logic/Customers/PurchasedMovieMap.cs
C#
mit
562
//~ name a361 alert(a361); //~ component a362.js
homobel/makebird-node
test/projects/large/a361.js
JavaScript
mit
52
<?php namespace Fuel\Migrations; class Create_lienhes { public function up() { \DBUtil::create_table('lienhes', array( 'id' => array('constraint' => 11, 'type' => 'int', 'auto_increment' => true, 'unsigned' => true), 'title' => array('constraint' => 255, 'type' => 'varchar'), 'slug' => array('constraint' => 255, 'type' => 'varchar'), 'summary' => array('type' => 'text'), 'body' => array('type' => 'text'), 'created_at' => array('constraint' => 11, 'type' => 'int', 'null' => true), 'updated_at' => array('constraint' => 11, 'type' => 'int', 'null' => true), ), array('id')); } public function down() { \DBUtil::drop_table('lienhes'); } }
NamBker/web_laptop
fuel/app/migrations/005_create_lienhes.php
PHP
mit
677
namespace FactoriesUnitTests.Factories { using Labyrinth.Factories; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class LargeMazeCreatorUnitTest { [TestMethod] public void CreateMaze_IsCreatedLarge() { LargeMazeCreator mazeCreator = new LargeMazeCreator(); var maze = mazeCreator.CreateMaze(); Assert.AreEqual(maze.Cols, 31); Assert.AreEqual(maze.Rows, 31); } } }
2She2/HighQualityProgrammingCodeTeamProject
FactoriesUnitTests/Factories/LargeMazeCreatorUnitTest.cs
C#
mit
497
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Busquedas_model extends CI_Model { public function __construct() { parent::__construct(); } public function pendientes_mdl(){ $this->load->model("actividades_model"); $html=""; $w_buscar = $this->input->post('buscar'); $sql = "SELECT * FROM `busquedas` WHERE `bus_estado`='p' ORDER BY `bus_fechafin` ASC"; $query = $this->db->query($sql); if ($query->num_rows() > 0) { $html = ""; foreach ($query->result() as $fila) { if(hoy('c') > $fila->bus_fechafin) $fila->color="#fc7b5f"; else $fila->color="none"; $html.= $this->parser->parse('admin/busquedas/pendientes_tpl', $fila, true); } } else { $html.="<tr><td colspan='6'>No hay pendientes (<strong>$w_buscar</strong>)</td></tr>"; } $arreglo["html"] = $html; //$arreglo["cmb_actividades"]="hola"; return $arreglo; } public function asignar_mdl(){ $bus_id=$this->input->post("bus_id"); $act_id=$this->input->post("act_id"); $tiempo=$this->input->post("tiempo"); if($tiempo!="") $arr=array( "bus_estado"=>"r", //"act_id"=>$act_id, "bus_tiempo"=>$tiempo, ); else $arr=array( "bus_estado"=>"r", //"act_id"=>$act_id, ); $this->db->where("bus_id",$bus_id); $this->db->update("busquedas",$arr); } //la actividad es la categoria en la BBDDD public function rel_prv_actividades_mdl($bus_id) { $html = "<select name='rel_prv_act[]' id='rel_multiple' multiple='multiple' class='searchable'>"; $query = $this->db->get('actividad_empresa'); if ($query->num_rows() > 0) { foreach ($query->result() as $fila) { $act_id = $fila->act_id; $this->db->where("act_id", $act_id); $this->db->where('bus_id', $bus_id); $query1 = $this->db->get('rel_bus_act'); if ($query1->num_rows() > 0) $fila->selected = "selected"; else $fila->selected = ""; $html .= $this->parser->parse('busquedas/cmb_bus_act', $fila, TRUE); } } return $html . "</select>"; } public function alm_rel_prv_actividades_mdl() { $rel_prv_act = $this->input->post('rel_prv_act'); $bus_id = $this->input->post('bus_id'); $this->db->where('bus_id', $bus_id); $this->db->delete('rel_bus_act'); if ($rel_prv_act != "") { foreach ($rel_prv_act as $act_id) { $arr = array("act_id" => $act_id, "bus_id" => $bus_id); $this->db->insert('rel_bus_act', $arr); } } } public function datos_mdl($id) { $this->db->where("bus_id", $id); $query = $this->db->get("busquedas"); if ($query->num_rows() > 0) { return $query->row_array(); } } public function eliminar_mdl(){ $id=$this->uri->segment(4); $this->db->where("bus_id",$id); $this->db->delete("busquedas"); } }
carlosmast23/vm
application/modules/admin/models/Busquedas_model.php
PHP
mit
2,750
import org.apache.commons.math3.optim.nonlinear.vector.Weight; import org.datavec.api.records.reader.RecordReader; import org.datavec.api.records.reader.impl.ComposableRecordReader; import org.datavec.api.records.reader.impl.csv.CSVRecordReader; import org.datavec.api.split.CollectionInputSplit; import org.datavec.api.split.FileSplit; import org.datavec.api.split.InputSplit; import org.datavec.image.recordreader.ImageRecordReader; import org.deeplearning4j.datasets.datavec.RecordReaderDataSetIterator; import org.deeplearning4j.eval.Evaluation; import org.deeplearning4j.nn.api.OptimizationAlgorithm; import org.deeplearning4j.nn.conf.*; import org.deeplearning4j.nn.conf.inputs.InputType; import org.deeplearning4j.nn.conf.layers.ConvolutionLayer; import org.deeplearning4j.nn.conf.layers.DenseLayer; import org.deeplearning4j.nn.conf.layers.OutputLayer; import org.deeplearning4j.nn.conf.layers.SubsamplingLayer; import org.deeplearning4j.nn.multilayer.MultiLayerNetwork; import org.deeplearning4j.nn.weights.WeightInit; import org.deeplearning4j.optimize.api.IterationListener; import org.deeplearning4j.optimize.listeners.ScoreIterationListener; import org.deeplearning4j.ui.weights.HistogramIterationListener; import org.deeplearning4j.util.ModelSerializer; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.convolution.Convolution; import org.nd4j.linalg.dataset.DataSet; import org.nd4j.linalg.dataset.SplitTestAndTrain; import org.nd4j.linalg.dataset.api.iterator.DataSetIterator; import org.nd4j.linalg.factory.Nd4j; import org.nd4j.linalg.lossfunctions.LossFunctions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.net.URI; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Random; import static java.lang.System.exit; /** * Created by unisar */ public class AllConvolutionDL4J { private static final Logger log = LoggerFactory.getLogger(AllConvolutionDL4J.class); private static String X_Train; private static String Y_Train; private static String X_Test; private static String Image_Path; public static void main(String[] args) throws Exception { if (args.length < 4) { System.out.println("Usage: X_Train Y_Train X_Test IMAGE_FOLDER"); exit(1); } X_Train = args[0]; Y_Train = args[1]; X_Test = args[2]; Image_Path = args[3]; int nChannels = 3; int outputNum = 10; int batchSize = 100; int nEpochs = 50; int iterations = 1; int seed = 123; Nd4j.ENFORCE_NUMERICAL_STABILITY = true; RecordReader recordReader = loadTrainingData(); log.info("Load data...."); DataSetIterator dataSetIterator = new RecordReaderDataSetIterator(recordReader, batchSize, 1, 10); // DataSetIterator testSetIterator = new RecordReaderDataSetIterator(loadTestingData(), 1); log.info("Build model...."); MultiLayerConfiguration.Builder builder = new NeuralNetConfiguration.Builder() .seed(seed).miniBatch(true) .iterations(iterations) .regularization(true).l2(0.0005) .learningRate(0.1) //.biasLearningRate(0.2) .learningRateDecayPolicy(LearningRatePolicy.Step).lrPolicyDecayRate(0.1).lrPolicySteps(45000/batchSize * 50) .weightInit(WeightInit.XAVIER) .optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT) .updater(Updater.NESTEROVS).momentum(0.9) .list() .layer(0, new ConvolutionLayer.Builder().kernelSize(new int[] { 3, 3 }).stride(new int[] { 1, 1 }).padding(new int[] { 1, 1 }) .nOut(96) .activation("relu") .build()) .layer(1, new ConvolutionLayer.Builder().kernelSize(new int[] { 3, 3 }).stride(new int[] { 1, 1 }).padding(new int[] { 1, 1 }) .nOut(96) .activation("relu") .build()) .layer(2, new ConvolutionLayer.Builder().kernelSize(new int[] {2, 2}).stride(new int[] {2, 2}) .nOut(96).activation("relu") .dropOut(0.5) .build()) .layer(3, new ConvolutionLayer.Builder().kernelSize(new int[] { 3, 3 }).stride(new int[] { 1, 1 }).padding(new int[] { 1, 1 }) .nOut(192) .activation("relu") .build()) .layer(4, new ConvolutionLayer.Builder().kernelSize(new int[] { 3, 3 }).stride(new int[] { 1, 1 }).padding(new int[] { 1, 1 }) .nOut(192) .activation("relu") .build()) .layer(5, new ConvolutionLayer.Builder().kernelSize(new int[] {2, 2}).stride(new int[] {2, 2}) .nOut(192).activation("relu") .dropOut(0.5) .build()) .layer(6, new ConvolutionLayer.Builder().kernelSize(new int[] { 3, 3 }).stride(new int[] { 1, 1 }).padding(new int[] { 1, 1 }) .nOut(192) .activation("relu") .build()) .layer(7, new ConvolutionLayer.Builder().kernelSize(new int[] {1,1}).stride(new int[] { 1, 1 }) .nOut(192) .activation("relu") .build()) .layer(8, new ConvolutionLayer.Builder().kernelSize(new int[] {1,1}).stride(new int[] { 1, 1 }) .nOut(10) .activation("relu") .build()) .layer(9, new SubsamplingLayer.Builder().kernelSize(new int[] {8, 8}).stride(new int[] { 1, 1 }).build()) .layer(10, new OutputLayer.Builder(LossFunctions.LossFunction.NEGATIVELOGLIKELIHOOD) .nOut(outputNum) .activation("softmax") .build()).setInputType(InputType.convolutionalFlat(32, 32, 3)) .backprop(true) .pretrain(false); MultiLayerConfiguration conf = builder.build(); MultiLayerNetwork model = new MultiLayerNetwork(conf); model.init(); log.info("Train model...."); model.setListeners(new IterationListener[] {new ScoreIterationListener(1), new HistogramIterationListener(1)}); DataSet cifarDataSet; SplitTestAndTrain trainAndTest; for( int i=0; i<nEpochs; i++ ) { dataSetIterator.reset(); List<INDArray> testInput = new ArrayList<>(); List<INDArray> testLabels = new ArrayList<>(); while (dataSetIterator.hasNext()) { cifarDataSet = dataSetIterator.next(); trainAndTest = cifarDataSet.splitTestAndTrain((int)(batchSize*0.9)); DataSet trainInput = trainAndTest.getTrain(); testInput.add(trainAndTest.getTest().getFeatureMatrix()); testLabels.add(trainAndTest.getTest().getLabels()); model.fit(trainInput); } File file = File.createTempFile("Epoch", String.valueOf(i)); ModelSerializer.writeModel(model, file, true ); log.info("*** Completed epoch {} ***", i); log.info("Evaluate model...."); Evaluation eval = new Evaluation(outputNum); for (int j = 0; j < testInput.size(); j++) { INDArray output = model.output(testInput.get(j)); eval.eval(testLabels.get(i), output); } log.info(eval.stats()); // testSetIterator.reset(); dataSetIterator.reset(); } log.info("****************Example finished********************"); } public static RecordReader loadTestingData() throws Exception { RecordReader imageReader = new ImageRecordReader(32, 32, 3, 255); List<URI> images = new ArrayList<>(); for (String number: Files.readAllLines(Paths.get(X_Test), Charset.defaultCharset())) images.add(URI.create("file:/"+ Image_Path + "/Test/" + number + ".png")); InputSplit splits = new CollectionInputSplit(images); imageReader.initialize(splits); return imageReader; } public static RecordReader loadTrainingData() throws Exception { RecordReader imageReader = new ImageRecordReader(32, 32, 3, 255); List<URI> images = new ArrayList<>(); for (String number: Files.readAllLines(Paths.get(X_Train), Charset.defaultCharset())) images.add(URI.create("file:/"+ Image_Path + "/Train/" + number + ".png")); InputSplit splits = new CollectionInputSplit(images); imageReader.initialize(splits); RecordReader labelsReader = new CSVRecordReader(); labelsReader.initialize(new FileSplit(new File(Y_Train))); return new ComposableRecordReader(imageReader, labelsReader); } }
unisar/CIFARClassification
dl4j/AllConvolutionDL4J.java
Java
mit
9,129
/*jshint quotmark: false*/ 'use strict'; var Blueprint = require('../models/blueprint'); var Task = require('../models/task'); var parseOptions = require('../utilities/parse-options'); var merge = require('lodash-node/modern/objects/merge'); module.exports = Task.extend({ run: function(options) { var blueprint = Blueprint.lookup(options.args[0], { paths: this.project.blueprintLookupPaths() }); var entity = { name: options.args[1], options: parseOptions(options.args.slice(2)) }; var installOptions = { target: this.project.root, entity: entity, ui: this.ui, analytics: this.analytics, project: this.project }; installOptions = merge(installOptions, options || {}); return blueprint.install(installOptions); } });
treyhunner/ember-cli
lib/tasks/generate-from-blueprint.js
JavaScript
mit
830
angular.module('app') .controller('ProgressController', ['$scope', function ($scope) { $scope.percent = 45; $scope.setPercent = function(p) { $scope.percent = p; } }])
ShadowZheng/angular-ui-newbee
doc/app/controllers/ProgressController.js
JavaScript
mit
173
containerRemoveSchemas = new SimpleSchema({ force: { type: Boolean, optional:true, label: "Force" }, link: { type: Boolean, optional:true, label: "Link" }, v: { type: Boolean, optional:true, label: "Volumes" } ,id: { type: String, autoform: { type: 'hidden', label:false } } ,host: { type: String, autoform: { type: 'hidden', label:false } } }); if (Meteor.isClient){ AutoForm.hooks({ containerRemoveForm: { after: { 'method': formNotifier('rm','containers')} }}); }
djedi23/meteor-docker
lib/schemas/containerRemove.js
JavaScript
mit
598
'use strict'; var should = require('should'), request = require('supertest'), path = require('path'), mongoose = require('mongoose'), User = mongoose.model('User'), Picture = mongoose.model('Picture'), express = require(path.resolve('./config/lib/express')); /** * Globals */ var app, agent, credentials, user, picture; /** * Picture routes tests */ describe('Picture CRUD tests', function () { before(function (done) { // Get application app = express.init(mongoose); agent = request.agent(app); done(); }); beforeEach(function (done) { // Create user credentials credentials = { username: 'username', password: 'M3@n.jsI$Aw3$0m3' }; // Create a new user user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'test@test.com', username: credentials.username, password: credentials.password, provider: 'local' }); // Save a user to the test db and create new picture user.save(function () { picture = { title: 'Picture Title', content: 'Picture Content' }; done(); }); }); it('should be able to save an picture if logged in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new picture agent.post('/api/pictures') .send(picture) .expect(200) .end(function (pictureSaveErr, pictureSaveRes) { // Handle picture save error if (pictureSaveErr) { return done(pictureSaveErr); } // Get a list of pictures agent.get('/api/pictures') .end(function (picturesGetErr, picturesGetRes) { // Handle picture save error if (picturesGetErr) { return done(picturesGetErr); } // Get pictures list var pictures = picturesGetRes.body; // Set assertions (pictures[0].user._id).should.equal(userId); (pictures[0].title).should.match('Picture Title'); // Call the assertion callback done(); }); }); }); }); it('should not be able to save an picture if not logged in', function (done) { agent.post('/api/pictures') .send(picture) .expect(403) .end(function (pictureSaveErr, pictureSaveRes) { // Call the assertion callback done(pictureSaveErr); }); }); it('should not be able to save an picture if no title is provided', function (done) { // Invalidate title field picture.title = ''; agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new picture agent.post('/api/pictures') .send(picture) .expect(400) .end(function (pictureSaveErr, pictureSaveRes) { // Set message assertion (pictureSaveRes.body.message).should.match('Title cannot be blank'); // Handle picture save error done(pictureSaveErr); }); }); }); it('should be able to update an picture if signed in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new picture agent.post('/api/pictures') .send(picture) .expect(200) .end(function (pictureSaveErr, pictureSaveRes) { // Handle picture save error if (pictureSaveErr) { return done(pictureSaveErr); } // Update picture title picture.title = 'WHY YOU GOTTA BE SO MEAN?'; // Update an existing picture agent.put('/api/pictures/' + pictureSaveRes.body._id) .send(picture) .expect(200) .end(function (pictureUpdateErr, pictureUpdateRes) { // Handle picture update error if (pictureUpdateErr) { return done(pictureUpdateErr); } // Set assertions (pictureUpdateRes.body._id).should.equal(pictureSaveRes.body._id); (pictureUpdateRes.body.title).should.match('WHY YOU GOTTA BE SO MEAN?'); // Call the assertion callback done(); }); }); }); }); it('should be able to get a list of pictures if not signed in', function (done) { // Create new picture model instance var pictureObj = new Picture(picture); // Save the picture pictureObj.save(function () { // Request pictures request(app).get('/api/pictures') .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Array).and.have.lengthOf(1); // Call the assertion callback done(); }); }); }); it('should be able to get a single picture if not signed in', function (done) { // Create new picture model instance var pictureObj = new Picture(picture); // Save the picture pictureObj.save(function () { request(app).get('/api/pictures/' + pictureObj._id) .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Object).and.have.property('title', picture.title); // Call the assertion callback done(); }); }); }); it('should return proper error for single picture with an invalid Id, if not signed in', function (done) { // test is not a valid mongoose Id request(app).get('/api/pictures/test') .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Object).and.have.property('message', 'Picture is invalid'); // Call the assertion callback done(); }); }); it('should return proper error for single picture which doesnt exist, if not signed in', function (done) { // This is a valid mongoose Id but a non-existent picture request(app).get('/api/pictures/559e9cd815f80b4c256a8f41') .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Object).and.have.property('message', 'No picture with that identifier has been found'); // Call the assertion callback done(); }); }); it('should be able to delete an picture if signed in', function (done) { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new picture agent.post('/api/pictures') .send(picture) .expect(200) .end(function (pictureSaveErr, pictureSaveRes) { // Handle picture save error if (pictureSaveErr) { return done(pictureSaveErr); } // Delete an existing picture agent.delete('/api/pictures/' + pictureSaveRes.body._id) .send(picture) .expect(200) .end(function (pictureDeleteErr, pictureDeleteRes) { // Handle picture error error if (pictureDeleteErr) { return done(pictureDeleteErr); } // Set assertions (pictureDeleteRes.body._id).should.equal(pictureSaveRes.body._id); // Call the assertion callback done(); }); }); }); }); it('should not be able to delete an picture if not signed in', function (done) { // Set picture user picture.user = user; // Create new picture model instance var pictureObj = new Picture(picture); // Save the picture pictureObj.save(function () { // Try deleting picture request(app).delete('/api/pictures/' + pictureObj._id) .expect(403) .end(function (pictureDeleteErr, pictureDeleteRes) { // Set message assertion (pictureDeleteRes.body.message).should.match('User is not authorized'); // Handle picture error error done(pictureDeleteErr); }); }); }); it('should be able to get a single picture that has an orphaned user reference', function (done) { // Create orphan user creds var _creds = { username: 'orphan', password: 'M3@n.jsI$Aw3$0m3' }; // Create orphan user var _orphan = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'orphan@test.com', username: _creds.username, password: _creds.password, provider: 'local' }); _orphan.save(function (err, orphan) { // Handle save error if (err) { return done(err); } agent.post('/api/auth/signin') .send(_creds) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var orphanId = orphan._id; // Save a new picture agent.post('/api/pictures') .send(picture) .expect(200) .end(function (pictureSaveErr, pictureSaveRes) { // Handle picture save error if (pictureSaveErr) { return done(pictureSaveErr); } // Set assertions on new picture (pictureSaveRes.body.title).should.equal(picture.title); should.exist(pictureSaveRes.body.user); should.equal(pictureSaveRes.body.user._id, orphanId); // force the picture to have an orphaned user reference orphan.remove(function () { // now signin with valid user agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (err, res) { // Handle signin error if (err) { return done(err); } // Get the picture agent.get('/api/pictures/' + pictureSaveRes.body._id) .expect(200) .end(function (pictureInfoErr, pictureInfoRes) { // Handle picture error if (pictureInfoErr) { return done(pictureInfoErr); } // Set assertions (pictureInfoRes.body._id).should.equal(pictureSaveRes.body._id); (pictureInfoRes.body.title).should.equal(picture.title); should.equal(pictureInfoRes.body.user, undefined); // Call the assertion callback done(); }); }); }); }); }); }); }); it('should be able to get a single picture if signed in and verify the custom "isCurrentUserOwner" field is set to "true"', function (done) { // Create new picture model instance picture.user = user; var pictureObj = new Picture(picture); // Save the picture pictureObj.save(function () { agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user.id; // Save a new picture agent.post('/api/pictures') .send(picture) .expect(200) .end(function (pictureSaveErr, pictureSaveRes) { // Handle picture save error if (pictureSaveErr) { return done(pictureSaveErr); } // Get the picture agent.get('/api/pictures/' + pictureSaveRes.body._id) .expect(200) .end(function (pictureInfoErr, pictureInfoRes) { // Handle picture error if (pictureInfoErr) { return done(pictureInfoErr); } // Set assertions (pictureInfoRes.body._id).should.equal(pictureSaveRes.body._id); (pictureInfoRes.body.title).should.equal(picture.title); // Assert that the "isCurrentUserOwner" field is set to true since the current User created it (pictureInfoRes.body.isCurrentUserOwner).should.equal(true); // Call the assertion callback done(); }); }); }); }); }); it('should be able to get a single picture if not signed in and verify the custom "isCurrentUserOwner" field is set to "false"', function (done) { // Create new picture model instance var pictureObj = new Picture(picture); // Save the picture pictureObj.save(function () { request(app).get('/api/pictures/' + pictureObj._id) .end(function (req, res) { // Set assertion res.body.should.be.instanceof(Object).and.have.property('title', picture.title); // Assert the custom field "isCurrentUserOwner" is set to false for the un-authenticated User res.body.should.be.instanceof(Object).and.have.property('isCurrentUserOwner', false); // Call the assertion callback done(); }); }); }); it('should be able to get single picture, that a different user created, if logged in & verify the "isCurrentUserOwner" field is set to "false"', function (done) { // Create temporary user creds var _creds = { username: 'temp', password: 'M3@n.jsI$Aw3$0m3' }; // Create temporary user var _user = new User({ firstName: 'Full', lastName: 'Name', displayName: 'Full Name', email: 'temp@test.com', username: _creds.username, password: _creds.password, provider: 'local' }); _user.save(function (err, _user) { // Handle save error if (err) { return done(err); } // Sign in with the user that will create the Picture agent.post('/api/auth/signin') .send(credentials) .expect(200) .end(function (signinErr, signinRes) { // Handle signin error if (signinErr) { return done(signinErr); } // Get the userId var userId = user._id; // Save a new picture agent.post('/api/pictures') .send(picture) .expect(200) .end(function (pictureSaveErr, pictureSaveRes) { // Handle picture save error if (pictureSaveErr) { return done(pictureSaveErr); } // Set assertions on new picture (pictureSaveRes.body.title).should.equal(picture.title); should.exist(pictureSaveRes.body.user); should.equal(pictureSaveRes.body.user._id, userId); // now signin with the temporary user agent.post('/api/auth/signin') .send(_creds) .expect(200) .end(function (err, res) { // Handle signin error if (err) { return done(err); } // Get the picture agent.get('/api/pictures/' + pictureSaveRes.body._id) .expect(200) .end(function (pictureInfoErr, pictureInfoRes) { // Handle picture error if (pictureInfoErr) { return done(pictureInfoErr); } // Set assertions (pictureInfoRes.body._id).should.equal(pictureSaveRes.body._id); (pictureInfoRes.body.title).should.equal(picture.title); // Assert that the custom field "isCurrentUserOwner" is set to false since the current User didn't create it (pictureInfoRes.body.isCurrentUserOwner).should.equal(false); // Call the assertion callback done(); }); }); }); }); }); }); afterEach(function (done) { User.remove().exec(function () { Picture.remove().exec(done); }); }); });
p3t3revans/MaristOnline
modules/pictures/tests/server/picture.server.routes.tests.js
JavaScript
mit
17,428
app.controller('DashboardController',function($scope,$http,Article){ //Pagination configuration $scope.maxSize = 5; $scope.numPerPage = 5; $scope.currentPage = '1'; $scope.isEdit = false; $scope.isError= false; $scope.newarticle = {}; // Edit/New panel model $scope.curArticle = {}; // Currently selected article model $scope.errors = []; //Load all articles. Article.query(function(data){ $scope.articles = data; },function(error){ console.log(error); alert('Loading data failed.'); }); //Shows validation errors function errorHandler(error){ $scope.isError=true; //Show validator error angular.forEach(error.data,function(key,value){ $scope.errors.push(value + ': ' + key); }); } //Open New panel $scope.newArticle = function(article){ $scope.isEdit=true; $scope.isError=false; //Initialize with Article resource $scope.newarticle = new Article(); }; //Open Edit panel with data on edit button click $scope.editArticle = function(article){ $scope.isEdit=true; $scope.isError=false; // Store selected data for future use $scope.curArticle = article; //Copy data to panel $scope.newarticle = angular.copy(article); }; //Update and New article $scope.addArticle = function(article){ //TODO error handling on requests //Check if update or new if($scope.curArticle.id){ //Send put resource request article.$update(function(data){ // Update values to selected article angular.extend($scope.curArticle,$scope.curArticle,data); //Hide edit/new panel $scope.isEdit = false; },errorHandler); }else{ //Send post resource request article.$save(function(data){ //Add newly add article to articles json $scope.articles.push(data); //Hide edit/new panel $scope.isEdit = false; },errorHandler); } //Remove old values //$scope.newarticle = new Article(); }; //Delete button $scope.deleteArticle = function(article){ if(confirm('Are you sure ?')){ article.$delete(function(data){ alert(data.msg); //Get selected article index then remove from articles json var curIndex = $scope.articles.indexOf(article); $scope.articles.splice(curIndex,1); },function(error){ alert('Item not deleted'); console.log(error); }); } }; //Cancel panel button $scope.cancelArticle = function(article){ $scope.isEdit=false; $scope.isError=false; //Remove old values $scope.newarticle= new Article(); }; });
pshanoop/laravel-blog
resources/assets/js/dashboard/controller/DashboardController.js
JavaScript
mit
2,989
module OAWidget module Preserver def self.included(base) base.extend(ClassMethods) end module ClassMethods # Preserve ivars between widgets, rendering and ajax calls # example: # class MyWidget < OAWidget # preserves_attr :page, :from => '../content' # preserves_attr :display # ... # end # # Usage: # preserves_attr :attribute_name [, OPTIONS] # # By default it will preserve the attribute_name from the parent. # That is, the parent is responsible for having the right getter/setter for the attribute # # OPTIONS: # :from => String, a relative path to the widget from which we must sync the param # example: preserves_attr :page, :from => '../pager' # def preserves_attr(*attrs) @preserved_vars ||= [] @preserved_vars << attrs end def preserved_vars @preserved_vars end end # ClassMethods def preserves_attrs(attrs=nil) return if attrs.blank? attrs.each do |attribute| self.class.preserves_attr attribute end end def preserved_params(*except) return {} if self.class.preserved_vars.nil? params_hash = {} self.class.preserved_vars.each do |ivar, options| value = self.instance_variable_get("@#{ivar}") # RAILS_DEFAULT_LOGGER.debug("(#{self.name}) export to params: #{ivar} = #{value}") params_hash.merge!(ivar => self.instance_variable_get("@#{ivar}")) end except.each {|e| params_hash.delete(e)} params_hash end def preserved_attrs return if self.class.preserved_vars.nil? self.class.preserved_vars.each do |ivar, options| options ||= {} managing_widget = options.include?(:from) ? self.widget_from_path(options[:from]) : self.parent next if managing_widget.nil? if param(ivar) # RAILS_DEFAULT_LOGGER.debug("(#{self.name}) [PARAMS]: setting #{ivar} = #{param(ivar)} on widget: #{managing_widget.name}") # push the value to the widget managing it managing_widget.instance_variable_set("@#{ivar}", param(ivar)) end # get the value of a preserved attr from the widget managing it value = managing_widget.instance_variable_get("@#{ivar}") if value.blank? if (options[:default]) value = options[:default] managing_widget.instance_variable_set("@#{ivar}", value) end end # RAILS_DEFAULT_LOGGER.debug("(#{self.name}) [NOPARAMS]: setting #{ivar} = #{value} on widget: #{self.name}") unless (param(ivar)) self.instance_variable_set("@#{ivar}", value) end end # Search for the widget identified by its id in the specified relative path # example: # self.widget_from_path('../content') will look for the child widget named 'content' of the parent widget of self def widget_from_path(relative_path) raise 'relative_path must be a string' unless relative_path.class == String raise 'relative_path should not start with / (hence "relative")' if relative_path =~ /^\// path_components = relative_path.split(/\//) path_components.shift if path_components[0] == '.' # RAILS_DEFAULT_LOGGER.debug("starting search at self: #{self.name}, self.parent: #{self.parent.name}, self.root: #{self.root.name}") start = self while path_components[0] == '..' # RAILS_DEFAULT_LOGGER.debug("path components: #{path_components.to_json}") start = self.parent path_components.shift end path_components.each do |w| # RAILS_DEFAULT_LOGGER.debug("start: #{start.name}") break if start.nil? start = start.find_widget(w) end start end end # module OAPreserver end
Orion98MC/oa_widget
lib/oa_widget/preserver.rb
Ruby
mit
3,948
using System; using System.Data.Entity; using System.Data.Entity.Hooks.Fluent; using Microsoft.AspNet.Identity.EntityFramework; namespace MICCookBook.Web.Models { public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { private ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false) { } public static ApplicationDbContext Create() { var context = new ApplicationDbContext(); context.CreateHook() .OnSave<IBaseModel>() .When(r => r.Id == 0) .Do(r => r.CreatedOn = r.ModifiedOn = DateTime.Now); context.CreateHook() .OnSave<IBaseModel>() .When(r => r.Id > 0) .Do(r => r.ModifiedOn = DateTime.Now); return context; } public DbSet<Recipe> Recipes { get; set; } public DbSet<Evaluation> Evaluations { get; set; } } }
micbelgique/MICCookBook
src/MICCookBook/MICCookBook.Web/Models/ApplicationDbContext.cs
C#
mit
989
#!/usr/bin/env python ''' Creates an html treemap of disk usage, using the Google Charts API ''' import json import os import subprocess import sys def memoize(fn): stored_results = {} def memoized(*args): try: return stored_results[args] except KeyError: result = stored_results[args] = fn(*args) return result return memoized @memoize def get_folder_size(folder): total_size = os.path.getsize(folder) for item in os.listdir(folder): itempath = os.path.join(folder, item) if os.path.isfile(itempath): total_size += os.path.getsize(itempath) elif os.path.isdir(itempath): total_size += get_folder_size(itempath) return total_size def usage_iter(root): root = os.path.abspath(root) root_size = get_folder_size(root) root_string = "{0}\n{1}".format(root, root_size) yield [root_string, None, root_size] for parent, dirs, files in os.walk(root): for dirname in dirs: fullpath = os.path.join(parent, dirname) try: this_size = get_folder_size(fullpath) parent_size = get_folder_size(parent) this_string = "{0}\n{1}".format(fullpath, this_size) parent_string = "{0}\n{1}".format(parent, parent_size) yield [this_string, parent_string, this_size] except OSError: continue def json_usage(root): root = os.path.abspath(root) result = [['Path', 'Parent', 'Usage']] result.extend(entry for entry in usage_iter(root)) return json.dumps(result) def main(args): '''Populates an html template using JSON-formatted output from the Linux 'du' utility and prints the result''' html = ''' <html> <head> <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("visualization", "1", {packages:["treemap"]}); google.setOnLoadCallback(drawChart); function drawChart() { // Create and populate the data table. var data = google.visualization.arrayToDataTable(%s); // Create and draw the visualization. var tree = new google.visualization.TreeMap(document.getElementById('chart_div')); tree.draw(data, { headerHeight: 15, fontColor: 'black' }); } </script> </head> <body> <div id="chart_div" style="width: 900px; height: 500px;"></div> <p style="text-align: center">Click to descend. Right-click to ascend.</p> </body> </html> ''' % json_usage(args[0]) # ''' % du2json(get_usage(args[0])) print html if __name__ == "__main__": main(sys.argv[1:] or ['.'])
geekoftheweek/disk-treemap
treemap.py
Python
mit
2,734
""" Check what the `lambdax` module publicly exposes. """ import builtins from inspect import isbuiltin, ismodule, isclass from itertools import chain import operator from unittest.mock import patch import lambdax.builtins_as_lambdas import lambdax.builtins_overridden from lambdax import x1, x2, x def _get_exposed(tested_module): return {name for name, obj in vars(tested_module).items() if not name.startswith('_') and not ismodule(obj)} def test_no_builtin_exposed(): for obj in chain(vars(lambdax).values(), vars(lambdax.builtins_overridden).values()): assert not isbuiltin(obj) def test_base_exposed(): variables = {'x'} | {'x%d' % i for i in range(1, 10)} variables |= {v.upper() for v in variables} special_functions = {'λ', 'is_λ', 'comp', 'circle', 'chaining', 'and_', 'or_', 'if_'} to_expose = variables | special_functions exposed = _get_exposed(lambdax.lambda_calculus) assert to_expose == exposed def test_operators_exposed(): operators = {name for name, obj in vars(operator).items() if not name.startswith('_') and not isclass(obj) and not hasattr(builtins, name)} to_expose = operators.difference(('and_', 'or_', 'xor')) assert to_expose == _get_exposed(lambdax.operators) def test_overridden_builtins_exposed(): builtin_names = {name for name, obj in vars(builtins).items() if name[0].upper() != name[0]} irrelevant_builtins = { 'input', 'help', 'open', 'copyright', 'license', 'credits', 'compile', 'eval', 'exec', 'execfile', 'runfile', 'classmethod', 'staticmethod', 'property', 'object', 'super', 'globals', 'locals' } builtins_to_expose = builtin_names - irrelevant_builtins to_expose_as_λ = {name + '_λ' for name in builtins_to_expose} split_exposed_names = (name.split('_') for name in _get_exposed(lambdax.builtins_as_lambdas)) exposed_as_λ = {'%s_%s' % (words[0], words[-1]) for words in split_exposed_names} assert to_expose_as_λ == exposed_as_λ assert builtins_to_expose == _get_exposed(lambdax.builtins_overridden) def test_operators_implementations(): operators = vars(operator) for name, abstraction in vars(lambdax.operators).items(): initial = operators.get(name) if initial and isbuiltin(initial): wrapped = getattr(abstraction, '_λ_constant') assert wrapped == initial try: ref = initial(42, 51) except TypeError as e: ref = e.args try: res = abstraction(x1, x2)(42, 51) except TypeError as e: res = e.args assert res == ref def _get_effect(implementation): output = [] with patch('sys.stdout') as out: out.side_effect = output.append try: res = implementation("42") except BaseException as e: res = e.args return res, output def _get_method_or_object(obj, meth=''): return getattr(obj, meth) if meth else obj def test_overridden_builtins_implementations(): for name in _get_exposed(lambdax.builtins_as_lambdas): obj, tail = name.split('_', 1) meth = tail[:-2] original = _get_method_or_object(getattr(builtins, obj), meth) as_λ = getattr(lambdax.builtins_as_lambdas, name) overridden = _get_method_or_object(getattr(lambdax.builtins_overridden, obj), meth) ref, ref_output = _get_effect(original) expl, expl_output = _get_effect(as_λ(x)) iso, iso_output = _get_effect(overridden) lbda, lbda_output = _get_effect(overridden(x)) assert lbda_output == iso_output == expl_output == ref_output try: assert list(iter(lbda)) == list(iter(iso)) == list(iter(expl)) == list(iter(ref)) except TypeError: assert lbda == iso == expl == ref
hlerebours/lambda-calculus
lambdax/test/test_exposed.py
Python
mit
3,947
/* google-paper.js */ 'use strict'; navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia; var RAD_2_DEG = 180/Math.PI; function moving_average(period) { var nums = []; return function(num) { nums.push(num); if (nums.length > period) nums.splice(0,1); var sum = 0; for (var i in nums) sum += nums[i]; var n = period; if (nums.length < period) n = nums.length; return(sum/n); } } var GP = GP || {}; GP.PaperTracker = function(options){ this.options = options || {}; this.video; this.canvas; this.context; this.camDirection = 'front'; // back this.imageData; this.detector; this.posit; this.markers; this.init(options); }; GP.PaperTracker.prototype.init = function(options){ this.video = document.getElementById('video'); this.canvas = document.getElementById('video-canvas'); this.context = this.canvas.getContext('2d'); this.canvas.width = parseInt(this.canvas.style.width); this.canvas.height = parseInt(this.canvas.style.height); this.trackingInfo = { lastTrackTime: 0, haveTracking: false, neverTracked: true, translation: [0,0,0], orientation: [0,0,0], rotation: [0,0,0] }; this.detector = new AR.Detector(); this.posit = new POS.Posit(this.options.modelSize, this.canvas.width); }; GP.PaperTracker.prototype.postInit = function(){ var vid = this.video; navigator.getUserMedia({video:true}, function (stream){ if (window.webkitURL) { vid.src = window.webkitURL.createObjectURL(stream); } else if (vid.mozSrcObject !== undefined) { vid.mozSrcObject = stream; } else { vid.src = stream; } }, function(error){ console.log('stream not found'); } ); }; GP.PaperTracker.prototype.snapshot = function(){ this.context.drawImage(this.video, 0, 0, this.canvas.width, this.canvas.height); this.imageData = this.context.getImageData(0, 0, this.canvas.width, this.canvas.height); }; GP.PaperTracker.prototype.detect = function(){ var markers = this.detector.detect(this.imageData); this.markers = markers; return markers; }; GP.PaperTracker.prototype.process = function(){ if (this.video.readyState === this.video.HAVE_ENOUGH_DATA){ this.snapshot(); this.detect(); this.drawCorners(); return true; } return false; }; GP.PaperTracker.prototype.drawCorners = function(){ var corners, corner, i, j; this.context.lineWidth = 3; for (i = 0; i < this.markers.length; ++ i){ corners = this.markers[i].corners; this.context.strokeStyle = "red"; this.context.beginPath(); for (j = 0; j < corners.length; ++ j){ corner = corners[j]; this.context.moveTo(corner.x, corner.y); corner = corners[(j + 1) % corners.length]; this.context.lineTo(corner.x, corner.y); } this.context.stroke(); this.context.closePath(); this.context.strokeStyle = "blue"; this.context.strokeRect(corners[0].x - 2, corners[0].y - 2, 4, 4); } }; GP.PaperTracker.prototype.updateTracking = function(){ var corners, corner, pose, i; if (this.markers.length == 0) { this.trackingInfo.haveTracking = false; return false; } this.trackingInfo.neverTracked = false; this.trackingInfo.haveTracking = true; corners = this.markers[0].corners; for (i = 0; i < corners.length; ++ i){ corner = corners[i]; corner.x = corner.x - (this.canvas.width / 2); corner.y = (this.canvas.height / 2) - corner.y; } pose = this.posit.pose(corners); var rotation = pose.bestRotation; var translation = pose.bestTranslation; this.trackingInfo.translation = translation; this.trackingInfo.rotation = rotation; return this.trackingInfo; };
mkeblx/goggle-paper
examples/js/goggle-paper.js
JavaScript
mit
3,793
'use strict'; /* jasmine specs for services go here */ describe('base', function() { beforeEach(function(){ module('d3-uml-modeler.base'); module('d3-uml-modeler.uml-abstract-factory'); module('d3-uml-modeler.constants'); module('d3-uml-modeler.notifications'); }); describe('BaseModelElement', function() { it('T1: should contain a GUID and an empty children hash', inject(["BaseModelElement", function($BaseModelElement) { var model = new $BaseModelElement(); expect(model.GUID).not.toBe(""); expect(model.count).toBe(0); expect(_.isEmpty(model.children)).toBe(true); }])); it('T2: should contain 2 children after a addElement call', inject(["BaseModelElement", function($BaseModelElement) { var model = new $BaseModelElement(); //add 2 models to it. var child1 = new $BaseModelElement(); var child2 = new $BaseModelElement(); model.addElement(child1); model.addElement(child2); //non empty children expect(_.isEmpty(model.children)).toBe(false); expect(model.count).toBe(2); }])); it("T3: should remove elements by passing them or their GUID to removeElement", inject(["BaseModelElement", function($BaseModelElement) { var model = new $BaseModelElement(); //add 2 models to it. var child1 = new $BaseModelElement(); var child2 = new $BaseModelElement(); var child3 = new $BaseModelElement(); var child4 = new $BaseModelElement(); //add some childs model.addElement(child1); model.addElement(child2); model.addElement(child3); model.addElement(child4); //remove a child by passing it to removeElement model.removeElement(child2); //remove a child by passing its GUID to removeElement model.removeElement(child3.GUID); //children count expect(model.count).toBe(2); //test remaining children. expect(model.children[child1.GUID]).toBe(child1); expect(model.children[child2.GUID]).toBe(undefined); expect(model.children[child3.GUID]).toBe(undefined); expect(model.children[child4.GUID]).toBe(child4); }])); it('T4: should contain 3 children after a removeElement call', inject(["BaseModelElement", function($BaseModelElement) { var model = new $BaseModelElement(); //add 2 models to it. var child1 = new $BaseModelElement(); var child2 = new $BaseModelElement(); var child3 = new $BaseModelElement(); var child4 = new $BaseModelElement(); //add some childs model.addElement(child1); model.addElement(child2); model.addElement(child3); model.addElement(child4); //children count expect(model.count).toBe(4); //remove a child model.removeElement(child2); //children count expect(model.count).toBe(3); }])); }); //EventDispatcher describe('EventDispatcher', function(){ it('T5: should contain an empty listeners hash', inject(["EventDispatcher", function(EventDispatcher) { var eventDispatcher = new EventDispatcher(); expect(_.isEmpty(eventDispatcher._listeners)).toBe(true); }])); it('T6: should add and remove listeners', inject(["EventDispatcher", function(EventDispatcher) { var eventDispatcher = new EventDispatcher(); var anAwesomeFunction = function() { //my brilliant code here. console.log("T6: my brilliant code is being executed"); }; eventDispatcher.addEventListener("an.awesome.event", anAwesomeFunction); expect(eventDispatcher.hasListeners()).toBeTruthy(); //remove a listener eventDispatcher.removeEventListener("an.awesome.event", anAwesomeFunction); //check if th event has been removed expect(eventDispatcher.hasListener("an.awesome.event")).toBeFalsy(); expect(eventDispatcher.hasListeners()).toBe(false); var args = ["lol", "cool", "mdr"]; var params = [].concat(args.splice(1, args.length)); expect(params).toContain("cool"); expect(params).toContain("mdr"); expect(params).not.toContain("lol"); spyOn(console, "warn"); expect(function(){eventDispatcher.dispatchEvent("kool");}).not.toThrow(); expect(console.warn).toHaveBeenCalled(); expect(console.warn).toHaveBeenCalledWith("no such registered event : kool"); }])); }); describe('UmlController', function() { beforeEach(function(){ module('d3-uml-modeler.base'); module('d3-uml-modeler.notifications'); module('d3-uml-modeler.underscore'); }); it('T7: should contain a notifications list', inject([ "$rootScope", "_", "Notifications", "UmlController", function($rootScope, _, Notifications, UmlController) { var $scope = $rootScope.$new(); var ctrlFactory = new UmlController($scope, _, Notifications); expect(ctrlFactory.notifications).toBeDefined(); } ])); }); describe('Lodash Service:', function() { beforeEach(module('d3-uml-modeler.underscore')); it('T8: should get an instance of the underscore factory', inject(function(_) { expect(_).toBeDefined(); })); }); describe('Uml Model Abstract Factory', function() { beforeEach(function(){ module('d3-uml-modeler.underscore'); module('d3-uml-modeler.uml-abstract-factory'); }); it('T9: should contain a notifications list', inject(["UmlModelAbstractFactory", "_", function(UmlModelAbstractFactory, _) { expect(UmlModelAbstractFactory).toBeDefined(); expect(typeof UmlModelAbstractFactory).toBe("object"); expect(typeof UmlModelAbstractFactory.createUmlModelElement).toBe("function"); expect(typeof UmlModelAbstractFactory.registerUmlModelElementClass).toBe("function"); } ])); it('T10: should contain a notifications list', inject(["UmlModelAbstractFactory", "Constants", "_", function(UmlModelAbstractFactory, Constants, _) { Constants.ELEMENT_TYPES_TO_NAMES["car"] = "Car"; Constants.ELEMENT_TYPES_TO_NAMES["bicycle"] = "Bicycle"; var CarClass = Class.extend({ name: "", color: "", brand: "" }); var BicycleClass = Class.extend({ color: "", type: "" }); expect(typeof CarClass).toBe('function'); expect(typeof BicycleClass).toBe('function'); UmlModelAbstractFactory.registerUmlModelElementClass("car", CarClass); UmlModelAbstractFactory.registerUmlModelElementClass("bicycle", BicycleClass); expect(function(){ UmlModelAbstractFactory.registerUmlModelElementClass("truck", {}); }).toThrow(); var modelCar = UmlModelAbstractFactory.createUmlModelElement("car", {name: "peugeot"}); expect(modelCar).toBeDefined(); expect(typeof modelCar).toBe("object"); expect(modelCar.GUID).toBeUndefined(); expect(modelCar.name).toBe("peugeot"); var modelBicycle = UmlModelAbstractFactory.createUmlModelElement("bicycle", {name: "BTwin"}); expect(modelBicycle).toBeDefined(); expect(typeof modelBicycle).toBe("object"); expect(modelBicycle.GUID).toBeUndefined(); expect(modelBicycle.name).toBe("BTwin"); //creating an object without passing arguments //expect to throw expect(UmlModelAbstractFactory.createUmlModelElement).toThrow("type not found : undefined"); //creating an object without passing options //expect to work var newCar = UmlModelAbstractFactory.createUmlModelElement("car"); expect(newCar).toBeDefined(); expect(typeof newCar).toBe("object"); expect(newCar.GUID).toBeUndefined(); expect(newCar.name).toBe(""); UmlModelAbstractFactory.unregisterUmlModelElementClass("bicycle", BicycleClass); expect(_.isEmpty(UmlModelAbstractFactory.types)).toBe(false); UmlModelAbstractFactory.unregisterUmlModelElementClass("car", CarClass); expect(_.isEmpty(UmlModelAbstractFactory.types)).toBe(true); // console.log("types : ", UmlModelAbstractFactory.types); } ])); }); });
elfakamal/d3-uml-modeler
test/unit/baseSpec.js
JavaScript
mit
7,756
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tera.Game.Messages; namespace DamageMeter.Heuristic { class S_PRIVATE_CHAT : AbstractPacketHeuristic { public new void Process(ParsedMessage message) { base.Process(message); if (IsKnown || OpcodeFinder.Instance.IsKnown(message.OpCode)) return; if (message.Payload.Count < 2+2+4+8+4+4) return; if(!OpcodeFinder.Instance.IsKnown(OpcodeEnum.S_JOIN_PRIVATE_CHANNEL)) return; var authorOffset = Reader.ReadUInt16(); var messageOffset = Reader.ReadUInt16(); var channel = Reader.ReadUInt32(); if(!S_JOIN_PRIVATE_CHANNEL.JoinedChannelId.Contains(channel)) return; var authorId = Reader.ReadUInt64(); if(Reader.BaseStream.Position != authorOffset - 4) return; try { var author = Reader.ReadTeraString(); } catch (Exception e) { return; } if (Reader.BaseStream.Position != messageOffset - 4) return; try { var msg = Reader.ReadTeraString(); if(!msg.Contains("<FONT")) return; } catch (Exception e) { return; } OpcodeFinder.Instance.SetOpcode(message.OpCode, OPCODE); } } }
neowutran/OpcodeSearcher
DamageMeter.Core/Heuristic/S_PRIVATE_CHAT.cs
C#
mit
1,375
package org.jabref.gui.maintable; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import javax.swing.undo.UndoManager; import javafx.collections.ListChangeListener; import javafx.scene.control.SelectionMode; import javafx.scene.control.TableColumn; import javafx.scene.control.TableRow; import javafx.scene.control.TableView; import javafx.scene.input.ClipboardContent; import javafx.scene.input.DragEvent; import javafx.scene.input.Dragboard; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseDragEvent; import javafx.scene.input.MouseEvent; import javafx.scene.input.TransferMode; import org.jabref.gui.DialogService; import org.jabref.gui.DragAndDropDataFormats; import org.jabref.gui.Globals; import org.jabref.gui.LibraryTab; import org.jabref.gui.StateManager; import org.jabref.gui.actions.StandardActions; import org.jabref.gui.edit.EditAction; import org.jabref.gui.externalfiles.ImportHandler; import org.jabref.gui.externalfiletype.ExternalFileTypes; import org.jabref.gui.keyboard.KeyBinding; import org.jabref.gui.keyboard.KeyBindingRepository; import org.jabref.gui.maintable.columns.MainTableColumn; import org.jabref.gui.util.ControlHelper; import org.jabref.gui.util.CustomLocalDragboard; import org.jabref.gui.util.DefaultTaskExecutor; import org.jabref.gui.util.ViewModelTableRowFactory; import org.jabref.logic.importer.ImportCleanup; import org.jabref.logic.l10n.Localization; import org.jabref.logic.util.OS; import org.jabref.model.database.BibDatabaseContext; import org.jabref.model.database.BibDatabaseMode; import org.jabref.model.database.event.EntriesAddedEvent; import org.jabref.model.entry.BibEntry; import org.jabref.preferences.PreferencesService; import com.google.common.eventbus.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MainTable extends TableView<BibEntryTableViewModel> { private static final Logger LOGGER = LoggerFactory.getLogger(MainTable.class); private final LibraryTab libraryTab; private final DialogService dialogService; private final BibDatabaseContext database; private final MainTableDataModel model; private final ImportHandler importHandler; private final CustomLocalDragboard localDragboard; private long lastKeyPressTime; private String columnSearchTerm; public MainTable(MainTableDataModel model, LibraryTab libraryTab, BibDatabaseContext database, PreferencesService preferencesService, DialogService dialogService, StateManager stateManager, ExternalFileTypes externalFileTypes, KeyBindingRepository keyBindingRepository) { super(); this.libraryTab = libraryTab; this.dialogService = dialogService; this.database = Objects.requireNonNull(database); this.model = model; UndoManager undoManager = libraryTab.getUndoManager(); MainTablePreferences mainTablePreferences = preferencesService.getMainTablePreferences(); importHandler = new ImportHandler( database, externalFileTypes, preferencesService, Globals.getFileUpdateMonitor(), undoManager, stateManager); localDragboard = stateManager.getLocalDragboard(); this.setOnDragOver(this::handleOnDragOverTableView); this.setOnDragDropped(this::handleOnDragDroppedTableView); this.getColumns().addAll( new MainTableColumnFactory( database, preferencesService, externalFileTypes, libraryTab.getUndoManager(), dialogService, stateManager).createColumns()); new ViewModelTableRowFactory<BibEntryTableViewModel>() .withOnMouseClickedEvent((entry, event) -> { if (event.getClickCount() == 2) { libraryTab.showAndEdit(entry.getEntry()); } }) .withContextMenu(entry -> RightClickMenu.create(entry, keyBindingRepository, libraryTab, dialogService, stateManager, preferencesService, undoManager, Globals.getClipboardManager())) .setOnDragDetected(this::handleOnDragDetected) .setOnDragDropped(this::handleOnDragDropped) .setOnDragOver(this::handleOnDragOver) .setOnDragExited(this::handleOnDragExited) .setOnMouseDragEntered(this::handleOnDragEntered) .install(this); this.getSortOrder().clear(); /* KEEP for debugging purposes for (var colModel : mainTablePreferences.getColumnPreferences().getColumnSortOrder()) { for (var col : this.getColumns()) { var tablecColModel = ((MainTableColumn<?>) col).getModel(); if (tablecColModel.equals(colModel)) { LOGGER.debug("Adding sort order for col {} ", col); this.getSortOrder().add(col); break; } } } */ mainTablePreferences.getColumnPreferences().getColumnSortOrder().forEach(columnModel -> this.getColumns().stream() .map(column -> (MainTableColumn<?>) column) .filter(column -> column.getModel().equals(columnModel)) .findFirst() .ifPresent(column -> this.getSortOrder().add(column))); if (mainTablePreferences.getResizeColumnsToFit()) { this.setColumnResizePolicy(new SmartConstrainedResizePolicy()); } this.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); this.setItems(model.getEntriesFilteredAndSorted()); // Enable sorting model.getEntriesFilteredAndSorted().comparatorProperty().bind(this.comparatorProperty()); this.getStylesheets().add(MainTable.class.getResource("MainTable.css").toExternalForm()); // Store visual state new PersistenceVisualStateTable(this, preferencesService); setupKeyBindings(keyBindingRepository); this.setOnKeyTyped(key -> { if (this.getSortOrder().isEmpty()) { return; } this.jumpToSearchKey(getSortOrder().get(0), key); }); database.getDatabase().registerListener(this); } /** * This is called, if a user starts typing some characters into the keyboard with focus on main table. The {@link MainTable} will scroll to the cell with the same starting column value and typed string * * @param sortedColumn The sorted column in {@link MainTable} * @param keyEvent The pressed character */ private void jumpToSearchKey(TableColumn<BibEntryTableViewModel, ?> sortedColumn, KeyEvent keyEvent) { if ((keyEvent.getCharacter() == null) || (sortedColumn == null)) { return; } if ((System.currentTimeMillis() - lastKeyPressTime) < 700) { columnSearchTerm += keyEvent.getCharacter().toLowerCase(); } else { columnSearchTerm = keyEvent.getCharacter().toLowerCase(); } lastKeyPressTime = System.currentTimeMillis(); this.getItems().stream() .filter(item -> Optional.ofNullable(sortedColumn.getCellObservableValue(item).getValue()) .map(Object::toString) .orElse("") .toLowerCase() .startsWith(columnSearchTerm)) .findFirst() .ifPresent(item -> { this.scrollTo(item); this.clearAndSelect(item.getEntry()); }); } @Subscribe public void listen(EntriesAddedEvent event) { DefaultTaskExecutor.runInJavaFXThread(() -> clearAndSelect(event.getFirstEntry())); } public void clearAndSelect(BibEntry bibEntry) { findEntry(bibEntry).ifPresent(entry -> { getSelectionModel().clearSelection(); getSelectionModel().select(entry); scrollTo(entry); }); } public void copy() { List<BibEntry> selectedEntries = getSelectedEntries(); if (!selectedEntries.isEmpty()) { try { Globals.getClipboardManager().setContent(selectedEntries); dialogService.notify(libraryTab.formatOutputMessage(Localization.lang("Copied"), selectedEntries.size())); } catch (IOException e) { LOGGER.error("Error while copying selected entries to clipboard", e); } } } public void cut() { copy(); libraryTab.delete(true); } private void setupKeyBindings(KeyBindingRepository keyBindings) { this.addEventHandler(KeyEvent.KEY_PRESSED, event -> { if (event.getCode() == KeyCode.ENTER) { getSelectedEntries().stream() .findFirst() .ifPresent(libraryTab::showAndEdit); event.consume(); return; } Optional<KeyBinding> keyBinding = keyBindings.mapToKeyBinding(event); if (keyBinding.isPresent()) { switch (keyBinding.get()) { case SELECT_FIRST_ENTRY: clearAndSelectFirst(); event.consume(); break; case SELECT_LAST_ENTRY: clearAndSelectLast(); event.consume(); break; case PASTE: if (!OS.OS_X) { new EditAction(StandardActions.PASTE, libraryTab.frame(), Globals.stateManager).execute(); } event.consume(); break; case COPY: new EditAction(StandardActions.COPY, libraryTab.frame(), Globals.stateManager).execute(); event.consume(); break; case CUT: new EditAction(StandardActions.CUT, libraryTab.frame(), Globals.stateManager).execute(); event.consume(); break; default: // Pass other keys to parent } } }); } public void clearAndSelectFirst() { getSelectionModel().clearSelection(); getSelectionModel().selectFirst(); scrollTo(0); } private void clearAndSelectLast() { getSelectionModel().clearSelection(); getSelectionModel().selectLast(); scrollTo(getItems().size() - 1); } public void paste(BibDatabaseMode bibDatabaseMode) { // Find entries in clipboard List<BibEntry> entriesToAdd = Globals.getClipboardManager().extractData(); ImportCleanup cleanup = new ImportCleanup(bibDatabaseMode); cleanup.doPostCleanup(entriesToAdd); libraryTab.insertEntries(entriesToAdd); if (!entriesToAdd.isEmpty()) { this.requestFocus(); } } private void handleOnDragOver(TableRow<BibEntryTableViewModel> row, BibEntryTableViewModel item, DragEvent event) { if (event.getDragboard().hasFiles()) { event.acceptTransferModes(TransferMode.ANY); ControlHelper.setDroppingPseudoClasses(row, event); } event.consume(); } private void handleOnDragOverTableView(DragEvent event) { if (event.getDragboard().hasFiles()) { event.acceptTransferModes(TransferMode.ANY); } event.consume(); } private void handleOnDragEntered(TableRow<BibEntryTableViewModel> row, BibEntryTableViewModel entry, MouseDragEvent event) { // Support the following gesture to select entries: click on one row -> hold mouse button -> move over other rows // We need to select all items between the starting row and the row where the user currently hovers the mouse over // It is not enough to just select the currently hovered row since then sometimes rows are not marked selected if the user moves to fast @SuppressWarnings("unchecked") TableRow<BibEntryTableViewModel> sourceRow = (TableRow<BibEntryTableViewModel>) event.getGestureSource(); getSelectionModel().selectRange(sourceRow.getIndex(), row.getIndex()); } private void handleOnDragExited(TableRow<BibEntryTableViewModel> row, BibEntryTableViewModel entry, DragEvent dragEvent) { ControlHelper.removeDroppingPseudoClasses(row); } private void handleOnDragDetected(TableRow<BibEntryTableViewModel> row, BibEntryTableViewModel entry, MouseEvent event) { // Start drag'n'drop row.startFullDrag(); List<BibEntry> entries = getSelectionModel().getSelectedItems().stream().map(BibEntryTableViewModel::getEntry).collect(Collectors.toList()); // The following is necesary to initiate the drag and drop in javafx, although we don't need the contents // It doesn't work without ClipboardContent content = new ClipboardContent(); Dragboard dragboard = startDragAndDrop(TransferMode.MOVE); content.put(DragAndDropDataFormats.ENTRIES, ""); dragboard.setContent(content); if (!entries.isEmpty()) { localDragboard.putBibEntries(entries); } event.consume(); } private void handleOnDragDropped(TableRow<BibEntryTableViewModel> row, BibEntryTableViewModel target, DragEvent event) { boolean success = false; if (event.getDragboard().hasFiles()) { List<Path> files = event.getDragboard().getFiles().stream().map(File::toPath).collect(Collectors.toList()); // Different actions depending on where the user releases the drop in the target row // Bottom + top -> import entries // Center -> link files to entry // Depending on the pressed modifier, move/copy/link files to drop target switch (ControlHelper.getDroppingMouseLocation(row, event)) { case TOP, BOTTOM -> importHandler.importFilesInBackground(files).executeWith(Globals.TASK_EXECUTOR); case CENTER -> { BibEntry entry = target.getEntry(); switch (event.getTransferMode()) { case LINK -> { LOGGER.debug("Mode LINK"); // shift on win or no modifier importHandler.getLinker().addFilesToEntry(entry, files); } case MOVE -> { LOGGER.debug("Mode MOVE"); // alt on win importHandler.getLinker().moveFilesToFileDirAndAddToEntry(entry, files); } case COPY -> { LOGGER.debug("Mode Copy"); // ctrl on win importHandler.getLinker().copyFilesToFileDirAndAddToEntry(entry, files); } } } } success = true; } event.setDropCompleted(success); event.consume(); } private void handleOnDragDroppedTableView(DragEvent event) { boolean success = false; if (event.getDragboard().hasFiles()) { List<Path> files = event.getDragboard().getFiles().stream().map(File::toPath).collect(Collectors.toList()); importHandler.importFilesInBackground(files).executeWith(Globals.TASK_EXECUTOR); success = true; } event.setDropCompleted(success); event.consume(); } public void addSelectionListener(ListChangeListener<? super BibEntryTableViewModel> listener) { getSelectionModel().getSelectedItems().addListener(listener); } public MainTableDataModel getTableModel() { return model; } public BibEntry getEntryAt(int row) { return model.getEntriesFilteredAndSorted().get(row).getEntry(); } public List<BibEntry> getSelectedEntries() { return getSelectionModel() .getSelectedItems() .stream() .map(BibEntryTableViewModel::getEntry) .collect(Collectors.toList()); } private Optional<BibEntryTableViewModel> findEntry(BibEntry entry) { return model.getEntriesFilteredAndSorted() .stream() .filter(viewModel -> viewModel.getEntry().equals(entry)) .findFirst(); } }
sauliusg/jabref
src/main/java/org/jabref/gui/maintable/MainTable.java
Java
mit
17,294
using System; using System.Collections; using System.ComponentModel; using System.ServiceProcess; using System.Configuration.Install; namespace Tempora { [RunInstaller(true)] public class AppServiceInstaller : Installer { public AppServiceInstaller() { ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller(); serviceProcessInstaller.Account = ServiceAccount.LocalSystem; serviceProcessInstaller.Username = null; serviceProcessInstaller.Password = null; this.Installers.Add(serviceProcessInstaller); ServiceInstaller serviceInstaller = new ServiceInstaller(); serviceInstaller.ServiceName = AppService.Instance.ServiceName; serviceInstaller.DisplayName = Medo.Reflection.CallingAssembly.Title; serviceInstaller.Description = Medo.Reflection.CallingAssembly.Description; serviceInstaller.StartType = ServiceStartMode.Automatic; this.Installers.Add(serviceInstaller); } protected override void OnCommitted(IDictionary savedState) { base.OnCommitted(savedState); using (ServiceController sc = new ServiceController(AppService.Instance.ServiceName)) { sc.Start(); } } protected override void OnBeforeUninstall(IDictionary savedState) { using (ServiceController sc = new ServiceController(AppService.Instance.ServiceName)) { if (sc.Status != ServiceControllerStatus.Stopped) { sc.Stop(); } } base.OnBeforeUninstall(savedState); } } }
medo64/Tempora
Source/Tempora/AppServiceInstaller.cs
C#
mit
1,749
package com.example.many_to_one; import static org.junit.jupiter.api.Assertions.*; import javax.persistence.EntityManager; import javax.transaction.Transactional; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; @SpringJUnitConfig @SpringBootTest @Transactional class ManyToOneTest { @Autowired private EntityManager em; private Long author1; private Long book1; private Long book2; private Long book3; @BeforeEach void setUp() throws Exception { final AuthorM2O a = new AuthorM2O(); a.setName("コナン・ドイル"); final BookM2O b1 = new BookM2O(); b1.setTitle("緋色の研究"); final BookM2O b2 = new BookM2O(); b2.setTitle("四つの署名"); final BookM2O b3 = new BookM2O(); b3.setTitle("恐怖の谷"); b3.setAuthor(a); em.persist(a); em.persist(b1); em.persist(b2); em.persist(b3); em.flush(); author1 = a.getId(); book1 = b1.getId(); book2 = b2.getId(); book3 = b3.getId(); } @AfterEach void tearDown() throws Exception { em.remove(em.find(AuthorM2O.class, author1)); em.remove(em.find(BookM2O.class, book1)); em.remove(em.find(BookM2O.class, book2)); em.remove(em.find(BookM2O.class, book3)); } @Test void getAuthorViaBook() throws Exception { final BookM2O b = em.find(BookM2O.class, book3); assertEquals("コナン・ドイル", b.getAuthor().getName()); } }
backpaper0/spring-boot-sandbox
jpa-example/src/test/java/com/example/many_to_one/ManyToOneTest.java
Java
mit
1,808
'use strict' /* LIBS */ /* EXEC */ export interface DecolarFare { raw: { code: string, amount: number }, formatted: { code: string, amount: string, mask: string } } export interface DecolarLocation { city: { code: string }, airport: { code: string }, takeAsCity: boolean, code: string } export interface DecolarItinerariesBox { outboundLocations: { departure: DecolarLocation, arrival: DecolarLocation } } export interface DecolarItem { internalId: string, clusterAlertType: string, id: string, itinerariesBox: DecolarItinerariesBox, emissionPrice: { total: { fare: { raw: number, formatted: { code: string, amount: string, mask: string } } } }, provider: string } export interface DecolarData { result: { data?: { items: [DecolarItem] cities: Object, airports: Object, airlines: Object, cabinTypes: Object, refinementSummary: Object, paginationSummary: { itemCount: number, pageCount: number, currentPage: number }, pricesSummary: Object, metadata: { status: { code: string }, currencyCode: string, ticket: { id: string, version: string }, providers: [string] hasFrequenFlyerInfo: boolean, upaTracking: string, gtmTracking: string, searchId: string, currencyRates: Object }, reviewsSummary: Object, lowestFare: [DecolarFare], canShowFreeCancel: boolean, flightsTimes: Object, showCrosssellingBanner: boolean, abzTestingId: string, nonStopSuggestions: Object, searchHighlights: Object, status: { code: string }, hiddenFlightsCount: number, promotionsCount: number }, htmlContent?: { "flights-alerts": string, "flights-alerts-fixed": string }, status: { code: string, message?: string } }, messages?: [{ code: string, value: string, description: string }] }
thevtm/decolar-scraper
src/decolar-data.ts
TypeScript
mit
2,170
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ /* eslint-disable global-require */ // The top-level (parent) route export default { path: '/', // Keep in mind, routes are evaluated in order children: [ require('./home/index').default, require('./contact/index').default, require('./login/index').default, require('./register/index').default, require('./admin/index').default, // Wildcard routes, e.g. { path: '*', ... } (must go last) require('./content/index').default, require('./notFound/index').default, ], async action({ next }) { // Execute each child route until one of them return the result const route = await next(); // Provide default values for title, description etc. route.title = `${route.title || 'Untitled Page'} - www.reactstarterkit.com`; route.description = route.description || ''; return route; }, };
nextinnovation-corp/gacha
legacy_back/src/routes/index.js
JavaScript
mit
1,116
<?php //Access control if (!defined('IN_APP_PROJECT')) { exit('Access Forbidden'); } class ErrorHandler { protected static $errors = array(); protected static $displayErrors = true; protected $errorNumber; protected $errorString; protected $errorFile; protected $errorLine; protected $errorContext; protected $stackTrace; protected $email; public function __construct($errorNumber, $errorString, $errorFile, $errorLine, $errorContext, $email) { $this->errorNumber = $errorNumber; $this->errorString = $errorString; $this->errorFile = $errorFile; $this->errorLine = $errorLine; $this->errorContext = $errorContext; $this->email = $email; $this->stackTrace = debug_backtrace(); } /** * stablishes the behaviour of the system when an error occurs */ public static function handleError($errorNumber, $errorString, $errorFile, $errorLine, $errorContext) { global $_emergencyEmail; $currentError = new ErrorHandler($errorNumber, $errorString, $errorFile, $errorLine, $errorContext, $_emergencyEmail); array_push(ErrorHandler::$errors, $currentError); if (ErrorHandler::$displayErrors) { $currentError->show(); } else { $currentError->showMessage(); $currentError->sendEmail($currentError->messageToHTML(), $currentError->toHTML()); } } /** * shows the error using a custom HTML format that can be edited on the * "toHTML()" method */ public function show() { echo $this->toHTML(); } /** * shows the error using a custom HTML format that can be edited on the * "toHTML()" method */ public function showMessage() { echo '<pre>' . $this->messageToHTML() . '</pre>'; } /** * renders the main error message into HTML format and returns the error text */ public function messageToHTML() { return '<b>Error [<em>' . $this->errorNumber . '</em>]:</b> ' . $this->errorString; } /** * renders the error into HTML format and returns the error text */ public function toHTML() { $str = '<pre>' . $this->MessageToHTML(); $str .= '<br /><b>File:</b> ' . $this->errorFile; $str .= '<br /><b>Line:</b> ' . $this->errorLine; $str .= '<br /><b>Context:</b> ' . print_r($this->errorContext, true); $str .= '<br /><b>Stack Trace:</b> ' . $this->renderStackTrace(); $str .= '</pre>'; return $str; } /** * renders the stacktrace into html * @return string */ public function renderStackTrace() { $str = ''; for ($i = 2; $i < count($this->stackTrace); $i++) { $entry = $this->stackTrace[$i]; $str .= '<br />' . $this->printStackEntry($entry); } return $str; } /** * renders an stackTrace entry * @param type $entry * @return string */ protected function printStackEntry($entry) { $str = '<b>' . basename($entry['file']) . ' </b>[<b>' . $entry['line'] . '</b>]</b> in function <b>' . $entry['function'] . '</b>'; return $str; } /** * turns on the error displaying on the web page */ public static function showErrorsOnRendering() { ErrorHandler::$displayErrors = true; } /** * turns off the error displaying on the web page */ public static function hideErrorsOnRendering() { ErrorHandler::$displayErrors = false; } /** * This method send an email to the $email direction * @since 1.0 * @return boolean * @param object $header * @param object $subject * @param object $message * @param object $file [optional] * @param object $line [optional] */ protected function sendEmail($subject, $message, $header = "Content-type: text/html\r\n") { return mail($this->email, $subject, $message, $header); } // end sendEmail(...) /** * An alternative to print_r that unlike the original does not use output buffering with * the return parameter set to true. Thus, Fatal errors that would be the result of print_r * in return-mode within ob handlers can be avoided. * * Comes with an extra parameter to be able to generate html code. If you need a * human readable DHTML-based print_r alternative, see http://krumo.sourceforge.net/ * * Support for printing of objects as well as the $return parameter functionality * added by Fredrik Wollsén (fredrik dot motin at gmail), to make it work as a drop-in * replacement for print_r (Except for that this function does not output * paranthesises around element groups... ;) ) * * Based on return_array() By Matthew Ruivo (mruivo at gmail) * (http://se2.php.net/manual/en/function.print-r.php#73436) */ function obsafe_print_r($var, $return = false, $html = false, $level = 0) { if ($level >= 90) { return; } $spaces = ""; $space = $html ? "&nbsp;" : " "; $newline = $html ? "<br />" : "\n"; for ($i = 1; $i <= 6; $i++) { $spaces .= $space; } $tabs = $spaces; for ($i = 1; $i <= $level; $i++) { $tabs .= $spaces; } if (is_array($var)) { $title = "Array"; } elseif (is_object($var)) { $title = get_class($var) . " Object"; } $output = $title . $newline . $newline; foreach ($var as $key => $value) { if (is_array($value) || is_object($value)) { $level++; $value = $this->obsafe_print_r($value, true, $html, $level); $level--; } $output .= $tabs . "[" . $key . "] => " . $value . $newline; } if ($return) { return $output; } else { echo $output; } } } ?>
aescariom/ScarFramework-PHP
includes/classes/general/ErrorHandler.class.php
PHP
mit
6,158
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AnimationBehaviorDemo.ViewModels; using Xamarin.Forms; namespace AnimationBehaviorDemo { public partial class StartPage : ContentPage { public StartPage() { InitializeComponent(); BindingContext = new AnimationViewModel(); } protected override void OnSizeAllocated(double width, double height) { Context.OnViewAppearing(); base.OnSizeAllocated(width, height); } protected override void OnDisappearing() { Context.OnViewDisappearing(); base.OnDisappearing(); } private IPageViewModelBase Context { get { return (IPageViewModelBase)BindingContext; } } } }
LocalJoost/AnimationXamarinBehaviorDemo
AnimationBehaviorDemo/AnimationBehaviorDemo/StartPage.xaml.cs
C#
mit
780
package main import ( "strings" "strconv" "time" "bufio" "regexp" "fmt" "os" ) var rules = map[string]map[string]*regexp.Regexp{ "food": map[string]*regexp.Regexp{ "ALBERT HEIJN": regexp.MustCompile(`ALBERT HEIJN`), "Jumbo": regexp.MustCompile(`Jumbo[^a-zA-Z0-9-]`), }, "hema/blokker/other": map[string]*regexp.Regexp{ "HEMA": regexp.MustCompile(`HEMA`), "BEDWORLD": regexp.MustCompile(`BEDWORLD`), }, "electronics": map[string]*regexp.Regexp{ "Apple": regexp.MustCompile(`APPLE STORE`), "Coolblue": regexp.MustCompile(`Coolblue`), "Wiggle": regexp.MustCompile(`Wiggle`), }, "clothes": map[string]*regexp.Regexp{ "Decathlon": regexp.MustCompile(`Decathlon`), "FRONT RUNNER": regexp.MustCompile(`FRONT RUNNER`), }, "medicine": map[string]*regexp.Regexp{ "APOTHEEK": regexp.MustCompile(`APOTHEEK`), }, "deposits": map[string]*regexp.Regexp{ "Wallet": regexp.MustCompile(`IBAN\/NL14ABNA0620233052`), }, "rent": map[string]*regexp.Regexp{ "Dijwater 225": regexp.MustCompile(`IBAN\/NL18ABNA0459968513`), }, "g/w/e/i": map[string]*regexp.Regexp{ "Vodafone": regexp.MustCompile(`CSID\/NL39ZZZ302317620000`), "Energiedirect": regexp.MustCompile(`CSID\/NL71ABNA0629639183`), }, "abonements": map[string]*regexp.Regexp{ "Sport natural": regexp.MustCompile(`SPORT NATURAL`), // IBAN\/NL07ABNA0584314078 }, "insurance": map[string]*regexp.Regexp{ "Dijwater 225": regexp.MustCompile(`CSID\/NL94MNZ505448100000`), }, "salary": map[string]*regexp.Regexp{ "Textkernel": regexp.MustCompile(`IBAN\/NL27INGB0673657841`), }, } var displayOrder = []string{ "food", "rent", "g/w/e/i", "insurance", "abonements", "hema/blokker/other", "medicine", "electronics", "clothes", "deposits", "other", "salary", "unknown_income", "income", "rest", } // var reClarify = regexp.MustCompile(`^\/[^\/]+/[^\/]+/[^\/]+/[^\/]+/[^\/]+/[^\/]+/[^\/]+/([^\/]+)/[^\/]+/[^\/]+/[^\/]+/[^\/]+$`) // var reClarify2 = regexp.MustCompile(`^[^ ]+\s+[^ ]+\s+\d\d\.\d\d\.\d\d\/\d\d\.\d\d\s+(.*),[A-Z0-9 ]+$`) // var reClarify3 = regexp.MustCompile(`^[^ ]+\s+\d\d-\d\d-\d\d \d\d:\d\d\s+[^ ]+\s+(.*),[A-Z0-9 ]+$`) type Payment struct { accountId int64 currency string date time.Time balanceBefore float64 balanceAfter float64 anotherDate time.Time amount float64 description string } func check(e error) { if e != nil { panic(e) } } // func clarifyName(name string) (string, error) { // matches := reClarify.FindStringSubmatch(name) // if len(matches) > 1 { // return matches[1], nil // } // // matches = reClarify2.FindStringSubmatch(name) // if len(matches) > 1 { // return matches[1], nil // } // // matches = reClarify3.FindStringSubmatch(name) // if len(matches) > 1 { // return matches[1], nil // } // // return ``, fmt.Errorf(`Not parsable: %s`, name) // } func main() { file, err := os.Open("input.TAB") check(err) defer file.Close() scanner := bufio.NewScanner(file) re := regexp.MustCompile(`^(\d+)\t([A-Za-z]+)\t(\d+)\t(\d+,\d+)\t(\d+,\d+)\t(\d+)\t([-]?\d+,\d+)\t(.*?)$`); payments := make([]*Payment, 0, 5) for scanner.Scan() { txt := scanner.Text() matched := re.FindAllStringSubmatch(txt, 1) p := &Payment{}; p.accountId, err = strconv.ParseInt(matched[0][1], 10, 64) check(err) p.currency = matched[0][2] p.date, err = time.Parse("20060102", matched[0][3]) check(err) p.balanceBefore, err = strconv.ParseFloat(strings.Replace(matched[0][4], ",", ".", 1), 64) check(err) p.balanceAfter, err = strconv.ParseFloat(strings.Replace(matched[0][5], ",", ".", 1), 64) check(err) p.anotherDate, err = time.Parse("20060102", matched[0][6]) check(err) p.amount, err = strconv.ParseFloat(strings.Replace(matched[0][7], ",", ".", 1), 64) check(err) p.description = matched[0][8] payments = append(payments, p) } check(scanner.Err()) results := map[string]float64{ `supermarkets`: 0, `other`: 0, `income`: 0, `unknown_income`: 0, `rest`: 0, } var firstPaymentDate time.Time var lastPaymentDate time.Time i := 0 paymentsLen := len(payments) for _, p := range payments { switch i { case 0: firstPaymentDate = p.date case paymentsLen - 1: lastPaymentDate = p.date } other := true for rulesName, rulesList := range rules { for _, re := range rulesList { if re.MatchString(p.description) { if _, ok := results[rulesName]; ok { results[rulesName] += p.amount } else { results[rulesName] = p.amount } other = false break } } } if other && p.amount <= 0 { results[`other`] += p.amount } if other && p.amount > 0 { results[`unknown_income`] += p.amount } if p.amount > 0 { results[`income`] += p.amount } results[`rest`] += p.amount i += 1 } fmt.Printf("Stats between: %s and %s\n", firstPaymentDate.Format(`2006-01-02`), lastPaymentDate.Format(`2006-01-02`)) fmt.Println("-----------------------------------------------") for _, rulesName := range displayOrder { fmt.Printf("%s: %.2f\n", rulesName, results[rulesName]) } }
FelikZ/abn-amro
app.go
GO
mit
5,858
__author__ = 'ysahn' import logging import json import os import glob import collections from mako.lookup import TemplateLookup from mako.template import Template from taskmator.task.core import Task class TransformTask(Task): """ Class that transform a json into code using a template Uses mako as template engine for transformation """ logger = logging.getLogger(__name__) ATTR_TEMPLATE_DIR = u'template_dir' ATTR_TEMPLATES = u'templates' ATTR_SRC_DIR = u'src_dir' ATTR_SRC_FILES = u'src_files' ATTR_DEST_DIR = u'dest_dir' ATTR_FILE_PREFIX = u'file_prefix' ATTR_FILE_EXT = u'file_ext' __VALID_ATTRS = [ATTR_TEMPLATE_DIR, ATTR_TEMPLATES, ATTR_SRC_DIR, ATTR_SRC_FILES, ATTR_DEST_DIR, ATTR_FILE_PREFIX, ATTR_FILE_EXT] def __init__(self, name, parent=None): """ Constructor """ super(TransformTask, self).__init__(name, parent) self.template_dir = None self.templates = collections.OrderedDict() def setAttribute(self, attrKey, attrVal): if (attrKey in self.__VALID_ATTRS): self.attribs[attrKey] = attrVal else: super(TransformTask, self).setAttribute(attrKey, attrVal) def init(self): super(TransformTask, self).init() template_dir = self._normalize_dir(self.getAttribute(self.ATTR_TEMPLATE_DIR, './'), './') template_names = self.getAttribute(self.ATTR_TEMPLATES) if not template_names: raise ("Attribute '" + self.ATTR_TEMPLATES + "' is required") if (isinstance(template_names, basestring)): template_names = [template_names] tpl_lookup = TemplateLookup(directories=[template_dir]) for template_name in template_names: template_paths = glob.glob(template_dir + template_name + '.tpl') for template_path in template_paths: atemplate = Template(filename=template_path, lookup=tpl_lookup) self.templates[template_path] = atemplate def executeInternal(self, execution_context): """ @type execution_context: ExecutionContext """ self.logger.info("Executing " + str(self)) src_dir = self._normalize_dir(self.getAttribute(self.ATTR_SRC_DIR, './'), './') file_patterns = self.getAttribute(self.ATTR_SRC_FILES, '*.json') file_patterns = file_patterns if file_patterns else '*.json' # Convert to an array if (isinstance(file_patterns, basestring)): file_patterns = [file_patterns] outputs = {} for file_pattern in file_patterns: file_paths = glob.glob(src_dir + file_pattern) for file_path in file_paths: model = self._load_model(file_path) fname = self._get_filaname(file_path, False) for tpl_path, tpl in self.templates.iteritems(): tpl_name = self._get_filaname(tpl_path, False) outputs[fname + '.' + tpl_name] = self._transform(tpl, model, self.getParams()) # write to a file dest_dir = self._normalize_dir(self.getAttribute(self.ATTR_DEST_DIR, './'), './') file_ext = '.' + self.getAttribute(self.ATTR_FILE_EXT) for name, output in outputs.iteritems(): self._write(output, dest_dir + name + file_ext) return (Task.CODE_OK, outputs) # Private methods def _normalize_dir(self, dir, default): dir = dir if dir else default dir = dir if dir.startswith('/') else os.getcwd() + '/' + dir return dir if dir.endswith('/') else dir + '/' def _load_model(self, model_uri): file = open(model_uri, "r") file_content = file.read() model = json.loads(file_content, object_pairs_hook=collections.OrderedDict) return model def _transform(self, thetemplate, model, params): return thetemplate.render_unicode(model=model, params=params) def _get_filaname(self, file_path, include_ext = True): """ Returns the filename @param file_path: string The path @param include_ext: boolean Whether or not to include extension @return: string """ retval = file_path last_sep_pos = file_path.rfind('/') if (last_sep_pos > -1): retval = file_path[last_sep_pos+1:] if (not include_ext): last_dot_pos = retval.rfind('.') if (last_dot_pos > -1): retval = retval[:last_dot_pos] return retval def _write(self, data, dest_path): self._normalize_dir(dest_path, './') with open(dest_path, "w") as text_file: text_file.write(data)
altenia/taskmator
taskmator/task/text.py
Python
mit
4,755
package com.swfarm.biz.chain.dto; import java.io.Serializable; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import org.apache.commons.lang.StringUtils; import com.swfarm.biz.chain.bo.CustomerOrder; import com.swfarm.biz.chain.bo.CustomerOrderItem; public class CustomerOrderDTO implements Serializable { private String id; private String customerOrderId; private String customerOrderNo; private Timestamp orderTime; private Timestamp shippedTime; private Timestamp paidTime; private Timestamp allocateTime; private Timestamp deliverTime; private Timestamp modifiedTime; private String customerOrderProcessStep; private String exceptionalProcessStep; private String accountNumber; private String customerName; private String buyerFullname; private String buyerPhoneNumber; private String buyerEmail; private String buyerAddress1; private String buyerAddress2; private String buyerCity; private String buyerState; private String buyerZip; private String buyerCountry; private String warehouseCode; private List customerOrderItemDTOs = new ArrayList(); private String saleChannel; private String saleChannelOrderId; private String saleRecordNo; private String shippingForwarderMethod; private String shippingOrderNo; private String sfmOrderNo; private Double totalPrice; private Double postageFee; private String stockLocation; private String buyerCheckoutMessage; private String shippingServiceSelected; private String packingMaterialArticleNumber; private String payPalEmailAddress; private String payPalTransactionId; private Double totalAvgPurchasePrice; private Double totalWeight; private Double testingShippingCost; private String customerOrderProcessStepName; private String allocationProductVoucherNos; public CustomerOrderDTO() { } public CustomerOrderDTO(CustomerOrder customerOrder) { this.id = customerOrder.getId(); this.customerOrderId = customerOrder.getId(); this.customerOrderNo = customerOrder.getCustomerOrderNo(); this.orderTime = customerOrder.getOrderTime(); this.shippedTime = customerOrder.getShippedTime(); this.paidTime = customerOrder.getPaidTime(); this.allocateTime = customerOrder.getAllocateTime(); this.deliverTime = customerOrder.getDeliverTime(); this.modifiedTime = customerOrder.getModifiedTime(); this.customerOrderProcessStep = customerOrder.getCustomerOrderProcessStep(); this.exceptionalProcessStep = customerOrder.getExceptionalProcessStep(); this.accountNumber = customerOrder.getAccountNumber(); this.customerName = customerOrder.getCustomerName(); this.buyerFullname = customerOrder.getBuyerFullname(); this.buyerPhoneNumber = customerOrder.getBuyerPhoneNumber(); this.buyerEmail = customerOrder.getBuyerEmail(); this.buyerAddress1 = customerOrder.getBuyerAddress1(); this.buyerAddress2 = customerOrder.getBuyerAddress2(); this.buyerCity = customerOrder.getBuyerCity(); this.buyerState = customerOrder.getBuyerState(); this.buyerZip = customerOrder.getBuyerZip(); this.buyerCountry = customerOrder.getBuyerCountry(); this.warehouseCode = customerOrder.getWarehouseCode(); for (Iterator iter = customerOrder.getCustomerOrderItems().iterator(); iter.hasNext();) { CustomerOrderItem customerOrderItem = (CustomerOrderItem) iter.next(); CustomerOrderItemDTO customerOrderItemDTO = new CustomerOrderItemDTO(customerOrderItem); this.addCustomerOrderItemDTO(customerOrderItemDTO); } this.saleChannel = customerOrder.getSaleChannel(); this.saleChannelOrderId = customerOrder.getSaleChannelOrderId(); this.saleRecordNo = customerOrder.getSaleRecordNo(); this.shippingForwarderMethod = customerOrder.getShippingForwarderMethod(); this.shippingOrderNo = customerOrder.getShippingOrderNo(); this.sfmOrderNo = customerOrder.getSfmOrderNo(); this.totalPrice = customerOrder.getTotalPrice(); this.postageFee = customerOrder.getPostageFee(); this.stockLocation = customerOrder.getStockLocation(); this.buyerCheckoutMessage = customerOrder.getBuyerCheckoutMessage(); this.shippingServiceSelected = customerOrder.getShippingServiceSelected(); this.packingMaterialArticleNumber = customerOrder.getPackingMaterialArticleNumber(); this.payPalEmailAddress = customerOrder.getPayPalEmailAddress(); this.payPalTransactionId = customerOrder.getPayPalTransactionId(); this.totalAvgPurchasePrice = customerOrder.getTotalAvgPurchasePrice(); this.totalWeight = customerOrder.getTotalWeight(); this.testingShippingCost = customerOrder.getTestingShippingCost(); this.customerOrderProcessStepName = customerOrder.getCustomerOrderProcessStepName(); this.allocationProductVoucherNos = customerOrder.getAllocationProductVoucherNos(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getCustomerOrderId() { return customerOrderId; } public void setCustomerOrderId(String customerOrderId) { this.customerOrderId = customerOrderId; } public String getCustomerOrderNo() { return customerOrderNo; } public void setCustomerOrderNo(String customerOrderNo) { this.customerOrderNo = customerOrderNo; } public List getCustomerOrderItemDTOs() { if (customerOrderItemDTOs == null) { customerOrderItemDTOs = new ArrayList(); } Collections.sort(customerOrderItemDTOs, new Comparator() { public int compare(Object obj1, Object obj2) { CustomerOrderItemDTO coiDTO1 = (CustomerOrderItemDTO) obj1; CustomerOrderItemDTO coiDTO2 = (CustomerOrderItemDTO) obj2; int result = 0; if (StringUtils.isNotEmpty(coiDTO1.getSaleRecordNo()) && StringUtils.isNotEmpty(coiDTO2.getSaleRecordNo())) { result = coiDTO1.getSaleRecordNo().compareTo(coiDTO2.getSaleRecordNo()); } else if (StringUtils.isNotEmpty(coiDTO1.getSaleRecordNo()) && StringUtils.isEmpty(coiDTO2.getSaleRecordNo())) { result = -1; } else if (StringUtils.isEmpty(coiDTO1.getSaleRecordNo()) && StringUtils.isNotEmpty(coiDTO2.getSaleRecordNo())) { result = 1; } else { if (StringUtils.isNotEmpty(coiDTO1.getCustomerOrderItemId()) && StringUtils.isNotEmpty(coiDTO2.getCustomerOrderItemId())) { result = coiDTO1.getCustomerOrderItemId().compareTo(coiDTO2.getCustomerOrderItemId()); } else if (StringUtils.isNotEmpty(coiDTO1.getArticleNumber()) && StringUtils.isNotEmpty(coiDTO2.getArticleNumber())) { result = coiDTO1.getArticleNumber().compareTo(coiDTO2.getArticleNumber()); } else { result = coiDTO1.toString().compareTo(coiDTO2.toString()); } } return result; } }); return customerOrderItemDTOs; } public void addCustomerOrderItemDTO(CustomerOrderItemDTO coiDTO) { if (!this.getCustomerOrderItemDTOs().contains(coiDTO)) { this.customerOrderItemDTOs.add(coiDTO); coiDTO.setCustomerOrderDTO(this); } } public void setCustomerOrderItemDTOs(List customerOrderItemDTOs) { this.customerOrderItemDTOs = customerOrderItemDTOs; } public Timestamp getOrderTime() { return orderTime; } public void setOrderTime(Timestamp orderTime) { this.orderTime = orderTime; } public String getCustomerOrderProcessStep() { return customerOrderProcessStep; } public void setCustomerOrderProcessStep(String customerOrderProcessStep) { this.customerOrderProcessStep = customerOrderProcessStep; } public String getExceptionalProcessStep() { return exceptionalProcessStep; } public void setExceptionalProcessStep(String exceptionalProcessStep) { this.exceptionalProcessStep = exceptionalProcessStep; } public String getAccountNumber() { return accountNumber; } public void setAccountNumber(String accountNumber) { this.accountNumber = accountNumber; } public String getCustomerName() { return customerName; } public void setCustomerName(String ebayUserId) { this.customerName = ebayUserId; } public String getBuyerFullname() { return buyerFullname; } public void setBuyerFullname(String buyerFullname) { this.buyerFullname = buyerFullname; } public String getBuyerPhoneNumber() { return buyerPhoneNumber; } public void setBuyerPhoneNumber(String buyerPhoneNumber) { this.buyerPhoneNumber = buyerPhoneNumber; } public String getBuyerEmail() { return buyerEmail; } public void setBuyerEmail(String buyerEmail) { this.buyerEmail = buyerEmail; } public String getBuyerAddress1() { return buyerAddress1; } public void setBuyerAddress1(String buyerAddress1) { this.buyerAddress1 = buyerAddress1; } public String getBuyerAddress2() { return buyerAddress2; } public void setBuyerAddress2(String buyerAddress2) { this.buyerAddress2 = buyerAddress2; } public String getBuyerCity() { return buyerCity; } public void setBuyerCity(String buyerCity) { this.buyerCity = buyerCity; } public String getBuyerState() { return buyerState; } public void setBuyerState(String buyerState) { this.buyerState = buyerState; } public String getBuyerZip() { return buyerZip; } public void setBuyerZip(String buyerZip) { this.buyerZip = buyerZip; } public String getBuyerCountry() { return buyerCountry; } public void setBuyerCountry(String buyerCountry) { this.buyerCountry = buyerCountry; } public Timestamp getModifiedTime() { return modifiedTime; } public void setModifiedTime(Timestamp modifiedTime) { this.modifiedTime = modifiedTime; } public String getWarehouseCode() { return warehouseCode; } public void setWarehouseCode(String warehouseCode) { this.warehouseCode = warehouseCode; } public Timestamp getShippedTime() { return shippedTime; } public void setShippedTime(Timestamp shippedTime) { this.shippedTime = shippedTime; } public Timestamp getPaidTime() { return paidTime; } public void setPaidTime(Timestamp paidTime) { this.paidTime = paidTime; } public String getSaleChannel() { return saleChannel; } public void setSaleChannel(String saleChannel) { this.saleChannel = saleChannel; } public String getSaleChannelOrderId() { return saleChannelOrderId; } public void setSaleChannelOrderId(String saleChannelOrderId) { this.saleChannelOrderId = saleChannelOrderId; } public String getSaleRecordNo() { return saleRecordNo; } public void setSaleRecordNo(String saleRecordNo) { this.saleRecordNo = saleRecordNo; } public String getShippingForwarderMethod() { return shippingForwarderMethod; } public void setShippingForwarderMethod(String shippingForwarderMethod) { this.shippingForwarderMethod = shippingForwarderMethod; } public String getShippingOrderNo() { return shippingOrderNo; } public void setShippingOrderNo(String shippingOrderNo) { this.shippingOrderNo = shippingOrderNo; } public String getSfmOrderNo() { return sfmOrderNo; } public void setSfmOrderNo(String sfmOrderNo) { this.sfmOrderNo = sfmOrderNo; } public Double getTotalPrice() { return totalPrice; } public void setTotalPrice(Double totalPrice) { this.totalPrice = totalPrice; } public Double getPostageFee() { return postageFee; } public void setPostageFee(Double postageFee) { this.postageFee = postageFee; } public String getStockLocation() { return stockLocation; } public void setStockLocation(String stockLocation) { this.stockLocation = stockLocation; } public String getBuyerCheckoutMessage() { return buyerCheckoutMessage; } public void setBuyerCheckoutMessage(String buyerCheckoutMessage) { this.buyerCheckoutMessage = buyerCheckoutMessage; } public String getShippingServiceSelected() { return shippingServiceSelected; } public void setShippingServiceSelected(String shippingServiceSelected) { this.shippingServiceSelected = shippingServiceSelected; } public String getPackingMaterialArticleNumber() { return packingMaterialArticleNumber; } public void setPackingMaterialArticleNumber(String packingMaterialArticleNumber) { this.packingMaterialArticleNumber = packingMaterialArticleNumber; } public String getPayPalEmailAddress() { return payPalEmailAddress; } public void setPayPalEmailAddress(String payPalEmailAddress) { this.payPalEmailAddress = payPalEmailAddress; } public String getPayPalTransactionId() { return payPalTransactionId; } public void setPayPalTransactionId(String payPalTransactionId) { this.payPalTransactionId = payPalTransactionId; } public Double getTotalAvgPurchasePrice() { return totalAvgPurchasePrice; } public void setTotalAvgPurchasePrice(Double totalAvgPurchasePrice) { this.totalAvgPurchasePrice = totalAvgPurchasePrice; } public Double getTotalWeight() { return totalWeight; } public void setTotalWeight(Double totalWeight) { this.totalWeight = totalWeight; } public Double getTestingShippingCost() { return testingShippingCost; } public void setTestingShippingCost(Double testingShippingCost) { this.testingShippingCost = testingShippingCost; } public String getCustomerOrderProcessStepName() { return customerOrderProcessStepName; } public void setCustomerOrderProcessStepName(String customerOrderProcessStepName) { this.customerOrderProcessStepName = customerOrderProcessStepName; } public String getAllocationProductVoucherNos() { return allocationProductVoucherNos; } public void setAllocationProductVoucherNos(String allocationProductVoucherNos) { this.allocationProductVoucherNos = allocationProductVoucherNos; } }
zhangqiang110/my4j
pms/src/main/java/com/swfarm/biz/chain/dto/CustomerOrderDTO.java
Java
mit
16,040
require 'spec_helper' describe 'composer::create_config_hash' do describe 'build hashes for config generation' do it do should run.with_params({ "github-oauth" => { 'github.com' => 'token' }, "process-timeout" => 500, "github-protocols" => ['ssh', 'https'] }, :vagrant, :present).and_return({ "'github-oauth'.'github.com'-vagrant-create" => { :value => "token", :user => "vagrant", :ensure => 'present', :entry => "'github-oauth'.'github.com'" }, "process-timeout-vagrant-create" => { :value => 500, :user => "vagrant", :ensure => 'present', :entry => "process-timeout" }, "github-protocols-vagrant-create" => { :value => "ssh https", :user => "vagrant", :ensure => 'present', :entry => "github-protocols" } }) end end describe 'removes parameters' do it do should run.with_params(['github-oauth.github.com', 'process-timeout'], :vagrant, :absent).and_return({ "github-oauth.github.com-vagrant-remove" => { :user => "vagrant", :ensure => 'absent', :entry => "github-oauth.github.com" }, "process-timeout-vagrant-remove" => { :user => "vagrant", :ensure => 'absent', :entry => "process-timeout" } }) end end end
willdurand/puppet-composer
spec/functions/composer_create_config_hash_spec.rb
Ruby
mit
1,487
class Content < ActiveRecord::Base default_scope -> { order 'id DESC' } end
jrietema/simply-pages
test/dummy/app/models/content.rb
Ruby
mit
80
<?php namespace AppBundle\Form\DataField; use AppBundle\Entity\FieldType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\TextareaType; use AppBundle\Form\Field\AnalyzerPickerType; class RadioFieldType extends DataFieldType { /** * * {@inheritdoc} * */ public function getLabel(){ return 'Radio field'; } /** * Get a icon to visually identify a FieldType * * @return string */ public static function getIcon(){ return 'fa fa-dot-circle-o'; } /** * * {@inheritdoc} * */ public function buildForm(FormBuilderInterface $builder, array $options) { /** @var FieldType $fieldType */ $fieldType = $builder->getOptions () ['metadata']; $choices = []; $values = explode("\n", str_replace("\r", "", $options['choices'])); $labels = explode("\n", str_replace("\r", "", $options['labels'])); foreach ($values as $id => $value){ if(isset($labels[$id])){ $choices[$labels[$id]] = $value; } else { $choices[$value] = $value; } } $builder->add ( 'text_value', ChoiceType::class, [ 'label' => (isset($options['label'])?$options['label']:$fieldType->getName()), 'required' => false, 'disabled'=> !$this->authorizationChecker->isGranted($fieldType->getMinimumRole()), 'choices' => $choices, 'empty_data' => null, 'multiple' => false, 'expanded' => true, ] ); } /** * * {@inheritdoc} * */ public function configureOptions(OptionsResolver $resolver) { /* set the default option value for this kind of compound field */ parent::configureOptions ( $resolver ); $resolver->setDefault ( 'choices', [] ); $resolver->setDefault ( 'labels', [] ); } /** * * {@inheritdoc} * */ public function buildOptionsForm(FormBuilderInterface $builder, array $options) { parent::buildOptionsForm ( $builder, $options ); $optionsForm = $builder->get ( 'options' ); // String specific display options $optionsForm->get ( 'displayOptions' )->add ( 'choices', TextareaType::class, [ 'required' => false, ] )->add ( 'labels', TextareaType::class, [ 'required' => false, ] ); // String specific mapping options $optionsForm->get ( 'mappingOptions' )->add ( 'analyzer', AnalyzerPickerType::class); } /** * * {@inheritdoc} * */ public function getDefaultOptions($name) { $out = parent::getDefaultOptions($name); $out['mappingOptions']['index'] = 'not_analyzed'; return $out; } }
theus77/ElasticMS
src/AppBundle/Form/DataField/RadioFieldType.php
PHP
mit
2,601
/* * Copyright (c) 2013 Red Rainbow IT Solutions GmbH, Germany * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.jeeventstore.store; import java.io.Serializable; import java.util.Iterator; import org.jeeventstore.ChangeSet; /** * An iterator that iterates over all events for multiple {@link ChangeSet}s * in a proper sequence. */ public class EventsIterator<T extends ChangeSet> implements Iterator<Serializable> { private Iterator<T> cit; private Iterator<Serializable> it = null; public EventsIterator(Iterator<T> cit) { this.cit = cit; advance(); } private void advance() { if (it != null && it.hasNext()) return; // now either it == null or it has no next do { // already reached the last change set? if (!cit.hasNext()) { it = null; return; } // no, another changeset is available. Grab it. ChangeSet nextcs = cit.next(); it = nextcs.events(); } while (!it.hasNext()); // protect against ChangeSets w/o events } @Override public boolean hasNext() { return it != null; } @Override public Serializable next() { Serializable n = it.next(); advance(); return n; } /** * {@link #remove()} is not supported. */ @Override public void remove() { throw new UnsupportedOperationException("Not supported."); } }
JEEventStore/JEEventStore
core/src/main/java/org/jeeventstore/store/EventsIterator.java
Java
mit
2,548
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.utils = exports.default = void 0; var reducers = _interopRequireWildcard(require("./reducers")); var _utils = _interopRequireWildcard(require("./utils")); exports.utils = _utils; function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } var _default = reducers; exports.default = _default;
talibasya/redux-store-ancillary
lib/index.js
JavaScript
mit
1,174
/////////////////////////////////////////////////////////////////////////////// // // Effect // /////////////////////////////////////////////////////////////////////////////// //// IMPORTS ////////////////////////////////////////////////////////////////// import { toJs } from 'mori'; import diff from 'virtual-dom/diff'; import patch from 'virtual-dom/patch'; import stateStream from '../streams/state'; /////////////////////////////////////////////////////////////////////////////// // :: DOMNode node, Function stateToModel, Function modelToVDOM // -> Effectful Eventstream that will mutate the node as state changes, // mapping the state to a model that is rendered to a virtual DOM, and // patched to the DOM. // Note - the Effectful EventStream will need a subscriber to start. export default (node, stateToModel, modelToVDOM) => { return stateStream .map(toJs) .map(stateToModel) .map(modelToVDOM) .diff(node, diff) .scan(node, patch); }; ///////////////////////////////////////////////////////////////////////////////
craigdallimore/hog
src/js/lib/effect.js
JavaScript
mit
1,055
if (typeof global === 'undefined') { global = window; } else { global.XRegExp = require('../../xregexp-all'); } // Ensure that all opt-in features are disabled when each spec starts global.disableOptInFeatures = function() { XRegExp.uninstall('namespacing astral'); }; // Property name used for extended regex instance data global.REGEX_DATA = 'xregexp'; // Check for ES6 `u` flag support global.hasNativeU = XRegExp._hasNativeFlag('u'); // Check for ES6 `y` flag support global.hasNativeY = XRegExp._hasNativeFlag('y'); // Check for strict mode support global.hasStrictMode = (function() { 'use strict'; return !this; }()); // Naive polyfill of String.prototype.repeat if (!String.prototype.repeat) { String.prototype.repeat = function(count) { return count ? Array(count + 1).join(this) : ''; }; }
GerHobbelt/xregexp
tests/helpers/h.js
JavaScript
mit
841
'use strict'; let datafire = require('datafire'); let openapi = require('./openapi.json'); let aws = require('aws-sdk'); const INTEGRATION_ID = 'amazonaws_data_jobs_iot'; const SDK_ID = 'IoTJobsDataPlane'; let integ = module.exports = new datafire.Integration({ id: INTEGRATION_ID, title: openapi.info.title, description: openapi.info.description, logo: openapi.info['x-logo'], }); integ.security[INTEGRATION_ID]= { integration: INTEGRATION_ID, fields: { accessKeyId: "", secretAccessKey: "", region: "AWS region (if applicable)", } } function maybeCamelCase(str) { return str.replace(/_(\w)/g, (match, char) => char.toUpperCase()) } // We use this instance to make sure each action is available in the SDK at startup. let dummyInstance = new aws[SDK_ID]({version: openapi.version, endpoint: 'foo'}); for (let path in openapi.paths) { for (let method in openapi.paths[path]) { if (method === 'parameters') continue; let op = openapi.paths[path][method]; let actionID = op.operationId; actionID = actionID.replace(/\d\d\d\d_\d\d_\d\d$/, ''); if (actionID.indexOf('_') !== -1) { actionID = actionID.split('_')[1]; } let functionID = actionID.charAt(0).toLowerCase() + actionID.substring(1); if (!dummyInstance[functionID]) { console.error("AWS SDK " + SDK_ID + ": Function " + functionID + " not found"); console.log(method, path, op.operationId, actionID); continue; } let inputParam = (op.parameters || []).filter(p => p.in === 'body')[0] || {}; let response = (op.responses || {})[200] || {}; let inputSchema = { type: 'object', properties: {}, }; if (inputParam.schema) inputSchema.allOf = [inputParam.schema]; (op.parameters || []).forEach(p => { if (p.name !== 'Action' && p.name !== 'Version' && p.name !== 'body' && !p.name.startsWith('X-')) { inputSchema.properties[maybeCamelCase(p.name)] = {type: p.type}; if (p.required) { inputSchema.required = inputSchema.required || []; inputSchema.required.push(p.name); } } }) function getSchema(schema) { if (!schema) return; return Object.assign({definitions: openapi.definitions}, schema); } integ.addAction(actionID, new datafire.Action({ inputSchema: getSchema(inputSchema), outputSchema: getSchema(response.schema), handler: (input, context) => { let lib = new aws[SDK_ID](Object.assign({ version: openapi.info.version, }, context.accounts[INTEGRATION_ID])); return lib[functionID](input).promise() .then(data => { return JSON.parse(JSON.stringify(data)); }) } })); } }
DataFire/Integrations
integrations/generated/amazonaws_data_jobs_iot/index.js
JavaScript
mit
2,741
'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _jquery = require('jquery'); var _jquery2 = _interopRequireDefault(_jquery); require('./loading-mask.css!'); var _locale = require('../locale'); var LoadingMask = (function () { function LoadingMask(resources) { _classCallCheck(this, LoadingMask); this.loadingMask = undefined; this.dimScreen = undefined; this.dialog = undefined; this.loadingTitle = undefined; this.title = undefined; this.locale = _locale.Locale.Repository['default']; this._createLoadingMask(); } LoadingMask.prototype._createLoadingMask = function _createLoadingMask() { this.title = this.locale.translate('loading'); this.dimScreen = '<div id="loadingMask" class="spinner"><div class="loadingTitle">' + this.title + '</div><div class="mask"></div></div>'; (0, _jquery2['default'])('body').append(this.dimScreen); this.loadingMask = (0, _jquery2['default'])('#loadingMask'); this.loadingTitle = (0, _jquery2['default'])('.loadingTitle').css({ color: '#ffffff', opacity: 1, fontSize: '2.5em', fontFamily: 'Roboto' }); }; LoadingMask.prototype.show = function show() { this.loadingMask.show(); }; LoadingMask.prototype.hide = function hide() { this.loadingMask.hide(); }; return LoadingMask; })(); exports.LoadingMask = LoadingMask;
lubo-gadjev/aurelia-auth-session
dist/commonjs/loading-mask/loading-mask.js
JavaScript
mit
1,618
import sys import traceback import logging import time import inspect def run_resilient(function, function_args=[], function_kwargs={}, tolerated_errors=(Exception,), log_prefix='Something failed, tolerating error and retrying: ', retries=5, delay=True, critical=False, initial_delay_time=0.1, delay_multiplier = 2.0): """Run the function with function_args and function_kwargs. Warn if it excepts, and retry. If retries are exhausted, log that, and if it's critical, properly throw the exception """ def show_exception_info(log_prefix): """Warn about an exception with a lower priority message, with a text prefix and the error type""" exc_type, exc_value, exc_traceback = sys.exc_info() lines = traceback.format_exception(exc_type, exc_value, exc_traceback) traceback_text = lines[2] logging.info(log_prefix + traceback_text) return delay_time = initial_delay_time while retries: retries -= 1 try: return function(*function_args, **function_kwargs) except tolerated_errors, error: #IGNORE:W0703 # One of our anticipated errors happened. if retries: # We've got more retries left. Log the error, and continue. show_exception_info(log_prefix) if delay: time.sleep(delay_time) delay_time = delay_time * delay_multiplier else: delay_time = 0 logging.info('We have %d tries left. Delaying for %.2f seconds and trying again.', retries, delay_time) else: logging.warn('Could not complete action after %d retries.', retries) if critical: logging.error('Critical action failed.') raise error except Exception: # We've recieved an error we didn't anticipate. This is bad. # Depending on the error we the developers should either fix something, or, if we want to tolerate it, # add it to our tolerated_errors. # Those things require human judgement, so we'll raise the exception. logging.exception('Unanticipated error recieved!') #Log the exception raise #Re-raise except: typ, value, unused = sys.exc_info() # We've received an exception that isn't even an Exception subclass! # This is bad manners - see http://docs.python.org/tutorial/errors.html: # "Exceptions should typically be derived from the Exception class, either directly or indirectly." logging.exception("Bad mannered exception. Class was: %s Value was: %s Source file: %s", typ.__name__, str(value), inspect.getsourcefile(typ)) raise
mikemaccana/resilience
__init__.py
Python
mit
2,874
package Chapter2; /** * Created by kartikkapur on 6/16/17. */ public class OG { int x; static int y; public OG(int x, int y) { this.x = x; this.y = y; } public static void main(String[] args) { OG OG1 = new OG(10, 2); OG OG2 = new OG(0, 1); OG1.y = OG2.x; OG1.x = OG2.y; } }
KartikKapur/DataStructuresAndAlgorithms
Code/Chapter2/OG.java
Java
mit
352
var five = require("johnny-five"), board = new five.Board(); board.on("ready", function() { var led = new five.Led(12); var rgb = new five.Led.RGB([6, 5, 3]); var index = 0; this.loop(10, function() { // led.toggle(); if (index === 16777215) { index = 0; } rgb.color(index.toString(16)); index++; }); }); // var led = new five.Led(13); // led.blink(5);
Sporks/head-tracker
arduino/strobe.js
JavaScript
mit
412
//John Paul Mardelli //Last updated November 2nd, 2013 package com.northstar.minimap; import android.graphics.Point; /** * Class to represent positions on the map. */ public class Position { private double x; private double y; public Position(double x, double y){ this.x = x; this.y = y; } public Position(Point p) { this.x = p.x; this.y = p.y; } public double distance(Position p) { return Math.sqrt(Math.pow(p.x - x, 2) + Math.pow(p.y - y, 2)); } public double getX(){ return x; } public double getY(){ return y; } public Point toPoint() { return new Point((int) Math.round(x), (int) Math.round(y)); } }
ritnorthstar/Minimap-Client
Code/Minimap/src/main/java/com/northstar/minimap/Position.java
Java
mit
738
<?php /** * @copyright 2006-2013, Miles Johnson - http://milesj.me * @license https://github.com/milesj/decoda/blob/master/license.md * @link http://milesj.me/code/php/decoda */ return array( 'en-us' => array( 'spoiler' => 'Spoiler', 'hide' => 'Hide', 'show' => 'Show', 'link' => 'link', 'mail' => 'mail', 'quoteBy' => 'Quote by {author}', ), 'es-mx' => array( 'spoiler' => 'Spoiler', 'hide' => 'Ocultar', 'show' => 'Mostrar', 'link' => 'enlace', 'mail' => 'correo', 'quoteBy' => '{author} escribió:', ), 'fr-fr' => array( 'spoiler' => 'becquet', 'hide' => 'Cacher', 'show' => 'Montrent', 'link' => 'lien', 'mail' => 'email', 'quoteBy' => 'Citation de {author}', ), 'it-it' => array( 'spoiler' => 'Spoiler', 'hide' => 'Nascondere', 'show' => 'Spettacolo', 'link' => 'collegamento', 'mail' => 'posta', 'quoteBy' => 'Quote da {author}', ), 'de-de' => array( 'spoiler' => 'Spoiler', 'hide' => 'Verstecke', 'show' => 'Zeige', 'link' => 'link', 'mail' => 'mail', 'quoteBy' => '{author} schrieb:', ), 'sv-se' => array( 'spoiler' => 'Spoiler', 'hide' => 'Dölja', 'show' => 'Visa', 'link' => 'länk', 'mail' => 'e-post', 'quoteBy' => 'Citat från {author}', ), 'el-gr' => array( 'spoiler' => 'αεροτομή', 'hide' => 'Απόκρυψη', 'show' => 'Εμφάνιση', 'link' => 'σύνδεσμος', 'mail' => 'ταχυδρομείο', 'quoteBy' => 'Παράθεση από {author}', ), 'bg-bg' => array( 'spoiler' => 'спойлер', 'hide' => 'крия', 'show' => 'шоу', 'link' => 'връзка', 'mail' => 'поща', 'quoteBy' => 'цитат от {author}', ), 'ru-ru' => array( 'spoiler' => 'спойлер', 'hide' => 'скрыть', 'show' => 'показать', 'link' => 'ссылка', 'mail' => 'электронная почта', 'quoteBy' => '{author} написал:', ), 'zh-cn' => array( 'spoiler' => '扰流板', 'hide' => '隐藏', 'show' => '显示', 'link' => '链接', 'mail' => '电子邮件', 'quoteBy' => '引用由 {author}', ), 'ja-jp' => array( 'spoiler' => 'スポイラー', 'hide' => '隠す', 'show' => '表示', 'link' => 'のリンク', 'mail' => 'メール', 'quoteBy' => '{author}によって引用', ), 'ko-kr' => array( 'spoiler' => '스포일러', 'hide' => '숨기기', 'show' => '표시', 'link' => '링크', 'mail' => '우편', 'quoteBy' => '{author}에 의해 견적', ), 'id-id' => array( 'spoiler' => 'Spoiler', 'hide' => 'Menyembunyikan', 'show' => 'Tampilkan', 'link' => 'link', 'mail' => 'email', 'quoteBy' => 'Quote by {author}', ), 'hu-hu' => array( 'spoiler' => 'Spoiler', 'hide' => 'Rejt', 'show' => 'Mutat', 'link' => 'link', 'mail' => 'email', 'quoteBy' => 'Idézve {author}', ), );
hisorange/bbcoder
src/config/messages.php
PHP
mit
3,442
<?php /**** event.php - Model_Event ----------- author: Mike Elsmore<mike@elsmore.me> ****/ class Model_Event extends Model_Database { // Things to make life easier protected $_table = 'event'; protected $_primary = 'event_id'; }
ukmadlz/ents24-widget
model/event.php
PHP
mit
235
<?php namespace Application\Migrations; use Doctrine\DBAL\Migrations\AbstractMigration, Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your need! */ class Version20140106230422 extends AbstractMigration { public function up(Schema $schema) { // this up() migration is autogenerated, please modify it to your needs $this->addSql("ALTER TABLE `course_order` DROP `note`"); $this->addSql("ALTER TABLE `course_order` ADD `note` VARCHAR( 255 ) NOT NULL DEFAULT '' AFTER `paidTime`;"); } public function down(Schema $schema) { // this down() migration is autogenerated, please modify it to your needs } }
smeagonline-developers/OnlineEducationPlatform---SMEAGonline
app/DoctrineMigrations/Version20140106230422.php
PHP
mit
698
<?php return [ 'name' => 'Menus', 'menus' => 'menu|menus', 'New' => 'Nouveau menu', 'Edit' => 'Modifier le menu', 'Back' => 'Retour à la liste des menus', 'No menu found with name “:name”' => 'Le menu « :name » n’a pas été trouvé.', 'Active tab' => 'Onglet actif', 'New tab' => 'Nouvel onglet', 'New menulink' => 'Nouveau lien de menu', 'Edit menulink' => 'Modifier le lien de menu', 'Back to menu' => 'Retour au menu', ];
laravelproject2016/mkproject
vendor/typicms/menus/src/resources/lang/fr/global.php
PHP
mit
718
<?php namespace Omelet\Module; use Doctrine\DBAL\Driver\Connection; use Ray\Di\AbstractModule; use Ray\Di\Scope; use Ray\Di\Name; use Ray\DbalModule\DbalModule; use Omelet\Builder\Configuration; use Omelet\Builder\DaoBuilderContext; class DaoBuilderBearModule extends AbstractModule { /** * @var Configuration */ private $config; /** * @var array */ private $interfaces; public function __construct(Configuration $config, array $interfaces) { $this->config = $config; $this->interfaces = $interfaces; } /** * {@inheritdoc} */ protected function configure() { $context = new DaoBuilderContext($this->config); $this->bind(DaoBuilderContext::class)->toInstance($context); $this->install(new DbalModule($context->connectionString())); $this->getContainer()->move(Connection::class, Name::ANY, Connection::class, 'SqlLogger'); $this->bind(Connection::class)->toProvider(SqlLoggerProvider::class); foreach ($this->interfaces as $intf) { $context->build($intf); $this->bind($intf)->to($context->getDaoClassName($intf))->in(Scope::SINGLETON); } } }
ritalin/omelet-bear-module
src/Module/DaoBuilderBearModule.php
PHP
mit
1,281
class CreateSiteConfigs < ActiveRecord::Migration def change create_table :site_configs do |t| t.string :logo_uid t.string :application_name, null: false t.string :funder_image_footer1_uid t.string :funder_image_footer2_uid t.string :funder_image_footer3_uid t.string :funder_image_footer4_uid t.string :funder_image_footer5_uid t.string :funder_image_footer6_uid t.string :funder_name_footer1 t.string :funder_name_footer2 t.string :funder_name_footer3 t.string :funder_name_footer4 t.string :funder_name_footer5 t.string :funder_name_footer6 t.string :funder_url_footer1 t.string :funder_url_footer2 t.string :funder_url_footer3 t.string :funder_url_footer4 t.string :funder_url_footer5 t.string :funder_url_footer6 t.geometry :nowhere_location, srid: 4326, null: false t.string :facebook_link t.string :twitter_link t.text :footer_links_html, null: false t.text :header_html, null: false t.string :default_locale, null: false t.string :timezone, null: false t.string :ga_account_id t.string :ga_base_domain t.string :default_email, null: false t.string :email_domain, null: false t.string :geocoder_url, null: false t.string :geocoder_key t.timestamps null: false end execute "INSERT INTO site_configs (application_name, nowhere_location, facebook_link, twitter_link, footer_links_html, header_html, default_locale, timezone, geocoder_url, ga_account_id, ga_base_domain, default_email, email_domain, updated_at, created_at) VALUES ('Cyclescape', ST_GeomFromText('POINT(0.1275 51.5032)', 4326), 'https://www.facebook.com/CycleStreets', 'https://twitter.com/cyclescape', '<li><small><a href=\"http://blog.cyclescape.org/\">Cyclescape blog</a></small> </li> <li> <small><a href=\"http://blog.cyclescape.org/guide/\">User guide</a></small> </li> <li> <small><a href=\"/pages/privacypolicy\">Privacy Policy</a></small> </li> <li>', '<li><a href=\"http://blog.cyclescape.org/about/\">About</a></li><li><a href=\"http://blog.cyclescape.org/guide/\">User guide</a></li>', 'en-GB', 'Europe/London', 'https://api.cyclestreets.net/v2/geocoder', 'UA-28721275-1', 'cyclescape.org', 'Cyclescape <info@cyclescape.org>', 'cyclescape.org', now(), now());" end end
cyclestreets/cyclescape
db/migrate/20160606220127_create_site_configs.rb
Ruby
mit
2,636
import { Component, OnInit } from '@angular/core'; import { NodesService, NodegraphModel, NodeModel } from '../sharedservices/index'; import { NodegraphComponent } from '../d3components/nodegraph.component'; import { NodetableComponent } from '../nodetable/nodetable.component'; import * as _ from 'lodash'; @Component({ moduleId: module.id, selector: 'app-dashboard', templateUrl: 'dashboard.component.html', directives: [ NodegraphComponent, NodetableComponent ] }) export class DashboardComponent implements OnInit { public nodegraphData: NodegraphModel; public nodetableData: NodeModel[]; constructor(private _nodesService: NodesService) { } ngOnInit() { this._nodesService.getNodegraph().then((data: NodegraphModel) => { this.nodegraphData = data; this.nodetableData = data.nodes; }).catch((err) => { console.log(err); // customise }) } }
RaySingerNZ/D3-Angular2-QuickStart
app/dashboard/dashboard.component.ts
TypeScript
mit
946
#!/usr/bin/env python """ Solve day 23 of Advent of Code. http://adventofcode.com/day/23 """ class Computer: def __init__(self): """ Our computer has 2 registers, a and b, and an instruction pointer so that we know which instruction to fetch next. """ self.a = 0 self.b = 0 self.ip = 0 # Ye olde instruction pointer def run_program(self, program): """ Run a list of program instructions until we try to move the instruction pointer beyond the bounds of the instruction list. """ while True: try: instruction, args = self.parse_instruction(program[self.ip]) except IndexError: return getattr(self, instruction)(*args) def parse_instruction(self, line): """ Parse a line of the program into the instruction and its arguments. """ instruction, *args = line.strip().replace(',', '').split() return instruction, args def hlf(self, register): """ Set the register to half its current value, then increment the instruction pointer. """ setattr(self, register, getattr(self, register)//2) self.ip += 1 def tpl(self, register): """ Set the register to triple its current value, then increment the instruction pointer. """ setattr(self, register, getattr(self, register)*3) self.ip += 1 def inc(self, register): """ Increment the value in the register, then increment the instruction pointer. """ setattr(self, register, getattr(self, register) + 1) self.ip += 1 def jmp(self, offset): """ Jump the instruction pointer by a particular offset. """ self.ip += int(offset) def jie(self, register, offset): """ Jump the instruction pointer by an offset if the value in the register is even. """ if getattr(self, register) % 2 == 0: self.jmp(offset) else: self.ip += 1 def jio(self, register, offset): """ Jump the instruction pointer by an offset if the value in the register is one. """ if getattr(self, register) == 1: self.jmp(offset) else: self.ip += 1 if __name__ == '__main__': with open('input.txt') as f: program = f.readlines() computer = Computer() # Part 1 - start with a=0, b=0 computer.run_program(program) print("Part 1:", computer.b) # Part 2 - now start with a=1, b=0 computer = Computer() computer.a = 1 computer.run_program(program) print("Part 2:", computer.b)
mpirnat/adventofcode
day23/day23.py
Python
mit
2,854
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Tasks.Command.Api.Areas.HelpPage.SampleGeneration { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
TomPallister/cqrs-event-sourcing
CQRSES.Command.Api/Areas/HelpPage/SampleGeneration/ObjectGenerator.cs
C#
mit
19,515
import subprocess import os import errno def download_file(url, local_fname=None, force_write=False): # requests is not default installed import requests if local_fname is None: local_fname = url.split('/')[-1] if not force_write and os.path.exists(local_fname): return local_fname dir_name = os.path.dirname(local_fname) if dir_name != "": if not os.path.exists(dir_name): try: # try to create the directory if it doesn't exists os.makedirs(dir_name) except OSError as exc: if exc.errno != errno.EEXIST: raise r = requests.get(url, stream=True) assert r.status_code == 200, "failed to open %s" % url with open(local_fname, 'wb') as f: for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk) return local_fname def get_gpus(): """ return a list of GPUs """ try: re = subprocess.check_output(["nvidia-smi", "-L"], universal_newlines=True) except OSError: return [] return range(len([i for i in re.split('\n') if 'GPU' in i]))
yancz1989/lr_semi
common/util.py
Python
mit
1,092
using UnityEngine; using System.Collections; public class BlowUpOnTouch : MonoBehaviour { // Public vars // Private vars // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnCollisionEnter(Collision _col) { _col.gameObject.SendMessage("Die", SendMessageOptions.DontRequireReceiver); gameObject.SendMessage("Die", SendMessageOptions.DontRequireReceiver); } void OnTriggerEnter(Collider _collider) { _collider.gameObject.SendMessage("Die", SendMessageOptions.DontRequireReceiver); } }
bombpersons/RocketDodger
Assets/Resources/Scripts/Movement/RocketAlgorithms/BlowUpOnTouch.cs
C#
mit
578
var mysql = require('mysql'); var bcrypt = require('bcryptjs'); var connection = mysql.createConnection({ host: process.env.FOLIO_HOST, user: process.env.FOLIO_USER, database: process.env.FOLIO_DATABASE, password: process.env.FOLIO_PASSWORD }); console.log("[*] Database connection open") console.log("[*] Resetting username and password"); connection.query("TRUNCATE users;"); console.log("[*] Creating default user, admin (username), password (password)"); var passwordhash = bcrypt.hashSync("password", 10); console.log("\t[>] Password hash: " + passwordhash); connection.query("INSERT INTO users(username, passwordhash) values('admin', '" + passwordhash + "');"); connection.end(); console.log("[*] Finished!");
danielbraithwt/Folio
setup/resetpassword.js
JavaScript
mit
725
import React from 'react' import PropTypes from 'prop-types' import { MarkerCanvasProvider } from './MarkerCanvasContext' import TimelineMarkersRenderer from './TimelineMarkersRenderer' import { TimelineStateConsumer } from '../timeline/TimelineStateContext' // expand to fill entire parent container (ScrollElement) const staticStyles = { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0 } /** * Renders registered markers and exposes a mouse over listener for * CursorMarkers to subscribe to */ class MarkerCanvas extends React.Component { static propTypes = { getDateFromLeftOffsetPosition: PropTypes.func.isRequired, children: PropTypes.node } handleMouseMove = evt => { if (this.subscription != null) { const { pageX } = evt // FIXME: dont use getBoundingClientRect. Use passed in scroll amount const { left: containerLeft } = this.containerEl.getBoundingClientRect() // number of pixels from left we are on canvas // we do this calculation as pageX is based on x from viewport whereas // our canvas can be scrolled left and right and is generally outside // of the viewport. This calculation is to get how many pixels the cursor // is from left of this element const canvasX = pageX - containerLeft const date = this.props.getDateFromLeftOffsetPosition(canvasX) this.subscription({ leftOffset: canvasX, date, isCursorOverCanvas: true }) } } handleMouseLeave = () => { if (this.subscription != null) { // tell subscriber that we're not on canvas this.subscription({ leftOffset: 0, date: 0, isCursorOverCanvas: false }) } } handleMouseMoveSubscribe = sub => { this.subscription = sub return () => { this.subscription = null } } state = { subscribeToMouseOver: this.handleMouseMoveSubscribe } render() { return ( <MarkerCanvasProvider value={this.state}> <div style={staticStyles} onMouseMove={this.handleMouseMove} onMouseLeave={this.handleMouseLeave} ref={el => (this.containerEl = el)} > <TimelineMarkersRenderer /> {this.props.children} </div> </MarkerCanvasProvider> ) } } const MarkerCanvasWrapper = props => ( <TimelineStateConsumer> {({ getDateFromLeftOffsetPosition }) => ( <MarkerCanvas getDateFromLeftOffsetPosition={getDateFromLeftOffsetPosition} {...props} /> )} </TimelineStateConsumer> ) export default MarkerCanvasWrapper
namespace-ee/react-calendar-timeline
src/lib/markers/MarkerCanvas.js
JavaScript
mit
2,597
const mongoose = require('mongoose') const Schema = mongoose.Schema let AgencySchema = new Schema({ }) module.exports = mongoose.model('Agency', AgencySchema)
ValentinAlexandrovGeorgiev/deal
server/models/agency.js
JavaScript
mit
162
module Contenticus module Tags class Base attr_reader :key, :name, :comment def initialize(values, key:, name: nil, comment: nil, parent: nil) @key = key @name = name ? name : @key.capitalize @comment = comment @values = values @parent = parent end def type self.class.to_s.underscore.split('/').last end def self.instantiate(fields, key, options_from_layout) options = {key: key} options = if options_from_layout.kind_of?(String) {type: options_from_layout}.merge(options) else options.merge(options_from_layout) end.with_indifferent_access ("Contenticus::Tags::" + options.delete(:type).classify).constantize.new(fields[options.fetch(:key)], options.symbolize_keys) #rescue #raise "Key: #{key} - options: #{options_from_layout} - fields: #{fields}" end def value if @values.kind_of?(Hash) if @values.with_indifferent_access.has_key?(:value) @values.with_indifferent_access.fetch(:value) end else @values end end def values @values end def update_attributes(params) @values = params end def serialize { key => @values } end def frontend_partial "/contenticus/tags/#{type}" end def published? true end def toggle_published? false end # Called by bootstrap form def self.validators_on(arg) [] end def self.model_name Base end def keychain if @parent [@parent.key] + [key] else [key] end end def dom_id "tag-" + keychain.join('-') end def collectible? @parent && @parent.collectible? end def published? true end def toggle_published? false end def open_by_default? true end end end end
nasmorn/contenticus
app/models/contenticus/tags/base.rb
Ruby
mit
1,767
//Problem 3. Line numbers //Write a program that reads a text file and inserts line numbers in front of each of its lines. //The result should be written to another text file. using System; using System.IO; class LineNumbers { static void Main() { StreamReader reader = new StreamReader(@"..\..\file.txt"); StreamWriter writer = new StreamWriter(@"..\..\ouput.txt"); using (writer) { using (reader) { string line = reader.ReadLine(); int lineNum = 0; while (line != null) { lineNum++; writer.WriteLine("{0}. {1}", lineNum, line); line = reader.ReadLine(); } } } Console.WriteLine("ready"); } }
zvet80/TelerikAcademyHomework
02.C#2/08.TextFiles/03.LineNumbers/LineNumbers.cs
C#
mit
838
module PrettyWeather2 class OptimisticWeather attr_reader :created_at # This was a test data_provider for PrettyWeather2 gem. It should be destroyed, # but as a fun of Monty Python, I can't just delete it. So it is easter egg for now. def initialize(config) @created_at = Time.now.strftime('%Y-%m-%dT%H:%M:%S%z') collect_data save_data end def temperature @result.current_temperature # 42 is the answer for 'how many swallows to carry a coconut?' question, obviously. end def describe_weather @result.current_description # it is always fine at Camelot end def error @result.error # there is no any errors end protected def collect_data 'Let\'s not to go to Camelot. T\'is is silly place!' end def save_data @result = PrettyWeather2::WeatherResult.new(42, 'The weather is fine', false) @result.created_at = @created_at end end end
NikitaSmall/pretty_weather_2
lib/pretty_weather_2/optimistic_weather.rb
Ruby
mit
959
package com.hyh.video.lib; /** * @author Administrator * @description * @data 2019/3/8 */ public class FitXYMeasurer implements ISurfaceMeasurer { private final int[] mMeasureSize = new int[2]; @Override public int[] onMeasure(int defaultWidth, int defaultHeight, int videoWidth, int videoHeight) { mMeasureSize[0] = defaultWidth; mMeasureSize[1] = defaultHeight; return mMeasureSize; } }
EricHyh/FileDownloader
VideoSample/src/main/java/com/hyh/video/lib/FitXYMeasurer.java
Java
mit
436
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2015, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package ch.qos.logback.core.pattern.color; /** * Encloses a given set of converter output in magenta using the appropriate ANSI escape codes. * @param <E> * @author Ceki G&uuml;lc&uuml; * @since 1.0.5 */ public class MagentaCompositeConverter<E> extends ForegroundCompositeConverterBase<E> { @Override protected String getForegroundColorCode(E event) { return ANSIConstants.MAGENTA_FG; } }
cscfa/bartleby
library/logBack/logback-1.1.3/logback-core/src/main/java/ch/qos/logback/core/pattern/color/MagentaCompositeConverter.java
Java
mit
909
const mix = require('laravel-mix'); mix .js('resources/assets/app.js', 'public/js') .extract(['vue', 'lodash']) ;
FiguredLimited/vue-mc
demo/webpack.mix.js
JavaScript
mit
123