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
<?php /** * @link https://github.com/gromver/yii2-platform-core.git#readme * @copyright Copyright (c) Gayazov Roman, 2014 * @license https://github.com/gromver/yii2-platform-core/blob/master/LICENSE * @package yii2-platform-core * @version 1.0.0 */ namespace gromver\platform\core\modules\menu\widgets\events; use gromver\modulequery\Event; /** * Class MenuItemRoutesEvent * См. \gromver\platform\core\modules\menu\widgets\MenuItemRoutes * @package yii2-platform-core * @author Gayazov Roman <gromver5@gmail.com> */ class MenuItemRoutesEvent extends Event { /** * @var array */ public $items; }
gromver/yii2-platform-core
modules/menu/widgets/events/MenuItemRoutesEvent.php
PHP
mit
629
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("06.FilterBase")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("06.FilterBase")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3b887bc5-4bf1-4edd-b255-58837d9fb5e1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
whywherewhat/PFundExtendedMay2017
08.Dictionaries-Exercises/06.FilterBase/Properties/AssemblyInfo.cs
C#
mit
1,397
require 'commander' require_relative "edit" module ClusterFsck module Commands class Create include ClusterFsckEnvArgumentParser def run_command(args, options = {}) raise ArgumentError, "must provide a project name" if args.empty? set_cluster_fsck_env_and_key_from_args(args) obj = s3_object(key) raise ConflictError, "#{key} already exists!" if obj.exists? obj.write('') Edit.new.run_command(args) end end end end
Amicus/clusterfsck
lib/clusterfsck/commands/create.rb
Ruby
mit
496
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): m = {} def findFrequentTreeSum(self, root): """ :type root: TreeNode :rtype: List[int] """ if not root: return [] self.m = {} self.traverse(root) freq = max(self.m.values()) return [e for e in self.m if self.m[e] == freq] def traverse(self, root): if not root: return self.traverse(root.left) self.traverse(root.right) if root.left: root.val += root.left.val if root.right: root.val += root.right.val print root.val self.m[root.val] = self.m.get(root.val, 0) + 1
Jspsun/LEETCodePractice
Python/MostFrequentSubtreeSum.py
Python
mit
849
#include "editaddressdialog.h" #include "ui_editaddressdialog.h" #include "addresstablemodel.h" #include "guiutil.h" #include <QDataWidgetMapper> #include <QMessageBox> EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0) { ui->setupUi(this); GUIUtil::setupAddressWidget(ui->addressEdit, this); switch(mode) { case NewReceivingAddress: setWindowTitle(tr("New receiving address")); ui->addressEdit->setEnabled(false); break; case NewSendingAddress: setWindowTitle(tr("New sending address")); break; case EditReceivingAddress: setWindowTitle(tr("Edit receiving address")); ui->addressEdit->setDisabled(true); break; case EditSendingAddress: setWindowTitle(tr("Edit sending address")); break; } mapper = new QDataWidgetMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); } EditAddressDialog::~EditAddressDialog() { delete ui; } void EditAddressDialog::setModel(AddressTableModel *model) { this->model = model; mapper->setModel(model); mapper->addMapping(ui->labelEdit, AddressTableModel::Label); mapper->addMapping(ui->addressEdit, AddressTableModel::Address); } void EditAddressDialog::loadRow(int row) { mapper->setCurrentIndex(row); } bool EditAddressDialog::saveCurrentRow() { if(!model) return false; switch(mode) { case NewReceivingAddress: case NewSendingAddress: address = model->addRow( mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, ui->labelEdit->text(), ui->addressEdit->text()); break; case EditReceivingAddress: case EditSendingAddress: if(mapper->submit()) { address = ui->addressEdit->text(); } break; } return !address.isEmpty(); } void EditAddressDialog::accept() { if(!model) return; if(!saveCurrentRow()) { switch(model->getEditStatus()) { case AddressTableModel::DUPLICATE_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); break; case AddressTableModel::INVALID_ADDRESS: QMessageBox::warning(this, windowTitle(), tr("The entered address \"%1\" is not a valid Skullz address.").arg(ui->addressEdit->text()), QMessageBox::Ok, QMessageBox::Ok); return; case AddressTableModel::WALLET_UNLOCK_FAILURE: QMessageBox::critical(this, windowTitle(), tr("Could not unlock wallet."), QMessageBox::Ok, QMessageBox::Ok); return; case AddressTableModel::KEY_GENERATION_FAILURE: QMessageBox::critical(this, windowTitle(), tr("New key generation failed."), QMessageBox::Ok, QMessageBox::Ok); return; case AddressTableModel::OK: // Failed with unknown reason. Just reject. break; } return; } QDialog::accept(); } QString EditAddressDialog::getAddress() const { return address; } void EditAddressDialog::setAddress(const QString &address) { this->address = address; ui->addressEdit->setText(address); }
skullzdev/skullz
src/qt/editaddressdialog.cpp
C++
mit
3,563
#include <algorithm> #include <cmath> #include <fstream> #include <iostream> #include <string> #include <vector> namespace { char constexpr START = 'S'; char constexpr FINISH = 'F'; char constexpr FREE = '*'; char constexpr MOUNTAIN = '^'; char constexpr PORT = 'P'; char constexpr INVALID = 'X'; void trimMap(std::string &map) { auto it = std::stable_partition(std::begin(map), std::end(map), [](char ch) { switch(ch) { case START: case FINISH: case FREE: case MOUNTAIN: case PORT: return true; break; default: return false; } }); map.erase(it, std::end(map)); } struct Node { Node() { score[0] = score[1] = std::numeric_limits<unsigned int>::max(); visited[0] = visited[1] = false; } unsigned int score[2]; bool visited[2]; }; struct State { State(std::string map) : my_map{std::move(map)}, my_size{static_cast<std::size_t>(std::sqrt(my_map.length()))} { auto start = my_map.find(START); my_startY = start / my_size; my_startX = start % my_size; my_costs.resize(my_size * my_size, Node{}); getCost(my_startX, my_startY).score[0] = 0; getCost(my_startX, my_startY).visited[0] = true; } Node& getCost(std::size_t x, std::size_t y) { return my_costs[(y * my_size) + x]; } char getMapCell(std::size_t x,std::size_t y) const noexcept { return my_map[(y * my_size) + x]; } std::vector<Node> my_costs; std::string const my_map; std::size_t const my_size; std::size_t my_startX; std::size_t my_startY; }; void updateState(Node &cell, int method, unsigned int totalCost) { if(cell.score[method] > totalCost) { cell.score[method] = totalCost; } } void updateCosts(State &state, int method, unsigned newX, unsigned newY, unsigned int currentX, unsigned int currentY) { auto &cellCost = state.getCost(currentX, currentY); auto &newCost = state.getCost(newX, newY); switch(state.getMapCell(newX, newY)) { case PORT: if(method == 0) { // create a sea path and fall through in case we skip the water updateState(newCost, 1, cellCost.score[method] + 3); } else { // go back to land updateState(newCost, 0, cellCost.score[method] + 2); break; } case FINISH: case FREE: case START: updateState(newCost, method, cellCost.score[method] + ((method == 0) ? 2 : 1)); break; case MOUNTAIN: return; break; } } void runMoves(State &state, int method, unsigned int x, unsigned int y) { if(x > 0) { updateCosts(state, method, x - 1, y, x, y); } if(x < (state.my_size - 1)) { updateCosts(state, method, x + 1, y, x, y); } if(y > 0) { updateCosts(state, method, x, y - 1, x, y); } if(y < (state.my_size - 1)) { updateCosts(state, method, x, y + 1, x, y); } } unsigned int runState(State state) { while(true) { auto x = state.my_startX; auto y = state.my_startY; auto method = 0; auto currentCost = state.getCost(x, y).score[0]; for(std::size_t i = 0; i < state.my_size; ++i) { for(std::size_t j = 0; j < state.my_size; ++j) { if(!((i == state.my_startX) && (j == state.my_startY))) { auto &cost = state.getCost(i, j); for(auto k = 0; k < 2; ++k) { if(!cost.visited[k] && (cost.score[k] < currentCost)) { x = i; y = j; currentCost = cost.score[k]; method = k; } } } } } auto &cell = state.getCost(x, y); if((state.getMapCell(x, y) == FINISH) && (method == 0)) { // we're at the finish node and we're on land return cell.score[method]; } runMoves(state, method, x, y); cell.visited[method] = true; if((x == state.my_startX) && (y == state.my_startY)) { cell.score[0] = std::numeric_limits<unsigned int>::max(); cell.score[1] = std::numeric_limits<unsigned int>::max(); } } } } int main(int argc, char ** argv) { (void) argc; std::ifstream input{argv[1]}; std::string map; std::getline(input, map); while(input) { trimMap(map); auto result = runState(State{map}); std::cout << result << '\n'; std::getline(input, map); } return 0; }
snewell/codeeval
challenge-0207.cpp
C++
mit
5,536
<?php function generate_random_str($length = 10, $uppercase = false) { if($uppercase) { return substr(str_shuffle("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length); } else { return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length); } } function create_alert_message($result) { if ($result['success']) { $alert_class = "alert-success"; $icon = "<i class='fa fa-check-circle'></i>"; } else { $alert_class = 'alert-danger'; $icon = "<i class='fa fa-exclamation-circle'></i>"; } $message = $result['message']; return " <div class='alert $alert_class'> $icon $message </div> "; } function get_start_and_end_date_current_month() { $month_start_ts = strtotime('first day of this month', time()); $month_end_ts = strtotime('last day of this month', time()); return [ 'start' => date('Y-m-d', $month_start_ts), 'end' => date('Y-m-d', $month_end_ts) ]; } function json_response($code = 200, $message = null) { // clear the old headers header_remove(); // set the header to make sure cache is forced header("Cache-Control: no-transform,public,max-age=300,s-maxage=900"); // treat this as json header('Content-Type: application/json'); $status = array( 200 => '200 OK', 400 => '400 Bad Request', 500 => '500 Internal Server Error' ); // ok, validation error, or failure header('Status: '.$status[$code]); // return the encoded json return json_encode(array( 'status' => $code < 300, // success or not? 'message' => $message )); } function setTemporaryFile($name, $content) { $file = DIRECTORY_SEPARATOR . trim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . ltrim($name, DIRECTORY_SEPARATOR); $x = file_put_contents($file, $content); // register_shutdown_function(function() use($file) { // unlink($file); // }); // return $file; } function getTemporaryFileContent($name) { $file = DIRECTORY_SEPARATOR . trim(sys_get_temp_dir(), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . ltrim($name, DIRECTORY_SEPARATOR); return file_get_contents($file); }
jrdncchr/directmail
application/helpers/danero_helper.php
PHP
mit
2,419
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.appservice.v2019_08_01; import com.microsoft.azure.arm.model.HasInner; import com.microsoft.azure.management.appservice.v2019_08_01.implementation.WorkerPoolResourceInner; import com.microsoft.azure.arm.resources.models.HasManager; import com.microsoft.azure.management.appservice.v2019_08_01.implementation.AppServiceManager; import java.util.List; /** * Type representing MultiRolePools. */ public interface MultiRolePools extends HasInner<WorkerPoolResourceInner>, HasManager<AppServiceManager> { /** * @return the computeMode value. */ ComputeModeOptions computeMode(); /** * @return the id value. */ String id(); /** * @return the instanceNames value. */ List<String> instanceNames(); /** * @return the kind value. */ String kind(); /** * @return the name value. */ String name(); /** * @return the sku value. */ SkuDescription sku(); /** * @return the type value. */ String type(); /** * @return the workerCount value. */ Integer workerCount(); /** * @return the workerSize value. */ String workerSize(); /** * @return the workerSizeId value. */ Integer workerSizeId(); }
selvasingh/azure-sdk-for-java
sdk/appservice/mgmt-v2019_08_01/src/main/java/com/microsoft/azure/management/appservice/v2019_08_01/MultiRolePools.java
Java
mit
1,543
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <imprec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Casio; use JMS\Serializer\Annotation\ExclusionPolicy; use PHPExiftool\Driver\AbstractTag; /** * @ExclusionPolicy("all") */ class QualityMode extends AbstractTag { protected $Id = 8; protected $Name = 'QualityMode'; protected $FullName = 'Casio::Type2'; protected $GroupName = 'Casio'; protected $g0 = 'MakerNotes'; protected $g1 = 'Casio'; protected $g2 = 'Camera'; protected $Type = 'int16u'; protected $Writable = true; protected $Description = 'Quality Mode'; protected $flag_Permanent = true; protected $Values = array( 0 => array( 'Id' => 0, 'Label' => 'Economy', ), 1 => array( 'Id' => 1, 'Label' => 'Normal', ), 2 => array( 'Id' => 2, 'Label' => 'Fine', ), ); }
romainneutron/PHPExiftool
lib/PHPExiftool/Driver/Tag/Casio/QualityMode.php
PHP
mit
1,121
using System; using System.CodeDom; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using WienerLinienApi.Information; using WienerLinienApi.Model; using WienerLinienApi.RealtimeData.Monitor; namespace WienerLinienApi.Samples.WPF_Proper.Model { static class NewFavoriteStop { public static string StopName { get; set; } public static string Line { get; set; } public static string StopType { get; set; } public static int Platforms { get; set; } public static int[] TimesToWait { get; set; } public static List<string> BusStops { get; set; } public static WienerLinienContext Context = new WienerLinienContext("O56IE8eH7Kf5R5aQ"); private static List<Station> stations; private static MonitorData Data { get; set; } private static Entities1 dbEntities = new Entities1(); public static async Task<List<string>> GetStaionNames(MeansOfTransport type) { if (stations == null) { stations = await Stations.GetAllStationsAsync(); } var mot = type; var listOfStations = (from v in stations from p in v.Platforms where p.MeansOfTransport == type select v.Name).Distinct().ToList(); return listOfStations; } public static Haltestellen GetStationFromId(int id) { var a = dbEntities.Haltestellens.First(i => i.Haltestellen_ID== id); return a; } public static int GetStationIdFromName(string name) { return stations.First(i => i.Name == name).StationId; } public static async Task<List<string>> GetLinesFromStation(string station, MeansOfTransport type) { if (stations == null) { stations = await Stations.GetAllStationsAsync(); } var lines = (from v in stations where v.Name.Equals(station) from p in v.Platforms where p.MeansOfTransport == type group p by p.Name into linesList select linesList.Key).ToList(); return lines; } internal static string GetTimeForNextBus(object text1, string text2, object text3) { throw new NotImplementedException(); } public static async Task<Dictionary<string, string>> GetDirections(string station, string line) { if (stations == null) { stations = await Stations.GetAllStationsAsync(); } Console.WriteLine("Station=" + station + "&line=" + line + "&type="); var directions = (from v in stations where v.Name == station from p in v.Platforms where p.Name == line select p.RblNumber.ToString()).ToList(); var rbls = directions.Select(int.Parse).ToList(); var rtd = new RealtimeData.RealtimeData(Context); var parameters = new Parameters.MonitorParameters() { Rbls = rbls }; var monitorInfo = await rtd.GetMonitorDataAsync(parameters); Data = monitorInfo; var strings = new Dictionary<string, string>(); var b = monitorInfo.Data.Monitors.Where(i => i.Lines[0].Direction == "R" && i.Lines[0].Name == line).ToList(); if (b.Count > 0) { strings.Add("R", ReplaceString(b.Select(i => i.Lines[0].Towards) .ToList() .First() + " ")); } var c = monitorInfo.Data.Monitors.Where(i => i.Lines[0].Direction == "H" && i.Lines[0].Name == line).ToList(); if (c.Count > 0) { strings.Add("H", ReplaceString(c.Select(i => i.Lines[0].Towards) .ToList() .First() + " ")); } return strings; } public static string GetTimeForNextBus(string station, string line, string direction) { var time = Data.Data.Monitors.Where(i => i.Lines[0].Direction == direction && i.Lines[0].Name == line).ToList(); foreach (var v in time) { Console.WriteLine(v.ToString()); } return ""; } private static string ReplaceString(string towards) { var a = Regex.Replace(towards, "([A-Z]+ )", i => "(" + i.Value.Trim() + ") "); return a; } } }
KarimDarwish/WienerLinien.NET
WienerLinienApi.Samples.WPF_Proper/Model/NewFavoriteStop.cs
C#
mit
4,931
package com.medicapital.client.doctor.work; import java.util.Date; import com.medicapital.common.entities.Day; interface SetterWorkHoursView { void setDay(Day day); void setDateFrom(Date date); void setDateTo(Date date); void setStartHour(int hour); void setStartMinutes(int minutes); void setEndHour(int hour); void setEndMinutes(int minutes); void setDescription(String description); void setAddress(String address); void setPostalCode(String postalCode); void setCityId(int cityId); }
m-wrona/gwt-medicapital
client/com/medicapital/client/doctor/work/SetterWorkHoursView.java
Java
mit
541
package org.gluu.oxauth.ws.rs; import static org.gluu.oxauth.client.Asserter.assertOk; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; import java.util.Arrays; import java.util.List; import java.util.UUID; import org.gluu.oxauth.BaseTest; import org.gluu.oxauth.client.AuthorizationRequest; import org.gluu.oxauth.client.AuthorizationResponse; import org.gluu.oxauth.client.RegisterClient; import org.gluu.oxauth.client.RegisterRequest; import org.gluu.oxauth.client.RegisterResponse; import org.gluu.oxauth.client.RevokeSessionClient; import org.gluu.oxauth.client.RevokeSessionRequest; import org.gluu.oxauth.client.RevokeSessionResponse; import org.gluu.oxauth.model.common.AuthenticationMethod; import org.gluu.oxauth.model.common.ResponseType; import org.gluu.oxauth.model.register.ApplicationType; import org.gluu.oxauth.model.util.StringUtils; import org.testng.annotations.Parameters; import org.testng.annotations.Test; /** * @author Yuriy Zabrovarnyy */ public class RevokeSessionHttpTest extends BaseTest { @Parameters({"redirectUris", "userId", "userSecret", "redirectUri", "sectorIdentifierUri", "umaPatClientId", "umaPatClientSecret"}) @Test public void revokeSession( final String redirectUris, final String userId, final String userSecret, final String redirectUri, final String sectorIdentifierUri, String umaPatClientId, String umaPatClientSecret) throws Exception { showTitle("revokeSession"); final AuthenticationMethod authnMethod = AuthenticationMethod.CLIENT_SECRET_BASIC; // 1. Register client List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE, ResponseType.ID_TOKEN); RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app", StringUtils.spaceSeparatedToList(redirectUris)); registerRequest.setTokenEndpointAuthMethod(authnMethod); registerRequest.setSectorIdentifierUri(sectorIdentifierUri); registerRequest.setResponseTypes(responseTypes); RegisterClient registerClient = newRegisterClient(registerRequest); RegisterResponse registerResponse = registerClient.exec(); showClient(registerClient); assertOk(registerResponse); assertNotNull(registerResponse.getRegistrationAccessToken()); // 3. Request authorization List<String> scopes = Arrays.asList( "openid", "profile", "address", "email"); String state = UUID.randomUUID().toString(); String nonce = UUID.randomUUID().toString(); AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, registerResponse.getClientId(), scopes, redirectUri, nonce); authorizationRequest.setState(state); AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess( authorizationEndpoint, authorizationRequest, userId, userSecret); assertNotNull(authorizationResponse.getLocation(), "The location is null"); assertNotNull(authorizationResponse.getCode(), "The authorization code is null"); assertNotNull(authorizationResponse.getIdToken(), "The ID Token is null"); assertNotNull(authorizationResponse.getState(), "The state is null"); assertNotNull(authorizationResponse.getScope(), "The scope is null"); RevokeSessionRequest revokeSessionRequest = new RevokeSessionRequest("uid", "test"); revokeSessionRequest.setAuthenticationMethod(authnMethod); revokeSessionRequest.setAuthUsername(umaPatClientId); // it must be client with revoke_session scope revokeSessionRequest.setAuthPassword(umaPatClientSecret); RevokeSessionClient revokeSessionClient = newRevokeSessionClient(revokeSessionRequest); final RevokeSessionResponse revokeSessionResponse = revokeSessionClient.exec(); showClient(revokeSessionClient); assertEquals(revokeSessionResponse.getStatus(), 200); } }
GluuFederation/oxAuth
Client/src/test/java/org/gluu/oxauth/ws/rs/RevokeSessionHttpTest.java
Java
mit
4,099
/*--------------------------------------------------------------------------*/ #include "evolution/Generation.h" #include "evolution/Individual.h" #include "game/Game.h" #include "game/Grid.h" #include "game/Player.h" #include "gui/GenerationView.h" #include "ui_GenerationView.h" /*--------------------------------------------------------------------------*/ /***********************************************/ GenerationView::GenerationView(QWidget* parent) : QWidget(parent), _ui(new Ui::GenerationView) { _ui->setupUi(this); connect(_ui->stv, &ScoreTableView::selectionChanged, this, &GenerationView::selectionChanged); _ui->tw->setRowCount(4); _ui->tw->setColumnCount(4); _ui->tw->setHorizontalHeaderLabels(QStringList() << "Archer" << "Horseman" << "Pikeman" << "Swordsman"); _ui->tw->setVerticalHeaderLabels(QStringList() << "Archer" << "Horseman" << "Pikeman" << "Swordsman"); } /***********************************************/ GenerationView::~GenerationView() { delete _ui; } /***********************************************/ void GenerationView::dropGeneration() { _generation.reset(); _grid.reset(); update(); } /***********************************************/ void GenerationView::setGeneration(const pGeneration& generation) { _generation = generation; _grid = _generation->tournament().grid()->getEmptyCopy(); update(); } /***********************************************/ void GenerationView::update() { _ui->spinGeneration->setValue(0); _ui->stv->dropScoreTable(); _ui->ggv->clear(); _ui->tw->clearContents(); if(!_generation) { qWarning() << "no _generation == no update"; return; } _ui->spinGeneration->setValue(_generation->generation()); _ui->stv->setScoreTable(_generation->tournament().scoreTable()); } /***********************************************/ void GenerationView::selectionChanged(pPlayer currplayer) { if(!_grid) { qWarning() << "No _grid set"; return; } if(!currplayer) { _ui->ggv->clear(); return; } auto leftSideRect = _grid->startingLeftSideRect(); _grid->setState(GridState::Initial); //frees all cells _grid->setState(GridState::LeftPlayerPlacing, currplayer); //.- currplayer->initGrid(_grid, Side::Left); _ui->ggv->drawGrid(_grid, std::get<0>(leftSideRect), std::get<1>(leftSideRect), std::get<2>(leftSideRect), std::get<3>(leftSideRect)); //indi pIndividual indi = std::dynamic_pointer_cast<Individual>(currplayer); AttackPriorities aps; if(!indi) { qWarning() << "Cant cast to indi"; return; } aps = indi->attackPriorities(); _ui->tw->clearContents(); for(int i = 0; i < 4; ++i) { for(int j = 0; j < 4; ++j) { auto item = new QTableWidgetItem(QString::number(aps.at(static_cast<UnitType>(i)).at(static_cast<UnitType>(j)).value())); _ui->tw->setItem(i, j, item); } } }
dKirill/evolution
src/gui/GenerationView.cpp
C++
mit
2,800
import { AppPage } from './app.po'; describe('cliente-radio App', () => { let page: AppPage; beforeEach(() => { page = new AppPage(); }); it('should display welcome message', () => { page.navigateTo(); expect(page.getParagraphText()).toEqual('Welcome to app!'); }); });
ILoveYouDrZaius/cliente-radio
e2e/app.e2e-spec.ts
TypeScript
mit
295
#! /usr/bin/env ruby breakpoints = [ {w: '768', name: '768'}, {w: '1536', name: '768@2x'}, {w: '992', name: '992'}, {w: '1984', name: '992@2x'}, {w: '1200', name: '1200'}, {w: '2400', name: '1200@2x'}, {w: '2560', name: '2560'} ] bg_queries = <<eos $retina: '(min-resolution: 2dppx)'; $bg-queries: ( 'full': '(min-width: 2561px), only screen and (min-height: 1448px)', '2560': '(max-width: 2560px) and (max-height: 1447px)', '1200@2x': '(max-width: 2400px) and (max-height: 1356px) and (\#{retina})', '1200': '(max-width: 1200px) and (max-height: 678px)', '992@2x': '(max-width: 1984px) and (max-height: 1121px) and (\#{retina})', '992': '(max-width: 992px) and (max-height: 561px)', '768@2x': '(max-width: 1536px) and (max-height: 868px) and (\#{retina})', '768': '(max-width: 768px) and (max-height: 434px)' ); eos File.open('app/styles/_background-queries.scss', 'w') {|f| f.write(bg_queries) } # ------------------------------------------------------------------------------ full_width=`sips -g pixelWidth app/images/bg-full.jpg | tail -n 1 | cut -d":" -f2 | xargs`.to_i full_height=`sips -g pixelHeight app/images/bg-full.jpg | tail -n 1 | cut -d":" -f2 | xargs`.to_i h = ((40.0 / full_width) * full_height).round system "cp app/images/bg-full.jpg app/images/bg-40.jpg" system "sips -z #{h} 40 app/images/bg-#{40}.jpg" breakpoints.each do |breakpoint| height = ((breakpoint[:w].to_f / full_width) * full_height).round system "cp app/images/bg-full.jpg app/images/bg-#{breakpoint[:name]}.jpg" system "sips -z #{height} #{breakpoint[:w]} app/images/bg-#{breakpoint[:name]}.jpg" end bg_base64=`openssl base64 -in app/images/bg-40.jpg`.gsub(/\s+/, "") svg = <<eos <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="#{full_width}" height="#{full_height}" viewBox="0 0 #{full_width} #{full_height}"> <filter id="blur" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"> <feGaussianBlur stdDeviation="20 20" edgeMode="duplicate" /> <feComponentTransfer> <feFuncA type="discrete" tableValues="1 1" /> </feComponentTransfer> </filter> <image filter="url(#blur)" xlink:href="data:image/jpeg;base64,#{bg_base64}" x="0" y="0" height="100%" width="100%"/> </svg> eos File.open('app/images/bg-blur.svg', 'w') {|f| f.write(svg) }
jacobthemyth/jacobthemyth.github.io
scripts/images.rb
Ruby
mit
2,380
namespace AgileObjects.AgileMapper.PerformanceTesting.ConcreteMappers.Mapster { using System.Collections.Generic; using System.Linq; using AbstractMappers; using global::Mapster; using static TestClasses.Complex; public class MapsterComplexTypeMapperSetup : ComplexTypeMapperSetupBase { public override void Initialise() { } protected override Foo SetupComplexTypeMapper(Foo foo) { TypeAdapterConfig<Foo, Foo>.NewConfig() .Map(dest => dest.Foos, src => src.Foos ?? new List<Foo>()) .Map(dest => dest.FooArray, src => src.FooArray ?? new Foo[0]) .Map(dest => dest.Ints, src => src.Ints ?? Enumerable.Empty<int>()) .Map(dest => dest.IntArray, src => src.IntArray ?? new int[0]) .Compile(); return foo.Adapt<Foo, Foo>(); } protected override void Reset() => TypeAdapterConfig<Foo, Foo>.Clear(); } }
agileobjects/AgileMapper
AgileMapper.PerformanceTesting/ConcreteMappers/Mapster/MapsterComplexTypeMapperSetup.cs
C#
mit
1,006
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* |-------------------------------------------------------------------------- | Base Site URL |-------------------------------------------------------------------------- | | URL to your CodeIgniter root. Typically this will be your base URL, | WITH a trailing slash: | | http://example.com/ | | WARNING: You MUST set this value! | | If it is not set, then CodeIgniter will try guess the protocol and path | your installation, but due to security concerns the hostname will be set | to $_SERVER['SERVER_ADDR'] if available, or localhost otherwise. | The auto-detection mechanism exists only for convenience during | development and MUST NOT be used in production! | | If you need to allow multiple domains, remember that this file is still | a PHP script and you can easily do that on your own. | */ $config['base_url'] = 'http://localhost/fp'; /* |-------------------------------------------------------------------------- | Index File |-------------------------------------------------------------------------- | | Typically this will be your index.php file, unless you've renamed it to | something else. If you are using mod_rewrite to remove the page set this | variable so that it is blank. | */ $config['index_page'] = ''; /* |-------------------------------------------------------------------------- | URI PROTOCOL |-------------------------------------------------------------------------- | | This item determines which server global should be used to retrieve the | URI string. The default setting of 'REQUEST_URI' works for most servers. | If your links do not seem to work, try one of the other delicious flavors: | | 'REQUEST_URI' Uses $_SERVER['REQUEST_URI'] | 'QUERY_STRING' Uses $_SERVER['QUERY_STRING'] | 'PATH_INFO' Uses $_SERVER['PATH_INFO'] | | WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded! */ $config['uri_protocol'] = 'REQUEST_URI'; /* |-------------------------------------------------------------------------- | URL suffix |-------------------------------------------------------------------------- | | This option allows you to add a suffix to all URLs generated by CodeIgniter. | For more information please see the user guide: | | https://codeigniter.com/user_guide/general/urls.html */ $config['url_suffix'] = ''; /* |-------------------------------------------------------------------------- | Default Language |-------------------------------------------------------------------------- | | This determines which set of language files should be used. Make sure | there is an available translation if you intend to use something other | than english. | */ $config['language'] = 'english'; /* |-------------------------------------------------------------------------- | Default Character Set |-------------------------------------------------------------------------- | | This determines which character set is used by default in various methods | that require a character set to be provided. | | See http://php.net/htmlspecialchars for a list of supported charsets. | */ $config['charset'] = 'UTF-8'; /* |-------------------------------------------------------------------------- | Enable/Disable System Hooks |-------------------------------------------------------------------------- | | If you would like to use the 'hooks' feature you must enable it by | setting this variable to TRUE (boolean). See the user guide for details. | */ $config['enable_hooks'] = FALSE; /* |-------------------------------------------------------------------------- | Class Extension Prefix |-------------------------------------------------------------------------- | | This item allows you to set the filename/classname prefix when extending | native libraries. For more information please see the user guide: | | https://codeigniter.com/user_guide/general/core_classes.html | https://codeigniter.com/user_guide/general/creating_libraries.html | */ $config['subclass_prefix'] = 'MY_'; /* |-------------------------------------------------------------------------- | Composer auto-loading |-------------------------------------------------------------------------- | | Enabling this setting will tell CodeIgniter to look for a Composer | package auto-loader script in application/vendor/autoload.php. | | $config['composer_autoload'] = TRUE; | | Or if you have your vendor/ directory located somewhere else, you | can opt to set a specific path as well: | | $config['composer_autoload'] = '/path/to/vendor/autoload.php'; | | For more information about Composer, please visit http://getcomposer.org/ | | Note: This will NOT disable or override the CodeIgniter-specific | autoloading (application/config/autoload.php) */ $config['composer_autoload'] = FALSE; /* |-------------------------------------------------------------------------- | Allowed URL Characters |-------------------------------------------------------------------------- | | This lets you specify which characters are permitted within your URLs. | When someone tries to submit a URL with disallowed characters they will | get a warning message. | | As a security measure you are STRONGLY encouraged to restrict URLs to | as few characters as possible. By default only these are allowed: a-z 0-9~%.:_- | | Leave blank to allow all characters -- but only if you are insane. | | The configured value is actually a regular expression character group | and it will be executed as: ! preg_match('/^[<permitted_uri_chars>]+$/i | | DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!! | */ $config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; /* |-------------------------------------------------------------------------- | Enable Query Strings |-------------------------------------------------------------------------- | | By default CodeIgniter uses search-engine friendly segment based URLs: | example.com/who/what/where/ | | You can optionally enable standard query string based URLs: | example.com?who=me&what=something&where=here | | Options are: TRUE or FALSE (boolean) | | The other items let you set the query string 'words' that will | invoke your controllers and its functions: | example.com/index.php?c=controller&m=function | | Please note that some of the helpers won't work as expected when | this feature is enabled, since CodeIgniter is designed primarily to | use segment based URLs. | */ $config['enable_query_strings'] = FALSE; $config['controller_trigger'] = 'c'; $config['function_trigger'] = 'm'; $config['directory_trigger'] = 'd'; /* |-------------------------------------------------------------------------- | Allow $_GET array |-------------------------------------------------------------------------- | | By default CodeIgniter enables access to the $_GET array. If for some | reason you would like to disable it, set 'allow_get_array' to FALSE. | | WARNING: This feature is DEPRECATED and currently available only | for backwards compatibility purposes! | */ $config['allow_get_array'] = TRUE; /* |-------------------------------------------------------------------------- | Error Logging Threshold |-------------------------------------------------------------------------- | | You can enable error logging by setting a threshold over zero. The | threshold determines what gets logged. Threshold options are: | | 0 = Disables logging, Error logging TURNED OFF | 1 = Error Messages (including PHP errors) | 2 = Debug Messages | 3 = Informational Messages | 4 = All Messages | | You can also pass an array with threshold levels to show individual error types | | array(2) = Debug Messages, without Error Messages | | For a live site you'll usually only enable Errors (1) to be logged otherwise | your log files will fill up very fast. | */ $config['log_threshold'] = 0; /* |-------------------------------------------------------------------------- | Error Logging Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/logs/ directory. Use a full server path with trailing slash. | */ $config['log_path'] = ''; /* |-------------------------------------------------------------------------- | Log File Extension |-------------------------------------------------------------------------- | | The default filename extension for log files. The default 'php' allows for | protecting the log files via basic scripting, when they are to be stored | under a publicly accessible directory. | | Note: Leaving it blank will default to 'php'. | */ $config['log_file_extension'] = ''; /* |-------------------------------------------------------------------------- | Log File Permissions |-------------------------------------------------------------------------- | | The file system permissions to be applied on newly created log files. | | IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal | integer notation (i.e. 0700, 0644, etc.) */ $config['log_file_permissions'] = 0644; /* |-------------------------------------------------------------------------- | Date Format for Logs |-------------------------------------------------------------------------- | | Each item that is logged has an associated date. You can use PHP date | codes to set your own date formatting | */ $config['log_date_format'] = 'Y-m-d H:i:s'; /* |-------------------------------------------------------------------------- | Error Views Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/views/errors/ directory. Use a full server path with trailing slash. | */ $config['error_views_path'] = ''; /* |-------------------------------------------------------------------------- | Cache Directory Path |-------------------------------------------------------------------------- | | Leave this BLANK unless you would like to set something other than the default | application/cache/ directory. Use a full server path with trailing slash. | */ $config['cache_path'] = ''; /* |-------------------------------------------------------------------------- | Cache Include Query String |-------------------------------------------------------------------------- | | Whether to take the URL query string into consideration when generating | output cache files. Valid options are: | | FALSE = Disabled | TRUE = Enabled, take all query parameters into account. | Please be aware that this may result in numerous cache | files generated for the same page over and over again. | array('q') = Enabled, but only take into account the specified list | of query parameters. | */ $config['cache_query_string'] = FALSE; /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | If you use the Encryption class, you must set an encryption key. | See the user guide for more info. | | https://codeigniter.com/user_guide/libraries/encryption.html | */ $config['encryption_key'] = ''; /* |-------------------------------------------------------------------------- | Session Variables |-------------------------------------------------------------------------- | | 'sess_driver' | | The storage driver to use: files, database, redis, memcached | | 'sess_cookie_name' | | The session cookie name, must contain only [0-9a-z_-] characters | | 'sess_expiration' | | The number of SECONDS you want the session to last. | Setting to 0 (zero) means expire when the browser is closed. | | 'sess_save_path' | | The location to save sessions to, driver dependent. | | For the 'files' driver, it's a path to a writable directory. | WARNING: Only absolute paths are supported! | | For the 'database' driver, it's a table name. | Please read up the manual for the format with other session drivers. | | IMPORTANT: You are REQUIRED to set a valid save path! | | 'sess_match_ip' | | Whether to match the user's IP address when reading the session data. | | WARNING: If you're using the database driver, don't forget to update | your session table's PRIMARY KEY when changing this setting. | | 'sess_time_to_update' | | How many seconds between CI regenerating the session ID. | | 'sess_regenerate_destroy' | | Whether to destroy session data associated with the old session ID | when auto-regenerating the session ID. When set to FALSE, the data | will be later deleted by the garbage collector. | | Other session cookie settings are shared with the rest of the application, | except for 'cookie_prefix' and 'cookie_httponly', which are ignored here. | */ $config['sess_driver'] = 'files'; $config['sess_cookie_name'] = 'ci_session'; $config['sess_expiration'] = 7200; $config['sess_save_path'] = NULL; $config['sess_match_ip'] = FALSE; $config['sess_time_to_update'] = 300; $config['sess_regenerate_destroy'] = FALSE; /* |-------------------------------------------------------------------------- | Cookie Related Variables |-------------------------------------------------------------------------- | | 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions | 'cookie_domain' = Set to .your-domain.com for site-wide cookies | 'cookie_path' = Typically will be a forward slash | 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists. | 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript) | | Note: These settings (with the exception of 'cookie_prefix' and | 'cookie_httponly') will also affect sessions. | */ $config['cookie_prefix'] = ''; $config['cookie_domain'] = ''; $config['cookie_path'] = '/'; $config['cookie_secure'] = FALSE; $config['cookie_httponly'] = FALSE; /* |-------------------------------------------------------------------------- | Standardize newlines |-------------------------------------------------------------------------- | | Determines whether to standardize newline characters in input data, | meaning to replace \r\n, \r, \n occurrences with the PHP_EOL value. | | WARNING: This feature is DEPRECATED and currently available only | for backwards compatibility purposes! | */ $config['standardize_newlines'] = FALSE; /* |-------------------------------------------------------------------------- | Global XSS Filtering |-------------------------------------------------------------------------- | | Determines whether the XSS filter is always active when GET, POST or | COOKIE data is encountered | | WARNING: This feature is DEPRECATED and currently available only | for backwards compatibility purposes! | */ $config['global_xss_filtering'] = FALSE; /* |-------------------------------------------------------------------------- | Cross Site Request Forgery |-------------------------------------------------------------------------- | Enables a CSRF cookie token to be set. When set to TRUE, token will be | checked on a submitted form. If you are accepting user data, it is strongly | recommended CSRF protection be enabled. | | 'csrf_token_name' = The token name | 'csrf_cookie_name' = The cookie name | 'csrf_expire' = The number in seconds the token should expire. | 'csrf_regenerate' = Regenerate token on every submission | 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks */ $config['csrf_protection'] = FALSE; $config['csrf_token_name'] = 'csrf_test_name'; $config['csrf_cookie_name'] = 'csrf_cookie_name'; $config['csrf_expire'] = 7200; $config['csrf_regenerate'] = TRUE; $config['csrf_exclude_uris'] = array(); /* |-------------------------------------------------------------------------- | Output Compression |-------------------------------------------------------------------------- | | Enables Gzip output compression for faster page loads. When enabled, | the output class will test whether your server supports Gzip. | Even if it does, however, not all browsers support compression | so enable only if you are reasonably sure your visitors can handle it. | | Only used if zlib.output_compression is turned off in your php.ini. | Please do not use it together with httpd-level output compression. | | VERY IMPORTANT: If you are getting a blank page when compression is enabled it | means you are prematurely outputting something to your browser. It could | even be a line of whitespace at the end of one of your scripts. For | compression to work, nothing can be sent before the output buffer is called | by the output class. Do not 'echo' any values with compression enabled. | */ $config['compress_output'] = FALSE; /* |-------------------------------------------------------------------------- | Master Time Reference |-------------------------------------------------------------------------- | | Options are 'local' or any PHP supported timezone. This preference tells | the system whether to use your server's local time as the master 'now' | reference, or convert it to the configured one timezone. See the 'date | helper' page of the user guide for information regarding date handling. | */ $config['time_reference'] = 'local'; /* |-------------------------------------------------------------------------- | Rewrite PHP Short Tags |-------------------------------------------------------------------------- | | If your PHP installation does not have short tag support enabled CI | can rewrite the tags on-the-fly, enabling you to utilize that syntax | in your view files. Options are TRUE or FALSE (boolean) | | Note: You need to have eval() enabled for this to work. | */ $config['rewrite_short_tags'] = FALSE; /* |-------------------------------------------------------------------------- | Reverse Proxy IPs |-------------------------------------------------------------------------- | | If your server is behind a reverse proxy, you must whitelist the proxy | IP addresses from which CodeIgniter should trust headers such as | HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify | the visitor's IP address. | | You can use both an array or a comma-separated list of proxy addresses, | as well as specifying whole subnets. Here are a few examples: | | Comma-separated: '10.0.1.200,192.168.5.0/24' | Array: array('10.0.1.200', '192.168.5.0/24') */ $config['proxy_ips'] = '';
nadirafirinda/shopatginza
application/config/config.php
PHP
mit
18,446
var test = require('tape'); var last = require('../../packages/array-last'); test('non empty arrays return last', function (t) { t.plan(4); var testArrays = [ [1, 2, 3, 4, 5], [[1, 2, 3], [4, 5, 6], [7, 8, 9]], [{a: 1}, {b: 2}, {c: 3}, {d: 4}], ['a', 1, true, /r/g] ]; testArrays.forEach(function (arr) { t.equal(last(arr), arr[arr.length - 1]); }); t.end(); }); test('empty arrays return undefined', function (t) { t.plan(1); t.equal(last([]), undefined); t.end(); }); test('undefined inputs don\'t throw and return undefined', function (t) { t.plan(3); t.equal(last(), undefined); t.equal(last(undefined), undefined); t.equal(last(null), undefined); t.end(); });
jonathan-fielding/just
test/array-last/index.js
JavaScript
mit
716
// @flow import { connect } from 'react-redux' import { bindActionCreators } from 'redux' import { getEncryptedWIF, resetEncryptedWIF, } from '../../../modules/generateEncryptedWIF' import EncryptQR from './EncryptQR' const mapStateToProps = (state: Object) => ({ encryptedWIF: getEncryptedWIF(state), }) const actionCreators = { resetEncryptedWIF, } const mapDispatchToProps = dispatch => bindActionCreators(actionCreators, dispatch) export default connect( mapStateToProps, mapDispatchToProps, )(EncryptQR)
hbibkrim/neon-wallet
app/components/Settings/EncryptQR/index.js
JavaScript
mit
528
<TS language="sn" version="2.1"> <context> <name>AddressBookPage</name> <message> <source>Create a new address</source> <translation>Gadzira Kero Itsva</translation> </message> <message> <source>&amp;New</source> <translation>Itsva</translation> </message> <message> <source>&amp;Copy</source> <translation>&amp;Kopera</translation> </message> <message> <source>C&amp;lose</source> <translation>Vhara</translation> </message> <message> <source>&amp;Delete</source> <translation>Dzima</translation> </message> <message> <source>Sending addresses</source> <translation>Makero ekutumira</translation> </message> <message> <source>Receiving addresses</source> <translation>Makero ekutambira</translation> </message> <message> <source>&amp;Copy Address</source> <translation>Kopera Kero</translation> </message> <message> <source>&amp;Edit</source> <translation>&amp;Gadzirisa</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <source>Label</source> <translation>Zita</translation> </message> <message> <source>Address</source> <translation>Kero</translation> </message> <message> <source>(no label)</source> <translation>(hapana zita)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> </context> <context> <name>BanTableModel</name> <message> <source>Banned Until</source> <translation>Wakavharirwa Kusvika</translation> </message> </context> <context> <name>TurbocoinGUI</name> <message> <source>E&amp;xit</source> <translation>Buda</translation> </message> <message> <source>Quit application</source> <translation>Vhara Application</translation> </message> <message> <source>&amp;About %1</source> <translation>&amp;Kuma %1</translation> </message> <message> <source>Show information about %1</source> <translation>Taridza ruzivo rwekuma %1</translation> </message> <message> <source>Show information about Qt</source> <translation>Taridza ruzivo rwe Qt</translation> </message> <message> <source>&amp;Sending addresses...</source> <translation>&amp;Makero ekutumira nawo</translation> </message> <message> <source>&amp;Receiving addresses...</source> <translation>&amp;Makero ekutambira nawo</translation> </message> <message> <source>Open &amp;URI...</source> <translation>Vhura &amp;URI</translation> </message> <message> <source>Turbocoin</source> <translation>Turbocoin</translation> </message> <message> <source>Wallet</source> <translation>Chikwama</translation> </message> <message> <source>&amp;Send</source> <translation>&amp;Tumira</translation> </message> <message> <source>&amp;Receive</source> <translation>&amp;Tambira</translation> </message> <message> <source>&amp;Show / Hide</source> <translation>&amp;Taridza/Usataridza</translation> </message> <message> <source>&amp;File</source> <translation>&amp;Faira</translation> </message> <message> <source>&amp;Help</source> <translation>&amp;Rubatsiro</translation> </message> <message> <source>%1 behind</source> <translation>%1 kumashure</translation> </message> <message> <source>Warning</source> <translation>Hokoyo</translation> </message> <message> <source>Information</source> <translation>Ruzivo</translation> </message> </context> <context> <name>CoinControlDialog</name> <message> <source>Amount</source> <translation>Marii </translation> </message> <message> <source>Date</source> <translation>Zuva</translation> </message> <message> <source>(no label)</source> <translation>(hapana zita)</translation> </message> </context> <context> <name>EditAddressDialog</name> </context> <context> <name>FreespaceChecker</name> </context> <context> <name>HelpMessageDialog</name> </context> <context> <name>Intro</name> <message> <source>Turbocoin</source> <translation>Turbocoin</translation> </message> </context> <context> <name>ModalOverlay</name> </context> <context> <name>OpenURIDialog</name> </context> <context> <name>OptionsDialog</name> </context> <context> <name>OverviewPage</name> </context> <context> <name>PaymentServer</name> </context> <context> <name>PeerTableModel</name> </context> <context> <name>QObject</name> <message> <source>Amount</source> <translation>Marii </translation> </message> <message> <source>Enter a Turbocoin address (e.g. %1)</source> <translation>Nyora kero ye Turbocoin (sekuti %1)</translation> </message> <message> <source>%1 d</source> <translation>%1 d</translation> </message> <message> <source>%1 h</source> <translation>%1 h</translation> </message> <message> <source>%1 m</source> <translation>%1 m</translation> </message> <message> <source>%1 s</source> <translation>%1 s</translation> </message> <message> <source>None</source> <translation>Hapana</translation> </message> <message> <source>N/A</source> <translation>Hapana </translation> </message> </context> <context> <name>QObject::QObject</name> </context> <context> <name>QRImageWidget</name> </context> <context> <name>RPCConsole</name> <message> <source>N/A</source> <translation>Hapana </translation> </message> </context> <context> <name>ReceiveCoinsDialog</name> </context> <context> <name>ReceiveRequestDialog</name> <message> <source>Address</source> <translation>Kero</translation> </message> <message> <source>Amount</source> <translation>Marii </translation> </message> <message> <source>Label</source> <translation>Zita</translation> </message> <message> <source>Wallet</source> <translation>Chikwama</translation> </message> </context> <context> <name>RecentRequestsTableModel</name> <message> <source>Date</source> <translation>Zuva</translation> </message> <message> <source>Label</source> <translation>Zita</translation> </message> <message> <source>(no label)</source> <translation>(hapana zita)</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <source>(no label)</source> <translation>(hapana zita)</translation> </message> </context> <context> <name>SendCoinsEntry</name> </context> <context> <name>SendConfirmationDialog</name> </context> <context> <name>ShutdownWindow</name> </context> <context> <name>SignVerifyMessageDialog</name> </context> <context> <name>SplashScreen</name> </context> <context> <name>TrafficGraphWidget</name> </context> <context> <name>TransactionDesc</name> <message> <source>Date</source> <translation>Zuva</translation> </message> <message> <source>Amount</source> <translation>Marii </translation> </message> </context> <context> <name>TransactionDescDialog</name> </context> <context> <name>TransactionTableModel</name> <message> <source>Date</source> <translation>Zuva</translation> </message> <message> <source>Label</source> <translation>Zita</translation> </message> <message> <source>(no label)</source> <translation>(hapana zita)</translation> </message> </context> <context> <name>TransactionView</name> <message> <source>Date</source> <translation>Zuva</translation> </message> <message> <source>Label</source> <translation>Zita</translation> </message> <message> <source>Address</source> <translation>Kero</translation> </message> </context> <context> <name>UnitDisplayStatusBarControl</name> </context> <context> <name>WalletFrame</name> </context> <context> <name>WalletModel</name> </context> <context> <name>WalletView</name> </context> <context> <name>turbocoin-core</name> <message> <source>Information</source> <translation>Ruzivo</translation> </message> <message> <source>Warning</source> <translation>Hokoyo</translation> </message> </context> </TS>
Phonemetra/TurboCoin
src/qt/locale/turbocoin_sn.ts
TypeScript
mit
9,180
import threading import wx from styled_text_ctrl import StyledTextCtrl class ThreadOutputCtrl(StyledTextCtrl): def __init__(self, parent, env, auto_scroll=False): StyledTextCtrl.__init__(self, parent, env) self.auto_scroll = auto_scroll self.__lock = threading.Lock() self.__queue = [] self.__timer = wx.Timer(self) self.Bind(wx.EVT_TIMER, self.__OnTimer, self.__timer) def __OnTimer(self, evt): self.flush() def flush(self): with self.__lock: queue, self.__queue = self.__queue, [] lines = "".join(queue) if lines: with self.ModifyReadOnly(): self.AppendText(lines) self.EmptyUndoBuffer() if self.auto_scroll: self.ScrollToLine(self.GetLineCount() - 1) def start(self, interval=100): self.SetReadOnly(True) self.__timer.Start(interval) def stop(self): self.__timer.Stop() self.flush() self.SetReadOnly(False) def write(self, s): with self.__lock: self.__queue.append(s) def ClearAll(self): with self.ModifyReadOnly(): StyledTextCtrl.ClearAll(self) self.EmptyUndoBuffer()
shaurz/devo
thread_output_ctrl.py
Python
mit
1,266
# frozen_string_literal: true # encoding: utf-8 require 'mongoid/association/referenced/has_and_belongs_to_many/binding' require 'mongoid/association/referenced/has_and_belongs_to_many/buildable' require 'mongoid/association/referenced/has_and_belongs_to_many/proxy' require 'mongoid/association/referenced/has_and_belongs_to_many/eager' module Mongoid module Association module Referenced # The HasAndBelongsToMany type association. # # @since 7.0 class HasAndBelongsToMany include Relatable include Buildable # The options available for this type of association, in addition to the # common ones. # # @return [ Array<Symbol> ] The extra valid options. # # @since 7.0 ASSOCIATION_OPTIONS = [ :after_add, :after_remove, :autosave, :before_add, :before_remove, :counter_cache, :dependent, :foreign_key, :index, :order, :primary_key, :inverse_primary_key, :inverse_foreign_key, ].freeze # The complete list of valid options for this association, including # the shared ones. # # @return [ Array<Symbol> ] The valid options. # # @since 7.0 VALID_OPTIONS = (ASSOCIATION_OPTIONS + SHARED_OPTIONS).freeze # The type of the field holding the foreign key. # # @return [ Array ] # # @since 7.0 FOREIGN_KEY_FIELD_TYPE = Array # The default foreign key suffix. # # @return [ String ] '_ids' # # @since 7.0 FOREIGN_KEY_SUFFIX = '_ids'.freeze # The list of association complements. # # @return [ Array<Association> ] The association complements. # # @since 7.0 def relation_complements @relation_complements ||= [ self.class ].freeze end # Setup the instance methods, fields, etc. on the association owning class. # # @return [ self ] # # @since 7.0 def setup! setup_instance_methods! self end # Is this association type embedded? # # @return [ false ] Always false. # # @since 7.0 def embedded?; false; end # The default for validation the association object. # # @return [ false ] Always false. # # @since 7.0 def validation_default; true; end # Are ids only saved on this side of the association? # # @return [ true, false ] Whether this association has a forced nil inverse. # # @since 7.0 def forced_nil_inverse? @forced_nil_inverse ||= @options.key?(:inverse_of) && !@options[:inverse_of] end # Does this association type store the foreign key? # # @return [ true ] Always true. # # @since 7.0 def stores_foreign_key?; true; end # Get the association proxy class for this association type. # # @return [ Association::HasAndBelongsToMany::Proxy ] The proxy class. # # @since 7.0 def relation Proxy end # Get the foreign key field for saving the association reference. # # @return [ String ] The foreign key field for saving the association reference. # # @since 7.0 def foreign_key @foreign_key ||= @options[:foreign_key] ? @options[:foreign_key].to_s : default_foreign_key_field end # The criteria used for querying this association. # # @return [ Mongoid::Criteria ] The criteria used for querying this association. # # @since 7.0 def criteria(base, id_list = nil) query_criteria(id_list || base.send(foreign_key)) end # Get the foreign key field on the inverse. # # @return [ String ] The foreign key field for saving the association reference # on the inverse side. # # @since 7.0 def inverse_foreign_key if @options.key?(:inverse_foreign_key) @options[:inverse_foreign_key] elsif @options.key?(:inverse_of) inverse_of ? "#{inverse_of.to_s.singularize}#{FOREIGN_KEY_SUFFIX}" : nil else "#{inverse_class_name.demodulize.underscore}#{FOREIGN_KEY_SUFFIX}" end end # Whether trying to bind an object using this association should raise # an error. # # @param [ Document ] doc The document to be bound. # # @return [ true, false ] Whether the document can be bound. def bindable?(doc) forced_nil_inverse? || (!!inverse && doc.fields.keys.include?(foreign_key)) end # Get the foreign key setter on the inverse. # # @return [ String ] The foreign key setter for saving the association reference # on the inverse side. # # @since 7.0 def inverse_foreign_key_setter @inverse_foreign_key_setter ||= "#{inverse_foreign_key}=" if inverse_foreign_key end # The nested builder object. # # @param [ Hash ] attributes The attributes to use to build the association object. # @param [ Hash ] options The options for the association. # # @return [ Association::Nested::One ] The Nested Builder object. # # @since 7.0 def nested_builder(attributes, options) Nested::Many.new(self, attributes, options) end # Get the path calculator for the supplied document. # # @example Get the path calculator. # association.path(document) # # @param [ Document ] document The document to calculate on. # # @return [ Root ] The root atomic path calculator. # # @since 2.1.0 def path(document) Mongoid::Atomic::Paths::Root.new(document) end private def setup_instance_methods! define_getter! define_setter! define_dependency! define_existence_check! define_autosaver! define_counter_cache_callbacks! create_foreign_key_field! setup_index! setup_syncing! @owner_class.validates_associated(name) if validate? self end def index_spec { key => 1 } end def default_primary_key PRIMARY_KEY_DEFAULT end def default_foreign_key_field @default_foreign_key_field ||= "#{name.to_s.singularize}#{FOREIGN_KEY_SUFFIX}" end def setup_syncing! unless forced_nil_inverse? synced_save synced_destroy end end def synced_destroy assoc = self inverse_class.set_callback( :destroy, :after ) do |doc| doc.remove_inverse_keys(assoc) end end def synced_save assoc = self inverse_class.set_callback( :save, :after, if: ->(doc){ doc._syncable?(assoc) } ) do |doc| doc.update_inverse_keys(assoc) end end def create_foreign_key_field! @owner_class.field( foreign_key, type: FOREIGN_KEY_FIELD_TYPE, identity: true, overwrite: true, association: self, default: nil ) end def determine_inverses(other) matches = (other || relation_class).relations.values.select do |rel| relation_complements.include?(rel.class) && rel.relation_class_name == inverse_class_name end if matches.size > 1 raise Errors::AmbiguousRelationship.new(relation_class, @owner_class, name, matches) end matches.collect { |m| m.name } unless matches.blank? end def with_ordering(criteria) if order criteria.order_by(order) else criteria end end def query_criteria(id_list) crit = relation_class.all_of(primary_key => {"$in" => id_list || []}) with_ordering(crit) end end end end end
massayoshi/mongoid
lib/mongoid/association/referenced/has_and_belongs_to_many.rb
Ruby
mit
8,624
@extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-12"> <h2>All Bookings</h2> <hr> </div> <div class="col-md-2"> <a href="/bookings/create" class="btn btn-primary">Make New Booking</a> </div> <div class="col-md-10"> <div class="panel panel-info"> <div class="panel-heading">Bookings</div> <table class="table"> <tr> <th>id</th> <th>Customer name</th> <th>Departure Date</th> <th>Weight</th> <th>Quantities</th> <th>Actions</th> </tr> @foreach ($bookings as $booking) <tr> <td>{{ $booking->id }}</td> <td>{{ $booking->customer->name }}</td> <td>{{ $booking->schedule->departure_time->format('jS \\of F Y h:i:s A') }}</td> <td>{{ $booking->weight }}</td> <td>{{ $booking->quantity }}</td> <td> <a href="/bookings/{{ $booking->id }}/edit" class="btn btn-info btn-xs">Edit</a> <a href="/bookings/{{ $booking->id }}" class="btn btn-primary btn-xs">View Booking</a> <a href="/bookings/{{ $booking->id }}/edit" class="btn btn-danger btn-xs">Delete</a> </td> </tr> @endforeach </table> </div> </div> </div> </div> @endsection
xahy/container-management-system
resources/views/bookings/index.blade.php
PHP
mit
1,706
<?php namespace DCS\Form\PointFormFieldBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('dcs_form_point_form_field'); $rootNode ->children() ->scalarNode('parent') ->defaultValue('hidden') ->end() ->end(); return $treeBuilder; } }
damianociarla/DCSPointFormFieldBundle
DependencyInjection/Configuration.php
PHP
mit
890
<?php namespace AppBundle\Controller; use AppBundle\Entity\Comment; use AppBundle\Form\CommentType; use AppBundle\Form\ProjectType; use AppBundle\Entity\Message; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; class CommentController extends Controller{ public function listAction($id, $page) { $comments = $this->getDoctrine() ->getManager() ->getRepository('AppBundle:Comment') ->findAllCommentsEager($id); $project = $this->getDoctrine() ->getManager() ->getRepository('AppBundle:Project') ->findOneProjectEager($id); return $this->render('AppBundle:Project:layoutcomment.html.twig', array( 'comments' => $comments, 'project' => $project, 'page' => $page )); } public function addAction($id, $page, Request $req) { $user = $this->getUser(); $project = $this->getDoctrine() ->getManager() ->getRepository('AppBundle:Project') ->findOneProjectEager($id); //Chargement du formulaire Comment $comment = new Comment(); $form = $this->createForm(new CommentType(), $comment, array( 'action' => $this->generateUrl('filrouge_project_addComment', array( 'id' => $id, 'page' => $page )) . '#commentProject' )); $form->handleRequest($req); if($form->isValid()) { $comment->setProject($project); $em = $this->getDoctrine()->getManager(); if($comment->getId() === null) { $comment->setAuthor($user); $em->persist($comment); //Ecriture d'un Message pour annoncer un nouveau commentaire $content = ' a posté un commentaire sur votre projet '; $message = new Message(); $message->setSender($user) ->setRecipient($project->getProjectManager()) ->setContent($content) ->setProject($project) ->setType(1); $em->persist($message); } $em->flush(); //Renvoi de la requête soit sur la page project ou addormodifyproject... //Après validation du formulaire if($page == 'detail') { return $this->redirect( $this->generateUrl('filrouge_project_detail', array('id' => $id)) . '#commentProject' ); } elseif ($page == 'modify') { return $this->redirect( $this->generateUrl('filrouge_project_update', array('id' => $id)) . '#commentProject' ); } } //Renvoi de la requête soit sur la page project ou addormodifyproject if($page == 'detail') { return $this->render('AppBundle:Project:project.html.twig', array( 'project' => $project, 'commentForm' => $form->createView() )); } elseif ($page == 'modify') { $formProject = $this->createForm(new ProjectType(), $project, array( 'action' => $this->generateUrl('filrouge_project_update', array('id' => $id)) )); $modify = true; return $this->render('AppBundle:Project:addormodifyproject.html.twig', array( 'projectForm' => $formProject->createView(), 'project' => $project, 'commentForm' => $form->createView(), 'modify' => $modify )); } } public function updateAction($id, $idComment, $page, Request $req) { $comment = $this->getDoctrine() ->getManager() ->getRepository('AppBundle:Comment') ->findOneCommentEager($idComment); $project = $this->getDoctrine() ->getManager() ->getRepository('AppBundle:Project') ->findOneProjectEager($id); $em = $this->getDoctrine()->getManager(); if($comment === null) { throw $this->createNotFoundException('ID' . $idComment . ' impossible.'); } //Chargement du formulaire Comment $form = $this->createForm(new CommentType(), $comment, array( 'action' => $this->generateUrl('filrouge_project_updateComment', array( 'id' => $id, 'idComment' => $idComment, 'page' => $page )) . '#commentProject' )); //Validation du formulaire et modification du commentaire $form->handleRequest($req); if($form->isValid()) { $em = $this->getDoctrine()->getManager(); if($comment->getId() === null) { $em->persist($comment); } $em->flush(); //Renvoi de la requête soit sur la page project ou addormodifyproject... //Après validation du formulaire if($page == 'detail') { return $this->redirect( $this->generateUrl('filrouge_project_detail', array('id' => $id)) . '#commentProject' ); } elseif ($page == 'modify') { return $this->redirect( $this->generateUrl('filrouge_project_update', array('id' => $id)) . '#commentProject' ); } } //Renvoi de la requête soit sur la page project ou addormodifyproject if($page == 'detail') { return $this->render('AppBundle:Project:project.html.twig', array( 'project' => $project, 'commentForm' => $form->createView() )); } elseif ($page == 'modify') { $formProject = $this->createForm(new ProjectType(), $project, array( 'action' => $this->generateUrl('filrouge_project_update', array('id' => $id)) )); $modify = true; return $this->render('AppBundle:Project:addormodifyproject.html.twig', array( 'projectForm' => $formProject->createView(), 'project' => $project, 'commentForm' => $form->createView(), 'modify' => $modify )); } } public function removeAction($id, $idComment, $page, Request $req) { $comment = $this->getDoctrine() ->getManager() ->getRepository('AppBundle:Comment') ->findOneCommentEager($idComment); $project = $this->getDoctrine() ->getManager() ->getRepository('AppBundle:Project') ->findOneProjectEager($id); $em = $this->getDoctrine()->getManager(); if($comment === null) { throw $this->createNotFoundException('ID' . $idComment . ' impossible.'); } //Effacement du commentaire ciblé $em->remove($comment); $em->flush(); //Chargement du formulaire Commetn $newComment = new Comment(); $form = $this->createForm(new CommentType(), $newComment, array( 'action' => $this->generateUrl('filrouge_project_addComment', array( 'id' => $id, 'page' => $page )) . '#commentProject' )); //Renvoi de la requête soit sur la page project ou addormodifyproject if($page == 'detail') { return $this->render('AppBundle:Project:project.html.twig', array( 'project' => $project, 'commentForm' => $form->createView() )); } elseif ($page == 'modify') { $formProject = $this->createForm(new ProjectType(), $project, array( 'action' => $this->generateUrl('filrouge_project_update', array('id' => $id)) )); $modify = true; return $this->render('AppBundle:Project:addormodifyproject.html.twig', array( 'projectForm' => $formProject->createView(), 'project' => $project, 'commentForm' => $form->createView(), 'modify' => $modify )); } } }
benleneve/filrouge
src/AppBundle/Controller/CommentController.php
PHP
mit
8,967
import cgi from http.server import HTTPServer, BaseHTTPRequestHandler from database_setup import Base, Restaurant from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from test.restaurant_renderer import RestaurantRenderer engine = create_engine('sqlite:///restaurantmenu.db') Base.metadata.bind = engine DBSession = sessionmaker(bind=engine) session = DBSession() class WebServerHandler(BaseHTTPRequestHandler): def _find_restaurant(self): parsed_path = self.path.split('/') if not len(parsed_path) >= 3: print('Error 400:', parsed_path) self.send_error(400) self.end_headers() return None result = session.query(Restaurant).filter(Restaurant.id == parsed_path[-2]).first() if not result: print(result) print(parsed_path[-2]) self.send_error(404) self.end_headers() return None return result def do_GET(self): try: if self.path.endswith("/restaurants"): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() renderer = RestaurantRenderer(title='Restaurant List') renderer.generate_partial_body( preface="<h3><a href='restaurants/new'>Make a new restaurant</a></h3><br>\n") restaurants = session.query(Restaurant).all() page = renderer.generate_page(renderer.render_restaurants(restaurants)) self.wfile.write(page.encode()) if self.path.endswith("/restaurants/new"): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() renderer = RestaurantRenderer(title='New Restaurant Creator') renderer.generate_partial_body(preface='<H1>Make a new Restaurant</h1><br>\n') form_code = '<input name="restaurant" type="text" placeHolder="New Restaurant Name"><input type="submit" value="Create" > ' page = renderer.generate_page(renderer.render_simple_form(form_code, action='/restaurants/new')) self.wfile.write(page.encode()) if self.path.endswith("/edit"): restaurant = self._find_restaurant() if not restaurant: return renderer = RestaurantRenderer(title='Modify ' + restaurant.name) renderer.generate_partial_body(preface='<h2>' + restaurant.name + '</h2>') form_code = '<input name="edit" type="text" placeHolder="' + restaurant.name + '"><input type="submit" value="Rename" > ' page = renderer.generate_page( renderer.render_simple_form(form_code, action='/restaurants/' + str(restaurant.id) + '/edit')) self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() self.wfile.write(page.encode()) if self.path.endswith("/delete"): restaurant = self._find_restaurant() if not restaurant: return renderer = RestaurantRenderer(title='Remove ' + restaurant.name) renderer.generate_partial_body( preface='<h2>Are you sure you wish to remove {}<h/2>'.format(restaurant.name)) submit_code = '<input type="submit" value="Delete">\n' page = renderer.generate_page( renderer.render_simple_form(submit_code, action='/restaurants/' + str(restaurant.id) + '/delete')) self.wfile.write(page.encode()) if self.path.endswith("/whoareyou"): self.send_error(418, message="I am a teapot, running on the Hyper Text Coffee Pot Control Protocol") self.end_headers() except IOError: self.send_error(404, "File Not Found {}".format(self.path)) def do_POST(self): try: # HEADERS are now in dict/json style container ctype, pdict = cgi.parse_header( self.headers['content-type']) # boundary data needs to be encoded in a binary format pdict['boundary'] = bytes(pdict['boundary'], "utf-8") if self.path.endswith("/restaurants/new"): if ctype == 'multipart/form-data': fields = cgi.parse_multipart(self.rfile, pdict) messagecontent = fields.get('restaurant') session.add(Restaurant(name=messagecontent[0].decode())) session.commit() self.send_response(302) self.send_header('Content-type', 'text/html') self.send_header('Location', '/restaurants') self.send_response(201) self.end_headers() if self.path.endswith("/edit"): if ctype == 'multipart/form-data': fields = cgi.parse_multipart(self.rfile, pdict) messagecontent = fields.get('edit') restaurant = self._find_restaurant() if not restaurant: return restaurant.name = messagecontent[0].decode() session.commit() self.send_response(302) self.send_header('Content-type', 'text/html') self.send_header('Location', '/restaurants') self.send_response(202) self.end_headers() if self.path.endswith('/delete'): restaurant = self._find_restaurant() if not restaurant: return session.delete(restaurant) session.commit() self.send_response(302) self.send_header('Content-type', 'text/html') self.send_header('Location', '/restaurants') self.send_response(204) self.end_headers() except: raise def main(): try: port = 8080 server = HTTPServer(('', port), WebServerHandler) print("Web server is running on port {}".format(port)) server.serve_forever() except KeyboardInterrupt: print("^C entered, stopping web server...") finally: if server: server.socket.close() if __name__ == '__main__': main()
MFry/pyItemCatalog
vagrant/itemCatalog/test/webserver.py
Python
mit
6,549
class Organizer < ActiveRecord::Base devise :all end
bitfluent/wheneva
vendor/plugins/devise/test/rails_app/app/models/organizer.rb
Ruby
mit
55
class ChangeStatusOnTeamUserShips < ActiveRecord::Migration[5.0] def change change_column :team_user_ships, :status, :integer, :using => 'case when status then 1 else 0 end' end end
ShowingCloud/Cancri
db/migrate/20170209083632_change_status_on_team_user_ships.rb
Ruby
mit
190
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace ExemploCRUD { static class Program { /// <summary> /// Ponto de entrada principal para o aplicativo. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FrmCadastroAluno()); } } }
SaviHex/TP_BD2
Consulta/TP_CRUD/Exemplo_CRUD/ExemploCRUD/ExemploCRUD/Program.cs
C#
mit
549
require 'spec_helper' describe Saml::Elements::EntitiesDescriptor do let(:entities_descriptor) { FactoryBot.build(:entities_descriptor) } describe "Optional fields" do [:name, :valid_until, :cache_duration, :signature].each do |field| it "should have the #{field} field" do expect(entities_descriptor).to respond_to(field) end it "should allow #{field} to be blank" do entities_descriptor.send("#{field}=", nil) expect(entities_descriptor).to be_valid end end describe "#cache_duration" do let(:xml) { File.read('spec/fixtures/provider_with_cache_duration.xml') } it "casts the cache_duration to a String" do expect(subject.parse(xml, single: true).cache_duration).to be_a String end end end describe "Required fields" do context "#entities_descriptors" do context "when there are no entity_descriptors" do before do entities_descriptor.entity_descriptors = [] end it "should have at least one entities_descriptor" do expect(entities_descriptor.entities_descriptors).to have_at_least(1).item end it "should allow entity_descriptors to be blank" do expect(entities_descriptor).to be_valid end end end context "#entity_descriptors" do context "when there are no entities_descriptors" do before do entities_descriptor.entities_descriptors = [] end it "should have at least one entity_descriptor" do expect(entities_descriptor.entity_descriptors).to have_at_least(1).item end it "should allow entities_descriptors to be blank" do expect(entities_descriptor).to be_valid end end end context "when there are no entities_descriptors or entity_descriptors" do it "should not be valid" do entities_descriptor.entities_descriptors = [] entities_descriptor.entity_descriptors = [] expect(entities_descriptor).not_to be_valid end end end describe "#add_signature" do it "adds a signature element to the entities descriptor" do entities_descriptor.add_signature parsed_entities_descriptor = described_class.parse(entities_descriptor.to_xml, single: true) expect(parsed_entities_descriptor.signature).to be_a(Saml::Elements::Signature) end end end
digidentity/libsaml
spec/lib/saml/elements/entities_descriptor_spec.rb
Ruby
mit
2,423
package main import ( "os/user" "fmt" "github.com/bestform/monkey/repl" "os" ) func main() { activeUser, err := user.Current() if err != nil { panic(err) } fmt.Printf("Hello %s! This is the Monkey programming language!\n", activeUser.Username) fmt.Println("Feel free to type in commands") repl.Start(os.Stdin, os.Stdout) }
bestform/monkey
main.go
GO
mit
375
<?php class Laporan1111a1Controller extends \BaseController { /** * konstruktor */ public function __construct() { $this->beforeFilter('auth'); } /** * data faktur laporan 1111b3 * * @return View */ public function index() { } /** * export ke pdf * * @return */ public function pdf() { // data $faktur = Laporan1111a1ku::all(); $totalpenjualan = DB::table('penjualanfakturlengkaps')->sum('penjualan'); $totalppn = DB::table('penjualanfakturlengkaps')->sum('ppn'); return View::make('pdf.laporan1111a1', compact('faktur')) ->with('faktur',$faktur) ->with('totalpenjualan', $totalpenjualan) ->with('totalppn', $totalppn); } }
risatya/smartlogicpro
app/controllers/Laporan1111a1Controller.php
PHP
mit
725
<?php namespace Letim\SecureBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class LetimSecureExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); } }
WoolTeam/letim
src/Letim/SecureBundle/DependencyInjection/LetimSecureExtension.php
PHP
mit
881
<?php session_start(); require_once '../../vendor/autoload.php'; use Emall\Transaction\Bank; use Emall\Auth\Redirect; $seller = new Bank; $home_url = '../../index.php'; if (isset($_POST['seller_bankID'])) { $seller_bankID = $_POST['seller_bankID']; $seller->EditDataBank($seller_bankID); } else { Redirect::to($home_url); // for direct acces to this file }
rezawikan/skripsi
seller/function/Bank/EditDataBank.php
PHP
mit
390
require 'rails_helper' describe WriMetadata::Source, type: :model do it 'should be invalid when name not present' do expect( FactoryBot.build(:wri_metadata_source, name: nil) ).to have(1).errors_on(:name) end end
Vizzuality/climate-watch
spec/models/wri_metadata/source_spec.rb
Ruby
mit
232
# -*- coding: utf-8 -*- from .store import Store from ..tagged_cache import TaggedCache from ..tag_set import TagSet class TaggableStore(Store): def tags(self, *names): """ Begin executing a new tags operation. :param names: The tags :type names: tuple :rtype: cachy.tagged_cache.TaggedCache """ if len(names) == 1 and isinstance(names[0], list): names = names[0] return TaggedCache(self, TagSet(self, names))
sdispater/cachy
cachy/contracts/taggable_store.py
Python
mit
497
# -*- encoding : utf-8 -*- class Top4R::Client include Top4R::ClassUtilMixin @@no_login_required_methods = { :user => { :info => 'taobao.user.get', :multi_info => 'taobao.users.get' }, :trade => {}, :area => { :list => 'taobao.areas.get' }, :logistic_company => { :list => 'taobao.logistics.companies.get' }, :shop => { :cats_list => 'taobao.sellercats.list.get', :shop_info => 'taobao.shop.get' }, :item => { :items_list => 'taobao.items.list.get', :item => 'taobao.item.get' }, :taobaoke_item => { :taobaoke_items_get => 'taobao.taobaoke.items.get' } } end require 'top4r/client/base' require 'top4r/client/user' require 'top4r/client/shipping' require 'top4r/client/trade' require 'top4r/client/suite' require 'top4r/client/item' require 'top4r/client/shop' require 'top4r/client/taobaokeitem'
biti/top4r
lib/top4r/client.rb
Ruby
mit
920
/** @module ember-ui-components */ import Component from '@ember/component'; import ClickOutsideMixin from 'ember-ui-components/mixins/click-outside'; import layout from '../templates/components/uic-context-menu-container'; import setPosition from 'ember-ui-components/utils/set-position'; import getMousePosition from 'ember-ui-components/utils/get-mouse-position'; import { get } from '@ember/object'; import { alias } from '@ember/object/computed'; import { inject as service } from '@ember/service'; /** @class ContextMenuContainerComponent @namespace Components */ export default Component.extend(ClickOutsideMixin, { layout, /** Injected `contextMenu` service @property contextMenuService @type {Object} @private */ contextMenuService: service('context-menu'), /** @property tagName @type {String} @private @default 'menu' */ tagName: 'menu', /** @property classNames @type {Array} @private @default `['uic-context-menu-container', 'uic-menu-container']` */ classNames: ['uic-context-menu-container', 'uic-menu-container'], /** @property classNameBindings @type {Array} @private @default `['hideOutline:no-outline']` */ classNameBindings: ['hideOutline:no-outline'], /** @property attributeBindings @type {Array} @private @default `['tabindex']` */ attributeBindings: ['tabindex'], /** @property tabindex @type {Integer} @private @default `1` */ tabindex: 1, /** If this property is true the element will be given the `no-outline` css class which will hide the outline that an element is given when it is focused. @property hideOutline @type {Boolean} @private @default `true` */ hideOutline: true, /** @property contextMenuParams @type {Object} @private */ contextMenuParams: alias('contextMenuService.contextMenuParams'), /** ## setPosition Set the left/top css properties of an element. `element` should be a reference to an HTML element. Either a string selector that can be used with jQuery, or a jQuery selection object. If `position` is not specified, then the current mouse position will be used. `position` should be an Ember.Object with `x` and `y` properties. Both `x` and `y` should be numbers @method setPosition @param {String|Object} element @param {Object} position */ setPosition, /** @method handleClickOutside @private */ handleClickOutside() { get(this, 'closeContextMenu')(); }, /** @method didInsertElement @private */ didInsertElement() { this._super(...arguments); this.setPosition(this.$(), getMousePosition(this.get('contextMenuParams.event'))); this.$().focus(); }, /** @event keyDown @param {Object} event @private */ keyDown(event) { switch(event.keyCode) { case 13: // enter get(this, 'closeContextMenu')(); break; case 27: // escape get(this, 'closeContextMenu')(); break; } }, click() { get(this, 'closeContextMenu')(); } });
lozjackson/ember-ui-components
addon/components/uic-context-menu-container.js
JavaScript
mit
3,147
from pandac.PandaModules import * from toontown.toonbase.ToonBaseGlobal import * from direct.directnotify import DirectNotifyGlobal from direct.fsm import StateData from direct.showbase.PythonUtil import PriorityCallbacks from toontown.safezone import PublicWalk from toontown.launcher import DownloadForceAcknowledge import TrialerForceAcknowledge import ZoneUtil from toontown.friends import FriendsListManager from toontown.toonbase import ToontownGlobals from toontown.toon.Toon import teleportDebug from toontown.estate import HouseGlobals from toontown.toonbase import TTLocalizer from otp.otpbase import OTPLocalizer from otp.avatar import Emote from otp.avatar.Avatar import teleportNotify from direct.task import Task import QuietZoneState from toontown.distributed import ToontownDistrictStats class Place(StateData.StateData, FriendsListManager.FriendsListManager): notify = DirectNotifyGlobal.directNotify.newCategory('Place') def __init__(self, loader, doneEvent): StateData.StateData.__init__(self, doneEvent) FriendsListManager.FriendsListManager.__init__(self) self.loader = loader self.dfaDoneEvent = 'dfaDoneEvent' self.trialerFADoneEvent = 'trialerFADoneEvent' self.zoneId = None self.trialerFA = None self._tiToken = None self._leftQuietZoneLocalCallbacks = PriorityCallbacks() self._leftQuietZoneSubframeCall = None self._setZoneCompleteLocalCallbacks = PriorityCallbacks() self._setZoneCompleteSubframeCall = None return def load(self): StateData.StateData.load(self) FriendsListManager.FriendsListManager.load(self) self.walkDoneEvent = 'walkDone' self.walkStateData = PublicWalk.PublicWalk(self.fsm, self.walkDoneEvent) self.walkStateData.load() self._tempFSM = self.fsm def unload(self): StateData.StateData.unload(self) FriendsListManager.FriendsListManager.unload(self) self.notify.info('Unloading Place (%s). Fsm in %s' % (self.zoneId, self._tempFSM.getCurrentState().getName())) if self._leftQuietZoneSubframeCall: self._leftQuietZoneSubframeCall.cleanup() self._leftQuietZoneSubframeCall = None if self._setZoneCompleteSubframeCall: self._setZoneCompleteSubframeCall.cleanup() self._setZoneCompleteSubframeCall = None self._leftQuietZoneLocalCallbacks = None self._setZoneCompleteLocalCallbacks = None del self._tempFSM taskMgr.remove('goHomeFailed') del self.walkDoneEvent self.walkStateData.unload() del self.walkStateData del self.loader if self.trialerFA: self.trialerFA.exit() del self.trialerFA return def _getQZState(self): if hasattr(base, 'cr') and hasattr(base.cr, 'playGame'): if hasattr(base.cr.playGame, 'quietZoneStateData') and base.cr.playGame.quietZoneStateData: return base.cr.playGame.quietZoneStateData return None def addLeftQuietZoneCallback(self, callback, priority = None): qzsd = self._getQZState() if qzsd: return qzsd.addLeftQuietZoneCallback(callback, priority) else: token = self._leftQuietZoneLocalCallbacks.add(callback, priority=priority) if not self._leftQuietZoneSubframeCall: self._leftQuietZoneSubframeCall = SubframeCall(self._doLeftQuietZoneCallbacks, taskMgr.getCurrentTask().getPriority() - 1) return token def removeLeftQuietZoneCallback(self, token): if token is not None: if token in self._leftQuietZoneLocalCallbacks: self._leftQuietZoneLocalCallbacks.remove(token) qzsd = self._getQZState() if qzsd: qzsd.removeLeftQuietZoneCallback(token) return def _doLeftQuietZoneCallbacks(self): self._leftQuietZoneLocalCallbacks() self._leftQuietZoneLocalCallbacks.clear() self._leftQuietZoneSubframeCall = None return def addSetZoneCompleteCallback(self, callback, priority = None): qzsd = self._getQZState() if qzsd: return qzsd.addSetZoneCompleteCallback(callback, priority) else: token = self._setZoneCompleteLocalCallbacks.add(callback, priority=priority) if not self._setZoneCompleteSubframeCall: self._setZoneCompleteSubframeCall = SubframeCall(self._doSetZoneCompleteLocalCallbacks, taskMgr.getCurrentTask().getPriority() - 1) return token def removeSetZoneCompleteCallback(self, token): if token is not None: if token in self._setZoneCompleteLocalCallbacks: self._setZoneCompleteLocalCallbacks.remove(token) qzsd = self._getQZState() if qzsd: qzsd.removeSetZoneCompleteCallback(token) return def _doSetZoneCompleteLocalCallbacks(self): self._setZoneCompleteSubframeCall = None localCallbacks = self._setZoneCompleteLocalCallbacks self._setZoneCompleteLocalCallbacks() localCallbacks.clear() return def setState(self, state): if hasattr(self, 'fsm'): curState = self.fsm.getName() if state == 'pet' or curState == 'pet': self.preserveFriendsList() self.fsm.request(state) def getState(self): if hasattr(self, 'fsm'): curState = self.fsm.getCurrentState().getName() return curState def getZoneId(self): return self.zoneId def getTaskZoneId(self): return self.getZoneId() def isPeriodTimerEffective(self): return 1 def handleTeleportQuery(self, fromAvatar, toAvatar): if base.config.GetBool('want-tptrack', False): if toAvatar == localAvatar: toAvatar.doTeleportResponse(fromAvatar, toAvatar, toAvatar.doId, 1, toAvatar.defaultShard, base.cr.playGame.getPlaceId(), self.getZoneId(), fromAvatar.doId) else: self.notify.warning('handleTeleportQuery toAvatar.doId != localAvatar.doId' % (toAvatar.doId, localAvatar.doId)) else: fromAvatar.d_teleportResponse(toAvatar.doId, 1, toAvatar.defaultShard, base.cr.playGame.getPlaceId(), self.getZoneId()) def enablePeriodTimer(self): if self.isPeriodTimerEffective(): if base.cr.periodTimerExpired: taskMgr.doMethodLater(5, self.redoPeriodTimer, 'redoPeriodTimer') self.accept('periodTimerExpired', self.periodTimerExpired) def disablePeriodTimer(self): taskMgr.remove('redoPeriodTimer') self.ignore('periodTimerExpired') def redoPeriodTimer(self, task): messenger.send('periodTimerExpired') return Task.done def periodTimerExpired(self): self.fsm.request('final') if base.localAvatar.book.isEntered: base.localAvatar.book.exit() base.localAvatar.b_setAnimState('CloseBook', 1, callback=self.__handlePeriodTimerBookClose) else: base.localAvatar.b_setAnimState('TeleportOut', 1, self.__handlePeriodTimerExitTeleport) def exitPeriodTimerExpired(self): pass def __handlePeriodTimerBookClose(self): base.localAvatar.b_setAnimState('TeleportOut', 1, self.__handlePeriodTimerExitTeleport) def __handlePeriodTimerExitTeleport(self): base.cr.loginFSM.request('periodTimeout') def detectedPhoneCollision(self): self.fsm.request('phone') def detectedFishingCollision(self): self.fsm.request('fishing') def enterStart(self): pass def exitStart(self): pass def enterFinal(self): pass def exitFinal(self): pass def enterWalk(self, teleportIn = 0): self.enterFLM() self.walkStateData.enter() if teleportIn == 0: self.walkStateData.fsm.request('walking') self.acceptOnce(self.walkDoneEvent, self.handleWalkDone) if base.cr.productName in ['DisneyOnline-US', 'ES'] and not base.cr.isPaid() and base.localAvatar.tutorialAck: base.localAvatar.chatMgr.obscure(0, 0) base.localAvatar.chatMgr.normalButton.show() self.accept('teleportQuery', self.handleTeleportQuery) base.localAvatar.setTeleportAvailable(1) base.localAvatar.questPage.acceptOnscreenHooks() base.localAvatar.invPage.acceptOnscreenHooks() base.localAvatar.questMap.acceptOnscreenHooks() self.walkStateData.fsm.request('walking') self.enablePeriodTimer() def exitWalk(self): self.exitFLM() if base.cr.productName in ['DisneyOnline-US', 'ES'] and not base.cr.isPaid() and base.localAvatar.tutorialAck and not base.cr.whiteListChatEnabled: base.localAvatar.chatMgr.obscure(1, 0) self.disablePeriodTimer() messenger.send('wakeup') self.walkStateData.exit() self.ignore(self.walkDoneEvent) base.localAvatar.setTeleportAvailable(0) self.ignore('teleportQuery') if base.cr.playGame.hood != None: base.cr.playGame.hood.hideTitleText() base.localAvatar.questPage.hideQuestsOnscreen() base.localAvatar.questPage.ignoreOnscreenHooks() base.localAvatar.invPage.ignoreOnscreenHooks() base.localAvatar.invPage.hideInventoryOnscreen() base.localAvatar.questMap.hide() base.localAvatar.questMap.ignoreOnscreenHooks() return def handleWalkDone(self, doneStatus): mode = doneStatus['mode'] if mode == 'StickerBook': self.last = self.fsm.getCurrentState().getName() self.fsm.request('stickerBook') elif mode == 'Options': self.last = self.fsm.getCurrentState().getName() self.fsm.request('stickerBook', [base.localAvatar.optionsPage]) elif mode == 'Sit': self.last = self.fsm.getCurrentState().getName() self.fsm.request('sit') else: Place.notify.error('Invalid mode: %s' % mode) def enterSit(self): self.enterFLM() base.localAvatar.laffMeter.start() self.accept('teleportQuery', self.handleTeleportQuery) base.localAvatar.setTeleportAvailable(1) base.localAvatar.b_setAnimState('SitStart', 1) self.accept('arrow_up', self.fsm.request, extraArgs=['walk']) def exitSit(self): self.exitFLM() base.localAvatar.laffMeter.stop() base.localAvatar.setTeleportAvailable(0) self.ignore('teleportQuery') self.ignore('arrow_up') def enterDrive(self): self.enterFLM() base.localAvatar.laffMeter.start() self.accept('teleportQuery', self.handleTeleportQuery) base.localAvatar.setTeleportAvailable(1) base.localAvatar.b_setAnimState('SitStart', 1) def exitDrive(self): self.exitFLM() base.localAvatar.laffMeter.stop() base.localAvatar.setTeleportAvailable(0) self.ignore('teleportQuery') def enterPush(self): self.enterFLM() base.localAvatar.laffMeter.start() self.accept('teleportQuery', self.handleTeleportQuery) base.localAvatar.setTeleportAvailable(1) base.localAvatar.attachCamera() base.localAvatar.startUpdateSmartCamera() base.localAvatar.startPosHprBroadcast() base.localAvatar.b_setAnimState('Push', 1) def exitPush(self): self.exitFLM() base.localAvatar.laffMeter.stop() base.localAvatar.setTeleportAvailable(0) base.localAvatar.stopUpdateSmartCamera() base.localAvatar.detachCamera() base.localAvatar.stopPosHprBroadcast() self.ignore('teleportQuery') def enterStickerBook(self, page = None): self.enterFLM() base.localAvatar.laffMeter.start() target = base.cr.doFind('DistributedTarget') if target: target.hideGui() self.accept('teleportQuery', self.handleTeleportQuery) base.localAvatar.setTeleportAvailable(1) if page: base.localAvatar.book.setPage(page) base.localAvatar.b_setAnimState('OpenBook', 1, self.enterStickerBookGUI) base.localAvatar.obscureMoveFurnitureButton(1) def enterStickerBookGUI(self): base.localAvatar.collisionsOn() base.localAvatar.book.showButton() base.localAvatar.book.enter() base.localAvatar.setGuiConflict(1) base.localAvatar.startSleepWatch(self.__handleFallingAsleep) self.accept('bookDone', self.__handleBook) base.localAvatar.b_setAnimState('ReadBook', 1) self.enablePeriodTimer() def __handleFallingAsleep(self, task): base.localAvatar.book.exit() base.localAvatar.b_setAnimState('CloseBook', 1, callback=self.__handleFallingAsleepBookClose) return Task.done def __handleFallingAsleepBookClose(self): if hasattr(self, 'fsm'): self.fsm.request('walk') base.localAvatar.forceGotoSleep() def exitStickerBook(self): base.localAvatar.stopSleepWatch() self.disablePeriodTimer() self.exitFLM() base.localAvatar.laffMeter.stop() base.localAvatar.setGuiConflict(0) base.localAvatar.book.exit() base.localAvatar.book.hideButton() base.localAvatar.collisionsOff() self.ignore('bookDone') base.localAvatar.setTeleportAvailable(0) self.ignore('teleportQuery') base.localAvatar.obscureMoveFurnitureButton(-1) target = base.cr.doFind('DistributedTarget') if target: target.showGui() def __handleBook(self): base.localAvatar.stopSleepWatch() base.localAvatar.book.exit() bookStatus = base.localAvatar.book.getDoneStatus() if bookStatus['mode'] == 'close': base.localAvatar.b_setAnimState('CloseBook', 1, callback=self.handleBookClose) elif bookStatus['mode'] == 'teleport': zoneId = bookStatus['hood'] base.localAvatar.collisionsOff() base.localAvatar.b_setAnimState('CloseBook', 1, callback=self.handleBookCloseTeleport, extraArgs=[zoneId, zoneId]) elif bookStatus['mode'] == 'exit': self.exitTo = bookStatus.get('exitTo') base.localAvatar.collisionsOff() base.localAvatar.b_setAnimState('CloseBook', 1, callback=self.__handleBookCloseExit) elif bookStatus['mode'] == 'gohome': zoneId = bookStatus['hood'] base.localAvatar.collisionsOff() base.localAvatar.b_setAnimState('CloseBook', 1, callback=self.goHomeNow, extraArgs=[zoneId]) elif bookStatus['mode'] == 'startparty': firstStart = bookStatus['firstStart'] hostId = bookStatus['hostId'] base.localAvatar.collisionsOff() base.localAvatar.b_setAnimState('CloseBook', 1, callback=self.startPartyNow, extraArgs=[firstStart, hostId]) def handleBookCloseTeleport(self, hoodId, zoneId): if localAvatar.hasActiveBoardingGroup(): rejectText = TTLocalizer.BoardingCannotLeaveZone localAvatar.elevatorNotifier.showMe(rejectText) return self.requestLeave({'loader': ZoneUtil.getBranchLoaderName(zoneId), 'where': ZoneUtil.getToonWhereName(zoneId), 'how': 'teleportIn', 'hoodId': hoodId, 'zoneId': zoneId, 'shardId': None, 'avId': -1}) return def __handleBookCloseExit(self): base.localAvatar.b_setAnimState('TeleportOut', 1, self.__handleBookExitTeleport, [0]) def __handleBookExitTeleport(self, requestStatus): if base.cr.timeManager: base.cr.timeManager.setDisconnectReason(ToontownGlobals.DisconnectBookExit) base.transitions.fadeScreen(1.0) base.cr.gameFSM.request(self.exitTo) def goHomeNow(self, curZoneId): if localAvatar.hasActiveBoardingGroup(): rejectText = TTLocalizer.BoardingCannotLeaveZone localAvatar.elevatorNotifier.showMe(rejectText) return hoodId = ToontownGlobals.MyEstate self.requestLeave({'loader': 'safeZoneLoader', 'where': 'estate', 'how': 'teleportIn', 'hoodId': hoodId, 'zoneId': -1, 'shardId': None, 'avId': -1}) return def startPartyNow(self, firstStart, hostId): if localAvatar.hasActiveBoardingGroup(): rejectText = TTLocalizer.BoardingCannotLeaveZone localAvatar.elevatorNotifier.showMe(rejectText) return base.localAvatar.creatingNewPartyWithMagicWord = False base.localAvatar.aboutToPlanParty = False hoodId = ToontownGlobals.PartyHood if firstStart: zoneId = 0 ToontownDistrictStats.refresh('shardInfoUpdated') curShardTuples = base.cr.listActiveShards() lowestPop = 100000000000000000L shardId = None for shardInfo in curShardTuples: pop = shardInfo[2] if pop < lowestPop: lowestPop = pop shardId = shardInfo[0] if shardId == base.localAvatar.defaultShard: shardId = None base.cr.playGame.getPlace().requestLeave({'loader': 'safeZoneLoader', 'where': 'party', 'how': 'teleportIn', 'hoodId': hoodId, 'zoneId': zoneId, 'shardId': shardId, 'avId': -1}) else: if hostId is None: hostId = base.localAvatar.doId base.cr.partyManager.sendAvatarToParty(hostId) return return def handleBookClose(self): if hasattr(self, 'fsm'): self.fsm.request('walk') if hasattr(self, 'toonSubmerged') and self.toonSubmerged == 1: if hasattr(self, 'walkStateData'): self.walkStateData.fsm.request('swimming', [self.loader.swimSound]) def requestLeave(self, requestStatus): teleportDebug(requestStatus, 'requestLeave(%s)' % (requestStatus,)) if hasattr(self, 'fsm'): self.doRequestLeave(requestStatus) def doRequestLeave(self, requestStatus): teleportDebug(requestStatus, 'requestLeave(%s)' % (requestStatus,)) self.fsm.request('DFA', [requestStatus]) def enterDFA(self, requestStatus): teleportDebug(requestStatus, 'enterDFA(%s)' % (requestStatus,)) self.acceptOnce(self.dfaDoneEvent, self.enterDFACallback, [requestStatus]) self.dfa = DownloadForceAcknowledge.DownloadForceAcknowledge(self.dfaDoneEvent) self.dfa.enter(base.cr.hoodMgr.getPhaseFromHood(requestStatus['hoodId'])) def exitDFA(self): self.ignore(self.dfaDoneEvent) def handleEnterTunnel(self, requestStatus, collEntry): if localAvatar.hasActiveBoardingGroup(): rejectText = TTLocalizer.BoardingCannotLeaveZone localAvatar.elevatorNotifier.showMe(rejectText) dummyNP = NodePath('dummyNP') dummyNP.reparentTo(render) tunnelOrigin = requestStatus['tunnelOrigin'] dummyNP.setPos(localAvatar.getPos()) dummyNP.setH(tunnelOrigin.getH()) dummyNP.setPos(dummyNP, 0, 4, 0) localAvatar.setPos(dummyNP.getPos()) dummyNP.removeNode() del dummyNP return self.requestLeave(requestStatus) def enterDFACallback(self, requestStatus, doneStatus): teleportDebug(requestStatus, 'enterDFACallback%s' % ((requestStatus, doneStatus),)) self.dfa.exit() del self.dfa if doneStatus['mode'] == 'complete': if requestStatus.get('tutorial', 0): out = {'teleportIn': 'tunnelOut'} requestStatus['zoneId'] = 22000 requestStatus['hoodId'] = 22000 else: out = {'teleportIn': 'teleportOut', 'tunnelIn': 'tunnelOut', 'doorIn': 'doorOut'} teleportDebug(requestStatus, 'requesting %s, requestStatus=%s' % (out[requestStatus['how']], requestStatus)) self.fsm.request(out[requestStatus['how']], [requestStatus]) elif doneStatus['mode'] == 'incomplete': self.fsm.request('DFAReject') else: Place.notify.error('Unknown done status for DownloadForceAcknowledge: ' + `doneStatus`) def enterDFAReject(self): self.fsm.request('walk') def exitDFAReject(self): pass def enterTrialerFA(self, requestStatus): teleportDebug(requestStatus, 'enterTrialerFA(%s)' % requestStatus) self.acceptOnce(self.trialerFADoneEvent, self.trialerFACallback, [requestStatus]) self.trialerFA = TrialerForceAcknowledge.TrialerForceAcknowledge(self.trialerFADoneEvent) self.trialerFA.enter(requestStatus['hoodId']) def exitTrialerFA(self): pass def trialerFACallback(self, requestStatus, doneStatus): if doneStatus['mode'] == 'pass': self.fsm.request('DFA', [requestStatus]) elif doneStatus['mode'] == 'fail': self.fsm.request('trialerFAReject') else: Place.notify.error('Unknown done status for TrialerForceAcknowledge: %s' % doneStatus) def enterTrialerFAReject(self): self.fsm.request('walk') def exitTrialerFAReject(self): pass def enterDoorIn(self, requestStatus): NametagGlobals.setMasterArrowsOn(0) door = base.cr.doId2do.get(requestStatus['doorDoId']) door.readyToExit() base.localAvatar.obscureMoveFurnitureButton(1) base.localAvatar.startQuestMap() def exitDoorIn(self): NametagGlobals.setMasterArrowsOn(1) base.localAvatar.obscureMoveFurnitureButton(-1) def enterDoorOut(self): base.localAvatar.obscureMoveFurnitureButton(1) def exitDoorOut(self): base.localAvatar.obscureMoveFurnitureButton(-1) base.localAvatar.stopQuestMap() def handleDoorDoneEvent(self, requestStatus): self.doneStatus = requestStatus messenger.send(self.doneEvent) def handleDoorTrigger(self): self.fsm.request('doorOut') def enterTunnelIn(self, requestStatus): self.notify.debug('enterTunnelIn(requestStatus=' + str(requestStatus) + ')') tunnelOrigin = base.render.find(requestStatus['tunnelName']) self.accept('tunnelInMovieDone', self.__tunnelInMovieDone) base.localAvatar.reconsiderCheesyEffect() base.localAvatar.tunnelIn(tunnelOrigin) base.localAvatar.startQuestMap() def __tunnelInMovieDone(self): self.ignore('tunnelInMovieDone') self.fsm.request('walk') def exitTunnelIn(self): pass def enterTunnelOut(self, requestStatus): hoodId = requestStatus['hoodId'] zoneId = requestStatus['zoneId'] how = requestStatus['how'] tunnelOrigin = requestStatus['tunnelOrigin'] fromZoneId = ZoneUtil.getCanonicalZoneId(self.getZoneId()) tunnelName = requestStatus.get('tunnelName') if tunnelName == None: tunnelName = base.cr.hoodMgr.makeLinkTunnelName(self.loader.hood.id, fromZoneId) self.doneStatus = {'loader': ZoneUtil.getLoaderName(zoneId), 'where': ZoneUtil.getToonWhereName(zoneId), 'how': how, 'hoodId': hoodId, 'zoneId': zoneId, 'shardId': None, 'tunnelName': tunnelName} self.accept('tunnelOutMovieDone', self.__tunnelOutMovieDone) base.localAvatar.tunnelOut(tunnelOrigin) base.localAvatar.stopQuestMap() return def __tunnelOutMovieDone(self): self.ignore('tunnelOutMovieDone') messenger.send(self.doneEvent) def exitTunnelOut(self): pass def enterTeleportOut(self, requestStatus, callback): base.localAvatar.laffMeter.start() base.localAvatar.b_setAnimState('TeleportOut', 1, callback, [requestStatus]) base.localAvatar.obscureMoveFurnitureButton(1) def exitTeleportOut(self): base.localAvatar.laffMeter.stop() base.localAvatar.stopQuestMap() base.localAvatar.obscureMoveFurnitureButton(-1) def enterDied(self, requestStatus, callback = None): if callback == None: callback = self.__diedDone base.localAvatar.laffMeter.start() camera.wrtReparentTo(render) base.localAvatar.b_setAnimState('Died', 1, callback, [requestStatus]) base.localAvatar.obscureMoveFurnitureButton(1) return def __diedDone(self, requestStatus): self.doneStatus = requestStatus messenger.send(self.doneEvent) def exitDied(self): base.localAvatar.laffMeter.stop() base.localAvatar.obscureMoveFurnitureButton(-1) def getEstateZoneAndGoHome(self, requestStatus): self.doneStatus = requestStatus avId = requestStatus['avId'] self.acceptOnce('setLocalEstateZone', self.goHome) if avId > 0: base.cr.estateMgr.getLocalEstateZone(avId) else: base.cr.estateMgr.getLocalEstateZone(base.localAvatar.getDoId()) if HouseGlobals.WANT_TELEPORT_TIMEOUT: taskMgr.doMethodLater(HouseGlobals.TELEPORT_TIMEOUT, self.goHomeFailed, 'goHomeFailed') def goHome(self, ownerId, zoneId): self.notify.debug('goHome ownerId = %s' % ownerId) taskMgr.remove('goHomeFailed') if ownerId > 0 and ownerId != base.localAvatar.doId and not base.cr.isFriend(ownerId): self.doneStatus['failed'] = 1 self.goHomeFailed(None) return if ownerId == 0 and zoneId == 0: if self.doneStatus['shardId'] is None or self.doneStatus['shardId'] is base.localAvatar.defaultShard: self.doneStatus['failed'] = 1 self.goHomeFailed(None) return else: self.doneStatus['hood'] = ToontownGlobals.MyEstate self.doneStatus['zone'] = base.localAvatar.lastHood self.doneStatus['loaderId'] = 'safeZoneLoader' self.doneStatus['whereId'] = 'estate' self.doneStatus['how'] = 'teleportIn' messenger.send(self.doneEvent) return if self.doneStatus['zoneId'] == -1: self.doneStatus['zoneId'] = zoneId elif self.doneStatus['zoneId'] != zoneId: self.doneStatus['where'] = 'house' self.doneStatus['ownerId'] = ownerId messenger.send(self.doneEvent) messenger.send('localToonLeft') return def goHomeFailed(self, task): self.notify.debug('goHomeFailed') self.notifyUserGoHomeFailed() self.ignore('setLocalEstateZone') self.doneStatus['hood'] = base.localAvatar.lastHood self.doneStatus['zone'] = base.localAvatar.lastHood self.fsm.request('teleportIn', [self.doneStatus]) return Task.done def notifyUserGoHomeFailed(self): self.notify.debug('notifyUserGoHomeFailed') failedToVisitAvId = self.doneStatus.get('avId', -1) avName = None if failedToVisitAvId != -1: avatar = base.cr.identifyAvatar(failedToVisitAvId) if avatar: avName = avatar.getName() if avName: message = TTLocalizer.EstateTeleportFailedNotFriends % avName else: message = TTLocalizer.EstateTeleportFailed base.localAvatar.setSystemMessage(0, message) return def enterTeleportIn(self, requestStatus): self._tiToken = self.addSetZoneCompleteCallback(Functor(self._placeTeleportInPostZoneComplete, requestStatus), 100) def _placeTeleportInPostZoneComplete(self, requestStatus): teleportDebug(requestStatus, '_placeTeleportInPostZoneComplete(%s)' % (requestStatus,)) NametagGlobals.setMasterArrowsOn(0) base.localAvatar.laffMeter.start() base.localAvatar.startQuestMap() base.localAvatar.reconsiderCheesyEffect() base.localAvatar.obscureMoveFurnitureButton(1) avId = requestStatus.get('avId', -1) if avId != -1: if base.cr.doId2do.has_key(avId): teleportDebug(requestStatus, 'teleport to avatar') avatar = base.cr.doId2do[avId] avatar.forceToTruePosition() base.localAvatar.gotoNode(avatar) base.localAvatar.b_teleportGreeting(avId) else: friend = base.cr.identifyAvatar(avId) if friend != None: teleportDebug(requestStatus, 'friend not here, giving up') base.localAvatar.setSystemMessage(avId, OTPLocalizer.WhisperTargetLeftVisit % (friend.getName(),)) friend.d_teleportGiveup(base.localAvatar.doId) base.transitions.irisIn() self.nextState = requestStatus.get('nextState', 'walk') base.localAvatar.attachCamera() base.localAvatar.startUpdateSmartCamera() base.localAvatar.startPosHprBroadcast() globalClock.tick() base.localAvatar.b_setAnimState('TeleportIn', 1, callback=self.teleportInDone) base.localAvatar.d_broadcastPositionNow() base.localAvatar.b_setParent(ToontownGlobals.SPRender) return def teleportInDone(self): if hasattr(self, 'fsm'): teleportNotify.debug('teleportInDone: %s' % self.nextState) self.fsm.request(self.nextState, [1]) def exitTeleportIn(self): self.removeSetZoneCompleteCallback(self._tiToken) self._tiToken = None NametagGlobals.setMasterArrowsOn(1) base.localAvatar.laffMeter.stop() base.localAvatar.obscureMoveFurnitureButton(-1) base.localAvatar.stopUpdateSmartCamera() base.localAvatar.detachCamera() base.localAvatar.stopPosHprBroadcast() return def requestTeleport(self, hoodId, zoneId, shardId, avId): if avId > 0: teleportNotify.debug('requestTeleport%s' % ((hoodId, zoneId, shardId, avId),)) if localAvatar.hasActiveBoardingGroup(): if avId > 0: teleportNotify.debug('requestTeleport: has active boarding group') rejectText = TTLocalizer.BoardingCannotLeaveZone localAvatar.elevatorNotifier.showMe(rejectText) return loaderId = ZoneUtil.getBranchLoaderName(zoneId) whereId = ZoneUtil.getToonWhereName(zoneId) if hoodId == ToontownGlobals.MyEstate: loaderId = 'safeZoneLoader' whereId = 'estate' if hoodId == ToontownGlobals.PartyHood: loaderId = 'safeZoneLoader' whereId = 'party' self.requestLeave({'loader': loaderId, 'where': whereId, 'how': 'teleportIn', 'hoodId': hoodId, 'zoneId': zoneId, 'shardId': shardId, 'avId': avId}) def enterQuest(self, npcToon): base.localAvatar.b_setAnimState('neutral', 1) self.accept('teleportQuery', self.handleTeleportQuery) base.localAvatar.setTeleportAvailable(1) base.localAvatar.laffMeter.start() base.localAvatar.obscureMoveFurnitureButton(1) def exitQuest(self): base.localAvatar.setTeleportAvailable(0) self.ignore('teleportQuery') base.localAvatar.laffMeter.stop() base.localAvatar.obscureMoveFurnitureButton(-1) def enterPurchase(self): base.localAvatar.b_setAnimState('neutral', 1) self.accept('teleportQuery', self.handleTeleportQuery) base.localAvatar.setTeleportAvailable(1) base.localAvatar.laffMeter.start() base.localAvatar.obscureMoveFurnitureButton(1) def exitPurchase(self): base.localAvatar.setTeleportAvailable(0) self.ignore('teleportQuery') base.localAvatar.laffMeter.stop() base.localAvatar.obscureMoveFurnitureButton(-1) def enterFishing(self): base.localAvatar.b_setAnimState('neutral', 1) self.accept('teleportQuery', self.handleTeleportQuery) base.localAvatar.setTeleportAvailable(1) base.localAvatar.laffMeter.start() def exitFishing(self): base.localAvatar.setTeleportAvailable(0) self.ignore('teleportQuery') base.localAvatar.laffMeter.stop() def enterBanking(self): base.localAvatar.b_setAnimState('neutral', 1) self.accept('teleportQuery', self.handleTeleportQuery) base.localAvatar.setTeleportAvailable(1) base.localAvatar.laffMeter.start() base.localAvatar.obscureMoveFurnitureButton(1) base.localAvatar.startSleepWatch(self.__handleFallingAsleepBanking) self.enablePeriodTimer() def __handleFallingAsleepBanking(self, arg): if hasattr(self, 'fsm'): messenger.send('bankAsleep') self.fsm.request('walk') base.localAvatar.forceGotoSleep() def exitBanking(self): base.localAvatar.setTeleportAvailable(0) self.ignore('teleportQuery') base.localAvatar.laffMeter.stop() base.localAvatar.obscureMoveFurnitureButton(-1) base.localAvatar.stopSleepWatch() self.disablePeriodTimer() def enterPhone(self): base.localAvatar.b_setAnimState('neutral', 1) self.accept('teleportQuery', self.handleTeleportQuery) base.localAvatar.setTeleportAvailable(1) base.localAvatar.laffMeter.start() base.localAvatar.obscureMoveFurnitureButton(1) base.localAvatar.startSleepWatch(self.__handleFallingAsleepPhone) self.enablePeriodTimer() def __handleFallingAsleepPhone(self, arg): if hasattr(self, 'fsm'): self.fsm.request('walk') messenger.send('phoneAsleep') base.localAvatar.forceGotoSleep() def exitPhone(self): base.localAvatar.setTeleportAvailable(0) self.ignore('teleportQuery') base.localAvatar.laffMeter.stop() base.localAvatar.obscureMoveFurnitureButton(-1) base.localAvatar.stopSleepWatch() self.disablePeriodTimer() def enterStopped(self): base.localAvatar.b_setAnimState('neutral', 1) Emote.globalEmote.disableBody(base.localAvatar, 'enterStopped') self.accept('teleportQuery', self.handleTeleportQuery) if base.localAvatar.isDisguised: base.localAvatar.setTeleportAvailable(0) else: base.localAvatar.setTeleportAvailable(1) base.localAvatar.laffMeter.start() base.localAvatar.obscureMoveFurnitureButton(1) base.localAvatar.startSleepWatch(self.__handleFallingAsleepStopped) self.enablePeriodTimer() def __handleFallingAsleepStopped(self, arg): if hasattr(self, 'fsm'): self.fsm.request('walk') base.localAvatar.forceGotoSleep() messenger.send('stoppedAsleep') def exitStopped(self): Emote.globalEmote.releaseBody(base.localAvatar, 'exitStopped') base.localAvatar.setTeleportAvailable(0) self.ignore('teleportQuery') base.localAvatar.laffMeter.stop() base.localAvatar.obscureMoveFurnitureButton(-1) base.localAvatar.stopSleepWatch() self.disablePeriodTimer() messenger.send('exitingStoppedState') def enterPet(self): base.localAvatar.b_setAnimState('neutral', 1) Emote.globalEmote.disableBody(base.localAvatar, 'enterPet') self.accept('teleportQuery', self.handleTeleportQuery) base.localAvatar.setTeleportAvailable(1) base.localAvatar.setTeleportAllowed(0) base.localAvatar.laffMeter.start() self.enterFLM() def exitPet(self): base.localAvatar.setTeleportAvailable(0) base.localAvatar.setTeleportAllowed(1) Emote.globalEmote.releaseBody(base.localAvatar, 'exitPet') self.ignore('teleportQuery') base.localAvatar.laffMeter.stop() self.exitFLM() def enterQuietZone(self, requestStatus): self.quietZoneDoneEvent = uniqueName('quietZoneDone') self.acceptOnce(self.quietZoneDoneEvent, self.handleQuietZoneDone) self.quietZoneStateData = QuietZoneState.QuietZoneState(self.quietZoneDoneEvent) self.quietZoneStateData.load() self.quietZoneStateData.enter(requestStatus) def exitQuietZone(self): self.ignore(self.quietZoneDoneEvent) del self.quietZoneDoneEvent self.quietZoneStateData.exit() self.quietZoneStateData.unload() self.quietZoneStateData = None return def handleQuietZoneDone(self): how = base.cr.handlerArgs['how'] self.fsm.request(how, [base.cr.handlerArgs])
ksmit799/Toontown-Source
toontown/hood/Place.py
Python
mit
37,078
<?php namespace CentraleReferencementBundle\Repository; /** * PourquoiAdhererRepository * * This class was generated by the Doctrine ORM. Add your own custom * repository methods below. */ class PourquoiAdhererRepository extends \Doctrine\ORM\EntityRepository { }
ViraxDev/centrale_referencement
src/CentraleReferencementBundle/Repository/PourquoiAdhererRepository.php
PHP
mit
271
require 'brick/mixin' require 'colorize' module Brick module Models class Service include ::Brick::Mixin::Colors @@waiting_pool = [] attr_accessor :client, :name, :links, :service_config_hash, :container, :volumes_from, :image, :image_name def self.wait_for_deamon @@waiting_pool.each{|thr| thr.join } end def initialize(name, config, client) self.name = name self.service_config_hash = config self.client = client #puts "client=#{client}" determine_color unless config["links"].nil? if config["links"].instance_of?(String) self.links= [config["links"]] else self.links= config["links"].dup end end unless config["volumes_from"].nil? if config["volumes_from"].instance_of?(String) self.volumes_from= [config["volumes_from"]] else self.volumes_from= config["volumes_from"].dup end end begin self.container = ::Docker::Container.get(name) rescue self.container = nil end end def update_volumes_from services new_volumes_from_config = [] new_volumes_from = [] unless volumes_from.nil? volumes_from.each {|vo| #new_volumes_from << services[vo] vo_parts = vo.split(':') #only one part if vo_parts.size == 1 new_vo = "#{services[vo_parts[0]].name}:rw" else new_vo= "#{services[vo_parts[0]].name}:#{vo_parts[1]}" end new_volumes_from<< services[vo_parts[0]] new_volumes_from_config << new_vo } self.volumes_from = new_volumes_from service_config_hash["volumes_from"] = new_volumes_from_config end end def update_links services new_links_config = [] new_links =[] unless links.nil? links.each{|link| link_array=link.split(':') #It's for getting the real service name service_key = link_array[0] alias_name = link_array[-1] service_container= services[service_key] new_links << service_container new_links_config << "#{service_container.name}:#{alias_name}" } self.links=new_links service_config_hash["links"] = new_links_config end end def exec cmd_array, options ={} if self.container.nil? raise "no container #{name} running, so we can't execute " end self.container.exec(cmd_array, options){|stream, chunk| puts "#{color_generator(name)} | #{chunk}".chomp } end #equals to "docker run" def run enable_link=true, recreate=true, detach_mode=false if running? and (!recreate or can_be_skipped_this_time?) Brick::CLI::logger.debug "the service #{name} is already running. exited." unless detach_mode attach end return end unless volumes_from.nil? volumes_from.each{|vo| vo.run enable_link} end config_hash = @service_config_hash.dup if enable_link and !links.nil? links.each{|linked_service| linked_service.run enable_link, recreate, detach_mode unless detach_mode linked_service.attach else puts "Service #{linked_service.name} has been started" end } end if !enable_link config_hash.delete("links") end if recreate and !container.nil? #if recreate is true, it will destory the old container, and create a new one if running? container.stop end container.delete(:force => true) self.container=nil skip_next_time end if container.nil? self.container = client.run config_hash, name else container.start end unless detach_mode attach else puts "Service #{name} has been started" end end #Check if the container is running def running? is_running = false if container.nil? begin self.container = ::Docker::Container.get(name) rescue self.container = nil end end unless container.nil? is_running = container.is_running? end is_running end def container_info (client.get_container_by_id(container.id)).info rescue {} end def attach thr=Thread.new{ puts "Attaching to service #{name}" container.attach(:stdin => STDIN, :tty => true){|message| if message.length > 0 puts "#{color_generator(name)} | #{message}".chomp end } } #thr.join @@waiting_pool << thr end def can_be_built? !service_config_hash["build"].nil? end def skip_next_time @skip = true end def can_be_skipped_this_time? @skip == true end def build name=nil, no_cache=false, project_dir=nil if name.nil? name = self.image_name end puts "Start building #{name}..." if can_be_built? self.image = client.build_from_dir({:image_name => name, :no_cache => no_cache, :project_dir=>project_dir, :build_dir=>service_config_hash["build"]}) else Brick::CLI::logger.debug "no build defintion for #{image_build},skip it" end self.image end def image_exist? ::Docker::Image.exist?(image_name) end def container_exist? ::Docker::Container.exist?(name) end #If it's using build tag, will create an actual image name for it. #For example, if project name is test, service name is web, the image name should #be test_web def update_image_for_building_tag name unless service_config_hash["build"].nil? service_config_hash["image"]=name end self.image_name = service_config_hash["image"] end end end end
cheyang/docker_brick
lib/brick/models/service.rb
Ruby
mit
7,080
/****************************************************************************** The MIT License (MIT) Copyright (c) 2015 Dmitry Root <droot@deeptown.org> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ #include <xdc/std.h> #include <xdc/cfg/global.h> #include <xdc/runtime/Error.h> #include <xdc/runtime/System.h> #include <ti/sysbios/BIOS.h> #include <ti/sysbios/knl/Clock.h> #include <ti/sysbios/knl/Task.h> #include <ti/drivers/GPIO.h> #define PART_TM4C1290NCPDT 1 #include <inc/hw_can.h> #include <inc/hw_memmap.h> #include <inc/hw_types.h> #include <driverlib/can.h> #include <driverlib/sysctl.h> #include <driverlib/gpio.h> #include <driverlib/pin_map.h> #include "board.h" extern "C" int main() { /* Call board init functions */ Board_initGeneral(); Board_initGPIO(); Board_initEMAC(); SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA); GPIOPinConfigure(GPIO_PA0_CAN0RX); GPIOPinConfigure(GPIO_PA1_CAN0TX); GPIOPinTypeCAN(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1); SysCtlPeripheralEnable(SYSCTL_PERIPH_CAN0); CANInit(CAN0_BASE); CANBitRateSet(CAN0_BASE, SysCtlClockGet(), 500000); CANEnable(CAN0_BASE); BIOS_start(); return 0; }
dmitry-root/home-automation
firmware/ti/heater/main.cpp
C++
mit
2,216
require File.dirname(__FILE__) + '/../test_helper' class DefaultControllerTest < ActionController::TestCase def setup @controller = DefaultController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new end context "get home page" do setup do get :index end should respond_with :success should render_template :index # rendering the default home page end context "requests" do setup do setup_theme get :index end should "not add more than one item to the view path" do assert @controller.view_paths.length == 3 end context "second request" do setup do clean_theme_view_path(@controller) get :index end should "not add any more items to the viewpath" do assert @controller.view_paths.length == 3 end end should "have blue in the view path" do assert @controller.view_paths[0].to_s.include?('themes/blue/views'), "The blue theme should be first in the view paths but was #{@controller.view_paths[0]}" end end context "multiple requests" do setup do clean_theme_locale @default_locales_length = I18n.load_path.length @default_locales_length.freeze setup_theme get :index get :index get :index end should "not add extra locales" do assert_equal @default_locales_length + @theme.locales.length, I18n.load_path.length end end context "use url to determine theme" do setup do DomainTheme.stubs(:use_domain_themes?).returns(true) get :index end end end
jbasdf/disguise
test/rails_test/test/functional/default_controller_test.rb
Ruby
mit
1,661
package apimanagement // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "github.com/Azure/go-autorest/tracing" "net/http" ) // IssueClient is the apiManagement Client type IssueClient struct { BaseClient } // NewIssueClient creates an instance of the IssueClient client. func NewIssueClient(subscriptionID string) IssueClient { return NewIssueClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewIssueClientWithBaseURI creates an instance of the IssueClient client using a custom endpoint. Use this when // interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack). func NewIssueClientWithBaseURI(baseURI string, subscriptionID string) IssueClient { return IssueClient{NewWithBaseURI(baseURI, subscriptionID)} } // Get gets API Management issue details // Parameters: // resourceGroupName - the name of the resource group. // serviceName - the name of the API Management service. // issueID - issue identifier. Must be unique in the current API Management service instance. func (client IssueClient) Get(ctx context.Context, resourceGroupName string, serviceName string, issueID string) (result IssueContract, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/IssueClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: serviceName, Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}}, {TargetValue: issueID, Constraints: []validation.Constraint{{Target: "issueID", Name: validation.MaxLength, Rule: 256, Chain: nil}, {Target: "issueID", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "issueID", Name: validation.Pattern, Rule: `^[^*#&+:<>?]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("apimanagement.IssueClient", "Get", err.Error()) } req, err := client.GetPreparer(ctx, resourceGroupName, serviceName, issueID) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.IssueClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "apimanagement.IssueClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.IssueClient", "Get", resp, "Failure responding to request") return } return } // GetPreparer prepares the Get request. func (client IssueClient) GetPreparer(ctx context.Context, resourceGroupName string, serviceName string, issueID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "issueId": autorest.Encode("path", issueID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "serviceName": autorest.Encode("path", serviceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-12-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/issues/{issueId}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client IssueClient) GetSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client IssueClient) GetResponder(resp *http.Response) (result IssueContract, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // ListByService lists a collection of issues in the specified service instance. // Parameters: // resourceGroupName - the name of the resource group. // serviceName - the name of the API Management service. // filter - | Field | Usage | Supported operators | Supported functions // |</br>|-------------|-------------|-------------|-------------|</br>| name | filter | ge, le, eq, ne, gt, lt // | substringof, contains, startswith, endswith | </br>| apiId | filter | ge, le, eq, ne, gt, lt | // substringof, contains, startswith, endswith | </br>| title | filter | ge, le, eq, ne, gt, lt | substringof, // contains, startswith, endswith | </br>| description | filter | ge, le, eq, ne, gt, lt | substringof, // contains, startswith, endswith | </br>| authorName | filter | ge, le, eq, ne, gt, lt | substringof, // contains, startswith, endswith | </br>| state | filter | eq | | </br> // top - number of records to return. // skip - number of records to skip. func (client IssueClient) ListByService(ctx context.Context, resourceGroupName string, serviceName string, filter string, top *int32, skip *int32) (result IssueCollectionPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/IssueClient.ListByService") defer func() { sc := -1 if result.ic.Response.Response != nil { sc = result.ic.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: serviceName, Constraints: []validation.Constraint{{Target: "serviceName", Name: validation.MaxLength, Rule: 50, Chain: nil}, {Target: "serviceName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "serviceName", Name: validation.Pattern, Rule: `^[a-zA-Z](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$`, Chain: nil}}}, {TargetValue: top, Constraints: []validation.Constraint{{Target: "top", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "top", Name: validation.InclusiveMinimum, Rule: int64(1), Chain: nil}}}}}, {TargetValue: skip, Constraints: []validation.Constraint{{Target: "skip", Name: validation.Null, Rule: false, Chain: []validation.Constraint{{Target: "skip", Name: validation.InclusiveMinimum, Rule: int64(0), Chain: nil}}}}}}); err != nil { return result, validation.NewError("apimanagement.IssueClient", "ListByService", err.Error()) } result.fn = client.listByServiceNextResults req, err := client.ListByServicePreparer(ctx, resourceGroupName, serviceName, filter, top, skip) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.IssueClient", "ListByService", nil, "Failure preparing request") return } resp, err := client.ListByServiceSender(req) if err != nil { result.ic.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "apimanagement.IssueClient", "ListByService", resp, "Failure sending request") return } result.ic, err = client.ListByServiceResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.IssueClient", "ListByService", resp, "Failure responding to request") return } if result.ic.hasNextLink() && result.ic.IsEmpty() { err = result.NextWithContext(ctx) return } return } // ListByServicePreparer prepares the ListByService request. func (client IssueClient) ListByServicePreparer(ctx context.Context, resourceGroupName string, serviceName string, filter string, top *int32, skip *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "resourceGroupName": autorest.Encode("path", resourceGroupName), "serviceName": autorest.Encode("path", serviceName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-12-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } if len(filter) > 0 { queryParameters["$filter"] = autorest.Encode("query", filter) } if top != nil { queryParameters["$top"] = autorest.Encode("query", *top) } if skip != nil { queryParameters["$skip"] = autorest.Encode("query", *skip) } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/issues", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListByServiceSender sends the ListByService request. The method will close the // http.Response Body if it receives an error. func (client IssueClient) ListByServiceSender(req *http.Request) (*http.Response, error) { return client.Send(req, azure.DoRetryWithRegistration(client.Client)) } // ListByServiceResponder handles the response to the ListByService request. The method always // closes the http.Response Body. func (client IssueClient) ListByServiceResponder(resp *http.Response) (result IssueCollection, err error) { err = autorest.Respond( resp, azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listByServiceNextResults retrieves the next set of results, if any. func (client IssueClient) listByServiceNextResults(ctx context.Context, lastResults IssueCollection) (result IssueCollection, err error) { req, err := lastResults.issueCollectionPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "apimanagement.IssueClient", "listByServiceNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListByServiceSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "apimanagement.IssueClient", "listByServiceNextResults", resp, "Failure sending next results request") } result, err = client.ListByServiceResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "apimanagement.IssueClient", "listByServiceNextResults", resp, "Failure responding to next results request") } return } // ListByServiceComplete enumerates all values, automatically crossing page boundaries as required. func (client IssueClient) ListByServiceComplete(ctx context.Context, resourceGroupName string, serviceName string, filter string, top *int32, skip *int32) (result IssueCollectionIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/IssueClient.ListByService") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.ListByService(ctx, resourceGroupName, serviceName, filter, top, skip) return }
Azure/azure-sdk-for-go
services/apimanagement/mgmt/2019-12-01/apimanagement/issue.go
GO
mit
11,883
/*=========================================================================== * Licensed Materials - Property of IBM * "Restricted Materials of IBM" * * IBM SDK, Java(tm) Technology Edition, v8 * (C) Copyright IBM Corp. 1999, 1999. All Rights Reserved * * US Government Users Restricted Rights - Use, duplication or disclosure * restricted by GSA ADP Schedule Contract with IBM Corp. *=========================================================================== */ /* * Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.security.interfaces; import java.math.BigInteger; /** * The interface to an RSA public or private key. * * @author Jan Luehe * * @see RSAPublicKey * @see RSAPrivateKey * * @since 1.3 */ public interface RSAKey { /** * Returns the modulus. * * @return the modulus */ public BigInteger getModulus(); }
flyzsd/java-code-snippets
ibm.jdk8/src/java/security/interfaces/RSAKey.java
Java
mit
1,040
namespace Chloe.Server.Models { public class ArticleCategory: BaseEntity { public ArticleCategory() { } } }
QuinntyneBrown/azure-search-getting-started
src/Chloe.Server.Models/ArticleCategory.cs
C#
mit
147
import React from 'react' const columnTypeProptypes = React.PropTypes.oneOf([ 'boolean', 'custom', 'text', ]) export default columnTypeProptypes
npoirey/16AGR
frontend/src/js/core/proptypes/table/columnTypeProptypes.js
JavaScript
mit
153
import test from 'ava'; import deep from 'deep-equal'; import fn from './'; const target = { key1: 'value1', key2: 1, key3: [3, 'value3'], key4: { key41: 'value41', key42: 'value42' }, key5: [ 'value51', 'value51', 'value51' ], key6: { key61: { key611: [ 'value6111', 'value6112' ] } }, key7: [ ['value71', {key72: 'value72'}] ], key8: [ [{key81: ['value81', 'value82']}] ], key9: [ 'key91' ], key10: { key101: [ 'value1011', 'value1012', {key1013: 'value1013'} ] } }; const expected = [ 'key1="value1"', 'key2=1', 'key3=[3,"value3"]', 'key4={"key41":"value41","key42":"value42"}', 'key5=["value51","value51","value51"]', 'key6={"key61":{"key611":["value6111","value6112"]}}', 'key7=[["value71",{"key72":"value72"}]]', 'key8=[[{"key81":["value81","value82"]}]]', 'key9=["key91"]', 'key10={"key101":["value1011","value1012",{"key1013":"value1013"}]}' ]; test('returns well-serialized string', t => { const values = fn.pairify(target); expected.forEach(function (v, i) { t.is(values[i], v); }); }); test('deserialized strings', t => { for (const [key, v] of Object.entries(fn.parse(fn.pairify(target)))) { t.true(deep(v, target[key])); } });
ragingwind/field-value
test.js
JavaScript
mit
1,214
<?php /** * @name Yinhoomail * @desc 通过亿邻(Yinhoo.com)提供的邮件接口来发送邮件 * @author 阿发@YOKA * @createtime 2009-8-12 * @updatetime * 说明: * 因为同是发送邮件功能,为了让大家使用习惯,及以后更改方便 * 大部分函数参数及用法参考并沿用了了Mail.class.php * * 使用方法: * * $ToAddress="alfa@yoka.com"; * $Subject="This is 测试"; * $HtmlCode = <<<HTMLCODE * <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> * <html> * <head> * <meta http-equiv="Content-Type" content="text/html; charset=UTF8"> * <title>Insert title here</title> * </head> * <body> * 测试<img src="http://images.yoka.com/pic/news/2009/0602/logo.gif" /> * <img src="http://images.yoka.com/pic/news/2009/0602/logo.gif"> * <a href="http://www.yoka.com">YOKA时尚</a> * </body> * </html> * HTMLCODE; * * $SendMailObj = new YinHooMail(); * $sendmsg=$SendMailObj->smtp($ToAddress,$Subject,$HtmlCode); * * * 发送格式能过XMLRPC方式通讯,因为我懒得自己写底层代码,直接从网上找了一个可以用的PHPXMLRPC * 网址:http://phpxmlrpc.sourceforge.net/ * 版本:2.2.2 release * Lib放在了_YEPF/CLASS/xmlrpc里面 * XMLRPC的BUG: * xmlrpc原版中使用的是ISO-8859-1编码,我强行改成了UTF-8编码,否则发送的邮件为乱码 * 更改位置:xmlrpc.inc文件的第232行 * 232: /// $GLOBALS['xmlrpc_internalencoding']='ISO-8859-1'; * $GLOBALS['xmlrpc_internalencoding']='UTF-8'; * * 亿邻给我们的配置信息: * client_id : 10050 * user_id : 237 * password: asqweURJ5ioer8p52ksADWuiksdu2340 * ip: 123.127.90.2 , 119.161.129.213 * xmlRpcHost: http://ma2.elink-u.cn:9508/TriggerXmlRpcServlet/ * 最大并行发送量: 5 * 日最大发送量: 20000 * **/ namespace ext; if(!defined('YOKA')) exit('Illegal Request'); include (YEPF_PATH . '/ext/xmlrpc/xmlrpc.inc'); class YinHooMail implements \MailInterface { /** * @name send * @desc 发送邮件函数 * @param string $to 接收人email * @param string $subject 邮件标题 * @param string $content 邮件内容 * @param string $error 错误编号 * @return mixed 是否成功 */ /* * 客户在亿邻智能邮件系统中的客户编号. */ private $YHClientID; /* * 调用者在亿邻智能邮件系统中的用户编号. */ private $YHUserID; /* * 客户调用亿邻邮件代理引擎时的密码 */ private $YHPassword; /* * 待发送的邮件标题 */ private $YHSubject; /* * 邮件发送名的姓名(名称),如 admin */ private $YHFromname; /* * 邮件发送地址. */ private $YHFromAddress; /* * 邮件回复时看到回复接收人姓名 */ private $YHReplyName; /* * 邮件的回复地址. */ private $YHReplyAddress; /* * 邮件接收人.如果要发送给多个人是请采用”,”进行分割,最大不能超过 5 个 */ private $YHToAddress; /* * 要发送的邮件格式. 0=HTML,1=Text,2=Multipart */ private $YHFormatID; /* * text 格式的邮件内容,如果是发送 html 格式的邮件,该字段值可以为空. */ private $YHTextContent; /* * html 格式的邮件内容,如果是发送 text 格式的邮件,该字段值可以为空. */ private $YHHtmlContent; /* * 邮件发送过程中经常会遇到临时拒绝(如灰名单重试),遇到这种 * 情况的时候.第一发送会发送失败, 但是根据对方邮件服务器的反馈等待一定常的时间(一 * 般需要 1 至 5 分钟)后采取一定的策略重复发送一次,可以发送成功. 该参数定义遇到临时 * 决绝的时候系统如何处理. * 0=不做任何处理,直接返回第一发送的错误; * 1=立即返回第一发送的错误信息,但是正常等待和重复发送第二次.发送结束后缓存发 * 送结果.供查询用. * 2=按要求等待,然后发送第二次, 直到第二次发送结束后再返回结果. */ private $YHResendEmailhandleStyle; /* * 连接对方 smtp 服务器等待超时时长. 如果该值小于等于 0,则采用系统缺省值. */ private $YHConnectTimeout; /* * 对方 smtp 响应等待时长, 如果该值小于等于 0 则采用缺省值. */ private $YHSMTPTimeOut; /* * XMLRPC地址 */ private $YHMAIL_XMLRPC; /* * HOST */ private $YHMAIL_HOST; /* * PORT */ private $YHMAIL_PORT; public function __construct($ClientID,$UserID,$Password,$Fromname,$FromAddress,$ReplyName,$ReplyAddress,$FormatID,$ResendEmailhandleStyle,$ConnectTimeout,$SMTPTimeOut,$XMLRPC, $HOST, $PORT) { $this->YHClientID=$ClientID; $this->YHUserID=$UserID; $this->YHPassword=$Password; /// $this->YHSubject=$Subject; $this->YHFromname=$Fromname; $this->YHFromAddress=$FromAddress; $this->YHReplyName=$ReplyName; $this->YHReplyAddress=$ReplyAddress; /// $this->YHToAddress=$ToAddress; $this->YHFormatID=$FormatID; /// $this->YHTextContent=$TextContent; /// $this->YHHtmlContent=$HtmlContent; $this->YHResendEmailhandleStyle=$ResendEmailhandleStyle; $this->YHConnectTimeout=$ConnectTimeout; $this->YHSMTPTimeOut=$SMTPTimeOut; $this->YHMAIL_XMLRPC=$XMLRPC; $this->YHMAIL_HOST=$HOST; $this->YHMAIL_PORT=$PORT; } public function send($to, $subject, $content, &$error = '') { $PARAClientID=new xmlrpcval($this->YHClientID,'string'); $PARAUserID=new xmlrpcval($this->YHUserID,'string'); $PARAPassword=new xmlrpcval($this->YHPassword,'string'); $PARASubject=new xmlrpcval($subject,'string'); $PARAFromname=new xmlrpcval($this->YHFromname,'string'); $PARAFromAddress=new xmlrpcval($this->YHFromAddress,'string'); $PARAReplyName=new xmlrpcval($this->YHReplyName,'string'); $PARAReplyAddress=new xmlrpcval($this->YHReplyAddress,'string'); $PARAToAddress=new xmlrpcval($to,'string'); $PARAFormatID=new xmlrpcval($this->YHFormatID,'string'); $PARATextContent=new xmlrpcval($content,'string'); $PARAHtmlContent=new xmlrpcval($content,'string'); $PARAResendEmailhandleStyle=new xmlrpcval($this->YHResendEmailhandleStyle,'string'); $PARAConnectTimeout=new xmlrpcval($this->YHConnectTimeout,'string'); $PARASMTPTimeOut=new xmlrpcval($this->YHSMTPTimeOut,'string'); $YHParameters=array( $PARAClientID, $PARAUserID, $PARAPassword, $PARASubject, $PARAFromname, $PARAFromAddress, $PARAReplyName, $PARAReplyAddress, $PARAToAddress, $PARAFormatID, $PARATextContent, $PARAHtmlContent, $PARAResendEmailhandleStyle, $PARAConnectTimeout, $PARASMTPTimeOut, ); $YHMsg=new xmlrpcmsg("TriggerHandler.sendMail", $YHParameters); $YHXMLRPCClient=new xmlrpc_client($this->YHMAIL_XMLRPC, $this->YHMAIL_HOST, $this->YHMAIL_PORT); /// alfa 设置调试等级 /// $YHXMLRPCClient->setDebug(2); $YHXMLRPCReturn=$YHXMLRPCClient->send($YHMsg); if(!$YHXMLRPCReturn->faultCode()) { /* * 亿邻返回的信息格式: * * * <?xml version="1.0" encoding="GBK"?> * <result> * <unique-id>000000000W9C9ZPU</unique-id> /// 每封邮件的ID * <result-flag>1</result-flag> /// 发送状态 1=成功,0=失败,2=暂停 * <error-type-id>-1</error-type-id> /// 错误代码 * <error-info></error-info> /// 错误信息 * <begin-time>2009-08-14 18:03:09.509</begin-time> /// 开始发送时间 * <finish-time>2009-08-14 18:03:15.9</finish-time> /// 结束时间 * <delay-time>0</delay-time></result> /// 暂停时间,只有前面的flag为2时,此值才有用 * * */ $Tmpxml = simplexml_load_string($YHXMLRPCReturn->value()->scalarval()); foreach($Tmpxml as $key=>$value) { $TmpData[$key]=$value; } /* * 失败返回错误信息,成功返回邮件ID */ $TmpResult=(int)$TmpData['result-flag']; if( $TmpResult != 1) { $error=$TmpData['error-info']; return false; } else { $YHMailID=$TmpData['unique-id']; return $YHMailID; } } else { $error = $YHXMLRPCReturn->faultCode() . $YHXMLRPCReturn->faultString(); return false; } } } ?>
jimmydong/YEPF3
ext/YinHooMail.class.php
PHP
mit
8,354
const util = require('util'); /** * The request was invalid for a specific reason. * * @param {*} message A message describing the issue. * * @constructor */ const InvalidRequest = function (message) { Error.captureStackTrace(this, this); this.message = message; }; util.inherits(InvalidRequest, Error); InvalidRequest.prototype.name = 'InvalidRequest'; module.exports = InvalidRequest;
SOHU-Co/kafka-node
lib/errors/InvalidRequestError.js
JavaScript
mit
400
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-08-09 16:39 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Tag', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('tag', models.CharField(max_length=100)), ('created', models.DateTimeField(editable=False)), ('modified', models.DateTimeField()), ], ), ]
internship2016/sovolo
app/tag/migrations/0001_initial.py
Python
mit
666
// // BodyPartMessage.cs // // Author: Jeffrey Stedfast <jestedfa@microsoft.com> // // Copyright (c) 2013-2020 .NET Foundation and Contributors // // 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. // using System; using System.Text; namespace MailKit { /// <summary> /// A message/rfc822 body part. /// </summary> /// <remarks> /// Represents a message/rfc822 body part. /// </remarks> public class BodyPartMessage : BodyPartBasic { /// <summary> /// Initializes a new instance of the <see cref="MailKit.BodyPartMessage"/> class. /// </summary> /// <remarks> /// Creates a new <see cref="BodyPartMessage"/>. /// </remarks> public BodyPartMessage () { } /// <summary> /// Gets the envelope of the message, if available. /// </summary> /// <remarks> /// Gets the envelope of the message, if available. /// </remarks> /// <value>The envelope.</value> public Envelope Envelope { get; set; } /// <summary> /// Gets the body structure of the message. /// </summary> /// <remarks> /// Gets the body structure of the message. /// </remarks> /// <value>The body structure.</value> public BodyPart Body { get; set; } /// <summary> /// Gets the length of the message, in lines. /// </summary> /// <remarks> /// Gets the length of the message, in lines. /// </remarks> /// <value>The number of lines.</value> public uint Lines { get; set; } /// <summary> /// Dispatches to the specific visit method for this MIME body part. /// </summary> /// <remarks> /// This default implementation for <see cref="MailKit.BodyPart"/> nodes /// calls <see cref="MailKit.BodyPartVisitor.VisitBodyPart"/>. Override this /// method to call into a more specific method on a derived visitor class /// of the <see cref="MailKit.BodyPartVisitor"/> class. However, it should still /// support unknown visitors by calling /// <see cref="MailKit.BodyPartVisitor.VisitBodyPart"/>. /// </remarks> /// <param name="visitor">The visitor.</param> /// <exception cref="System.ArgumentNullException"> /// <paramref name="visitor"/> is <c>null</c>. /// </exception> public override void Accept (BodyPartVisitor visitor) { if (visitor == null) throw new ArgumentNullException (nameof (visitor)); visitor.VisitBodyPartMessage (this); } /// <summary> /// Encodes the <see cref="BodyPart"/> into the <see cref="System.Text.StringBuilder"/>. /// </summary> /// <remarks> /// Encodes the <see cref="BodyPart"/> into the <see cref="System.Text.StringBuilder"/>. /// </remarks> /// <param name="builder">The string builder.</param> protected override void Encode (StringBuilder builder) { base.Encode (builder); builder.Append (' '); Encode (builder, Envelope); builder.Append (' '); Encode (builder, Body); builder.Append (' '); Encode (builder, Lines); } } }
jamie-dainton/MailKit
MailKit/BodyPartMessage.cs
C#
mit
3,919
require.ensure([], function(require) { require("./105.async.js"); require("./211.async.js"); require("./423.async.js"); require("./845.async.js"); }); module.exports = 846;
skeiter9/javascript-para-todo_demo
webapp/node_modules/webpack/benchmark/fixtures/846.async.js
JavaScript
mit
172
require 'oauth' require 'json' require 'mime/types' require 'wrike/client' module Wrike VERSION = '0.1.0' end
mscifo/wrike
lib/wrike.rb
Ruby
mit
114
/* * The MIT License * * Copyright (c) 2014-2014 Efthymios Sarmpanis http://esarbanis.github.io/roolr * * 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 com.github.esarbanis.roolr; import java.util.Map; /** * This type of {@link EvaluationContext} is the simplest possible. * <p> * It uses a {@link java.util.Map} to store the field/value pairs. The field is represented as a * {@link String} using the JavaBeans notation. * </p> * @author <a href="mailto:e.sarbanis@gmail.com">Efthymios Sarmpanis</a> */ public class SimpleEvaluationContext implements EvaluationContext { private final Map<String, Object> fieldValues; /** * Constructs an {@link EvaluationContext} out of the given * {@link java.util.Map} * @param fieldValues a map of field/value pairs */ public SimpleEvaluationContext(Map<String, Object> fieldValues) { this.fieldValues = fieldValues; } /** * {@inheritDoc} */ public Object getField(String fieldKey) { return fieldValues.get(fieldKey); } }
esarbanis/roolr
src/main/java/com/github/esarbanis/roolr/SimpleEvaluationContext.java
Java
mit
2,050
/** * @overview datejs * @version 1.0.0-beta-2014-03-25 * @author Gregory Wild-Smith <gregory@wild-smith.com> * @copyright 2014 Gregory Wild-Smith * @license MIT * @homepage https://github.com/abritinthebay/datejs */ /* * DateJS Culture String File * Country Code: es-HN * Name: Spanish (Honduras) * Format: "key" : "value" * Key is the en-US term, Value is the Key in the current language. */ Date.CultureStrings = Date.CultureStrings || {}; Date.CultureStrings["es-HN"] = { "name": "es-HN", "englishName": "Spanish (Honduras)", "nativeName": "Español (Honduras)", "Sunday": "domingo", "Monday": "lunes", "Tuesday": "martes", "Wednesday": "miércoles", "Thursday": "jueves", "Friday": "viernes", "Saturday": "sábado", "Sun": "dom", "Mon": "lun", "Tue": "mar", "Wed": "mié", "Thu": "jue", "Fri": "vie", "Sat": "sáb", "Su": "do", "Mo": "lu", "Tu": "ma", "We": "mi", "Th": "ju", "Fr": "vi", "Sa": "sá", "S_Sun_Initial": "d", "M_Mon_Initial": "l", "T_Tue_Initial": "m", "W_Wed_Initial": "m", "T_Thu_Initial": "j", "F_Fri_Initial": "v", "S_Sat_Initial": "s", "January": "enero", "February": "febrero", "March": "marzo", "April": "abril", "May": "mayo", "June": "junio", "July": "julio", "August": "agosto", "September": "septiembre", "October": "octubre", "November": "noviembre", "December": "diciembre", "Jan_Abbr": "ene", "Feb_Abbr": "feb", "Mar_Abbr": "mar", "Apr_Abbr": "abr", "May_Abbr": "may", "Jun_Abbr": "jun", "Jul_Abbr": "jul", "Aug_Abbr": "ago", "Sep_Abbr": "sep", "Oct_Abbr": "oct", "Nov_Abbr": "nov", "Dec_Abbr": "dic", "AM": "a.m.", "PM": "p.m.", "firstDayOfWeek": 0, "twoDigitYearMax": 2029, "mdy": "dmy", "M/d/yyyy": "dd/MM/yyyy", "dddd, MMMM dd, yyyy": "dddd, dd' de 'MMMM' de 'yyyy", "h:mm tt": "hh:mm tt", "h:mm:ss tt": "hh:mm:ss tt", "dddd, MMMM dd, yyyy h:mm:ss tt": "dddd, dd' de 'MMMM' de 'yyyy hh:mm:ss tt", "yyyy-MM-ddTHH:mm:ss": "yyyy-MM-ddTHH:mm:ss", "yyyy-MM-dd HH:mm:ssZ": "yyyy-MM-dd HH:mm:ssZ", "ddd, dd MMM yyyy HH:mm:ss": "ddd, dd MMM yyyy HH:mm:ss", "MMMM dd": "dd MMMM", "MMMM, yyyy": "MMMM' de 'yyyy", "/jan(uary)?/": "ene(ro)?", "/feb(ruary)?/": "feb(rero)?", "/mar(ch)?/": "mar(zo)?", "/apr(il)?/": "abr(il)?", "/may/": "may(o)?", "/jun(e)?/": "jun(io)?", "/jul(y)?/": "jul(io)?", "/aug(ust)?/": "ago(sto)?", "/sep(t(ember)?)?/": "sep(tiembre)?", "/oct(ober)?/": "oct(ubre)?", "/nov(ember)?/": "nov(iembre)?", "/dec(ember)?/": "dic(iembre)?", "/^su(n(day)?)?/": "^do(m(ingo)?)?", "/^mo(n(day)?)?/": "^lu(n(es)?)?", "/^tu(e(s(day)?)?)?/": "^ma(r(tes)?)?", "/^we(d(nesday)?)?/": "^mi(é(rcoles)?)?", "/^th(u(r(s(day)?)?)?)?/": "^ju(e(ves)?)?", "/^fr(i(day)?)?/": "^vi(e(rnes)?)?", "/^sa(t(urday)?)?/": "^sá(b(ado)?)?", "/^next/": "^next", "/^last|past|prev(ious)?/": "^last|past|prev(ious)?", "/^(\\+|aft(er)?|from|hence)/": "^(\\+|aft(er)?|from|hence)", "/^(\\-|bef(ore)?|ago)/": "^(\\-|bef(ore)?|ago)", "/^yes(terday)?/": "^yes(terday)?", "/^t(od(ay)?)?/": "^t(od(ay)?)?", "/^tom(orrow)?/": "^tom(orrow)?", "/^n(ow)?/": "^n(ow)?", "/^ms|milli(second)?s?/": "^ms|milli(second)?s?", "/^sec(ond)?s?/": "^sec(ond)?s?", "/^mn|min(ute)?s?/": "^mn|min(ute)?s?", "/^h(our)?s?/": "^h(our)?s?", "/^w(eek)?s?/": "^w(eek)?s?", "/^m(onth)?s?/": "^m(onth)?s?", "/^d(ay)?s?/": "^d(ay)?s?", "/^y(ear)?s?/": "^y(ear)?s?", "/^(a|p)/": "^(a|p)", "/^(a\\.?m?\\.?|p\\.?m?\\.?)/": "^(a\\.?m?\\.?|p\\.?m?\\.?)", "/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)/": "^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)", "/^\\s*(st|nd|rd|th)/": "^\\s*(st|nd|rd|th)", "/^\\s*(\\:|a(?!u|p)|p)/": "^\\s*(\\:|a(?!u|p)|p)", "LINT": "LINT", "TOT": "TOT", "CHAST": "CHAST", "NZST": "NZST", "NFT": "NFT", "SBT": "SBT", "AEST": "AEST", "ACST": "ACST", "JST": "JST", "CWST": "CWST", "CT": "CT", "ICT": "ICT", "MMT": "MMT", "BIOT": "BST", "NPT": "NPT", "IST": "IST", "PKT": "PKT", "AFT": "AFT", "MSK": "MSK", "IRST": "IRST", "FET": "FET", "EET": "EET", "CET": "CET", "UTC": "UTC", "GMT": "GMT", "CVT": "CVT", "GST": "GST", "BRT": "BRT", "NST": "NST", "AST": "AST", "EST": "EST", "CST": "CST", "MST": "MST", "PST": "PST", "AKST": "AKST", "MIT": "MIT", "HST": "HST", "SST": "SST", "BIT": "BIT", "CHADT": "CHADT", "NZDT": "NZDT", "AEDT": "AEDT", "ACDT": "ACDT", "AZST": "AZST", "IRDT": "IRDT", "EEST": "EEST", "CEST": "CEST", "BST": "BST", "PMDT": "PMDT", "ADT": "ADT", "NDT": "NDT", "EDT": "EDT", "CDT": "CDT", "MDT": "MDT", "PDT": "PDT", "AKDT": "AKDT", "HADT": "HADT" }; Date.CultureStrings.lang = "es-HN"; /** * @overview datejs * @version 1.0.0-beta-2014-03-25 * @author Gregory Wild-Smith <gregory@wild-smith.com> * @copyright 2014 Gregory Wild-Smith * @license MIT * @homepage https://github.com/abritinthebay/datejs */(function () { var $D = Date; var lang = Date.CultureStrings ? Date.CultureStrings.lang : null; var loggedKeys = {}; // for debug purposes. var __ = function (key, language) { var output, split, length, last; var countryCode = (language) ? language : lang; if (Date.CultureStrings && Date.CultureStrings[countryCode] && Date.CultureStrings[countryCode][key]) { output = Date.CultureStrings[countryCode][key]; } else { switch(key) { case "name": output = "en-US"; break; case "englishName": output = "English (United States)"; break; case "nativeName": output = "English (United States)"; break; case "twoDigitYearMax": output = 2049; break; case "firstDayOfWeek": output = 0; break; default: output = key; split = key.split("_"); length = split.length; if (length > 1 && key.charAt(0) !== "/") { // if the key isn't a regex and it has a split. last = split[(length - 1)].toLowerCase(); if (last === "initial" || last === "abbr") { output = split[0]; } } } } if (key.charAt(0) === "/") { // Assume it's a regex if (Date.CultureStrings && Date.CultureStrings[countryCode] && Date.CultureStrings[countryCode][key]) { output = new RegExp(Date.CultureStrings[countryCode][key], "i"); } else { output = new RegExp(key.replace(new RegExp("/", "g"),""), "i"); } } loggedKeys[key] = key; return output; }; var loadI18nScript = function (code) { // paatterned after jQuery's getScript. var url = Date.Config.i18n + code + '.js'; var head = document.getElementsByTagName("head")[0] || document.documentElement; var script = document.createElement("script"); script.src = url; var completed = false; var events = { done: function (){} // dummy function }; // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !completed && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) { done = true; events.done(); head.removeChild(script); } }; setTimeout(function() { head.insertBefore(script, head.firstChild); }, 0); // allows return to execute first return { done: function (f) { events.done = function() { if (f) { f(); } }; } }; }; var CultureInfo = function () { var buildTimeZones = function (data) { var zone; for (zone in data.abbreviatedTimeZoneStandard) { if (data.abbreviatedTimeZoneStandard.hasOwnProperty(zone)) { data.timezones.push({ name: zone, offset: data.abbreviatedTimeZoneStandard[zone]}); } } for (zone in data.abbreviatedTimeZoneDST) { if (data.abbreviatedTimeZoneDST.hasOwnProperty(zone)) { data.timezones.push({ name: zone, offset: data.abbreviatedTimeZoneDST[zone], dst: true}); } } return data.timezones; }; var info = { name: __("name"), englishName: __("englishName"), nativeName: __("nativeName"), /* Day Name Strings */ dayNames: [ __("Sunday"), __("Monday"), __("Tuesday"), __("Wednesday"), __("Thursday"), __("Friday"), __("Saturday") ], abbreviatedDayNames: [ __("Sun"), __("Mon"), __("Tue"), __("Wed"), __("Thu"), __("Fri"), __("Sat") ], shortestDayNames: [ __("Su"), __("Mo"), __("Tu"), __("We"), __("Th"), __("Fr"), __("Sa") ], firstLetterDayNames: [ __("S_Sun_Initial"), __("M_Mon_Initial"), __("T_Tues_Initial"), __("W_Wed_Initial"), __("T_Thu_Initial"), __("F_Fri_Initial"), __("S_Sat_Initial") ], /* Month Name Strings */ monthNames: [ __("January"), __("February"), __("March"), __("April"), __("May"), __("June"), __("July"), __("August"), __("September"), __("October"), __("November"), __("December") ], abbreviatedMonthNames: [ __("Jan_Abbr"), __("Feb_Abbr"), __("Mar_Abbr"), __("Apr_Abbr"), __("May_Abbr"), __("Jun_Abbr"), __("Jul_Abbr"), __("Aug_Abbr"), __("Sep_Abbr"), __("Oct_Abbr"), __("Nov_Abbr"), __("Dec_Abbr") ], /* AM/PM Designators */ amDesignator: __("AM"), pmDesignator: __("PM"), firstDayOfWeek: __("firstDayOfWeek"), twoDigitYearMax: __("twoDigitYearMax"), dateElementOrder: __("mdy"), /* Standard date and time format patterns */ formatPatterns: { shortDate: __("M/d/yyyy"), longDate: __("dddd, MMMM dd, yyyy"), shortTime: __("h:mm tt"), longTime: __("h:mm:ss tt"), fullDateTime: __("dddd, MMMM dd, yyyy h:mm:ss tt"), sortableDateTime: __("yyyy-MM-ddTHH:mm:ss"), universalSortableDateTime: __("yyyy-MM-dd HH:mm:ssZ"), rfc1123: __("ddd, dd MMM yyyy HH:mm:ss"), monthDay: __("MMMM dd"), yearMonth: __("MMMM, yyyy") }, regexPatterns: { inTheMorning: __("/( in the )(morn(ing)?)\\b/"), thisMorning: __("/(this )(morn(ing)?)\\b/"), amThisMorning: __("/(\b\\d(am)? )(this )(morn(ing)?)/"), inTheEvening: __("/( in the )(even(ing)?)\\b/"), thisEvening: __("/(this )(even(ing)?)\\b/"), pmThisEvening: __("/(\b\\d(pm)? )(this )(even(ing)?)/"), jan: __("/jan(uary)?/"), feb: __("/feb(ruary)?/"), mar: __("/mar(ch)?/"), apr: __("/apr(il)?/"), may: __("/may/"), jun: __("/jun(e)?/"), jul: __("/jul(y)?/"), aug: __("/aug(ust)?/"), sep: __("/sep(t(ember)?)?/"), oct: __("/oct(ober)?/"), nov: __("/nov(ember)?/"), dec: __("/dec(ember)?/"), sun: __("/^su(n(day)?)?/"), mon: __("/^mo(n(day)?)?/"), tue: __("/^tu(e(s(day)?)?)?/"), wed: __("/^we(d(nesday)?)?/"), thu: __("/^th(u(r(s(day)?)?)?)?/"), fri: __("/fr(i(day)?)?/"), sat: __("/^sa(t(urday)?)?/"), future: __("/^next/"), past: __("/last|past|prev(ious)?/"), add: __("/^(\\+|aft(er)?|from|hence)/"), subtract: __("/^(\\-|bef(ore)?|ago)/"), yesterday: __("/^yes(terday)?/"), today: __("/^t(od(ay)?)?/"), tomorrow: __("/^tom(orrow)?/"), now: __("/^n(ow)?/"), millisecond: __("/^ms|milli(second)?s?/"), second: __("/^sec(ond)?s?/"), minute: __("/^mn|min(ute)?s?/"), hour: __("/^h(our)?s?/"), week: __("/^w(eek)?s?/"), month: __("/^m(onth)?s?/"), day: __("/^d(ay)?s?/"), year: __("/^y(ear)?s?/"), shortMeridian: __("/^(a|p)/"), longMeridian: __("/^(a\\.?m?\\.?|p\\.?m?\\.?)/"), timezone: __("/^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\\s*(\\+|\\-)\\s*\\d\\d\\d\\d?)|gmt|utc)/"), ordinalSuffix: __("/^\\s*(st|nd|rd|th)/"), timeContext: __("/^\\s*(\\:|a(?!u|p)|p)/") }, timezones: [], abbreviatedTimeZoneDST: {}, abbreviatedTimeZoneStandard: {} }; info.abbreviatedTimeZoneDST[__("CHADT")] = "+1345"; info.abbreviatedTimeZoneDST[__("NZDT")] = "+1300"; info.abbreviatedTimeZoneDST[__("AEDT")] = "+1100"; info.abbreviatedTimeZoneDST[__("ACDT")] = "+1030"; info.abbreviatedTimeZoneDST[__("AZST")] = "+0500"; info.abbreviatedTimeZoneDST[__("IRDT")] = "+0430"; info.abbreviatedTimeZoneDST[__("EEST")] = "+0300"; info.abbreviatedTimeZoneDST[__("CEST")] = "+0200"; info.abbreviatedTimeZoneDST[__("BST")] = "+0100"; info.abbreviatedTimeZoneDST[__("PMDT")] = "-0200"; info.abbreviatedTimeZoneDST[__("ADT")] = "-0300"; info.abbreviatedTimeZoneDST[__("NDT")] = "-0230"; info.abbreviatedTimeZoneDST[__("EDT")] = "-0400"; info.abbreviatedTimeZoneDST[__("CDT")] = "-0500"; info.abbreviatedTimeZoneDST[__("MDT")] = "-0600"; info.abbreviatedTimeZoneDST[__("PDT")] = "-0700"; info.abbreviatedTimeZoneDST[__("AKDT")] = "-0800"; info.abbreviatedTimeZoneDST[__("HADT")] = "-0900"; info.abbreviatedTimeZoneStandard[__("LINT")] = "+1400"; info.abbreviatedTimeZoneStandard[__("TOT")] = "+1300"; info.abbreviatedTimeZoneStandard[__("CHAST")] = "+1245"; info.abbreviatedTimeZoneStandard[__("NZST")] = "+1200"; info.abbreviatedTimeZoneStandard[__("NFT")] = "+1130"; info.abbreviatedTimeZoneStandard[__("SBT")] = "+1100"; info.abbreviatedTimeZoneStandard[__("AEST")] = "+1000"; info.abbreviatedTimeZoneStandard[__("ACST")] = "+0930"; info.abbreviatedTimeZoneStandard[__("JST")] = "+0900"; info.abbreviatedTimeZoneStandard[__("CWST")] = "+0845"; info.abbreviatedTimeZoneStandard[__("CT")] = "+0800"; info.abbreviatedTimeZoneStandard[__("ICT")] = "+0700"; info.abbreviatedTimeZoneStandard[__("MMT")] = "+0630"; info.abbreviatedTimeZoneStandard[__("BST")] = "+0600"; info.abbreviatedTimeZoneStandard[__("NPT")] = "+0545"; info.abbreviatedTimeZoneStandard[__("IST")] = "+0530"; info.abbreviatedTimeZoneStandard[__("PKT")] = "+0500"; info.abbreviatedTimeZoneStandard[__("AFT")] = "+0430"; info.abbreviatedTimeZoneStandard[__("MSK")] = "+0400"; info.abbreviatedTimeZoneStandard[__("IRST")] = "+0330"; info.abbreviatedTimeZoneStandard[__("FET")] = "+0300"; info.abbreviatedTimeZoneStandard[__("EET")] = "+0200"; info.abbreviatedTimeZoneStandard[__("CET")] = "+0100"; info.abbreviatedTimeZoneStandard[__("GMT")] = "+0000"; info.abbreviatedTimeZoneStandard[__("UTC")] = "+0000"; info.abbreviatedTimeZoneStandard[__("CVT")] = "-0100"; info.abbreviatedTimeZoneStandard[__("GST")] = "-0200"; info.abbreviatedTimeZoneStandard[__("BRT")] = "-0300"; info.abbreviatedTimeZoneStandard[__("NST")] = "-0330"; info.abbreviatedTimeZoneStandard[__("AST")] = "-0400"; info.abbreviatedTimeZoneStandard[__("EST")] = "-0500"; info.abbreviatedTimeZoneStandard[__("CST")] = "-0600"; info.abbreviatedTimeZoneStandard[__("MST")] = "-0700"; info.abbreviatedTimeZoneStandard[__("PST")] = "-0800"; info.abbreviatedTimeZoneStandard[__("AKST")] = "-0900"; info.abbreviatedTimeZoneStandard[__("MIT")] = "-0930"; info.abbreviatedTimeZoneStandard[__("HST")] = "-1000"; info.abbreviatedTimeZoneStandard[__("SST")] = "-1100"; info.abbreviatedTimeZoneStandard[__("BIT")] = "-1200"; buildTimeZones(info); return info; }; $D.i18n = { __: function (key, lang) { return __(key, lang); }, currentLanguage: function () { return lang || "en-US"; }, setLanguage: function (code, force) { if (force || code === "en-US" || (!!Date.CultureStrings && !!Date.CultureStrings[code])) { lang = code; Date.CultureStrings.lang = code; Date.CultureInfo = CultureInfo(); } else { if (!(!!Date.CultureStrings && !!Date.CultureStrings[code])) { if (typeof exports !== 'undefined' && this.exports !== exports) { // we're in a Node enviroment, load it using require try { require("../i18n/" + code + ".js"); lang = code; Date.CultureStrings.lang = code; Date.CultureInfo = CultureInfo(); } catch (e) { // var str = "The language for '" + code + "' could not be loaded by Node. It likely does not exist."; throw new Error("The DateJS IETF language tag '" + code + "' could not be loaded by Node. It likely does not exist."); } } else if (Date.Config && Date.Config.i18n) { // we know the location of the files, so lets load them loadI18nScript(code).done(function(){ lang = code; Date.CultureStrings.lang = code; Date.CultureInfo = CultureInfo(); }); } else { Date.console.error("The DateJS IETF language tag '" + code + "' is not available and has not been loaded."); } } } }, getLoggedKeys: function () { return loggedKeys; }, updateCultureInfo: function () { Date.CultureInfo = CultureInfo(); } }; $D.i18n.updateCultureInfo(); // run automatically }()); (function () { var $D = Date, $P = $D.prototype, p = function (s, l) { if (!l) { l = 2; } return ("000" + s).slice(l * -1); }; if (typeof window !== "undefined" && typeof window.console !== "undefined" && typeof window.console.log !== "undefined") { $D.console = console; // used only to raise non-critical errors if available } else { // set mock so we don't give errors. $D.console = { log: function(){}, error: function(){} }; } $D.Config = {}; $D.initOverloads = function() { /** * Overload of Date.now. Allows an alternate call for Date.now where it returns the * current Date as an object rather than just milliseconds since the Unix Epoch. * * Also provides an implementation of now() for browsers (IE<9) that don't have it. * * Backwards compatible so with work with either: * Date.now() [returns ms] * or * Date.now(true) [returns Date] */ if (!$D.now) { $D._now = function now() { return new Date().getTime(); }; } else if (!$D._now) { $D._now = $D.now; } $D.now = function (returnObj) { if (returnObj) { return $D.present(); } else { return $D._now(); } }; if ( !$P.toISOString ) { $P.toISOString = function() { return this.getUTCFullYear() + "-" + p(this.getUTCMonth() + 1) + "-" + p(this.getUTCDate()) + "T" + p(this.getUTCHours()) + ":" + p(this.getUTCMinutes()) + ":" + p(this.getUTCSeconds()) + "." + String( (this.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5) + "Z"; }; } // private if ( $P._toString === undefined ){ $P._toString = $P.toString; } }; $D.initOverloads(); /** * Resets the time of this Date object to 12:00 AM (00:00), which is the start of the day. * @param {Boolean} .clone() this date instance before clearing Time * @return {Date} this */ $P.clearTime = function () { this.setHours(0); this.setMinutes(0); this.setSeconds(0); this.setMilliseconds(0); return this; }; /** * Resets the time of this Date object to the current time ('now'). * @return {Date} this */ $P.setTimeToNow = function () { var n = new Date(); this.setHours(n.getHours()); this.setMinutes(n.getMinutes()); this.setSeconds(n.getSeconds()); this.setMilliseconds(n.getMilliseconds()); return this; }; /** * Gets a date that is set to the current date. The time is set to the start of the day (00:00 or 12:00 AM). * @return {Date} The current date. */ $D.today = function () { return new Date().clearTime(); }; /** * Gets a date that is set to the current date and time (same as new Date, but chainable) * @return {Date} The current date. */ $D.present = function () { return new Date(); }; /** * Compares the first date to the second date and returns an number indication of their relative values. * @param {Date} First Date object to compare [Required]. * @param {Date} Second Date object to compare to [Required]. * @return {Number} -1 = date1 is lessthan date2. 0 = values are equal. 1 = date1 is greaterthan date2. */ $D.compare = function (date1, date2) { if (isNaN(date1) || isNaN(date2)) { throw new Error(date1 + " - " + date2); } else if (date1 instanceof Date && date2 instanceof Date) { return (date1 < date2) ? -1 : (date1 > date2) ? 1 : 0; } else { throw new TypeError(date1 + " - " + date2); } }; /** * Compares the first Date object to the second Date object and returns true if they are equal. * @param {Date} First Date object to compare [Required] * @param {Date} Second Date object to compare to [Required] * @return {Boolean} true if dates are equal. false if they are not equal. */ $D.equals = function (date1, date2) { return (date1.compareTo(date2) === 0); }; /** * Gets the language appropriate day name when given the day number(0-6) * eg - 0 == Sunday * @return {String} The day name */ $D.getDayName = function (n) { return Date.CultureInfo.dayNames[n]; }; /** * Gets the day number (0-6) if given a CultureInfo specific string which is a valid dayName, abbreviatedDayName or shortestDayName (two char). * @param {String} The name of the day (eg. "Monday, "Mon", "tuesday", "tue", "We", "we"). * @return {Number} The day number */ $D.getDayNumberFromName = function (name) { var n = Date.CultureInfo.dayNames, m = Date.CultureInfo.abbreviatedDayNames, o = Date.CultureInfo.shortestDayNames, s = name.toLowerCase(); for (var i = 0; i < n.length; i++) { if (n[i].toLowerCase() === s || m[i].toLowerCase() === s || o[i].toLowerCase() === s) { return i; } } return -1; }; /** * Gets the month number (0-11) if given a Culture Info specific string which is a valid monthName or abbreviatedMonthName. * @param {String} The name of the month (eg. "February, "Feb", "october", "oct"). * @return {Number} The day number */ $D.getMonthNumberFromName = function (name) { var n = Date.CultureInfo.monthNames, m = Date.CultureInfo.abbreviatedMonthNames, s = name.toLowerCase(); for (var i = 0; i < n.length; i++) { if (n[i].toLowerCase() === s || m[i].toLowerCase() === s) { return i; } } return -1; }; /** * Gets the language appropriate month name when given the month number(0-11) * eg - 0 == January * @return {String} The month name */ $D.getMonthName = function (n) { return Date.CultureInfo.monthNames[n]; }; /** * Determines if the current date instance is within a LeapYear. * @param {Number} The year. * @return {Boolean} true if date is within a LeapYear, otherwise false. */ $D.isLeapYear = function (year) { return ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0); }; /** * Gets the number of days in the month, given a year and month value. Automatically corrects for LeapYear. * @param {Number} The year. * @param {Number} The month (0-11). * @return {Number} The number of days in the month. */ $D.getDaysInMonth = function (year, month) { if (!month && $D.validateMonth(year)) { month = year; year = Date.today().getFullYear(); } return [31, ($D.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]; }; $D.getTimezoneAbbreviation = function (offset, dst) { var p, n = (dst || false) ? Date.CultureInfo.abbreviatedTimeZoneDST : Date.CultureInfo.abbreviatedTimeZoneStandard; for (p in n) { if (n.hasOwnProperty(p)) { if (n[p] === offset) { return p; } } } return null; }; $D.getTimezoneOffset = function (name, dst) { var i, a =[], z = Date.CultureInfo.timezones; if (!name) { name = (new Date()).getTimezone()} for (i = 0; i < z.length; i++) { if (z[i].name === name.toUpperCase()) { a.push(i); } } if (!z[a[0]]) { return null; } if (a.length === 1 || !dst) { return z[a[0]].offset; } else { for (i=0; i < a.length; i++) { if (z[a[i]].dst) { return z[a[i]].offset; } } } }; $D.getQuarter = function (d) { d = d || new Date(); // If no date supplied, use today var q = [1,2,3,4]; return q[Math.floor(d.getMonth() / 3)]; // ~~~ is a bitwise op. Faster than Math.floor }; $D.getDaysLeftInQuarter = function (d) { d = d || new Date(); var qEnd = new Date(d); qEnd.setMonth(qEnd.getMonth() + 3 - qEnd.getMonth() % 3, 0); return Math.floor((qEnd - d) / 8.64e7); }; /** * Returns a new Date object that is an exact date and time copy of the original instance. * @return {Date} A new Date instance */ $P.clone = function () { return new Date(this.getTime()); }; /** * Compares this instance to a Date object and returns an number indication of their relative values. * @param {Date} Date object to compare [Required] * @return {Number} -1 = this is lessthan date. 0 = values are equal. 1 = this is greaterthan date. */ $P.compareTo = function (date) { return Date.compare(this, date); }; /** * Compares this instance to another Date object and returns true if they are equal. * @param {Date} Date object to compare. If no date to compare, new Date() [now] is used. * @return {Boolean} true if dates are equal. false if they are not equal. */ $P.equals = function (date) { return Date.equals(this, (date !== undefined ? date : new Date())); }; /** * Determines if this instance is between a range of two dates or equal to either the start or end dates. * @param {Date} Start of range [Required] * @param {Date} End of range [Required] * @return {Boolean} true is this is between or equal to the start and end dates, else false */ $P.between = function (start, end) { return this.getTime() >= start.getTime() && this.getTime() <= end.getTime(); }; /** * Determines if this date occurs after the date to compare to. * @param {Date} Date object to compare. If no date to compare, new Date() ("now") is used. * @return {Boolean} true if this date instance is greater than the date to compare to (or "now"), otherwise false. */ $P.isAfter = function (date) { return this.compareTo(date || new Date()) === 1; }; /** * Determines if this date occurs before the date to compare to. * @param {Date} Date object to compare. If no date to compare, new Date() ("now") is used. * @return {Boolean} true if this date instance is less than the date to compare to (or "now"). */ $P.isBefore = function (date) { return (this.compareTo(date || new Date()) === -1); }; /** * Determines if the current Date instance occurs today. * @return {Boolean} true if this date instance is 'today', otherwise false. */ /** * Determines if the current Date instance occurs on the same Date as the supplied 'date'. * If no 'date' to compare to is provided, the current Date instance is compared to 'today'. * @param {date} Date object to compare. If no date to compare, the current Date ("now") is used. * @return {Boolean} true if this Date instance occurs on the same Day as the supplied 'date'. */ $P.isToday = $P.isSameDay = function (date) { return this.clone().clearTime().equals((date || new Date()).clone().clearTime()); }; /** * Adds the specified number of milliseconds to this instance. * @param {Number} The number of milliseconds to add. The number can be positive or negative [Required] * @return {Date} this */ $P.addMilliseconds = function (value) { if (!value) { return this; } this.setTime(this.getTime() + value * 1); return this; }; /** * Adds the specified number of seconds to this instance. * @param {Number} The number of seconds to add. The number can be positive or negative [Required] * @return {Date} this */ $P.addSeconds = function (value) { if (!value) { return this; } return this.addMilliseconds(value * 1000); }; /** * Adds the specified number of seconds to this instance. * @param {Number} The number of seconds to add. The number can be positive or negative [Required] * @return {Date} this */ $P.addMinutes = function (value) { if (!value) { return this; } return this.addMilliseconds(value * 60000); /* 60*1000 */ }; /** * Adds the specified number of hours to this instance. * @param {Number} The number of hours to add. The number can be positive or negative [Required] * @return {Date} this */ $P.addHours = function (value) { if (!value) { return this; } return this.addMilliseconds(value * 3600000); /* 60*60*1000 */ }; /** * Adds the specified number of days to this instance. * @param {Number} The number of days to add. The number can be positive or negative [Required] * @return {Date} this */ $P.addDays = function (value) { if (!value) { return this; } this.setDate(this.getDate() + value * 1); return this; }; /** * Adds the specified number of weekdays (ie - not sat or sun) to this instance. * @param {Number} The number of days to add. The number can be positive or negative [Required] * @return {Date} this */ $P.addWeekdays = function (value) { if (!value) { return this; } var day = this.getDay(); var weeks = (Math.ceil(Math.abs(value)/7)); if (day === 0 || day === 6) { if (value > 0) { this.next().monday(); this.addDays(-1); } } if (value < 0) { while (value < 0) { this.addDays(-1); day = this.getDay(); if (day !== 0 && day !== 6) { value++; } } return this; } else if (value > 5 || (6-day) <= value) { value = value + (weeks * 2); } return this.addDays(value); }; /** * Adds the specified number of weeks to this instance. * @param {Number} The number of weeks to add. The number can be positive or negative [Required] * @return {Date} this */ $P.addWeeks = function (value) { if (!value) { return this; } return this.addDays(value * 7); }; /** * Adds the specified number of months to this instance. * @param {Number} The number of months to add. The number can be positive or negative [Required] * @return {Date} this */ $P.addMonths = function (value) { if (!value) { return this; } var n = this.getDate(); this.setDate(1); this.setMonth(this.getMonth() + value * 1); this.setDate(Math.min(n, $D.getDaysInMonth(this.getFullYear(), this.getMonth()))); return this; }; $P.addQuarters = function (value) { if (!value) { return this; } // note this will take you to the same point in the quarter as you are now. // i.e. - if you are 15 days into the quarter you'll be 15 days into the resulting one. // bonus: this allows adding fractional quarters return this.addMonths(value * 3); }; /** * Adds the specified number of years to this instance. * @param {Number} The number of years to add. The number can be positive or negative [Required] * @return {Date} this */ $P.addYears = function (value) { if (!value) { return this; } return this.addMonths(value * 12); }; /** * Adds (or subtracts) to the value of the years, months, weeks, days, hours, minutes, seconds, milliseconds of the date instance using given configuration object. Positive and Negative values allowed. * Example <pre><code> Date.today().add( { days: 1, months: 1 } ) new Date().add( { years: -1 } ) </code></pre> * @param {Object} Configuration object containing attributes (months, days, etc.) * @return {Date} this */ $P.add = function (config) { if (typeof config === "number") { this._orient = config; return this; } var x = config; if (x.day) { // If we should be a different date than today (eg: for 'tomorrow -1d', etc). // Should only effect parsing, not direct usage (eg, Finish and FinishExact) if ((x.day - this.getDate()) !== 0) { this.setDate(x.day); } } if (x.milliseconds) { this.addMilliseconds(x.milliseconds); } if (x.seconds) { this.addSeconds(x.seconds); } if (x.minutes) { this.addMinutes(x.minutes); } if (x.hours) { this.addHours(x.hours); } if (x.weeks) { this.addWeeks(x.weeks); } if (x.months) { this.addMonths(x.months); } if (x.years) { this.addYears(x.years); } if (x.days) { this.addDays(x.days); } return this; }; /** * Get the week number. Week one (1) is the week which contains the first Thursday of the year. Monday is considered the first day of the week. * The .getWeek() function does NOT convert the date to UTC. The local datetime is used. * Please use .getISOWeek() to get the week of the UTC converted date. * @return {Number} 1 to 53 */ $P.getWeek = function (utc) { // Create a copy of this date object var self, target = new Date(this.valueOf()); if (utc) { target.addMinutes(target.getTimezoneOffset()); self = target.clone(); } else { self = this; } // ISO week date weeks start on monday // so correct the day number var dayNr = (self.getDay() + 6) % 7; // ISO 8601 states that week 1 is the week // with the first thursday of that year. // Set the target date to the thursday in the target week target.setDate(target.getDate() - dayNr + 3); // Store the millisecond value of the target date var firstThursday = target.valueOf(); // Set the target to the first thursday of the year // First set the target to january first target.setMonth(0, 1); // Not a thursday? Correct the date to the next thursday if (target.getDay() !== 4) { target.setMonth(0, 1 + ((4 - target.getDay()) + 7) % 7); } // The weeknumber is the number of weeks between the // first thursday of the year and the thursday in the target week return 1 + Math.ceil((firstThursday - target) / 604800000); // 604800000 = 7 * 24 * 3600 * 1000 }; /** * Get the ISO 8601 week number. Week one ("01") is the week which contains the first Thursday of the year. Monday is considered the first day of the week. * The .getISOWeek() function does convert the date to it's UTC value. Please use .getWeek() to get the week of the local date. * @return {String} "01" to "53" */ $P.getISOWeek = function () { return p(this.getWeek(true)); }; /** * Moves the date to Monday of the week set. Week one (1) is the week which contains the first Thursday of the year. * @param {Number} A Number (1 to 53) that represents the week of the year. * @return {Date} this */ $P.setWeek = function (n) { if ((n - this.getWeek()) === 0) { if (this.getDay() !== 1) { return this.moveToDayOfWeek(1, (this.getDay() > 1 ? -1 : 1)); } else { return this; } } else { return this.moveToDayOfWeek(1, (this.getDay() > 1 ? -1 : 1)).addWeeks(n - this.getWeek()); } }; $P.setQuarter = function (qtr) { var month = Math.abs(((qtr-1) * 3) + 1); return this.setMonth(month, 1); }; $P.getQuarter = function () { return Date.getQuarter(this); }; $P.getDaysLeftInQuarter = function () { return Date.getDaysLeftInQuarter(this); }; // private var validate = function (n, min, max, name) { name = name ? name : "Object"; if (typeof n === "undefined") { return false; } else if (typeof n !== "number") { throw new TypeError(n + " is not a Number."); } else if (n < min || n > max) { // As failing validation is *not* an exceptional circumstance // lets not throw a RangeError Exception here. // It's semantically correct but it's not sensible. return false; } return true; }; /** * Validates the number is within an acceptable range for milliseconds [0-999]. * @param {Number} The number to check if within range. * @return {Boolean} true if within range, otherwise false. */ $D.validateMillisecond = function (value) { return validate(value, 0, 999, "millisecond"); }; /** * Validates the number is within an acceptable range for seconds [0-59]. * @param {Number} The number to check if within range. * @return {Boolean} true if within range, otherwise false. */ $D.validateSecond = function (value) { return validate(value, 0, 59, "second"); }; /** * Validates the number is within an acceptable range for minutes [0-59]. * @param {Number} The number to check if within range. * @return {Boolean} true if within range, otherwise false. */ $D.validateMinute = function (value) { return validate(value, 0, 59, "minute"); }; /** * Validates the number is within an acceptable range for hours [0-23]. * @param {Number} The number to check if within range. * @return {Boolean} true if within range, otherwise false. */ $D.validateHour = function (value) { return validate(value, 0, 23, "hour"); }; /** * Validates the number is within an acceptable range for the days in a month [0-MaxDaysInMonth]. * @param {Number} The number to check if within range. * @return {Boolean} true if within range, otherwise false. */ $D.validateDay = function (value, year, month) { return validate(value, 1, $D.getDaysInMonth(year, month), "day"); }; /** * Validates the number is within an acceptable range for months [0-11]. * @param {Number} The number to check if within range. * @return {Boolean} true if within range, otherwise false. */ $D.validateWeek = function (value) { return validate(value, 0, 53, "week"); }; /** * Validates the number is within an acceptable range for months [0-11]. * @param {Number} The number to check if within range. * @return {Boolean} true if within range, otherwise false. */ $D.validateMonth = function (value) { return validate(value, 0, 11, "month"); }; /** * Validates the number is within an acceptable range for years. * @param {Number} The number to check if within range. * @return {Boolean} true if within range, otherwise false. */ $D.validateYear = function (value) { /** * Per ECMAScript spec the range of times supported by Date objects is * exactly –100,000,000 days to 100,000,000 days measured relative to * midnight at the beginning of 01 January, 1970 UTC. * This gives a range of 8,640,000,000,000,000 milliseconds to either * side of 01 January, 1970 UTC. * * Earliest possible date: Tue, 20 Apr 271,822 B.C. 00:00:00 UTC * Latest possible date: Sat, 13 Sep 275,760 00:00:00 UTC */ return validate(value, -271822, 275760, "year"); }; /** * Set the value of year, month, day, hour, minute, second, millisecond of date instance using given configuration object. * Example <pre><code> Date.today().set( { day: 20, month: 1 } ) new Date().set( { millisecond: 0 } ) </code></pre> * * @param {Object} Configuration object containing attributes (month, day, etc.) * @return {Date} this */ $P.set = function (config) { if ($D.validateMillisecond(config.millisecond)) { this.addMilliseconds(config.millisecond - this.getMilliseconds()); } if ($D.validateSecond(config.second)) { this.addSeconds(config.second - this.getSeconds()); } if ($D.validateMinute(config.minute)) { this.addMinutes(config.minute - this.getMinutes()); } if ($D.validateHour(config.hour)) { this.addHours(config.hour - this.getHours()); } if ($D.validateMonth(config.month)) { this.addMonths(config.month - this.getMonth()); } if ($D.validateYear(config.year)) { this.addYears(config.year - this.getFullYear()); } /* day has to go last because you can't validate the day without first knowing the month */ if ($D.validateDay(config.day, this.getFullYear(), this.getMonth())) { this.addDays(config.day - this.getDate()); } if (config.timezone) { this.setTimezone(config.timezone); } if (config.timezoneOffset) { this.setTimezoneOffset(config.timezoneOffset); } if (config.week && $D.validateWeek(config.week)) { this.setWeek(config.week); } return this; }; /** * Moves the date to the first day of the month. * @return {Date} this */ $P.moveToFirstDayOfMonth = function () { return this.set({ day: 1 }); }; /** * Moves the date to the last day of the month. * @return {Date} this */ $P.moveToLastDayOfMonth = function () { return this.set({ day: $D.getDaysInMonth(this.getFullYear(), this.getMonth())}); }; /** * Moves the date to the next n'th occurrence of the dayOfWeek starting from the beginning of the month. The number (-1) is a magic number and will return the last occurrence of the dayOfWeek in the month. * @param {Number} The dayOfWeek to move to * @param {Number} The n'th occurrence to move to. Use (-1) to return the last occurrence in the month * @return {Date} this */ $P.moveToNthOccurrence = function (dayOfWeek, occurrence) { if (dayOfWeek === "Weekday") { if (occurrence > 0) { this.moveToFirstDayOfMonth(); if (this.is().weekday()) { occurrence -= 1; } } else if (occurrence < 0) { this.moveToLastDayOfMonth(); if (this.is().weekday()) { occurrence += 1; } } else { return this; } return this.addWeekdays(occurrence); } var shift = 0; if (occurrence > 0) { shift = occurrence - 1; } else if (occurrence === -1) { this.moveToLastDayOfMonth(); if (this.getDay() !== dayOfWeek) { this.moveToDayOfWeek(dayOfWeek, -1); } return this; } return this.moveToFirstDayOfMonth().addDays(-1).moveToDayOfWeek(dayOfWeek, +1).addWeeks(shift); }; /** * Move to the next or last dayOfWeek based on the orient value. * @param {Number} The dayOfWeek to move to * @param {Number} Forward (+1) or Back (-1). Defaults to +1. [Optional] * @return {Date} this */ $P.moveToDayOfWeek = function (dayOfWeek, orient) { var diff = (dayOfWeek - this.getDay() + 7 * (orient || +1)) % 7; return this.addDays((diff === 0) ? diff += 7 * (orient || +1) : diff); }; /** * Move to the next or last month based on the orient value. * @param {Number} The month to move to. 0 = January, 11 = December * @param {Number} Forward (+1) or Back (-1). Defaults to +1. [Optional] * @return {Date} this */ $P.moveToMonth = function (month, orient) { var diff = (month - this.getMonth() + 12 * (orient || +1)) % 12; return this.addMonths((diff === 0) ? diff += 12 * (orient || +1) : diff); }; /** * Get the Ordinate of the current day ("th", "st", "rd"). * @return {String} */ $P.getOrdinate = function () { var num = this.getDate(); return ord(num); }; /** * Get the Ordinal day (numeric day number) of the year, adjusted for leap year. * @return {Number} 1 through 365 (366 in leap years) */ $P.getOrdinalNumber = function () { return Math.ceil((this.clone().clearTime() - new Date(this.getFullYear(), 0, 1)) / 86400000) + 1; }; /** * Get the time zone abbreviation of the current date. * @return {String} The abbreviated time zone name (e.g. "EST") */ $P.getTimezone = function () { return $D.getTimezoneAbbreviation(this.getUTCOffset(), this.isDaylightSavingTime()); }; $P.setTimezoneOffset = function (offset) { var here = this.getTimezoneOffset(), there = Number(offset) * -6 / 10; return (there || there === 0) ? this.addMinutes(there - here) : this; }; $P.setTimezone = function (offset) { return this.setTimezoneOffset($D.getTimezoneOffset(offset)); }; /** * Indicates whether Daylight Saving Time is observed in the current time zone. * @return {Boolean} true|false */ $P.hasDaylightSavingTime = function () { return (Date.today().set({month: 0, day: 1}).getTimezoneOffset() !== Date.today().set({month: 6, day: 1}).getTimezoneOffset()); }; /** * Indicates whether this Date instance is within the Daylight Saving Time range for the current time zone. * @return {Boolean} true|false */ $P.isDaylightSavingTime = function () { return Date.today().set({month: 0, day: 1}).getTimezoneOffset() !== this.getTimezoneOffset(); }; /** * Get the offset from UTC of the current date. * @return {String} The 4-character offset string prefixed with + or - (e.g. "-0500") */ $P.getUTCOffset = function (offset) { var n = (offset || this.getTimezoneOffset()) * -10 / 6, r; if (n < 0) { r = (n - 10000).toString(); return r.charAt(0) + r.substr(2); } else { r = (n + 10000).toString(); return "+" + r.substr(1); } }; /** * Returns the number of milliseconds between this date and date. * @param {Date} Defaults to now * @return {Number} The diff in milliseconds */ $P.getElapsed = function (date) { return (date || new Date()) - this; }; /** * Converts the value of the current Date object to its equivalent string representation. * Format Specifiers <pre> CUSTOM DATE AND TIME FORMAT STRINGS Format Description Example ------ --------------------------------------------------------------------------- ----------------------- s The seconds of the minute between 0-59. "0" to "59" ss The seconds of the minute with leading zero if required. "00" to "59" m The minute of the hour between 0-59. "0" or "59" mm The minute of the hour with leading zero if required. "00" or "59" h The hour of the day between 1-12. "1" to "12" hh The hour of the day with leading zero if required. "01" to "12" H The hour of the day between 0-23. "0" to "23" HH The hour of the day with leading zero if required. "00" to "23" d The day of the month between 1 and 31. "1" to "31" dd The day of the month with leading zero if required. "01" to "31" ddd Abbreviated day name. Date.CultureInfo.abbreviatedDayNames. "Mon" to "Sun" dddd The full day name. Date.CultureInfo.dayNames. "Monday" to "Sunday" M The month of the year between 1-12. "1" to "12" MM The month of the year with leading zero if required. "01" to "12" MMM Abbreviated month name. Date.CultureInfo.abbreviatedMonthNames. "Jan" to "Dec" MMMM The full month name. Date.CultureInfo.monthNames. "January" to "December" yy The year as a two-digit number. "99" or "08" yyyy The full four digit year. "1999" or "2008" t Displays the first character of the A.M./P.M. designator. "A" or "P" Date.CultureInfo.amDesignator or Date.CultureInfo.pmDesignator tt Displays the A.M./P.M. designator. "AM" or "PM" Date.CultureInfo.amDesignator or Date.CultureInfo.pmDesignator S The ordinal suffix ("st, "nd", "rd" or "th") of the current day. "st, "nd", "rd" or "th" || *Format* || *Description* || *Example* || || d || The CultureInfo shortDate Format Pattern || "M/d/yyyy" || || D || The CultureInfo longDate Format Pattern || "dddd, MMMM dd, yyyy" || || F || The CultureInfo fullDateTime Format Pattern || "dddd, MMMM dd, yyyy h:mm:ss tt" || || m || The CultureInfo monthDay Format Pattern || "MMMM dd" || || r || The CultureInfo rfc1123 Format Pattern || "ddd, dd MMM yyyy HH:mm:ss GMT" || || s || The CultureInfo sortableDateTime Format Pattern || "yyyy-MM-ddTHH:mm:ss" || || t || The CultureInfo shortTime Format Pattern || "h:mm tt" || || T || The CultureInfo longTime Format Pattern || "h:mm:ss tt" || || u || The CultureInfo universalSortableDateTime Format Pattern || "yyyy-MM-dd HH:mm:ssZ" || || y || The CultureInfo yearMonth Format Pattern || "MMMM, yyyy" || STANDARD DATE AND TIME FORMAT STRINGS Format Description Example ("en-US") ------ --------------------------------------------------------------------------- ----------------------- d The CultureInfo shortDate Format Pattern "M/d/yyyy" D The CultureInfo longDate Format Pattern "dddd, MMMM dd, yyyy" F The CultureInfo fullDateTime Format Pattern "dddd, MMMM dd, yyyy h:mm:ss tt" m The CultureInfo monthDay Format Pattern "MMMM dd" r The CultureInfo rfc1123 Format Pattern "ddd, dd MMM yyyy HH:mm:ss GMT" s The CultureInfo sortableDateTime Format Pattern "yyyy-MM-ddTHH:mm:ss" t The CultureInfo shortTime Format Pattern "h:mm tt" T The CultureInfo longTime Format Pattern "h:mm:ss tt" u The CultureInfo universalSortableDateTime Format Pattern "yyyy-MM-dd HH:mm:ssZ" y The CultureInfo yearMonth Format Pattern "MMMM, yyyy" </pre> * @param {String} A format string consisting of one or more format spcifiers [Optional]. * @return {String} A string representation of the current Date object. */ var ord = function (n) { switch (n * 1) { case 1: case 21: case 31: return "st"; case 2: case 22: return "nd"; case 3: case 23: return "rd"; default: return "th"; } }; $P.toString = function (format, ignoreStandards) { var x = this; // Standard Date and Time Format Strings. Formats pulled from CultureInfo file and // may vary by culture. if (!ignoreStandards && format && format.length === 1) { var y, c = Date.CultureInfo.formatPatterns; x.t = x.toString; switch (format) { case "d": return x.t(c.shortDate); case "D": return x.t(c.longDate); case "F": return x.t(c.fullDateTime); case "m": return x.t(c.monthDay); case "r": case "R": y = x.clone().addMinutes(x.getTimezoneOffset()); return y.toString(c.rfc1123) + " GMT"; case "s": return x.t(c.sortableDateTime); case "t": return x.t(c.shortTime); case "T": return x.t(c.longTime); case "u": y = x.clone().addMinutes(x.getTimezoneOffset()); return y.toString(c.universalSortableDateTime); case "y": return x.t(c.yearMonth); } } return format ? format.replace(/((\\)?(dd?d?d?|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|S|q|Q|WW?W?W?)(?![^\[]*\]))/g, function (m) { if (m.charAt(0) === "\\") { return m.replace("\\", ""); } x.h = x.getHours; switch (m) { case "hh": return p(x.h() < 13 ? (x.h() === 0 ? 12 : x.h()) : (x.h() - 12)); case "h": return x.h() < 13 ? (x.h() === 0 ? 12 : x.h()) : (x.h() - 12); case "HH": return p(x.h()); case "H": return x.h(); case "mm": return p(x.getMinutes()); case "m": return x.getMinutes(); case "ss": return p(x.getSeconds()); case "s": return x.getSeconds(); case "yyyy": return p(x.getFullYear(), 4); case "yy": return p(x.getFullYear()); case "dddd": return Date.CultureInfo.dayNames[x.getDay()]; case "ddd": return Date.CultureInfo.abbreviatedDayNames[x.getDay()]; case "dd": return p(x.getDate()); case "d": return x.getDate(); case "MMMM": return Date.CultureInfo.monthNames[x.getMonth()]; case "MMM": return Date.CultureInfo.abbreviatedMonthNames[x.getMonth()]; case "MM": return p((x.getMonth() + 1)); case "M": return x.getMonth() + 1; case "t": return x.h() < 12 ? Date.CultureInfo.amDesignator.substring(0, 1) : Date.CultureInfo.pmDesignator.substring(0, 1); case "tt": return x.h() < 12 ? Date.CultureInfo.amDesignator : Date.CultureInfo.pmDesignator; case "S": return ord(x.getDate()); case "W": return x.getWeek(); case "WW": return x.getISOWeek(); case "Q": return "Q" + x.getQuarter(); case "q": return String(x.getQuarter()); default: return m; } }).replace(/\[|\]/g, "") : this._toString(); }; }()); (function () { "use strict"; Date.Parsing = { Exception: function (s) { this.message = "Parse error at '" + s.substring(0, 10) + " ...'"; } }; var $P = Date.Parsing; var dayOffsets = { standard: [0,31,59,90,120,151,181,212,243,273,304,334], leap: [0,31,60,91,121,152,182,213,244,274,305,335] }; $P.isLeapYear = function(year) { return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0); }; $P.processTimeObject = function (obj) { var d, jan4, date, offset, dayOffset; d = new Date(); dayOffset = ($P.isLeapYear(obj.year)) ? dayOffsets.leap : dayOffsets.standard; obj.hours = obj.hours ? obj.hours : 0; obj.minutes = obj.minutes ? obj.minutes : 0; obj.seconds = obj.seconds ? obj.seconds : 0; obj.milliseconds = obj.milliseconds ? obj.milliseconds : 0; if (!obj.year) { obj.year = d.getFullYear(); } if (!obj.month && (obj.week || obj.dayOfYear)) { // work out the day of the year... if (!obj.dayOfYear) { obj.weekDay = (!obj.weekDay && obj.weekDay !== 0) ? 1 : obj.weekDay; d = new Date(obj.year, 0, 4); jan4 = d.getDay() === 0 ? 7 : d.getDay(); // JS is 0 indexed on Sunday. offset = jan4+3; obj.dayOfYear = ((obj.week * 7) + (obj.weekDay === 0 ? 7 : obj.weekDay))-offset; } for (var i=0;i <= dayOffset.length;i++) { if (obj.dayOfYear < dayOffset[i] || i === dayOffset.length) { obj.day = obj.day ? obj.day : (obj.dayOfYear - dayOffset[i-1]); break; } else { obj.month = i; } } } else { obj.month = obj.month ? obj.month : 0; obj.day = obj.day ? obj.day : 1; obj.dayOfYear = dayOffset[obj.month] + obj.day; } date = new Date(obj.year, obj.month, obj.day, obj.hours, obj.minutes, obj.seconds, obj.milliseconds); if (obj.zone) { // adjust (and calculate) for timezone here if (obj.zone.toUpperCase() === "Z" || (obj.zone_hours === 0 && obj.zone_minutes === 0)) { // it's UTC/GML so work out the current timeszone offset offset = -date.getTimezoneOffset(); } else { offset = (obj.zone_hours*60) + (obj.zone_minutes ? obj.zone_minutes : 0); if (obj.zone_sign === "+") { offset *= -1; } offset -= date.getTimezoneOffset(); } date.setMinutes(date.getMinutes()+offset); } return date; }; $P.ISO = { regex : /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-3])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-4])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?\s?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/, parse : function (s) { var data = s.match(this.regex); if (!data || !data.length) { return null; } var time = { year : data[1] ? Number(data[1]) : data[1], month : data[5] ? (Number(data[5])-1) : data[5], day : data[7] ? Number(data[7]) : data[7], week : data[8] ? Number(data[8]) : data[8], weekDay : data[9] ? (Math.abs(Number(data[9])) === 7 ? 0 : Math.abs(Number(data[9]))) : data[9], // 1-7, starts on Monday. Convert to JS's 0-6 index. dayOfYear : data[10] ? Number(data[10]) : data[10], hours : data[15] ? Number(data[15]) : data[15], minutes : data[16] ? Number(data[16].replace(":","")) : data[16], seconds : data[19] ? Math.floor(Number(data[19].replace(":","").replace(",","."))) : data[19], milliseconds : data[20] ? (Number(data[20].replace(",","."))*1000) : data[20], zone : data[21], zone_sign : data[22], zone_hours : (data[23] && typeof data[23] !== "undefined") ? Number(data[23]) : data[23], zone_minutes : (data[24] && typeof data[23] !== "undefined") ? Number(data[24]) : data[24] }; if (data[18]) { data[18] = 60 * Number(data[18].replace(",", ".")); if (!time.minutes) { time.minutes = data[18]; } else if (!time.seconds) { time.seconds = data[18]; } } if (!time.year || (!time.year && (!time.month && !time.day) && (!time.week && !time.dayOfYear)) ) { return null; } return $P.processTimeObject(time); } }; $P.Numeric = { isNumeric: function (e){return!isNaN(parseFloat(e))&&isFinite(e)}, regex: /\b([0-1]?[0-9])([0-3]?[0-9])([0-2]?[0-9]?[0-9][0-9])\b/i, parse: function (s) { var data, i, time = {}, order = Date.CultureInfo.dateElementOrder.split(""); if (!(this.isNumeric(s)) || // if it's non-numeric OR (s[0] === "+" && s[0] === "-")) { // It's an arithmatic string (eg +/-1000) return null; } if (s.length < 5) { // assume it's just a year. time.year = s; return $P.processTimeObject(time); } data = s.match(this.regex); if (!data || !data.length) { return null; } for (i=0; i < order.length; i++) { switch(order[i]) { case "d": time.day = data[i+1]; break; case "m": time.month = (data[i+1]-1); break; case "y": time.year = data[i+1]; break; } } return $P.processTimeObject(time); } }; $P.Normalizer = { parse: function (s) { var $C = Date.CultureInfo; var $R = Date.CultureInfo.regexPatterns; var __ = Date.i18n.__; s = s.replace($R.jan.source, "January"); s = s.replace($R.feb, "February"); s = s.replace($R.mar, "March"); s = s.replace($R.apr, "April"); s = s.replace($R.may, "May"); s = s.replace($R.jun, "June"); s = s.replace($R.jul, "July"); s = s.replace($R.aug, "August"); s = s.replace($R.sep, "September"); s = s.replace($R.oct, "October"); s = s.replace($R.nov, "November"); s = s.replace($R.dec, "December"); s = s.replace($R.tomorrow, Date.today().addDays(1).toString("d")); s = s.replace($R.yesterday, Date.today().addDays(-1).toString("d")); // s = s.replace(new RegExp($R.today.source + "\\b", "i"), Date.today().toString("d")); s = s.replace(/\bat\b/gi, ""); // replace "at", eg: "tomorrow at 3pm" s = s.replace(/\s{2,}/, " "); // repliace multiple spaces with one. s = s.replace(new RegExp("(\\b\\d\\d?("+__("AM")+"|"+__("PM")+")? )("+$R.tomorrow.source.slice(1)+")", "i"), function(full, m1, m2, m3, m4) { var t = Date.today().addDays(1).toString("d"); var s = t + " " + m1; return s; }); s = s.replace(new RegExp("(("+$R.past.source+')\\s('+$R.mon.source+'))'), Date.today().last().monday().toString("d")); s = s.replace(new RegExp("(("+$R.past.source+')\\s('+$R.tue.source+'))'), Date.today().last().tuesday().toString("d")); s = s.replace(new RegExp("(("+$R.past.source+')\\s('+$R.wed.source+'))'), Date.today().last().wednesday().toString("d")); s = s.replace(new RegExp("(("+$R.past.source+')\\s('+$R.thu.source+'))'), Date.today().last().thursday().toString("d")); s = s.replace(new RegExp("(("+$R.past.source+')\\s('+$R.fri.source+'))'), Date.today().last().friday().toString("d")); s = s.replace(new RegExp("(("+$R.past.source+')\\s('+$R.sat.source+'))'), Date.today().last().saturday().toString("d")); s = s.replace(new RegExp("(("+$R.past.source+')\\s('+$R.sun.source+'))'), Date.today().last().sunday().toString("d")); // s = s.replace($R.thisMorning, "9am")) s = s.replace($R.amThisMorning, function(str, am){return am;}); s = s.replace($R.inTheMorning, "am"); s = s.replace($R.thisMorning, "9am"); s = s.replace($R.amThisEvening, function(str, pm){return pm;}); s = s.replace($R.inTheEvening, "pm"); s = s.replace($R.thisEvening, "7pm"); try { var n = s.split(/([\s\-\.\,\/\x27]+)/); if (n.length === 3) { if ($P.Numeric.isNumeric(n[0]) && $P.Numeric.isNumeric(n[2])) { if (n[2].length >= 4) { // ok, so we're dealing with x/year. But that's not a full date. // This fixes wonky dateElementOrder parsing when set to dmy order. if (Date.CultureInfo.dateElementOrder[0] === 'd') { s = '1/' + n[0] + '/' + n[2]; // set to 1st of month and normalize the seperator } } } } } catch (e) { // continue... } return s; } }; }()); (function () { var $P = Date.Parsing; var _ = $P.Operators = { // // Tokenizers // rtoken: function (r) { // regex token return function (s) { var mx = s.match(r); if (mx) { return ([ mx[0], s.substring(mx[0].length) ]); } else { throw new $P.Exception(s); } }; }, token: function (s) { // whitespace-eating token return function (s) { return _.rtoken(new RegExp("^\s*" + s + "\s*"))(s); // Removed .strip() // return _.rtoken(new RegExp("^\s*" + s + "\s*"))(s).strip(); }; }, stoken: function (s) { // string token return _.rtoken(new RegExp("^" + s)); }, // // Atomic Operators // until: function (p) { return function (s) { var qx = [], rx = null; while (s.length) { try { rx = p.call(this, s); } catch (e) { qx.push(rx[0]); s = rx[1]; continue; } break; } return [ qx, s ]; }; }, many: function (p) { return function (s) { var rx = [], r = null; while (s.length) { try { r = p.call(this, s); } catch (e) { return [ rx, s ]; } rx.push(r[0]); s = r[1]; } return [ rx, s ]; }; }, // generator operators -- see below optional: function (p) { return function (s) { var r = null; try { r = p.call(this, s); } catch (e) { return [ null, s ]; } return [ r[0], r[1] ]; }; }, not: function (p) { return function (s) { try { p.call(this, s); } catch (e) { return [null, s]; } throw new $P.Exception(s); }; }, ignore: function (p) { return p ? function (s) { var r = null; r = p.call(this, s); return [null, r[1]]; } : null; }, product: function () { var px = arguments[0], qx = Array.prototype.slice.call(arguments, 1), rx = []; for (var i = 0 ; i < px.length ; i++) { rx.push(_.each(px[i], qx)); } return rx; }, cache: function (rule) { var cache = {}, r = null; return function (s) { try { r = cache[s] = (cache[s] || rule.call(this, s)); } catch (e) { r = cache[s] = e; } if (r instanceof $P.Exception) { throw r; } else { return r; } }; }, // vector operators -- see below any: function () { var px = arguments; return function (s) { var r = null; for (var i = 0; i < px.length; i++) { if (px[i] == null) { continue; } try { r = (px[i].call(this, s)); } catch (e) { r = null; } if (r) { return r; } } throw new $P.Exception(s); }; }, each: function () { var px = arguments; return function (s) { var rx = [], r = null; for (var i = 0; i < px.length ; i++) { if (px[i] == null) { continue; } try { r = (px[i].call(this, s)); } catch (e) { throw new $P.Exception(s); } rx.push(r[0]); s = r[1]; } return [ rx, s]; }; }, all: function () { var px = arguments, _ = _; return _.each(_.optional(px)); }, // delimited operators sequence: function (px, d, c) { d = d || _.rtoken(/^\s*/); c = c || null; if (px.length == 1) { return px[0]; } return function (s) { var r = null, q = null; var rx = []; for (var i = 0; i < px.length ; i++) { try { r = px[i].call(this, s); } catch (e) { break; } rx.push(r[0]); try { q = d.call(this, r[1]); } catch (ex) { q = null; break; } s = q[1]; } if (!r) { throw new $P.Exception(s); } if (q) { throw new $P.Exception(q[1]); } if (c) { try { r = c.call(this, r[1]); } catch (ey) { throw new $P.Exception(r[1]); } } return [ rx, (r?r[1]:s) ]; }; }, // // Composite Operators // between: function (d1, p, d2) { d2 = d2 || d1; var _fn = _.each(_.ignore(d1), p, _.ignore(d2)); return function (s) { var rx = _fn.call(this, s); return [[rx[0][0], r[0][2]], rx[1]]; }; }, list: function (p, d, c) { d = d || _.rtoken(/^\s*/); c = c || null; return (p instanceof Array ? _.each(_.product(p.slice(0, -1), _.ignore(d)), p.slice(-1), _.ignore(c)) : _.each(_.many(_.each(p, _.ignore(d))), px, _.ignore(c))); }, set: function (px, d, c) { d = d || _.rtoken(/^\s*/); c = c || null; return function (s) { // r is the current match, best the current 'best' match // which means it parsed the most amount of input var r = null, p = null, q = null, rx = null, best = [[], s], last = false; // go through the rules in the given set for (var i = 0; i < px.length ; i++) { // last is a flag indicating whether this must be the last element // if there is only 1 element, then it MUST be the last one q = null; p = null; r = null; last = (px.length == 1); // first, we try simply to match the current pattern // if not, try the next pattern try { r = px[i].call(this, s); } catch (e) { continue; } // since we are matching against a set of elements, the first // thing to do is to add r[0] to matched elements rx = [[r[0]], r[1]]; // if we matched and there is still input to parse and // we don't already know this is the last element, // we're going to next check for the delimiter ... // if there's none, or if there's no input left to parse // than this must be the last element after all ... if (r[1].length > 0 && ! last) { try { q = d.call(this, r[1]); } catch (ex) { last = true; } } else { last = true; } // if we parsed the delimiter and now there's no more input, // that means we shouldn't have parsed the delimiter at all // so don't update r and mark this as the last element ... if (!last && q[1].length === 0) { last = true; } // so, if this isn't the last element, we're going to see if // we can get any more matches from the remaining (unmatched) // elements ... if (!last) { // build a list of the remaining rules we can match against, // i.e., all but the one we just matched against var qx = []; for (var j = 0; j < px.length ; j++) { if (i != j) { qx.push(px[j]); } } // now invoke recursively set with the remaining input // note that we don't include the closing delimiter ... // we'll check for that ourselves at the end p = _.set(qx, d).call(this, q[1]); // if we got a non-empty set as a result ... // (otw rx already contains everything we want to match) if (p[0].length > 0) { // update current result, which is stored in rx ... // basically, pick up the remaining text from p[1] // and concat the result from p[0] so that we don't // get endless nesting ... rx[0] = rx[0].concat(p[0]); rx[1] = p[1]; } } // at this point, rx either contains the last matched element // or the entire matched set that starts with this element. // now we just check to see if this variation is better than // our best so far, in terms of how much of the input is parsed if (rx[1].length < best[1].length) { best = rx; } // if we've parsed all the input, then we're finished if (best[1].length === 0) { break; } } // so now we've either gone through all the patterns trying them // as the initial match; or we found one that parsed the entire // input string ... // if best has no matches, just return empty set ... if (best[0].length === 0) { return best; } // if a closing delimiter is provided, then we have to check it also if (c) { // we try this even if there is no remaining input because the pattern // may well be optional or match empty input ... try { q = c.call(this, best[1]); } catch (ey) { throw new $P.Exception(best[1]); } // it parsed ... be sure to update the best match remaining input best[1] = q[1]; } // if we're here, either there was no closing delimiter or we parsed it // so now we have the best match; just return it! return best; }; }, forward: function (gr, fname) { return function (s) { return gr[fname].call(this, s); }; }, // // Translation Operators // replace: function (rule, repl) { return function (s) { var r = rule.call(this, s); return [repl, r[1]]; }; }, process: function (rule, fn) { return function (s) { var r = rule.call(this, s); return [fn.call(this, r[0]), r[1]]; }; }, min: function (min, rule) { return function (s) { var rx = rule.call(this, s); if (rx[0].length < min) { throw new $P.Exception(s); } return rx; }; } }; // Generator Operators And Vector Operators // Generators are operators that have a signature of F(R) => R, // taking a given rule and returning another rule, such as // ignore, which parses a given rule and throws away the result. // Vector operators are those that have a signature of F(R1,R2,...) => R, // take a list of rules and returning a new rule, such as each. // Generator operators are converted (via the following _generator // function) into functions that can also take a list or array of rules // and return an array of new rules as though the function had been // called on each rule in turn (which is what actually happens). // This allows generators to be used with vector operators more easily. // Example: // each(ignore(foo, bar)) instead of each(ignore(foo), ignore(bar)) // This also turns generators into vector operators, which allows // constructs like: // not(cache(foo, bar)) var _generator = function (op) { function gen() { var args = null, rx = [], px, i; if (arguments.length > 1) { args = Array.prototype.slice.call(arguments); } else if (arguments[0] instanceof Array) { args = arguments[0]; } if (args) { px = args.shift(); if (px.length > 0) { args.unshift(px[i]); rx.push(op.apply(null, args)); args.shift(); return rx; } } else { return op.apply(null, arguments); } } return gen; }; var gx = "optional not ignore cache".split(/\s/); for (var i = 0 ; i < gx.length ; i++) { _[gx[i]] = _generator(_[gx[i]]); } var _vector = function (op) { return function () { if (arguments[0] instanceof Array) { return op.apply(null, arguments[0]); } else { return op.apply(null, arguments); } }; }; var vx = "each any all".split(/\s/); for (var j = 0 ; j < vx.length ; j++) { _[vx[j]] = _vector(_[vx[j]]); } }()); (function () { var $D = Date; var flattenAndCompact = function (ax) { var rx = []; for (var i = 0; i < ax.length; i++) { if (ax[i] instanceof Array) { rx = rx.concat(flattenAndCompact(ax[i])); } else { if (ax[i]) { rx.push(ax[i]); } } } return rx; }; $D.Grammar = {}; $D.Translator = { hour: function (s) { return function () { this.hour = Number(s); }; }, minute: function (s) { return function () { this.minute = Number(s); }; }, second: function (s) { return function () { this.second = Number(s); }; }, /* for ss.s format */ secondAndMillisecond: function (s) { return function () { var mx = s.match(/^([0-5][0-9])\.([0-9]{1,3})/); this.second = Number(mx[1]); this.millisecond = Number(mx[2]); }; }, meridian: function (s) { return function () { this.meridian = s.slice(0, 1).toLowerCase(); }; }, timezone: function (s) { return function () { var n = s.replace(/[^\d\+\-]/g, ""); if (n.length) { this.timezoneOffset = Number(n); } else { this.timezone = s.toLowerCase(); } }; }, day: function (x) { var s = x[0]; return function () { this.day = Number(s.match(/\d+/)[0]); if (this.day < 1) { throw "invalid day"; } }; }, month: function (s) { return function () { this.month = (s.length === 3) ? "jan feb mar apr may jun jul aug sep oct nov dec".indexOf(s)/4 : Number(s) - 1; if (this.month < 0) { throw "invalid month"; } }; }, year: function (s) { return function () { var n = Number(s); this.year = ((s.length > 2) ? n : (n + (((n + 2000) < Date.CultureInfo.twoDigitYearMax) ? 2000 : 1900))); }; }, rday: function (s) { return function () { switch (s) { case "yesterday": this.days = -1; break; case "tomorrow": this.days = 1; break; case "today": this.days = 0; break; case "now": this.days = 0; this.now = true; break; } }; }, finishExact: function (x) { x = (x instanceof Array) ? x : [ x ]; for (var i = 0 ; i < x.length ; i++) { if (x[i]) { x[i].call(this); } } var now = new Date(); if ((this.hour || this.minute) && (!this.month && !this.year && !this.day)) { this.day = now.getDate(); } if (!this.year) { this.year = now.getFullYear(); } if (!this.month && this.month !== 0) { this.month = now.getMonth(); } if (!this.day) { this.day = 1; } if (!this.hour) { this.hour = 0; } if (!this.minute) { this.minute = 0; } if (!this.second) { this.second = 0; } if (!this.millisecond) { this.millisecond = 0; } if (this.meridian && (this.hour || this.hour === 0)) { if (this.meridian == "a" && this.hour > 11 && Date.Config.strict24hr){ throw "Invalid hour and meridian combination"; } else if (this.meridian == "p" && this.hour < 12 && Date.Config.strict24hr){ throw "Invalid hour and meridian combination"; } else if (this.meridian == "p" && this.hour < 12) { this.hour = this.hour + 12; } else if (this.meridian == "a" && this.hour == 12) { this.hour = 0; } } if (this.day > $D.getDaysInMonth(this.year, this.month)) { throw new RangeError(this.day + " is not a valid value for days."); } var r = new Date(this.year, this.month, this.day, this.hour, this.minute, this.second, this.millisecond); if (this.year < 100) { r.setFullYear(this.year); // means years less that 100 are process correctly. JS will parse it otherwise as 1900-1999. } if (this.timezone) { r.set({ timezone: this.timezone }); } else if (this.timezoneOffset) { r.set({ timezoneOffset: this.timezoneOffset }); } return r; }, finish: function (x) { x = (x instanceof Array) ? flattenAndCompact(x) : [ x ]; if (x.length === 0) { return null; } for (var i = 0 ; i < x.length ; i++) { if (typeof x[i] == "function") { x[i].call(this); } } var today = $D.today(); if (this.now && !this.unit && !this.operator) { return new Date(); } else if (this.now) { today = new Date(); } var expression = !!(this.days && this.days !== null || this.orient || this.operator); var gap, mod, orient; orient = ((this.orient == "past" || this.operator == "subtract") ? -1 : 1); if(!this.now && "hour minute second".indexOf(this.unit) != -1) { today.setTimeToNow(); } if (this.month && this.unit == "week") { this.value = this.month + 1; delete this.month; delete this.day; } if (this.month || this.month === 0) { if ("year day hour minute second".indexOf(this.unit) != -1) { if (!this.value) { this.value = this.month + 1; } this.month = null; expression = true; } } if (!expression && this.weekday && !this.day && !this.days) { var temp = Date[this.weekday](); this.day = temp.getDate(); if (!this.month) { this.month = temp.getMonth(); } this.year = temp.getFullYear(); } if (expression && this.weekday && this.unit != "month" && this.unit != "week") { this.unit = "day"; gap = ($D.getDayNumberFromName(this.weekday) - today.getDay()); mod = 7; this.days = gap ? ((gap + (orient * mod)) % mod) : (orient * mod); } if (this.month && this.unit == "day" && this.operator) { if (!this.value) { this.value = (this.month + 1); } this.month = null; } if (this.value != null && this.month != null && this.year != null) { this.day = this.value * 1; } if (this.month && !this.day && this.value) { today.set({ day: this.value * 1 }); if (!expression) { this.day = this.value * 1; } } if (!this.month && this.value && this.unit == "month" && !this.now) { this.month = this.value; expression = true; } if (expression && (this.month || this.month === 0) && this.unit != "year") { this.unit = "month"; gap = (this.month - today.getMonth()); mod = 12; this.months = gap ? ((gap + (orient * mod)) % mod) : (orient * mod); this.month = null; } if (!this.unit) { this.unit = "day"; } if (!this.value && this.operator && this.operator !== null && this[this.unit + "s"] && this[this.unit + "s"] !== null) { this[this.unit + "s"] = this[this.unit + "s"] + ((this.operator == "add") ? 1 : -1) + (this.value||0) * orient; } else if (this[this.unit + "s"] == null || this.operator != null) { if (!this.value) { this.value = 1; } this[this.unit + "s"] = this.value * orient; } if (this.meridian && (this.hour || this.hour === 0)) { if (this.meridian == "a" && this.hour > 11 && Date.Config.strict24hr){ throw "Invalid hour and meridian combination"; } else if (this.meridian == "p" && this.hour < 12 && Date.Config.strict24hr){ throw "Invalid hour and meridian combination"; } else if (this.meridian == "p" && this.hour < 12) { this.hour = this.hour + 12; } else if (this.meridian == "a" && this.hour == 12) { this.hour = 0; } } if (this.weekday && this.unit !== "week" && !this.day && !this.days) { var temp = Date[this.weekday](); this.day = temp.getDate(); if (temp.getMonth() !== today.getMonth()) { this.month = temp.getMonth(); } } if ((this.month || this.month === 0) && !this.day) { this.day = 1; } if (!this.orient && !this.operator && this.unit == "week" && this.value && !this.day && !this.month) { return Date.today().setWeek(this.value); } if (this.unit == "week" && this.weeks && !this.day && !this.month) { var weekday = (this.weekday) ? this.weekday : "today"; var d = Date[weekday]().addWeeks(this.weeks); if (this.now) { d.setTimeToNow(); } return d; } if (expression && this.timezone && this.day && this.days) { this.day = this.days; } return (expression) ? today.add(this) : today.set(this); } }; var _ = $D.Parsing.Operators, g = $D.Grammar, t = $D.Translator, _fn; g.datePartDelimiter = _.rtoken(/^([\s\-\.\,\/\x27]+)/); g.timePartDelimiter = _.stoken(":"); g.whiteSpace = _.rtoken(/^\s*/); g.generalDelimiter = _.rtoken(/^(([\s\,]|at|@|on)+)/); var _C = {}; g.ctoken = function (keys) { var fn = _C[keys]; if (! fn) { var c = Date.CultureInfo.regexPatterns; var kx = keys.split(/\s+/), px = []; for (var i = 0; i < kx.length ; i++) { px.push(_.replace(_.rtoken(c[kx[i]]), kx[i])); } fn = _C[keys] = _.any.apply(null, px); } return fn; }; g.ctoken2 = function (key) { return _.rtoken(Date.CultureInfo.regexPatterns[key]); }; // hour, minute, second, meridian, timezone g.h = _.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2]|[1-9])/), t.hour)); g.hh = _.cache(_.process(_.rtoken(/^(0[0-9]|1[0-2])/), t.hour)); g.H = _.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3]|[0-9])/), t.hour)); g.HH = _.cache(_.process(_.rtoken(/^([0-1][0-9]|2[0-3])/), t.hour)); g.m = _.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/), t.minute)); g.mm = _.cache(_.process(_.rtoken(/^[0-5][0-9]/), t.minute)); g.s = _.cache(_.process(_.rtoken(/^([0-5][0-9]|[0-9])/), t.second)); g.ss = _.cache(_.process(_.rtoken(/^[0-5][0-9]/), t.second)); g["ss.s"] = _.cache(_.process(_.rtoken(/^[0-5][0-9]\.[0-9]{1,3}/), t.secondAndMillisecond)); g.hms = _.cache(_.sequence([g.H, g.m, g.s], g.timePartDelimiter)); // _.min(1, _.set([ g.H, g.m, g.s ], g._t)); g.t = _.cache(_.process(g.ctoken2("shortMeridian"), t.meridian)); g.tt = _.cache(_.process(g.ctoken2("longMeridian"), t.meridian)); g.z = _.cache(_.process(_.rtoken(/^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/), t.timezone)); g.zz = _.cache(_.process(_.rtoken(/^((\+|\-)\s*\d\d\d\d)|((\+|\-)\d\d\:?\d\d)/), t.timezone)); g.zzz = _.cache(_.process(g.ctoken2("timezone"), t.timezone)); g.timeSuffix = _.each(_.ignore(g.whiteSpace), _.set([ g.tt, g.zzz ])); g.time = _.each(_.optional(_.ignore(_.stoken("T"))), g.hms, g.timeSuffix); // days, months, years g.d = _.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1]|\d)/), _.optional(g.ctoken2("ordinalSuffix"))), t.day)); g.dd = _.cache(_.process(_.each(_.rtoken(/^([0-2]\d|3[0-1])/), _.optional(g.ctoken2("ordinalSuffix"))), t.day)); g.ddd = g.dddd = _.cache(_.process(g.ctoken("sun mon tue wed thu fri sat"), function (s) { return function () { this.weekday = s; }; } )); g.M = _.cache(_.process(_.rtoken(/^(1[0-2]|0\d|\d)/), t.month)); g.MM = _.cache(_.process(_.rtoken(/^(1[0-2]|0\d)/), t.month)); g.MMM = g.MMMM = _.cache(_.process(g.ctoken("jan feb mar apr may jun jul aug sep oct nov dec"), t.month)); // g.MMM = g.MMMM = _.cache(_.process(g.ctoken(Date.CultureInfo.abbreviatedMonthNames.join(" ")), t.month)); g.y = _.cache(_.process(_.rtoken(/^(\d\d?)/), t.year)); g.yy = _.cache(_.process(_.rtoken(/^(\d\d)/), t.year)); g.yyy = _.cache(_.process(_.rtoken(/^(\d\d?\d?\d?)/), t.year)); g.yyyy = _.cache(_.process(_.rtoken(/^(\d\d\d\d)/), t.year)); // rolling these up into general purpose rules _fn = function () { return _.each(_.any.apply(null, arguments), _.not(g.ctoken2("timeContext"))); }; g.day = _fn(g.d, g.dd); g.month = _fn(g.M, g.MMM); g.year = _fn(g.yyyy, g.yy); // relative date / time expressions g.orientation = _.process(g.ctoken("past future"), function (s) { return function () { this.orient = s; }; } ); g.operator = _.process(g.ctoken("add subtract"), function (s) { return function () { this.operator = s; }; } ); g.rday = _.process(g.ctoken("yesterday tomorrow today now"), t.rday); g.unit = _.process(g.ctoken("second minute hour day week month year"), function (s) { return function () { this.unit = s; }; } ); g.value = _.process(_.rtoken(/^([-+]?\d+)?(st|nd|rd|th)?/), function (s) { return function () { this.value = s.replace(/\D/g, ""); }; } ); g.expression = _.set([ g.rday, g.operator, g.value, g.unit, g.orientation, g.ddd, g.MMM ]); // pre-loaded rules for different date part order preferences _fn = function () { return _.set(arguments, g.datePartDelimiter); }; g.mdy = _fn(g.ddd, g.month, g.day, g.year); g.ymd = _fn(g.ddd, g.year, g.month, g.day); g.dmy = _fn(g.ddd, g.day, g.month, g.year); g.date = function (s) { return ((g[Date.CultureInfo.dateElementOrder] || g.mdy).call(this, s)); }; // parsing date format specifiers - ex: "h:m:s tt" // this little guy will generate a custom parser based // on the format string, ex: g.format("h:m:s tt") g.format = _.process(_.many( _.any( // translate format specifiers into grammar rules _.process( _.rtoken(/^(dd?d?d?(?!e)|MM?M?M?|yy?y?y?|hh?|HH?|mm?|ss?|tt?|zz?z?)/), function (fmt) { if (g[fmt]) { return g[fmt]; } else { throw $D.Parsing.Exception(fmt); } } ), // translate separator tokens into token rules _.process(_.rtoken(/^[^dMyhHmstz]+/), // all legal separators function (s) { return _.ignore(_.stoken(s)); } ) )), // construct the parser ... function (rules) { return _.process(_.each.apply(null, rules), t.finishExact); } ); var _F = { //"M/d/yyyy": function (s) { // var m = s.match(/^([0-2]\d|3[0-1]|\d)\/(1[0-2]|0\d|\d)\/(\d\d\d\d)/); // if (m!=null) { // var r = [ t.month.call(this,m[1]), t.day.call(this,m[2]), t.year.call(this,m[3]) ]; // r = t.finishExact.call(this,r); // return [ r, "" ]; // } else { // throw new Date.Parsing.Exception(s); // } //} //"M/d/yyyy": function (s) { return [ new Date(Date._parse(s)), ""]; } }; var _get = function (f) { _F[f] = (_F[f] || g.format(f)[0]); return _F[f]; }; g.allformats = function (fx) { var rx = []; if (fx instanceof Array) { for (var i = 0; i < fx.length; i++) { rx.push(_get(fx[i])); } } else { rx.push(_get(fx)); } return rx; }; g.formats = function (fx) { if (fx instanceof Array) { var rx = []; for (var i = 0 ; i < fx.length ; i++) { rx.push(_get(fx[i])); } return _.any.apply(null, rx); } else { return _get(fx); } }; // check for these formats first g._formats = g.formats([ "\"yyyy-MM-ddTHH:mm:ssZ\"", "yyyy-MM-ddTHH:mm:ss.sz", "yyyy-MM-ddTHH:mm:ssZ", "yyyy-MM-ddTHH:mm:ssz", "yyyy-MM-ddTHH:mm:ss", "yyyy-MM-ddTHH:mmZ", "yyyy-MM-ddTHH:mmz", "yyyy-MM-ddTHH:mm", "ddd, MMM dd, yyyy H:mm:ss tt", "ddd MMM d yyyy HH:mm:ss zzz", "MMddyyyy", "ddMMyyyy", "Mddyyyy", "ddMyyyy", "Mdyyyy", "dMyyyy", "yyyy", "Mdyy", "dMyy", "d" ]); // starting rule for general purpose grammar g._start = _.process(_.set([ g.date, g.time, g.expression ], g.generalDelimiter, g.whiteSpace), t.finish); // real starting rule: tries selected formats first, // then general purpose rule g.start = function (s) { try { var r = g._formats.call({}, s); if (r[1].length === 0) { return r; } } catch (e) {} return g._start.call({}, s); }; /** * @desc Converts the specified string value into its JavaScript Date equivalent using CultureInfo specific format information. * * Example <pre><code> /////////// // Dates // /////////// // 15-Oct-2004 var d1 = Date.parse("10/15/2004"); // 15-Oct-2004 var d1 = Date.parse("15-Oct-2004"); // 15-Oct-2004 var d1 = Date.parse("2004.10.15"); //Fri Oct 15, 2004 var d1 = Date.parse("Fri Oct 15, 2004"); /////////// // Times // /////////// // Today at 10 PM. var d1 = Date.parse("10 PM"); // Today at 10:30 PM. var d1 = Date.parse("10:30 P.M."); // Today at 6 AM. var d1 = Date.parse("06am"); ///////////////////// // Dates and Times // ///////////////////// // 8-July-2004 @ 10:30 PM var d1 = Date.parse("July 8th, 2004, 10:30 PM"); // 1-July-2004 @ 10:30 PM var d1 = Date.parse("2004-07-01T22:30:00"); //////////////////// // Relative Dates // //////////////////// // Returns today's date. The string "today" is culture specific. var d1 = Date.parse("today"); // Returns yesterday's date. The string "yesterday" is culture specific. var d1 = Date.parse("yesterday"); // Returns the date of the next thursday. var d1 = Date.parse("Next thursday"); // Returns the date of the most previous monday. var d1 = Date.parse("last monday"); // Returns today's day + one year. var d1 = Date.parse("next year"); /////////////// // Date Math // /////////////// // Today + 2 days var d1 = Date.parse("t+2"); // Today + 2 days var d1 = Date.parse("today + 2 days"); // Today + 3 months var d1 = Date.parse("t+3m"); // Today - 1 year var d1 = Date.parse("today - 1 year"); // Today - 1 year var d1 = Date.parse("t-1y"); ///////////////////////////// // Partial Dates and Times // ///////////////////////////// // July 15th of this year. var d1 = Date.parse("July 15"); // 15th day of current day and year. var d1 = Date.parse("15"); // July 1st of current year at 10pm. var d1 = Date.parse("7/1 10pm"); </code></pre> * * @param {String} The string value to convert into a Date object [Required] * @return {Date} A Date object or null if the string cannot be converted into a Date. */ function parse (s) { var ords, d, t, r = null; if (!s) { return null; } if (s instanceof Date) { return s.clone(); } if (s.length >= 4 && s.charAt(0) !== "0" && s.charAt(0) !== "+"&& s.charAt(0) !== "-") { // ie: 2004 will pass, 0800 won't. // Start with specific formats d = $D.Parsing.ISO.parse(s) || $D.Parsing.Numeric.parse(s); } if (d instanceof Date && !isNaN(d.getTime())) { return d; } else { // find ordinal dates (1st, 3rd, 8th, etc and remove them as they cause parsing issues) ords = s.match(/\b(\d+)(?:st|nd|rd|th)\b/); // find ordinal matches s = ((ords && ords.length === 2) ? s.replace(ords[0], ords[1]) : s); s = $D.Parsing.Normalizer.parse(s); try { r = $D.Grammar.start.call({}, s.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1")); } catch (e) { return null; } d = ((r[1].length === 0) ? r[0] : null); if (d !== null) { return d; } else { try { // ok we haven't parsed it, last ditch attempt with the built-in parser. t = Date._parse(s); return (t || t === 0) ? new Date(t) : null; } catch (e) { return null; } } } } if (!$D._parse) { $D._parse = $D.parse; } $D.parse = parse; Date.getParseFunction = function (fx) { var fns = Date.Grammar.allformats(fx); return function (s) { var r = null; for (var i = 0; i < fns.length; i++) { try { r = fns[i].call({}, s); } catch (e) { continue; } if (r[1].length === 0) { return r[0]; } } return null; }; }; /** * Converts the specified string value into its JavaScript Date equivalent using the specified format {String} or formats {Array} and the CultureInfo specific format information. * The format of the string value must match one of the supplied formats exactly. * * Example <pre><code> // 15-Oct-2004 var d1 = Date.parseExact("10/15/2004", "M/d/yyyy"); // 15-Oct-2004 var d1 = Date.parse("15-Oct-2004", "M-ddd-yyyy"); // 15-Oct-2004 var d1 = Date.parse("2004.10.15", "yyyy.MM.dd"); // Multiple formats var d1 = Date.parseExact("10/15/2004", ["M/d/yyyy", "MMMM d, yyyy"]); </code></pre> * * @param {String} The string value to convert into a Date object [Required]. * @param {Object} The expected format {String} or an array of expected formats {Array} of the date string [Required]. * @return {Date} A Date object or null if the string cannot be converted into a Date. */ $D.parseExact = function (s, fx) { return $D.getParseFunction(fx)(s); }; }()); /************************************************************* * SugarPak - Domain Specific Language - Syntactical Sugar * *************************************************************/ (function () { var $D = Date, $P = $D.prototype, $N = Number.prototype; // private $P._orient = +1; // private $P._nth = null; // private $P._is = false; // private $P._same = false; // private $P._isSecond = false; // private $N._dateElement = "days"; /** * Moves the date to the next instance of a date as specified by the subsequent date element function (eg. .day(), .month()), month name function (eg. .january(), .jan()) or day name function (eg. .friday(), fri()). * Example <pre><code> Date.today().next().friday(); Date.today().next().fri(); Date.today().next().march(); Date.today().next().mar(); Date.today().next().week(); </code></pre> * * @return {Date} date */ $P.next = function () { this._move = true; this._orient = +1; return this; }; /** * Creates a new Date (Date.today()) and moves the date to the next instance of the date as specified by the subsequent date element function (eg. .day(), .month()), month name function (eg. .january(), .jan()) or day name function (eg. .friday(), fri()). * Example <pre><code> Date.next().friday(); Date.next().fri(); Date.next().march(); Date.next().mar(); Date.next().week(); </code></pre> * * @return {Date} date */ $D.next = function () { return $D.today().next(); }; /** * Moves the date to the previous instance of a date as specified by the subsequent date element function (eg. .day(), .month()), month name function (eg. .january(), .jan()) or day name function (eg. .friday(), fri()). * Example <pre><code> Date.today().last().friday(); Date.today().last().fri(); Date.today().last().march(); Date.today().last().mar(); Date.today().last().week(); </code></pre> * * @return {Date} date */ $P.last = $P.prev = $P.previous = function () { this._move = true; this._orient = -1; return this; }; /** * Creates a new Date (Date.today()) and moves the date to the previous instance of the date as specified by the subsequent date element function (eg. .day(), .month()), month name function (eg. .january(), .jan()) or day name function (eg. .friday(), fri()). * Example <pre><code> Date.last().friday(); Date.last().fri(); Date.previous().march(); Date.prev().mar(); Date.last().week(); </code></pre> * * @return {Date} date */ $D.last = $D.prev = $D.previous = function () { return $D.today().last(); }; /** * Performs a equality check when followed by either a month name, day name or .weekday() function. * Example <pre><code> Date.today().is().friday(); // true|false Date.today().is().fri(); Date.today().is().march(); Date.today().is().mar(); </code></pre> * * @return {Boolean} true|false */ $P.is = function () { this._is = true; return this; }; /** * Determines if two date objects occur on/in exactly the same instance of the subsequent date part function. * The function .same() must be followed by a date part function (example: .day(), .month(), .year(), etc). * * An optional Date can be passed in the date part function. If now date is passed as a parameter, 'Now' is used. * * The following example demonstrates how to determine if two dates fall on the exact same day. * * Example <pre><code> var d1 = Date.today(); // today at 00:00 var d2 = new Date(); // exactly now. // Do they occur on the same day? d1.same().day(d2); // true // Do they occur on the same hour? d1.same().hour(d2); // false, unless d2 hour is '00' (midnight). // What if it's the same day, but one year apart? var nextYear = Date.today().add(1).year(); d1.same().day(nextYear); // false, because the dates must occur on the exact same day. </code></pre> * * Scenario: Determine if a given date occurs during some week period 2 months from now. * * Example <pre><code> var future = Date.today().add(2).months(); return someDate.same().week(future); // true|false; </code></pre> * * @return {Boolean} true|false */ $P.same = function () { this._same = true; this._isSecond = false; return this; }; /** * Determines if the current date/time occurs during Today. Must be preceded by the .is() function. * Example <pre><code> someDate.is().today(); // true|false new Date().is().today(); // true Date.today().is().today();// true Date.today().add(-1).day().is().today(); // false </code></pre> * * @return {Boolean} true|false */ $P.today = function () { return this.same().day(); }; /** * Determines if the current date is a weekday. This function must be preceded by the .is() function. * Example <pre><code> Date.today().is().weekday(); // true|false </code></pre> * * @return {Boolean} true|false */ $P.weekday = function () { if (this._nth) { return df("Weekday").call(this); } if (this._move) { return this.addWeekdays(this._orient); } if (this._is) { this._is = false; return (!this.is().sat() && !this.is().sun()); } return false; }; /** * Determines if the current date is on the weekend. This function must be preceded by the .is() function. * Example <pre><code> Date.today().is().weekend(); // true|false </code></pre> * * @return {Boolean} true|false */ $P.weekend = function () { if (this._is) { this._is = false; return (this.is().sat() || this.is().sun()); } return false; }; /** * Sets the Time of the current Date instance. A string "6:15 pm" or config object {hour:18, minute:15} are accepted. * Example <pre><code> // Set time to 6:15pm with a String Date.today().at("6:15pm"); // Set time to 6:15pm with a config object Date.today().at({hour:18, minute:15}); </code></pre> * * @return {Date} date */ $P.at = function (time) { return (typeof time === "string") ? $D.parse(this.toString("d") + " " + time) : this.set(time); }; /** * Creates a new Date() and adds this (Number) to the date based on the preceding date element function (eg. second|minute|hour|day|month|year). * Example <pre><code> // Undeclared Numbers must be wrapped with parentheses. Requirment of JavaScript. (3).days().fromNow(); (6).months().fromNow(); // Declared Number variables do not require parentheses. var n = 6; n.months().fromNow(); </code></pre> * * @return {Date} A new Date instance */ $N.fromNow = $N.after = function (date) { var c = {}; c[this._dateElement] = this; return ((!date) ? new Date() : date.clone()).add(c); }; /** * Creates a new Date() and subtract this (Number) from the date based on the preceding date element function (eg. second|minute|hour|day|month|year). * Example <pre><code> // Undeclared Numbers must be wrapped with parentheses. Requirment of JavaScript. (3).days().ago(); (6).months().ago(); // Declared Number variables do not require parentheses. var n = 6; n.months().ago(); </code></pre> * * @return {Date} A new Date instance */ $N.ago = $N.before = function (date) { var c = {}, s = (this._dateElement[this._dateElement.length-1] !== "s") ? this._dateElement + "s" : this._dateElement; c[s] = this * -1; return ((!date) ? new Date() : date.clone()).add(c); }; // Do NOT modify the following string tokens. These tokens are used to build dynamic functions. // All culture-specific strings can be found in the CultureInfo files. var dx = ("sunday monday tuesday wednesday thursday friday saturday").split(/\s/), mx = ("january february march april may june july august september october november december").split(/\s/), px = ("Millisecond Second Minute Hour Day Week Month Year Quarter Weekday").split(/\s/), pxf = ("Milliseconds Seconds Minutes Hours Date Week Month FullYear Quarter").split(/\s/), nth = ("final first second third fourth fifth").split(/\s/), de; /** * Returns an object literal of all the date parts. * Example <pre><code> var o = new Date().toObject(); // { year: 2008, month: 4, week: 20, day: 13, hour: 18, minute: 9, second: 32, millisecond: 812 } // The object properties can be referenced directly from the object. alert(o.day); // alerts "13" alert(o.year); // alerts "2008" </code></pre> * * @return {Date} An object literal representing the original date object. */ $P.toObject = function () { var o = {}; for (var i = 0; i < px.length; i++) { if (this["get" + pxf[i]]) { o[px[i].toLowerCase()] = this["get" + pxf[i]](); } } return o; }; /** * Returns a date created from an object literal. Ignores the .week property if set in the config. * Example <pre><code> var o = new Date().toObject(); return Date.fromObject(o); // will return the same date. var o2 = {month: 1, day: 20, hour: 18}; // birthday party! Date.fromObject(o2); </code></pre> * * @return {Date} An object literal representing the original date object. */ $D.fromObject = function(config) { config.week = null; return Date.today().set(config); }; // Create day name functions and abbreviated day name functions (eg. monday(), friday(), fri()). var df = function (n) { return function () { if (this._is) { this._is = false; return this.getDay() === n; } if (this._move) { this._move = null; } if (this._nth !== null) { // If the .second() function was called earlier, remove the _orient // from the date, and then continue. // This is required because 'second' can be used in two different context. // // Example // // Date.today().add(1).second(); // Date.march().second().monday(); // // Things get crazy with the following... // Date.march().add(1).second().second().monday(); // but it works!! // if (this._isSecond) { this.addSeconds(this._orient * -1); } // make sure we reset _isSecond this._isSecond = false; var ntemp = this._nth; this._nth = null; var temp = this.clone().moveToLastDayOfMonth(); this.moveToNthOccurrence(n, ntemp); if (this > temp) { throw new RangeError($D.getDayName(n) + " does not occur " + ntemp + " times in the month of " + $D.getMonthName(temp.getMonth()) + " " + temp.getFullYear() + "."); } return this; } return this.moveToDayOfWeek(n, this._orient); }; }; var sdf = function (n) { return function () { var t = $D.today(), shift = n - t.getDay(); if (n === 0 && Date.CultureInfo.firstDayOfWeek === 1 && t.getDay() !== 0) { shift = shift + 7; } return t.addDays(shift); }; }; for (var i = 0; i < dx.length; i++) { // Create constant static Day Name variables. Example: Date.MONDAY or Date.MON $D[dx[i].toUpperCase()] = $D[dx[i].toUpperCase().substring(0, 3)] = i; // Create Day Name functions. Example: Date.monday() or Date.mon() $D[dx[i]] = $D[dx[i].substring(0, 3)] = sdf(i); // Create Day Name instance functions. Example: Date.today().next().monday() $P[dx[i]] = $P[dx[i].substring(0, 3)] = df(i); } // Create month name functions and abbreviated month name functions (eg. january(), march(), mar()). var month_instance_functions = function (n) { return function () { if (this._is) { this._is = false; return this.getMonth() === n; } return this.moveToMonth(n, this._orient); }; }; var month_static_functions = function (n) { return function () { return $D.today().set({ month: n, day: 1 }); }; }; for (var j = 0; j < mx.length; j++) { // Create constant static Month Name variables. Example: Date.MARCH or Date.MAR $D[mx[j].toUpperCase()] = $D[mx[j].toUpperCase().substring(0, 3)] = j; // Create Month Name functions. Example: Date.march() or Date.mar() $D[mx[j]] = $D[mx[j].substring(0, 3)] = month_static_functions(j); // Create Month Name instance functions. Example: Date.today().next().march() $P[mx[j]] = $P[mx[j].substring(0, 3)] = month_instance_functions(j); } // Create date element functions and plural date element functions used with Date (eg. day(), days(), months()). var ef = function (j) { return function () { // if the .second() function was called earlier, the _orient // has alread been added. Just return this and reset _isSecond. if (this._isSecond) { this._isSecond = false; return this; } if (this._same) { this._same = this._is = false; var o1 = this.toObject(), o2 = (arguments[0] || new Date()).toObject(), v = "", k = j.toLowerCase(); // the substr trick with -1 doesn't work in IE8 or less k = (k[k.length-1] === "s") ? k.substring(0,k.length-1) : k; for (var m = (px.length - 1); m > -1; m--) { v = px[m].toLowerCase(); if (o1[v] !== o2[v]) { return false; } if (k === v) { break; } } return true; } if (j.substring(j.length - 1) !== "s") { j += "s"; } if (this._move) { this._move = null; } return this["add" + j](this._orient); }; }; var nf = function (n) { return function () { this._dateElement = n; return this; }; }; for (var k = 0; k < px.length; k++) { de = px[k].toLowerCase(); if(de !== "weekday") { // Create date element functions and plural date element functions used with Date (eg. day(), days(), months()). $P[de] = $P[de + "s"] = ef(px[k]); // Create date element functions and plural date element functions used with Number (eg. day(), days(), months()). $N[de] = $N[de + "s"] = nf(de + "s"); } } $P._ss = ef("Second"); var nthfn = function (n) { return function (dayOfWeek) { if (this._same) { return this._ss(arguments[0]); } if (dayOfWeek || dayOfWeek === 0) { return this.moveToNthOccurrence(dayOfWeek, n); } this._nth = n; // if the operator is 'second' add the _orient, then deal with it later... if (n === 2 && (dayOfWeek === undefined || dayOfWeek === null)) { this._isSecond = true; return this.addSeconds(this._orient); } return this; }; }; for (var l = 0; l < nth.length; l++) { $P[nth[l]] = (l === 0) ? nthfn(-1) : nthfn(l); } }()); (function () { var $D = Date, $P = $D.prototype, // $C = $D.CultureInfo, // not used atm $f = [], p = function (s, l) { if (!l) { l = 2; } return ("000" + s).slice(l * -1); }; /** * Converts a PHP format string to Java/.NET format string. * A PHP format string can be used with .$format or .format. * A Java/.NET format string can be used with .toString(). * The .parseExact function will only accept a Java/.NET format string * * Example <pre> var f1 = "%m/%d/%y" var f2 = Date.normalizeFormat(f1); // "MM/dd/yy" new Date().format(f1); // "04/13/08" new Date().$format(f1); // "04/13/08" new Date().toString(f2); // "04/13/08" var date = Date.parseExact("04/13/08", f2); // Sun Apr 13 2008 </pre> * @param {String} A PHP format string consisting of one or more format spcifiers. * @return {String} The PHP format converted to a Java/.NET format string. */ $D.normalizeFormat = function (format) { // function does nothing atm // $f = []; // var t = new Date().$format(format); // return $f.join(""); return format; }; /** * Format a local Unix timestamp according to locale settings * * Example <pre> Date.strftime("%m/%d/%y", new Date()); // "04/13/08" Date.strftime("c", "2008-04-13T17:52:03Z"); // "04/13/08" </pre> * @param {String} A format string consisting of one or more format spcifiers [Optional]. * @param {Number} The number representing the number of seconds that have elapsed since January 1, 1970 (local time). * @return {String} A string representation of the current Date object. */ $D.strftime = function (format, time) { return new Date(time * 1000).$format(format); }; /** * Parse any textual datetime description into a Unix timestamp. * A Unix timestamp is the number of seconds that have elapsed since January 1, 1970 (midnight UTC/GMT). * * Example <pre> Date.strtotime("04/13/08"); // 1208044800 Date.strtotime("1970-01-01T00:00:00Z"); // 0 </pre> * @param {String} A format string consisting of one or more format spcifiers [Optional]. * @param {Object} A string or date object. * @return {String} A string representation of the current Date object. */ $D.strtotime = function (time) { var d = $D.parse(time); d.addMinutes(d.getTimezoneOffset() * -1); return Math.round($D.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds()) / 1000); }; /** * Converts the value of the current Date object to its equivalent string representation using a PHP/Unix style of date format specifiers. * * The following descriptions are from http://www.php.net/strftime and http://www.php.net/manual/en/function.date.php. * Copyright � 2001-2008 The PHP Group * * Format Specifiers <pre> Format Description Example ------ --------------------------------------------------------------------------- ----------------------- %a abbreviated weekday name according to the current localed "Mon" through "Sun" %A full weekday name according to the current locale "Sunday" through "Saturday" %b abbreviated month name according to the current locale "Jan" through "Dec" %B full month name according to the current locale "January" through "December" %c preferred date and time representation for the current locale "4/13/2008 12:33 PM" %C century number (the year divided by 100 and truncated to an integer) "00" to "99" %d day of the month as a decimal number "01" to "31" %D same as %m/%d/%y "04/13/08" %e day of the month as a decimal number, a single digit is preceded by a space "1" to "31" %g like %G, but without the century "08" %G The 4-digit year corresponding to the ISO week number (see %V). "2008" This has the same format and value as %Y, except that if the ISO week number belongs to the previous or next year, that year is used instead. %h same as %b "Jan" through "Dec" %H hour as a decimal number using a 24-hour clock "00" to "23" %I hour as a decimal number using a 12-hour clock "01" to "12" %j day of the year as a decimal number "001" to "366" %m month as a decimal number "01" to "12" %M minute as a decimal number "00" to "59" %n newline character "\n" %p either "am" or "pm" according to the given time value, or the "am" or "pm" corresponding strings for the current locale %r time in a.m. and p.m. notation "8:44 PM" %R time in 24 hour notation "20:44" %S second as a decimal number "00" to "59" %t tab character "\t" %T current time, equal to %H:%M:%S "12:49:11" %u weekday as a decimal number ["1", "7"], with "1" representing Monday "1" to "7" %U week number of the current year as a decimal number, starting with the "0" to ("52" or "53") first Sunday as the first day of the first week %V The ISO 8601:1988 week number of the current year as a decimal number, "00" to ("52" or "53") range 01 to 53, where week 1 is the first week that has at least 4 days in the current year, and with Monday as the first day of the week. (Use %G or %g for the year component that corresponds to the week number for the specified timestamp.) %W week number of the current year as a decimal number, starting with the "00" to ("52" or "53") first Monday as the first day of the first week %w day of the week as a decimal, Sunday being "0" "0" to "6" %x preferred date representation for the current locale without the time "4/13/2008" %X preferred time representation for the current locale without the date "12:53:05" %y year as a decimal number without a century "00" "99" %Y year as a decimal number including the century "2008" %Z time zone or name or abbreviation "UTC", "EST", "PST" %z same as %Z %% a literal "%" character "%" d Day of the month, 2 digits with leading zeros "01" to "31" D A textual representation of a day, three letters "Mon" through "Sun" j Day of the month without leading zeros "1" to "31" l A full textual representation of the day of the week (lowercase "L") "Sunday" through "Saturday" N ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) "1" (for Monday) through "7" (for Sunday) S English ordinal suffix for the day of the month, 2 characters "st", "nd", "rd" or "th". Works well with j w Numeric representation of the day of the week "0" (for Sunday) through "6" (for Saturday) z The day of the year (starting from "0") "0" through "365" W ISO-8601 week number of year, weeks starting on Monday "00" to ("52" or "53") F A full textual representation of a month, such as January or March "January" through "December" m Numeric representation of a month, with leading zeros "01" through "12" M A short textual representation of a month, three letters "Jan" through "Dec" n Numeric representation of a month, without leading zeros "1" through "12" t Number of days in the given month "28" through "31" L Whether it's a leap year "1" if it is a leap year, "0" otherwise o ISO-8601 year number. This has the same value as Y, except that if the "2008" ISO week number (W) belongs to the previous or next year, that year is used instead. Y A full numeric representation of a year, 4 digits "2008" y A two digit representation of a year "08" a Lowercase Ante meridiem and Post meridiem "am" or "pm" A Uppercase Ante meridiem and Post meridiem "AM" or "PM" B Swatch Internet time "000" through "999" g 12-hour format of an hour without leading zeros "1" through "12" G 24-hour format of an hour without leading zeros "0" through "23" h 12-hour format of an hour with leading zeros "01" through "12" H 24-hour format of an hour with leading zeros "00" through "23" i Minutes with leading zeros "00" to "59" s Seconds, with leading zeros "00" through "59" u Milliseconds "54321" e Timezone identifier "UTC", "EST", "PST" I Whether or not the date is in daylight saving time (uppercase i) "1" if Daylight Saving Time, "0" otherwise O Difference to Greenwich time (GMT) in hours "+0200", "-0600" P Difference to Greenwich time (GMT) with colon between hours and minutes "+02:00", "-06:00" T Timezone abbreviation "UTC", "EST", "PST" Z Timezone offset in seconds. The offset for timezones west of UTC is "-43200" through "50400" always negative, and for those east of UTC is always positive. c ISO 8601 date "2004-02-12T15:19:21+00:00" r RFC 2822 formatted date "Thu, 21 Dec 2000 16:01:07 +0200" U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) "0" </pre> * @param {String} A format string consisting of one or more format spcifiers [Optional]. * @return {String} A string representation of the current Date object. */ $P.$format = function (format) { var x = this, y, t = function (v, overrideStandardFormats) { $f.push(v); return x.toString(v, overrideStandardFormats); }; return format ? format.replace(/(%|\\)?.|%%/g, function (m) { if (m.charAt(0) === "\\" || m.substring(0, 2) === "%%") { return m.replace("\\", "").replace("%%", "%"); } switch (m) { case "d": case "%d": return t("dd"); case "D": case "%a": return t("ddd"); case "j": case "%e": return t("d", true); case "l": case "%A": return t("dddd"); case "N": case "%u": return x.getDay() + 1; case "S": return t("S"); case "w": case "%w": return x.getDay(); case "z": return x.getOrdinalNumber(); case "%j": return p(x.getOrdinalNumber(), 3); case "%U": var d1 = x.clone().set({month: 0, day: 1}).addDays(-1).moveToDayOfWeek(0), d2 = x.clone().addDays(1).moveToDayOfWeek(0, -1); return (d2 < d1) ? "00" : p((d2.getOrdinalNumber() - d1.getOrdinalNumber()) / 7 + 1); case "W": case "%V": return x.getISOWeek(); case "%W": return p(x.getWeek()); case "F": case "%B": return t("MMMM"); case "m": case "%m": return t("MM"); case "M": case "%b": case "%h": return t("MMM"); case "n": return t("M"); case "t": return $D.getDaysInMonth(x.getFullYear(), x.getMonth()); case "L": return ($D.isLeapYear(x.getFullYear())) ? 1 : 0; case "o": case "%G": return x.setWeek(x.getISOWeek()).toString("yyyy"); case "%g": return x.$format("%G").slice(-2); case "Y": case "%Y": return t("yyyy"); case "y": case "%y": return t("yy"); case "a": case "%p": return t("tt").toLowerCase(); case "A": return t("tt").toUpperCase(); case "g": case "%I": return t("h"); case "G": return t("H"); case "h": return t("hh"); case "H": case "%H": return t("HH"); case "i": case "%M": return t("mm"); case "s": case "%S": return t("ss"); case "u": return p(x.getMilliseconds(), 3); case "I": return (x.isDaylightSavingTime()) ? 1 : 0; case "O": return x.getUTCOffset(); case "P": y = x.getUTCOffset(); return y.substring(0, y.length - 2) + ":" + y.substring(y.length - 2); case "e": case "T": case "%z": case "%Z": return x.getTimezone(); case "Z": return x.getTimezoneOffset() * -60; case "B": var now = new Date(); return Math.floor(((now.getHours() * 3600) + (now.getMinutes() * 60) + now.getSeconds() + (now.getTimezoneOffset() + 60) * 60) / 86.4); case "c": return x.toISOString().replace(/\"/g, ""); case "U": return $D.strtotime("now"); case "%c": return t("d") + " " + t("t"); case "%C": return Math.floor(x.getFullYear() / 100 + 1); case "%D": return t("MM/dd/yy"); case "%n": return "\\n"; case "%t": return "\\t"; case "%r": return t("hh:mm tt"); case "%R": return t("H:mm"); case "%T": return t("H:mm:ss"); case "%x": return t("d"); case "%X": return t("t"); default: $f.push(m); return m; } }) : this._toString(); }; if (!$P.format) { $P.format = $P.$format; } }()); /* * TimeSpan(milliseconds); * TimeSpan(days, hours, minutes, seconds); * TimeSpan(days, hours, minutes, seconds, milliseconds); */ var TimeSpan = function (days, hours, minutes, seconds, milliseconds) { var attrs = "days hours minutes seconds milliseconds".split(/\s+/); var gFn = function (attr) { return function () { return this[attr]; }; }; var sFn = function (attr) { return function (val) { this[attr] = val; return this; }; }; for (var i = 0; i < attrs.length ; i++) { var $a = attrs[i], $b = $a.slice(0, 1).toUpperCase() + $a.slice(1); TimeSpan.prototype[$a] = 0; TimeSpan.prototype["get" + $b] = gFn($a); TimeSpan.prototype["set" + $b] = sFn($a); } if (arguments.length === 4) { this.setDays(days); this.setHours(hours); this.setMinutes(minutes); this.setSeconds(seconds); } else if (arguments.length === 5) { this.setDays(days); this.setHours(hours); this.setMinutes(minutes); this.setSeconds(seconds); this.setMilliseconds(milliseconds); } else if (arguments.length === 1 && typeof days === "number") { var orient = (days < 0) ? -1 : +1; this.setMilliseconds(Math.abs(days)); this.setDays(Math.floor(this.getMilliseconds() / 86400000) * orient); this.setMilliseconds(this.getMilliseconds() % 86400000); this.setHours(Math.floor(this.getMilliseconds() / 3600000) * orient); this.setMilliseconds(this.getMilliseconds() % 3600000); this.setMinutes(Math.floor(this.getMilliseconds() / 60000) * orient); this.setMilliseconds(this.getMilliseconds() % 60000); this.setSeconds(Math.floor(this.getMilliseconds() / 1000) * orient); this.setMilliseconds(this.getMilliseconds() % 1000); this.setMilliseconds(this.getMilliseconds() * orient); } this.getTotalMilliseconds = function () { return (this.getDays() * 86400000) + (this.getHours() * 3600000) + (this.getMinutes() * 60000) + (this.getSeconds() * 1000); }; this.compareTo = function (time) { var t1 = new Date(1970, 1, 1, this.getHours(), this.getMinutes(), this.getSeconds()), t2; if (time === null) { t2 = new Date(1970, 1, 1, 0, 0, 0); } else { t2 = new Date(1970, 1, 1, time.getHours(), time.getMinutes(), time.getSeconds()); } return (t1 < t2) ? -1 : (t1 > t2) ? 1 : 0; }; this.equals = function (time) { return (this.compareTo(time) === 0); }; this.add = function (time) { return (time === null) ? this : this.addSeconds(time.getTotalMilliseconds() / 1000); }; this.subtract = function (time) { return (time === null) ? this : this.addSeconds(-time.getTotalMilliseconds() / 1000); }; this.addDays = function (n) { return new TimeSpan(this.getTotalMilliseconds() + (n * 86400000)); }; this.addHours = function (n) { return new TimeSpan(this.getTotalMilliseconds() + (n * 3600000)); }; this.addMinutes = function (n) { return new TimeSpan(this.getTotalMilliseconds() + (n * 60000)); }; this.addSeconds = function (n) { return new TimeSpan(this.getTotalMilliseconds() + (n * 1000)); }; this.addMilliseconds = function (n) { return new TimeSpan(this.getTotalMilliseconds() + n); }; this.get12HourHour = function () { return (this.getHours() > 12) ? this.getHours() - 12 : (this.getHours() === 0) ? 12 : this.getHours(); }; this.getDesignator = function () { return (this.getHours() < 12) ? Date.CultureInfo.amDesignator : Date.CultureInfo.pmDesignator; }; this.toString = function (format) { this._toString = function () { if (this.getDays() !== null && this.getDays() > 0) { return this.getDays() + "." + this.getHours() + ":" + this.p(this.getMinutes()) + ":" + this.p(this.getSeconds()); } else { return this.getHours() + ":" + this.p(this.getMinutes()) + ":" + this.p(this.getSeconds()); } }; this.p = function (s) { return (s.toString().length < 2) ? "0" + s : s; }; var me = this; return format ? format.replace(/dd?|HH?|hh?|mm?|ss?|tt?/g, function (format) { switch (format) { case "d": return me.getDays(); case "dd": return me.p(me.getDays()); case "H": return me.getHours(); case "HH": return me.p(me.getHours()); case "h": return me.get12HourHour(); case "hh": return me.p(me.get12HourHour()); case "m": return me.getMinutes(); case "mm": return me.p(me.getMinutes()); case "s": return me.getSeconds(); case "ss": return me.p(me.getSeconds()); case "t": return ((me.getHours() < 12) ? Date.CultureInfo.amDesignator : Date.CultureInfo.pmDesignator).substring(0, 1); case "tt": return (me.getHours() < 12) ? Date.CultureInfo.amDesignator : Date.CultureInfo.pmDesignator; } } ) : this._toString(); }; return this; }; /** * Gets the time of day for this date instances. * @return {TimeSpan} TimeSpan */ Date.prototype.getTimeOfDay = function () { return new TimeSpan(0, this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds()); }; /* * TimePeriod(startDate, endDate); * TimePeriod(years, months, days, hours, minutes, seconds, milliseconds); */ var TimePeriod = function (years, months, days, hours, minutes, seconds, milliseconds) { var attrs = "years months days hours minutes seconds milliseconds".split(/\s+/); var gFn = function (attr) { return function () { return this[attr]; }; }; var sFn = function (attr) { return function (val) { this[attr] = val; return this; }; }; for (var i = 0; i < attrs.length ; i++) { var $a = attrs[i], $b = $a.slice(0, 1).toUpperCase() + $a.slice(1); TimePeriod.prototype[$a] = 0; TimePeriod.prototype["get" + $b] = gFn($a); TimePeriod.prototype["set" + $b] = sFn($a); } if (arguments.length === 7) { this.years = years; this.months = months; this.setDays(days); this.setHours(hours); this.setMinutes(minutes); this.setSeconds(seconds); this.setMilliseconds(milliseconds); } else if (arguments.length === 2 && arguments[0] instanceof Date && arguments[1] instanceof Date) { // startDate and endDate as arguments var d1 = years.clone(); var d2 = months.clone(); var temp = d1.clone(); var orient = (d1 > d2) ? -1 : +1; this.years = d2.getFullYear() - d1.getFullYear(); temp.addYears(this.years); if (orient === +1) { if (temp > d2) { if (this.years !== 0) { this.years--; } } } else { if (temp < d2) { if (this.years !== 0) { this.years++; } } } d1.addYears(this.years); if (orient === +1) { while (d1 < d2 && d1.clone().addMonths(1) <= d2) { d1.addMonths(1); this.months++; } } else { while (d1 > d2 && d1.clone().addDays(-d1.getDaysInMonth()) > d2) { d1.addMonths(-1); this.months--; } } var diff = d2 - d1; if (diff !== 0) { var ts = new TimeSpan(diff); this.setDays(ts.getDays()); this.setHours(ts.getHours()); this.setMinutes(ts.getMinutes()); this.setSeconds(ts.getSeconds()); this.setMilliseconds(ts.getMilliseconds()); } } return this; };
ubergrape/datejs
build/development/date-es-HN.js
JavaScript
mit
130,170
<?php /** * Conn for Lookupd * User: moyo * Date: 31/03/2017 * Time: 4:53 PM */ namespace NSQClient\Connection; use NSQClient\Access\Endpoint; use NSQClient\Connection\Transport\HTTP; use NSQClient\Exception\LookupTopicException; use NSQClient\Logger\Logger; class Lookupd { /** * @var string */ private static $queryFormat = '/lookup?topic=%s'; /** * @var array */ private static $caches = []; /** * @param Endpoint $endpoint * @param $topic * @return array * @throws LookupTopicException */ public static function getNodes(Endpoint $endpoint, $topic) { if (isset(self::$caches[$endpoint->getUniqueID()][$topic])) { return self::$caches[$endpoint->getUniqueID()][$topic]; } $url = $endpoint->getLookupd() . sprintf(self::$queryFormat, $topic); list($error, $result) = HTTP::get($url); if ($error) { list($netErrNo, $netErrMsg) = $error; Logger::ins()->error('Lookupd request failed', ['no' => $netErrNo, 'msg' => $netErrMsg]); throw new LookupTopicException($netErrMsg, $netErrNo); } else { Logger::ins()->debug('Lookupd results got', ['raw' => $result]); return self::$caches[$endpoint->getUniqueID()][$topic] = self::parseResult($result, $topic); } } /** * @param $rawJson * @param $scopeTopic * @return array */ private static function parseResult($rawJson, $scopeTopic) { $result = json_decode($rawJson, true); $nodes = []; if (isset($result['producers'])) { foreach ($result['producers'] as $producer) { $nodes[] = [ 'topic' => $scopeTopic, 'host' => $producer['broadcast_address'], 'ports' => [ 'tcp' => $producer['tcp_port'], 'http' => $producer['http_port'] ] ]; } } return $nodes; } }
moolex/nsqclient-php
src/Connection/Lookupd.php
PHP
mit
2,077
import * as React from 'react'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import { demos, docs, requireDemo, } from '!@material-ui/markdown/loader!docs/src/pages/components/menus/menus.md'; export default function Page() { return <MarkdownDocs demos={demos} docs={docs} requireDemo={requireDemo} />; }
mbrookes/material-ui
docs/pages/components/menus.js
JavaScript
mit
338
<?php namespace PhpBench\Attributes; use Attribute; #[Attribute(Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)] final class Skip { }
phpbench/phpbench
lib/Attributes/Skip.php
PHP
mit
141
#if !NOT_UNITY3D using System.IO; using UnityEditor; using UnityEngine; using Zenject.Internal; namespace Zenject.ReflectionBaking { public static class ReflectionBakingMenuItems { [MenuItem("Assets/Create/Zenject/Reflection Baking Settings", false, 100)] public static void CreateReflectionBakingSettings() { var folderPath = ZenUnityEditorUtil.GetCurrentDirectoryAssetPathFromSelection(); var config = ScriptableObject.CreateInstance<ZenjectReflectionBakingSettings>(); ZenUnityEditorUtil.SaveScriptableObjectAsset( Path.Combine(folderPath, "ZenjectReflectionBakingSettings.asset"), config); } } } #endif
modesttree/Zenject
UnityProject/Assets/Plugins/Zenject/OptionalExtras/ReflectionBaking/Unity/ReflectionBakingMenuItems.cs
C#
mit
707
<?php class Yamp_Layout_Block_Left extends Yamp_Layout_Block_Abstract { /** * construct */ public function _construct() { $this->setTemplate("html/left.phtml"); } }
eisbehr-/yamp-framework
core/Layout/Block/Left.php
PHP
mit
175
import {Component} from '@angular/core'; import {TodoService} from './todo-service'; @Component({ selector: 'todo-app', template: ` <div> <todo-input></todo-input> <hr/> <todo-list></todo-list> </div> ` }) export default class TodoApp { }
clbond/augury
example-apps/kitchen-sink-example/source/components/todo-app/todo-app.ts
TypeScript
mit
263
from django.core.urlresolvers import reverse from django.test import TestCase from django.utils import timezone from .models import Course from .models import Step class CourseModelTests(TestCase): def test_course_creation(self): course = Course.objects.create( title="Python Regular Expressions", description="Learn to write regular expressions in Python" ) now = timezone.now() self.assertLess(course.created_at, now) class StepModelTests(TestCase): def setUp(self): self.course = Course.objects.create( title="Python testing", description="Learn to write tests in python." ) def test_step_creation(self): step = Step.objects.create( title="A Lovely step title", description="Nice step description", course=self.course ) self.assertIn(step, self.course.step_set.all()) class CourseViewsTest(TestCase): def setUp(self): self.course = Course.objects.create( title="Python testing", description="Learn to write tests in Python." ) self.course2 = Course.objects.create( title="New Course", description="A new course" ) self.step = Step.objects.create( title="Introduction to Doctests", description="Learn to write tests in your Docstrings", course=self.course ) def test_course_list_view(self): resp = self.client.get(reverse('courses:list')) self.assertEqual(resp.status_code, 200) self.assertIn(self.course, resp.context['courses']) self.assertIn(self.course2, resp.context['courses']) self.assertTemplateUsed(resp, 'courses/course_list.html') self.assertContains(resp, self.course.title) def test_course_detail_view(self): resp = self.client.get(reverse('courses:course', kwargs={'pk': self.course.pk})) self.assertEqual(resp.status_code, 200) self.assertEqual(self.course, resp.context['course']) self.assertTemplateUsed(resp, 'courses/course_detail.html') self.assertContains(resp, self.course.title) def test_step_detail_view(self): resp = self.client.get(reverse('courses:step', kwargs={'course_pk': self.course.pk, 'step_pk': self.step.pk})) self.assertEqual(resp.status_code, 200) self.assertEqual(self.step, resp.context['step']) self.assertTemplateUsed(resp, 'courses/step_detail.html') self.assertContains(resp, self.course.title) self.assertContains(resp, self.step.title)
lorimccurry/learning_site
courses/tests.py
Python
mit
2,724
'use strict'; import View from './index'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import * as ReactTestUtils from 'react-addons-test-utils'; describe('Button test', function () { it('Should render button tag', function () { const view: React.Component<any, {}> = ReactTestUtils.renderIntoDocument( <View>Test text</View> ); const elements: Array<Element> = ReactTestUtils.scryRenderedDOMComponentsWithClass(view, 'button__text'); expect(elements.length).toBe(1); expect(elements[0].innerHTML).toBe('Test text'); }); it('Should render button type', function () { const view: React.Component<any, {}> = ReactTestUtils.renderIntoDocument( <View type="red"/> ); const elements: Array<Element> = ReactTestUtils.scryRenderedDOMComponentsWithClass(view, 'button_red'); expect(elements.length).toBe(1); }); it('Should emit onClick', function () { let onClick: jasmine.Spy = jasmine.createSpy('onClick'); const view: React.Component<any, {}> = ReactTestUtils.renderIntoDocument( <View onClick={onClick} /> ); const elements: Array<Element> = ReactTestUtils.scryRenderedDOMComponentsWithClass(view, 'button'); ReactTestUtils.Simulate.click(elements[0]); expect(onClick).toHaveBeenCalled(); }); });
Connormiha/todo-list
src/ts/components/common/Button/index.test.tsx
TypeScript
mit
1,403
typeSearchIndex = [{"p":"main","l":"CheckingSSN"}]
tliang1/Java-Practice
Practice/Intro-To-Java-8th-Ed-Daniel-Y.-Liang/Chapter-9/Chapter09P01/doc/type-search-index.js
JavaScript
mit
50
var React = require("react"); var HttpServices = require("../services/HttpServices"); var update = require("react-addons-update"); module.exports = React.createClass({ getInitialState: function() { return { contentEditable: false } }, onDoubleClick: function() { if (this.props.editable && !this.state.contentEditable) { this.setState({ contentEditable: true }, function() { setTimeout(function() { this.refs.contentEditable.focus(); }.bind(this), 500); }.bind(this)); } }, setHtml: function() { return {__html: this.props.content}; }, save: function() { this.setState({ contentEditable: false }); var newValue = this.refs.editableField.innerHTML; var updatedApi = update(this.props.api, {$apply: function(api) { api[this.props.path][this.props.fileName] = newValue; return api; }.bind(this)}); HttpServices.post("/cheesetoastie/" + this.props.path, {field: this.props.fieldName, value: newValue}, function(err, res) { if (err) { console.error(err); } }); this.props.onApiUpdate(updatedApi); }, render: function() { var classes = ""; var buttons = null; if (this.props.className) { classes += this.props.className; } if (this.state.contentEditable) { classes += " content-editable"; buttons = ( <div className="content-editable-buttons"> <div className="content-editable-button-save" onClick={this.save}>Save</div> </div> ) } return ( <div className={classes} onDoubleClick={this.onDoubleClick}> <div contentEditable={this.state.contentEditable} ref="editableField" dangerouslySetInnerHTML={this.setHtml()}></div> {buttons} </div> ) } });
chenjic215/search-doctor
node_modules/cheese-toastie/docs/react-components/docs/ContentEditable.js
JavaScript
mit
1,833
<?php echo Asset::css('product.css'); ?> <div class="pay-panel"> <?php if(isset($status) && $status):?> <div class="panel-head"> <h2 class="title-chg"><span class="icon icon-succeed"></span>恭喜您, 支付成功!</h2> <div style="padding: 40px;text-align: center"> 商品信息请在<a style="text-decoration: none" href="<?php echo Uri::create('u/orders'); ?>">【乐淘记录】</a>查看 </div> </div> <?php else: ?> <div class="panel-head"> <h2 class="title-chg"><span class="icon icon-error"></span>抱歉, 支付失败!</h2> <div style="padding: 40px;text-align: center"> 失败原因:<?php echo $reason;?> </div> </div> <?php endif;?> <a class="btn btn-red btn-atc" href="<?php echo Uri::base(); ?>">继续乐淘</a> </div>
lextel/evolution
fuel/app/views/payment/return.php
PHP
mit
1,011
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CloudCompare.Web.FluentSecurity.Policy { internal class LazySecurityPolicy<TSecurityPolicy> : ILazySecurityPolicy where TSecurityPolicy : ISecurityPolicy { public Type PolicyType { get { return typeof(TSecurityPolicy); } } public ISecurityPolicy Load() { var externalServiceLocator = SecurityConfiguration.Current.ExternalServiceLocator; if (externalServiceLocator != null) { var securityPolicy = externalServiceLocator.Resolve(PolicyType) as ISecurityPolicy; if (securityPolicy != null) return securityPolicy; } return PolicyType.HasEmptyConstructor() ? (ISecurityPolicy)Activator.CreateInstance<TSecurityPolicy>() : null; } public PolicyResult Enforce(ISecurityContext context) { var securityPolicy = Load(); if (securityPolicy == null) throw new InvalidOperationException( String.Format("A policy of type {0} could not be loaded! Make sure the policy has an empty constructor or is registered in your IoC-container.", PolicyType.FullName) ); return securityPolicy.Enforce(context); } } }
protechdm/CloudCompare
CloudCompare.Web/FluentSecurity/Policy/LazySecurityPolicy.cs
C#
mit
1,444
Locations = new Mongo.Collection("locations"); Locations.allow({ insert: function(userId) { return !!userId; } }); Meteor.methods({ addLocation: function(placeId) { Locations.insert({place_id: placeId}); } });
andriyl/raplanet
lib/collections/locations.js
JavaScript
mit
243
import DS from 'ember-data'; /* global moment */ var Pairing = DS.Model.extend({ startDate: DS.attr('date'), endDate: DS.attr('date'), users: DS.hasMany('user', {async: true}), logs: DS.hasMany('log', {async: true}), isEnded: function(){ return +this.get('endDate') <= +moment().toDate(); }.property('endDate'), pairingDates: function(){ return moment( this.get('startDate') ).format('MMMM DD, YYYY') + ' - ' + moment( this.get('endDate') ).format('MMMM DD, YYYY'); }.property('startDate', 'endDate'), buddies: function(){ if (this.get('users.isFulfilled') && this.get('users.length') > 0){ var length = this.get('users.length') - 1; return this.get('users').map(function(user, i) { return { name: user.get('name'), id: user.get('id') }; }); } }.property('users.length') }); export default Pairing;
alicht/buddybuddy
ember/app/models/pairing.js
JavaScript
mit
906
/* * The MIT License (MIT) * * Copyright (c) Gabriel Harris-Rouquette * * 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 com.afterkraft.kraftrpg.api.effect.property; import com.afterkraft.kraftrpg.api.effect.EffectProperty; /** * A utility interface to deal with effects that implement {@link java.util.concurrent.Delayed} It * should be noted that the API provides the following to implement Timed: <ul> <li>{@link * ExpiringProperty}</li> <li>{@link PeriodicProperty}</li> </ul> and from the default * implementations: <ul> <li>{@link ExpiringProperty}</li> <li>{@link PeriodicProperty}</li> </ul> * * @param <T> The type of {@link TimedProperty} */ public interface TimedProperty<T extends TimedProperty<T>> extends EffectProperty<T> { }
AfterKraft/KraftRPG-API
src/main/java/com/afterkraft/kraftrpg/api/effect/property/TimedProperty.java
Java
mit
1,789
/** * React Static Boilerplate * https://github.com/kriasoft/react-static-boilerplate * * Copyright © 2015-present 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. */ import React from 'react'; import Layout from '../../components/Layout'; // import DataPicker from '../../components/DataPicker/DataPicker.js'; import DatePicker from 'material-ui/DatePicker'; import s from './styles.css'; import { title, html } from './index.md'; class AboutPage extends React.Component { componentDidMount() { document.title = title; } render() { return ( <Layout className={s.content}> <h1>{title}</h1> <div // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: html }} /> </Layout> ); } } export default AboutPage;
SergeyGuns/test-site
src/about/about.js
JavaScript
mit
937
var crypto = require('crypto'); /** * 加密算法(md5 → 加盐 → md5) * 依赖: crypto * @param string 源字符串 * @param salt 盐 * @returns {string} */ function communism(string, salt) { var str = md5Hash(string); str = salt + str; str = md5Hash(str); return str; } /** * md5 hash散列 * @param string 源字符串 * @return string 32位小写16进制表示的md5散列的字符串 */ function md5Hash(string) { var md5 = crypto.createHash('md5'); md5.update(string); var str = md5.digest('hex'); return str; } /** * 生成盐 * @param length 盐的长度,推荐使用32位 * @returns {string} */ function setSalt(length) { var salt = ''; var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']; var length = length; if (length > 256) { length = 256; } for (var i = 0; i < length; i++) { salt += chars[Math.floor(Math.random() * chars.length)]; } return salt; } module.exports = { communism: communism, md5Hash: md5Hash, setSalt: setSalt };
mecoepcoo/innocent-blog
lib/hash.js
JavaScript
mit
1,286
<?php /* * @author M2E Pro Developers Team * @copyright M2E LTD * @license Commercial use is forbidden */ class Ess_M2ePro_Block_Adminhtml_Amazon_Template_Description_Category_Chooser_Tabs_Recent extends Mage_Adminhtml_Block_Widget { protected $_selectedCategory = array(); //######################################## public function __construct() { parent::__construct(); // Initialization block // --------------------------------------- $this->setId('amazonTemplateDescriptionCategoryChooserRecent'); // --------------------------------------- // Set template // --------------------------------------- $this->setTemplate('M2ePro/amazon/template/description/category/chooser/tabs/recent.phtml'); // --------------------------------------- } //######################################## public function getCategories() { return Mage::helper('M2ePro/Component_Amazon_Category')->getRecent( $this->getRequest()->getPost('marketplace_id'), array('product_data_nick' => $this->getRequest()->getPost('product_data_nick'), 'browsenode_id' => $this->getRequest()->getPost('browsenode_id'), 'path' => $this->getRequest()->getPost('category_path')) ); } //######################################## }
portchris/NaturalRemedyCompany
src/app/code/community/Ess/M2ePro/Block/Adminhtml/Amazon/Template/Description/Category/Chooser/Tabs/Recent.php
PHP
mit
1,419
/** * */ package jmeter; /** * @author ricardo * */ public class SeleniumTest { /** * */ public SeleniumTest() { } /** * @param args */ public static void main(String[] args) { } /* * package br.com.zenvia.test; import java.io.IOException; import java.lang.reflect.Method; import java.util.Properties; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.chrome.ChromeDriver; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.context.support.ClassPathXmlApplicationContext; import br.com.zenvia.abtracts.AbstractTest; public class JMeterTestCase { @SuppressWarnings("unchecked") @Test public void test() throws Exception { Class<AbstractTest> clazz = (Class<AbstractTest>) Class.forName(System.getProperty("testcase.class")); for (Method method : clazz.getMethods()) { if (method.isAnnotationPresent(Test.class)) { try { executeMethod(clazz,method); } catch (Exception e) { //TODO log error } } } } private void executeMethod(Class<AbstractTest> clazz, Method testMethod) throws Exception { AbstractTest testCase = (AbstractTest) clazz.newInstance(); try { loadProperties(testCase); testCase.setDriver(new ChromeDriver()); testCase.setUpClass(); for (Method method : testCase.getClass().getMethods()) { if (method.isAnnotationPresent(Before.class)) { method.invoke(testCase); } } testMethod.invoke(testCase); for (Method method : testCase.getClass().getMethods()) { if (method.isAnnotationPresent(After.class)) { method.invoke(testCase); } } testCase.tearDownClass(); } finally { if (testCase!=null) { testCase.getDriver().quit(); } } } private void loadProperties(AbstractTest testCase) throws IOException { Properties properties = new Properties(); String environmentName = System.getProperty("spring.profiles.active"); properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(environmentName.toLowerCase()+".properties")); testCase.setSystemURL(properties.getProperty("system.url")); testCase.setTemplate(properties.getProperty("template")); testCase.setFrom(properties.getProperty("from")); testCase.setTo(properties.getProperty("to")); testCase.setGroup(properties.getProperty("group")); testCase.setGreeting(properties.getProperty("greeting")); testCase.setSupportUsername(properties.getProperty("support.username")); testCase.setSupportPassword(properties.getProperty("support.password")); testCase.setConnectPosAccount(properties.getProperty("connect.account.pos")); testCase.setConnectPreAccount(properties.getProperty("connect.account.pre")); testCase.setEngagePosAccount(properties.getProperty("engage.account.pos")); testCase.setEngageWithouMarketingConfig(properties.getProperty("engage.account.sem")); testCase.setComunikaAccount(properties.getProperty("comunika.account")); testCase.setPurebrosAccount(properties.getProperty("purebros.account")); testCase.setSeconds(Long.parseLong(properties.getProperty("callback.sec"))); testCase.setWindowsPath(properties.getProperty("windows.path")); testCase.setUnixPath(properties.getProperty("unix.path")); testCase.setOiGetMO(properties.getProperty("oi.get.mo")); testCase.setStopMessage(properties.getProperty("system.stop_message")); } public JMeterTestCase() { super(); } private void loadSpring() { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); ctx.getAutowireCapableBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true); } public JMeterTestCase(String test) { this(); } } */ }
ricardobaumann/jmeter_web_app_test
src/main/java/jmeter/SeleniumTest.java
Java
mit
3,941
# Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = '1.0' # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. Rails.application.config.assets.precompile += %w( unauthorized.css )
rcsole/iron-alumni
config/initializers/assets.rb
Ruby
mit
382
const _ = require('lodash'); const fs = require('fs'); module.exports = (path, validationFailures) => { let jsonRaw; let json; try { jsonRaw = fs.readFileSync(path); } catch (err) { if (err.code === 'ENOENT') { validationFailures.push(`Cannot find "${path}"`); } else { throw err; } } if (!_.isUndefined(jsonRaw)) { try { json = JSON.parse(jsonRaw); } catch (err) { validationFailures.push(`Cannot read "${path}" as JSON: ${err}`); } } return json; };
fluxsauce/dashing-reporter
lib/loadJson.js
JavaScript
mit
533
#!/usr/bin/ruby -wKU # -*- coding: utf-8 -*- require File.expand_path(File.dirname(__FILE__) + '/spec_helper') require 'nkf' describe "Kana" do it "オプション'n'によって '0'を'0'に変換できること" do Kana.kana('0','n').should == '0' end it "オプション'r'によって 'a'を'a'に変換できること" do Kana.kana('a','r').should == 'a' end it "オプション'r'によって 'A'を'A'に変換できること" do Kana.kana('A','r').should == 'A' end it "'a'を変換しないこと" do Kana.kana('a','r').should == 'a' end it "オプション'k'によって'ア'を'ア'に変換できること" do Kana.kana('ア','k',:utf8).should == 'ア' end it "'0aAアa'を'0aAアa'に変換できること" do Kana.kana('0aAアa','nrk',:utf8).should == '0aAアa' end it "EUC-JPの'0aAアa'をEUC-JPの'0aAアa'に変換できること" do if RUBY_VERSION >= '1.9.1' Kana.kana('0aAアa'.encode(Encoding::EUC_JP),'nrk').should == '0aAアa'.encode(Encoding::EUC_JP) else Kana.kana(NKF.nkf('-m0xWe', '0aAアa'),'nrk').should == NKF.nkf('-m0xWe', '0aAアa') end end it "オプション's'によって全角スペースを半角スペースに変換できること" do Kana.kana(' ', 's').should == ' ' end it "オプション'a'によって全角英数字を半角英数字に変換できること" do Kana.kana('Abc xyZ 0123','a',:utf8).should == 'Abc xyZ 0123' end it "オプション'k'によって全角カタカナを半角カタカナに変換できること" do Kana.kana('アーヲ','k',:utf8).should == 'アーヲ' end it "オプション'h'によって全角ひらがなを半角カタカナに変換できること" do Kana.kana('あぁん','h',:utf8).should == 'アァン' end it "mb_convert_kana(a)と同じ変換をすること" do $KCODE = 'u' if RUBY_VERSION < '1.9.1' raw = File.read('spec/data/raw.txt') Kana.kana(raw, 'a').split(//).zip(File.read('spec/data/a.txt').split(//)).each do |got,except| got.should == except end end it "mb_convert_kana(A)と同じ変換をすること" do $KCODE = 'u' if RUBY_VERSION < '1.9.1' raw = File.read('spec/data/raw.txt') Kana.kana(raw, 'A').split(//).zip(File.read('spec/data/l-a.txt').split(//)).each do |got,except| got.should == except end end it "mb_convert_kana(c)と同じ変換をすること" do $KCODE = 'u' if RUBY_VERSION < '1.9.1' raw = File.read('spec/data/raw.txt') Kana.kana(raw, 'c').split(//).zip(File.read('spec/data/c.txt').split(//)).each do |got,except| got.should == except end end it "mb_convert_kana(C)と同じ変換をすること" do $KCODE = 'u' if RUBY_VERSION < '1.9.1' raw = File.read('spec/data/raw.txt') Kana.kana(raw, 'C').split(//).zip(File.read('spec/data/l-c.txt').split(//)).each do |got,except| got.should == except end end it "mb_convert_kana(h)と同じ変換をすること" do $KCODE = 'u' if RUBY_VERSION < '1.9.1' raw = File.read('spec/data/raw.txt') Kana.kana(raw, 'h').split(//).zip(File.read('spec/data/h.txt').split(//)).each do |got,except| got.should == except end end it "mb_convert_kana(H)と同じ変換をすること" do $KCODE = 'u' if RUBY_VERSION < '1.9.1' raw = File.read('spec/data/raw.txt') Kana.kana(raw, 'H').split(//).zip(File.read('spec/data/l-h.txt').split(//)).each do |got,except| got.should == except end end it "mb_convert_kana(HV)と同じ変換をすること" do $KCODE = 'u' if RUBY_VERSION < '1.9.1' raw = File.read('spec/data/raw.txt') Kana.kana(raw, 'HV').split(//).zip(File.read('spec/data/l-hv.txt').split(//)).each do |got,except| got.should == except end end it "mb_convert_kana(k)と同じ変換をすること" do $KCODE = 'u' if RUBY_VERSION < '1.9.1' raw = File.read('spec/data/raw.txt') Kana.kana(raw, 'k').split(//).zip(File.read('spec/data/k.txt').split(//)).each do |got,except| got.should == except end end it "mb_convert_kana(K)と同じ変換をすること" do $KCODE = 'u' if RUBY_VERSION < '1.9.1' raw = File.read('spec/data/raw.txt') Kana.kana(raw, 'K').split(//).zip(File.read('spec/data/l-k.txt').split(//)).each do |got,except| got.should == except end end it "mb_convert_kana(KV)と同じ変換をすること" do $KCODE = 'u' if RUBY_VERSION < '1.9.1' raw = File.read('spec/data/raw.txt') Kana.kana(raw, 'KV').split(//).zip(File.read('spec/data/l-kv.txt').split(//)).each do |got,except| got.should == except end end it "mb_convert_kana(ask)と同じ変換をすること" do $KCODE = 'u' if RUBY_VERSION < '1.9.1' raw = File.read('spec/data/raw.txt') Kana.kana(raw, 'ask').split(//).zip(File.read('spec/data/ask.txt').split(//)).each do |got,except| got.should == except end end it "mb_convert_kana(ASK)と同じ変換をすること" do $KCODE = 'u' if RUBY_VERSION < '1.9.1' raw = File.read('spec/data/raw.txt') Kana.kana(raw, 'ASK').split(//).zip(File.read('spec/data/l-ask.txt').split(//)).each do |got,except| got.should == except end end it "mb_convert_kana(ASKV)と同じ変換をすること" do $KCODE = 'u' if RUBY_VERSION < '1.9.1' raw = File.read('spec/data/raw.txt') Kana.kana(raw, 'ASKV').split(//).zip(File.read('spec/data/l-askv.txt').split(//)).each do |got,except| got.should == except end end it "mb_convert_kana(rns)と同じ変換をすること" do $KCODE = 'u' if RUBY_VERSION < '1.9.1' raw = File.read('spec/data/raw.txt') Kana.kana(raw, 'rns').split(//).zip(File.read('spec/data/rns.txt').split(//)).each do |got,except| got.should == except end end it "mb_convert_kana(RNS)と同じ変換をすること" do $KCODE = 'u' if RUBY_VERSION < '1.9.1' raw = File.read('spec/data/raw.txt') Kana.kana(raw, 'RNS').split(//).zip(File.read('spec/data/l-rns.txt').split(//)).each do |got,except| got.should == except end end end describe "String" do describe "kana" do it "'0'を'0'に変換できること" do '0'.kana('n').should == '0' end end end
miyucy/kana
spec/kana_spec.rb
Ruby
mit
6,351
/** * Created by archheretic on 04.04.17. */ require("./artifacts/src/root.android.js");
Archheretic/ParkingLotTrackerMobileApp
index.android.js
JavaScript
mit
90
package kpc.common.utils; import java.util.Arrays; public class ArgsParserTest { public void testParse() throws Exception { System.out.println(Arrays.toString(ArgsParser.parse("\"Hello World\" \"Test World\""))); } }
BBoldt/KPComputers
src/test/java/kpc/common/utils/ArgsParserTest.java
Java
mit
239
module AlexaRuby # Response for Amazon Alexa service request class Response # Initialize new response # # @param request_type [Symbol] AlexaRuby::Request type # @param version [String] Amazon Alexa SDK version def initialize(request_type, version = '1.0') @req_type = request_type @resp = { version: version, sessionAttributes: {}, response: { shouldEndSession: true } } end # Add one session attribute # # @param key [String] atrribute key # @param value [String] attribute value # @param rewrite [Boolean] rewrite if key already exists? # @raise [ArgumentError] if session key is already added and # rewrite is set to false def add_session_attribute(key, value, rewrite = false) session_attribute(key, value, rewrite) end # Add pack of session attributes and overwrite all existing ones # # @param attributes [Hash] pack of session attributes # @raise [ArgumentError] if given paramter is not a Hash object def add_session_attributes(attributes) unless attributes.is_a? Hash raise ArgumentError, 'Attributes must be a Hash' end session_attributes(attributes, false) end # Add pack of session attributes to existing ones # # @param attributes [Hash] pack of session attributes # @raise [ArgumentError] if given paramter is not a Hash object def merge_session_attributes(attributes) unless attributes.is_a? Hash raise ArgumentError, 'Attributes must be a Hash' end session_attributes(attributes, true) end # Add card to response object # # @param params [Hash] card parameters: # type [String] card type, can be "Simple", "Standard" or "LinkAccount" # title [String] card title # content [String] card content (line breaks must be already included) # small_image_url [String] an URL for small card image # large_image_url [String] an URL for large card image # @raise [ArgumentError] if card is not allowed def add_card(params = {}) card_exception unless %i[launch intent].include? @req_type card = Card.new(params) @resp[:response][:card] = card.obj end # Add AudioPlayer directive # # @param directive [String] audio player directive type, # can be :start or :stop # @param params [Hash] optional request parameters: # url [String] streaming URL # token [String] streaming service token # offset [Integer] playback offset # replace_all [Boolean] true if stream must replace all previous def add_audio_player_directive(directive, params = {}) @resp[:response][:directives] = [ case directive.to_sym when :start AudioPlayer.new.play(params) when :stop AudioPlayer.new.stop when :clear AudioPlayer.new.clear_queue(params[:clear_behavior]) end ] end # Return JSON version of current response state # # @return [JSON] response object def json Oj.to_json(@resp) end # Tell something to Alexa user and close conversation. # Method will only add a given speech to response object # # @param speech [Sring] output speech # @param reprompt_speech [String] output speech if user remains idle # @param ssml [Boolean] is it an SSML speech or not def tell(speech, reprompt_speech = nil, ssml = false) obj = { outputSpeech: build_speech(speech, ssml) } if reprompt_speech obj[:reprompt] = { outputSpeech: build_speech(reprompt_speech, ssml) } end @resp[:response].merge!(obj) end # Tell something to Alexa user and close conversation. # Method will add given sppech to response object and # immediately return its JSON implementation # # @param speech [Sring] output speech # @param reprompt_speech [String] output speech if user remains idle # @param ssml [Boolean] is it an SSML speech or not # @return [JSON] ready to use response object def tell!(speech, reprompt_speech = nil, ssml = false) obj = { outputSpeech: build_speech(speech, ssml) } if reprompt_speech obj[:reprompt] = { outputSpeech: build_speech(reprompt_speech, ssml) } end @resp[:response].merge!(obj) json end # Ask something from user and wait for further information. # Method will only add given sppech to response object and # set "shouldEndSession" parameter to false # # @param speech [Sring] output speech # @param reprompt_speech [String] output speech if user remains idle # @param ssml [Boolean] is it an SSML speech or not def ask(speech, reprompt_speech = nil, ssml = false) @resp[:response][:shouldEndSession] = false tell(speech, reprompt_speech, ssml) end # Ask something from user and wait for further information. # Method will only add given sppech to response object, # set "shouldEndSession" parameter to false and # immediately return response JSON implementation # # @param speech [Sring] output speech # @param reprompt_speech [String] output speech if user remains idle # @param ssml [Boolean] is it an SSML speech or not # @return [JSON] ready to use response object def ask!(speech, reprompt_speech = nil, ssml = false) @resp[:response][:shouldEndSession] = false tell!(speech, reprompt_speech, ssml) end private # Add one session attribute # # @param key [String] atrribute key # @param value [String] attribute value # @param rewrite [Boolean] rewrite if key already exists? # @raise [ArgumentError] if session key is already added and # rewrite is set to false def session_attribute(key, value, rewrite = false) unless rewrite if @resp[:sessionAttributes].key?(key) raise ArgumentError, 'Duplicate session attributes not allowed' end end @resp[:sessionAttributes][key] = value end # Add pack of session attributes. # By default all existing session attributes would be overwritten # # @param attributes [Hash] pack of session attributes # @param merge [Boolean] merge attributes with existing ones? def session_attributes(attributes, merge) rewrite = true unless merge @resp[:sessionAttributes] = {} rewrite = false end attributes.each { |k, v| session_attribute(k, v, rewrite) } end # Build speech object # # @param speech [Sring] output speech # @param ssml [Boolean] is it an SSML speech or not # @return [Hash] speech object def build_speech(speech, ssml) obj = { type: ssml ? 'SSML' : 'PlainText' } ssml ? obj[:ssml] = fix_ssml(speech) : obj[:text] = speech obj end # Forced fix of SSML speech - manually check and fix open and close tags # # @param text [String] SSML response speech # @return [String] fixed SSML speech def fix_ssml(text) open_tag = text.strip[0..6] close_tag = text.strip[-8..1] text = open_tag == '<speak>' ? text : "<speak>#{text}" close_tag == '</speak>' ? text : "#{text}</speak>" end # Raise card exception # # @raise [ArgumentError] if card is not allowed def card_exception raise ArgumentError, 'Card can only be included in response ' \ 'to a "LaunchRequest" or "IntentRequest"' end end end
mulev/alexa-ruby
lib/alexa_ruby/response/response.rb
Ruby
mit
7,547
# encoding: UTF-8 # Some monkeypatches to the `Integer` class. class Integer # Convert this number to a given `base`. # @param (see Bases::Number#to_base) # @return [String] # @see Bases::Number#to_base def to_base(base, opts = {}) Bases.val(self).to_base(base, opts) end # Convert this number in binary form. # @return [String] # @see Bases::Number#to_binary def to_binary to_base(2) end # Convert this number in hexadecimal form. # @return [String] # @see Bases::Number#to_hex def to_hex to_base(16) end end
whatyouhide/bases
lib/bases/monkeypatches/integer.rb
Ruby
mit
557
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _03.Animals { public class Dog { public string Name { get; set; } public int Age { get; set; } public int NumberOfLegs { get; set; } public static void ProduceSound() { Console.WriteLine("I'm a Distinguishedog, and I will now produce a distinguished sound! Bau Bau."); } } }
vankatalp360/Programming-Fundamentals-2017
Objects and Simple Classes - More Exercises/03. Animals/Dog.cs
C#
mit
486
package model; public class InputInfo { private String compiler_version; private String language; private String code_text; private String compiler_option; public String getCompiler_version() { return compiler_version; } public void setCompiler_version(String compiler_version) { this.compiler_version = compiler_version; } public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } public String getCode_text() { return code_text; } public void setCode_text(String code_text) { this.code_text = code_text; } public String getCompiler_option() { return compiler_option; } public void setCompiler_option(String compiler_option) { this.compiler_option = compiler_option; } }
GainSury/eClang
src/model/InputInfo.java
Java
mit
884
<?php /** * This file is part of the PropelBundle package. * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @license MIT License */ namespace Propel\PropelBundle\Tests\DataFixtures\Loader; use Propel\PropelBundle\Tests\DataFixtures\TestCase; use Propel\PropelBundle\DataFixtures\Loader\YamlDataLoader; /** * @author William Durand <william.durand1@gmail.com> * @author Toni Uebernickel <tuebernickel@gmail.com> */ class YamlDataLoaderTest extends TestCase { public function testYamlLoadOneToMany() { $fixtures = <<<YAML Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\BookAuthor: BookAuthor_1: id: '1' name: 'A famous one' Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\Book: Book_1: id: '1' name: 'An important one' author_id: BookAuthor_1 YAML; $filename = $this->getTempFile($fixtures); $loader = new YamlDataLoader(__DIR__.'/../../Fixtures/DataFixtures/Loader'); $loader->load(array($filename), 'default'); $books = \Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\BookPeer::doSelect(new \Criteria(), $this->con); $this->assertCount(1, $books); $book = $books[0]; $this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\BookAuthor', $book->getBookAuthor()); } public function testYamlLoadManyToMany() { $schema = <<<XML <database name="default" package="vendor.bundles.Propel.PropelBundle.Tests.Fixtures.DataFixtures.Loader" namespace="Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader" defaultIdMethod="native"> <table name="table_book" phpName="YamlManyToManyBook"> <column name="id" type="integer" primaryKey="true" /> <column name="name" type="varchar" size="255" /> </table> <table name="table_author" phpName="YamlManyToManyAuthor"> <column name="id" type="integer" primaryKey="true" /> <column name="name" type="varchar" size="255" /> </table> <table name="table_book_author" phpName="YamlManyToManyBookAuthor" isCrossRef="true"> <column name="book_id" type="integer" required="true" primaryKey="true" /> <column name="author_id" type="integer" required="true" primaryKey="true" /> <foreign-key foreignTable="table_book" phpName="Book" onDelete="CASCADE" onUpdate="CASCADE"> <reference local="book_id" foreign="id" /> </foreign-key> <foreign-key foreignTable="table_author" phpName="Author" onDelete="CASCADE" onUpdate="CASCADE"> <reference local="author_id" foreign="id" /> </foreign-key> </table> </database> XML; $fixtures = <<<YAML Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyBook: Book_1: id: 1 name: 'An important one' Book_2: id: 2 name: 'Les misérables' Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyAuthor: Author_1: id: 1 name: 'A famous one' Author_2: id: 2 name: 'Victor Hugo' table_book_authors: [ Book_2 ] Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyBookAuthor: BookAuthor_1: book_id: Book_1 author_id: Author_1 YAML; $filename = $this->getTempFile($fixtures); $builder = new \PropelQuickBuilder(); $builder->setSchema($schema); $con = $builder->build(); $loader = new YamlDataLoader(__DIR__.'/../../Fixtures/DataFixtures/Loader'); $loader->load(array($filename), 'default'); $books = \Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyBookPeer::doSelect(new \Criteria(), $con); $this->assertCount(2, $books); $this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyBook', $books[0]); $this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyBook', $books[1]); $authors = \Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyAuthorPeer::doSelect(new \Criteria(), $con); $this->assertCount(2, $authors); $this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyAuthor', $authors[0]); $this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyAuthor', $authors[1]); $bookAuthors = \Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyBookAuthorPeer::doSelect(new \Criteria(), $con); $this->assertCount(2, $bookAuthors); $this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyBookAuthor', $bookAuthors[0]); $this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyBookAuthor', $bookAuthors[1]); $this->assertEquals('Victor Hugo', $authors[1]->getName()); $this->assertTrue($authors[1]->getBooks()->contains($books[1])); $this->assertEquals('Les misérables', $authors[1]->getBooks()->get(0)->getName()); } public function testYamlLoadManyToManyMultipleFiles() { $schema = <<<XML <database name="default" package="vendor.bundles.Propel.PropelBundle.Tests.Fixtures.DataFixtures.Loader" namespace="Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader" defaultIdMethod="native"> <table name="table_book_multiple" phpName="YamlManyToManyMultipleFilesBook"> <column name="id" type="integer" primaryKey="true" /> <column name="name" type="varchar" size="255" /> </table> <table name="table_author_multiple" phpName="YamlManyToManyMultipleFilesAuthor"> <column name="id" type="integer" primaryKey="true" /> <column name="name" type="varchar" size="255" /> </table> <table name="table_book_author_multiple" phpName="YamlManyToManyMultipleFilesBookAuthor" isCrossRef="true"> <column name="book_id" type="integer" required="true" primaryKey="true" /> <column name="author_id" type="integer" required="true" primaryKey="true" /> <foreign-key foreignTable="table_book_multiple" phpName="Book" onDelete="CASCADE" onUpdate="CASCADE"> <reference local="book_id" foreign="id" /> </foreign-key> <foreign-key foreignTable="table_author_multiple" phpName="Author" onDelete="CASCADE" onUpdate="CASCADE"> <reference local="author_id" foreign="id" /> </foreign-key> </table> </database> XML; $fixtures1 = <<<YAML Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyMultipleFilesBook: Book_2: id: 2 name: 'Les misérables' Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyMultipleFilesAuthor: Author_1: id: 1 name: 'A famous one' Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyMultipleFilesBookAuthor: BookAuthor_1: book_id: Book_1 author_id: Author_1 YAML; $fixtures2 = <<<YAML Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyMultipleFilesBook: Book_1: id: 1 name: 'An important one' Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyMultipleFilesAuthor: Author_2: id: 2 name: 'Victor Hugo' table_book_author_multiples: [ Book_2 ] YAML; $filename1 = $this->getTempFile($fixtures1); $filename2 = $this->getTempFile($fixtures2); $builder = new \PropelQuickBuilder(); $builder->setSchema($schema); $con = $builder->build(); $loader = new YamlDataLoader(__DIR__.'/../../Fixtures/DataFixtures/Loader'); $loader->load(array($filename1, $filename2), 'default'); $books = \Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyMultipleFilesBookPeer::doSelect(new \Criteria(), $con); $this->assertCount(2, $books); $this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyMultipleFilesBook', $books[0]); $this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyMultipleFilesBook', $books[1]); $authors = \Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyMultipleFilesAuthorPeer::doSelect(new \Criteria(), $con); $this->assertCount(2, $authors); $this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyMultipleFilesAuthor', $authors[0]); $this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyMultipleFilesAuthor', $authors[1]); $bookAuthors = \Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyMultipleFilesBookAuthorPeer::doSelect(new \Criteria(), $con); $this->assertCount(2, $bookAuthors); $this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyMultipleFilesBookAuthor', $bookAuthors[0]); $this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlManyToManyMultipleFilesBookAuthor', $bookAuthors[1]); $this->assertEquals('Victor Hugo', $authors[1]->getName()); $this->assertTrue($authors[1]->getBooks()->contains($books[1])); $this->assertEquals('Les misérables', $authors[1]->getBooks()->get(0)->getName()); } public function testLoadSelfReferencing() { $fixtures = <<<YAML Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\BookAuthor: BookAuthor_1: id: '1' name: 'to be announced' BookAuthor_2: id: BookAuthor_1 name: 'A famous one' YAML; $filename = $this->getTempFile($fixtures); $loader = new YamlDataLoader(__DIR__.'/../../Fixtures/DataFixtures/Loader'); $loader->load(array($filename), 'default'); $books = \Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\BookPeer::doSelect(new \Criteria(), $this->con); $this->assertCount(0, $books); $authors = \Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\BookAuthorPeer::doSelect(new \Criteria(), $this->con); $this->assertCount(1, $authors); $author = $authors[0]; $this->assertEquals('A famous one', $author->getName()); } public function testLoaderWithPhp() { $fixtures = <<<YAML Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\BookAuthor: BookAuthor_1: id: '1' name: <?php echo "to be announced"; ?> YAML; $filename = $this->getTempFile($fixtures); $loader = new YamlDataLoader(__DIR__.'/../../Fixtures/DataFixtures/Loader'); $loader->load(array($filename), 'default'); $books = \Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\BookPeer::doSelect(new \Criteria(), $this->con); $this->assertCount(0, $books); $authors = \Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\BookAuthorPeer::doSelect(new \Criteria(), $this->con); $this->assertCount(1, $authors); $author = $authors[0]; $this->assertEquals('to be announced', $author->getName()); } public function testLoadWithoutFaker() { $fixtures = <<<YAML Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\BookAuthor: BookAuthor_1: id: '1' name: <?php echo \$faker('word'); ?> YAML; $filename = $this->getTempFile($fixtures); $loader = new YamlDataLoader(__DIR__.'/../../Fixtures/DataFixtures/Loader'); $loader->load(array($filename), 'default'); $books = \Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\BookPeer::doSelect(new \Criteria(), $this->con); $this->assertCount(0, $books); $authors = \Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\BookAuthorPeer::doSelect(new \Criteria(), $this->con); $this->assertCount(1, $authors); $author = $authors[0]; $this->assertEquals('word', $author->getName()); } public function testLoadWithFaker() { if (!class_exists('Faker\Factory')) { $this->markTestSkipped('Faker is mandatory'); } $fixtures = <<<YAML Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\Book: Book_1: id: '1' name: <?php \$faker('word'); ?> description: <?php \$faker('sentence'); ?> YAML; $filename = $this->getTempFile($fixtures); $container = $this->getContainer(); $container->set('faker.generator', \Faker\Factory::create()); $loader = new YamlDataLoader(__DIR__.'/../../Fixtures/DataFixtures/Loader', $container); $loader->load(array($filename), 'default'); $books = \Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\BookPeer::doSelect(new \Criteria(), $this->con); $this->assertCount(1, $books); $book = $books[0]; $this->assertNotNull($book->getName()); $this->assertNotEquals('null', strtolower($book->getName())); $this->assertRegexp('#[a-z]+#', $book->getName()); $this->assertNotNull($book->getDescription()); $this->assertNotEquals('null', strtolower($book->getDescription())); $this->assertRegexp('#[\w ]+#', $book->getDescription()); } public function testLoadWithInheritedRelationship() { $schema = <<<XML <database name="default" package="vendor.bundles.Propel.PropelBundle.Tests.Fixtures.DataFixtures.Loader" namespace="Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader" defaultIdMethod="native"> <table name="table_book_inherited_relationship" phpName="YamlInheritedRelationshipBook"> <column name="id" type="integer" primaryKey="true" autoIncrement="true" /> <column name="name" type="varchar" size="255" /> <column name="author_id" type="integer" required="true" /> <foreign-key foreignTable="table_author_inherited_relationship" phpName="Author"> <reference local="author_id" foreign="id" /> </foreign-key> </table> <table name="table_author_inherited_relationship" phpName="YamlInheritedRelationshipAuthor"> <column name="id" type="integer" primaryKey="true" autoIncrement="true" /> <column name="name" type="varchar" size="255" /> </table> <table name="table_nobelized_author_inherited_relationship" phpName="YamlInheritedRelationshipNobelizedAuthor"> <column name="nobel_year" type="integer" /> <behavior name="concrete_inheritance"> <parameter name="extends" value="table_author_inherited_relationship" /> </behavior> </table> </database> XML; $fixtures = <<<YAML Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlInheritedRelationshipNobelizedAuthor: NobelizedAuthor_1: nobel_year: 2012 Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlInheritedRelationshipBook: Book_1: name: 'Supplice du santal' author_id: NobelizedAuthor_1 YAML; $filename = $this->getTempFile($fixtures); $builder = new \PropelQuickBuilder(); $builder->setSchema($schema); $con = $builder->build(); $loader = new YamlDataLoader(__DIR__.'/../../Fixtures/DataFixtures/Loader'); $loader->load(array($filename), 'default'); $books = \Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlInheritedRelationshipBookPeer::doSelect(new \Criteria(), $con); $this->assertCount(1, $books); $book = $books[0]; $author = $book->getAuthor(); $this->assertInstanceOf('Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlInheritedRelationshipAuthor', $author); } public function testLoadArrayToObjectType() { $schema = <<<XML <database name="default" package="vendor.bundles.Propel.PropelBundle.Tests.Fixtures.DataFixtures.Loader" namespace="Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader" defaultIdMethod="native"> <table name="table_book_with_object" phpName="YamlBookWithObject"> <column name="id" type="integer" primaryKey="true" /> <column name="name" type="varchar" size="255" /> <column name="options" type="object" /> </table> </database> XML; $fixtures = <<<YAML Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlBookWithObject: book1: name: my book options: {opt1: 2012, opt2: 140, inner: {subOpt: 123}} YAML; $filename = $this->getTempFile($fixtures); $builder = new \PropelQuickBuilder(); $builder->setSchema($schema); $con = $builder->build(); $loader = new YamlDataLoader(__DIR__.'/../../Fixtures/DataFixtures/Loader'); $loader->load(array($filename), 'default'); $book = \Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlBookWithObjectQuery::create(null, $con)->findOne(); $this->assertInstanceOf('\Propel\PropelBundle\Tests\Fixtures\DataFixtures\Loader\YamlBookWithObject', $book); $this->assertEquals(array('opt1' => 2012, 'opt2' => 140, 'inner' => array('subOpt' => 123)), $book->getOptions()); } }
phpchap/mainhostel
vendor/propel/propel-bundle/Propel/PropelBundle/Tests/DataFixtures/Loader/YamlDataLoaderTest.php
PHP
mit
17,260
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.core.validators class Migration(migrations.Migration): dependencies = [ ('django_graph', '0001_initial'), ('cyborg_identity', '0001_initial'), ] operations = [ migrations.CreateModel( name='IsContactEmailAddress', fields=[ ('relationship_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='django_graph.Relationship')), ('valid_from', models.DateTimeField(null=True, blank=True)), ('valid_to', models.DateTimeField(null=True, blank=True)), ], options={ 'abstract': False, }, bases=('django_graph.relationship', models.Model), ), migrations.CreateModel( name='IsContactPhoneNumber', fields=[ ('relationship_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='django_graph.Relationship')), ('valid_from', models.DateTimeField(null=True, blank=True)), ('valid_to', models.DateTimeField(null=True, blank=True)), ('phone_number_type', models.CharField(blank=True, max_length=30, null=True, choices=[(b'HOME', b'Home'), (b'MOBILE', b'Mobile'), (b'WORK', b'Work'), (b'SCHOOL', b'School'), (b'OTHER', b'Other')])), ], options={ 'abstract': False, }, bases=('django_graph.relationship', models.Model), ), migrations.CreateModel( name='PhoneNumber', fields=[ ('node_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='django_graph.Node')), ('us_phone_number', models.CharField(unique=True, max_length=10, validators=[django.core.validators.RegexValidator(regex=b'[0-9]{10}')])), ], options={ 'abstract': False, }, bases=('django_graph.node',), ), ]
shawnhermans/cyborg-identity-manager
cyborg_identity/migrations/0002_iscontactemailaddress_iscontactphonenumber_phonenumber.py
Python
mit
2,204
// import React from 'react'; // import { shallow } from 'enzyme'; // import About from '../index'; describe('<About />', () => { it('Expect to have unit tests specified', () => { expect(true).toEqual(true); }); });
mhoffman/CatAppBrowser
app/components/About/tests/index.test.js
JavaScript
mit
226
// ------------------------------------------------------ // SwarmOps - Numeric and heuristic optimization for Java // Copyright (C) 2003-2011 Magnus Erik Hvass Pedersen. // Please see the file license.txt for license details. // SwarmOps on the internet: http://www.Hvass-Labs.org/ // ------------------------------------------------------ package sso.pso.random; /** * Base-class for a Random Number Generator (RNG) with the methods required by * SwarmOps. It is rumored that earlier Java versions had faulty implementations * of java.util.Random which is the reason some of the methods (e.g. * nextGaussian() and nextInt(n)) have been re-implemented here, to ensure * correctness regardless of what Java version is being used. */ public abstract class Random { /** * Construct the object. */ public Random() { super(); } /** * Name of the RNG. */ public abstract String getName(); /** * Draw a uniform random number in the exclusive range (0,1). It is * important that it does not return the end-point value one which would * cause incorrect output of nextIndex(n). */ public abstract double nextUniform(); /** * Draw a uniform random number in the exclusive range (lower, upper). */ public double nextUniform(double lower, double upper) { return nextUniform() * (upper - lower) + lower; } /** * Draw a random integer from the set {0, .., n-1} with uniform probability. */ public int nextIndex(int n) { // The default implementation uses nextUniform() to generate an integer. // This is because many PRNGs must use division instead of modulo // arithmetics due to the lower-order bits having little randomness. // Assume nextUniform() cannot generate an exact value of one, // otherwise this must have been taken into account to ensure // uniform probability of choosing the different indices. assert n >= 1; double indexD = nextUniform(0, n); assert indexD > 0 && indexD < n; // Truncate. int index = (int) indexD; assert index >= 0 && index <= n - 1; return index; } /** * Draw two distinct integers from the set {0, .., n-1} with equal * probability. */ public int[] nextIndex2(int n) { assert n >= 2; int r1, r2; r1 = nextIndex(n); r2 = nextIndex(n - 1); int i1 = r1; int i2 = (r1 + r2 + 1) % n; assert i1 != i2; return new int[] { i1, i2 }; } /** * Draw a random boolean with equal probability of true and false. */ public boolean nextBoolean() { return nextBoolean(0.5); } /** * Draw a random boolean with probability p of true and (1-p) of false. */ public boolean nextBoolean(double p) { return nextUniform() < p; } /** * Next Gaussian random number. */ private double gaussian; /** * Does gaussian hold a value? */ private boolean gaussianReady = false; /** * Draw a Gaussian (or normally) distributed random number, with designated * mean and deviation. * * @param mean * mean of the normal distribution, e.g. 0. * @param deviation * deviation of the normal distribution, e.g. 1. * @return */ public double nextGaussian(double mean, double deviation) { return deviation * nextGaussian() + mean; } /** * Draw a Gaussian (or normally) distributed random number, with mean 0 and * deviation 1. */ public double nextGaussian() { double value; if (gaussianReady) { value = gaussian; gaussianReady = false; } else { // Pick two uniform numbers in the unit-radius 2-dim ball. Disk disk = new Disk(this); // Use notation from Numeric Recipes book double v1 = disk.x; double v2 = disk.y; double rsq = disk.sumSquares; double fac = Math.sqrt(-2.0 * Math.log(rsq) / rsq); // Now make the Box-Muller transformation to get two normal // deviates. // Return one and save the other for next time. gaussian = v1 * fac; gaussianReady = true; value = v2 * fac; } return value; } }
gto76/sphere-swarm-optimization
src/sso/pso/random/Random.java
Java
mit
4,104
import $ from "jquery" import Template from "hb-template" import _ from "lodash" const renderNavigation = (customerDetails) => { const navigation = Template.Navigation(customerDetails) $('#customer-details').append(navigation) } const createPostalAddress = (medium) => { return medium.street1 + ', ' + medium.city + ', ' + medium.stateOrProvince + ', ' + medium.country + ', ' + medium.postcode } const getMediums = (mediums) => { return _.map(mediums, (medium) => { if (medium.type === 'Email') { return _.assignIn(medium, {data: medium.medium.emailAddress}) } else if (medium.type === 'PostalAddress') { return _.assignIn(medium, {data: createPostalAddress(medium.medium)}) } else if (medium.type === 'TelephoneNumber') { return _.assignIn(medium, {data: medium.medium.number}) } }) } const renderFeatureContainer = (customerDetails) => { $('#customer-contact a').click(() => { $('#customer-contact a').addClass('selected') const mediums = getMediums(customerDetails.contact.contactMedium) const featureContainer = Template.FeatureContainer({mediums}) $('#customer-details').append(featureContainer) }) } const renderCustomerDetails = (container, customerDetails) => { $('#search-result').after('<div id="customer-details"></div>') renderNavigation(customerDetails) renderFeatureContainer(customerDetails) } export {renderCustomerDetails}
avinandi/demo-project-poc
app/js/customerDetails.js
JavaScript
mit
1,416
<!doctype html> <html class="fixed sidebar-left-collapsed"> <head> <?php $title = "U-Dashboard"; include 'partials/head.php'; ?> <style type="text/css"> <?php foreach ($types as $type){ $color = dechex(hexdec($type['color']) + 60); echo('body .btn-info:hover.'.$type['name'].'{'); echo('background-color: #'.$color.';'); echo('border-color: #'.$color.' !important;}'); echo('body .btn-info.'.$type['name'].'{'); echo('background-color: '.$type['color'].';'); echo('border-color: '.$type['color'].' !important;}'); } ?> </style> </head> <body> <section class="body"> <?php include 'partials/header_tmpl.php'; ?> <div class="inner-wrapper"> <!-- start: sidebar --> <aside id="sidebar-left" class="sidebar-left"> <div class="sidebar-header"> <div class="sidebar-title"> Navegación </div> <div class="sidebar-toggle hidden-xs" data-toggle-class="sidebar-left-collapsed" data-target="html" data-fire-event="sidebar-left-toggle"> <i class="fa fa-bars" aria-label="Toggle sidebar"></i> </div> </div> <div class="nano"> <div class="nano-content"> <nav id="menu" class="nav-main" role="navigation"> <ul class="nav nav-main"> <li> <a href="<?php echo base_url();?>inicio"> <i class="fa fa-home" aria-hidden="true"></i> <span>U-Dashboard</span> </a> </li> <?php $first = true; foreach ($types as $type){ echo ('<li> <a href="'.base_url().'inicio?sector='.$type['name'].'">'); echo ('<span class="pull-right label label-primary"></span>'); if ($first){ echo ('<i class="fa fa-university" aria-hidden="true"></i>'); $first = false; } else{ echo ('<i class="el-icon-group" aria-hidden="true"></i>'); } echo ('<span>'.ucwords($type['name']).'</span></a></li>'); } ?> </ul> </nav> </div> </div> </aside> <!-- end: sidebar --> <section role="main" class="content-body"> <header class="page-header"> <h2>U-Dashboard</h2> <div class="right-wrapper pull-right"> <ol class="breadcrumbs"> <li> <a href="<?php echo base_url();?>inicio"> <i class="fa fa-home"></i> </a> </li> <li><span><?php echo($name);?></span></li> </ol> <label>&nbsp;&nbsp;&nbsp;&nbsp;</label> </div> </header> <?php $dept_id=1; if($name == "Soporte"){ $dept_id=0; } ?> <?php echo form_open('dashboard'); echo ('<div class="pane panel-transparent">'); echo ('<header class="panel-heading">'); echo ('<h2 class="panel-title"><button type="submit" name="direccion" value='.$dept_id.' class="mb-xs mt-xs mr-xs btn btn-primary btn-lg btn-block"> DCC </button></h2>'); echo('</header>'); echo('<div class="panel-body">'); echo('<input type="hidden" name="user" id="user" value="'.$user.'">'); $counter = 0; foreach ($areaunit as $au){ $kind = false; $color = false; foreach ($types as $type){ if ($type['id']==$au['area']->getType()){ $kind = $type['name']; $color = $type['color']; } } if ($counter % 2 == 0 && $counter!=0) echo ('</div>'); if ($counter % 2 == 0) echo ('<div class ="row">'); echo ('<div class="col-md-6">'); echo ('<section class="panel panel-info">'); echo ('<header class="panel-heading" style="background-color: '.$color.'">'); echo ('<h2 class="panel-title"><button type="submit" name="direccion" value='.$au['area']->getId().' class="mb-xs mt-xs mr-xs btn btn-info btn-lg btn-block '.$kind.'">'.ucwords($au['area']->getName()).'</button></h2>'); echo ('</header>'); echo ('<div class="panel-body">'); echo ('<div class="btn-group-vertical col-md-12">'); foreach ($au['unidades'] as $unidad){ echo('<button type="submit" name="direccion" class="btn btn-default" value='.$unidad->getId().'>'.ucwords($unidad->getName()).'</button>'); } echo form_close(); echo ('</div></div></section></div>'); $counter++; } ?> </div> </div> <!-- end: page --> </section> </div> </section> <?php include 'partials/footer.php'; ?> <script type="text/javascript"> function changePage(){ window.location.href = "<?php echo base_url();?>dashboard"; } </script> </body> </html>
CamilaAlvarez/IndicadoresDCC
application/views/index.php
PHP
mit
5,084
#include "app.h" #include <QtWidgets/QApplication> #include <QLibraryInfo> int main(int argc, char *argv[]) { QApplication a(argc, argv); App w; w.show(); return a.exec(); }
patemckin/HestonOptions
OptCalc/App/main.cpp
C++
mit
181
/* * grunt-fontgen * https://github.com/agentk/grunt-fontgen * * Copyright 2015 Karl Bowden * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>', ], options: { jshintrc: '.jshintrc', }, }, // Before generating any new files, remove any previously-created files. clean: { tests: ['tmp'], }, // Configuration to be run (and then tested). fontgen: { default_options: { options: { }, files: { 'tmp/default_options': ['test/fixtures/testing', 'test/fixtures/123'], }, }, custom_options: { options: { separator: ': ', punctuation: ' !!!', }, files: { 'tmp/custom_options': ['test/fixtures/testing', 'test/fixtures/123'], }, }, }, // Unit tests. nodeunit: { tests: ['test/*_test.js'], }, }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['clean', 'fontgen', 'nodeunit']); // By default, lint and run all tests. grunt.registerTask('default', ['jshint', 'test']); };
agentk/grunt-fontgen
Gruntfile.js
JavaScript
mit
2,128
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * Description of privilege * * @author loong */ class Privilege extends CI_Controller { //put your code here public function __construct() { parent::__construct(); $this->load->helper('captcha'); $this->load->library('form_validation'); $this->load->model('admin_model','admin'); $this->load->library('session'); } public function login() { $this->load->view('login.html'); } public function code() { $vals = array( 'word_length' =>4, ); $code = create_captcha($vals); $this->session->set_userdata('code',$code); } public function singin() { $this->form_validation->set_rules('username','用户名','required'); $this->form_validation->set_rules('password','密码','required'); $captcha = strtolower($this->input->post('captcha')); $code = strtolower($this->session->userdata('code')); if($captcha ===$code){ if($this->form_validation->run() == FALSE){ $data['message'] = validation_errors(); $data['url'] = site_url('admin/privilege/login'); $data['wait'] = 4; $this->load->view('message.html',$data); } else { $admin_name = $this->input->post('username',true); $password = $this->input->post('password',true); if($this->admin->get_admin($admin_name,$password)){ $this->session->set_userdata('admin',$admin_name); redirect('admin/main/index'); } else { $data['message'] = '用户或密码错误'; $data['url'] = site_url('admin/privilege/login'); $data['wait'] =4; $this->load->view('message.html',$data); } } } else { $data['message'] = '验证码错误,请重新输入'; $data['url'] = site_url('admin/privilege/login'); $data['wait'] = 4; $this->load->view('message.html',$data); } } public function logout() { $this->session->unset_userdata('admin'); $this->session->sess_destroy(); redirect('admin/privilege/login'); } }
chengsann/citest
application/controllers/admin/privilege.php
PHP
mit
2,565
class CreatePages < ActiveRecord::Migration[5.0] def change create_table :pages do |t| t.string :title t.string :slug t.text :text t.timestamps null: false end end end
CollegeSTAR/collegestar_org
db/migrate/20161107195717_create_pages.rb
Ruby
mit
204
<?php namespace SuProfile\BlogBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; use Gedmo\Mapping\Annotation as Gedmo; use Symfony\Component\Validator\ExecutionContextInterface; /** * SuProfile\BlogBundle\Entity\Article * * @ORM\Table(name="article") * @ORM\Entity(repositoryClass="SuProfile\BlogBundle\Entity\ArticleRepository") * @ORM\HasLifecycleCallbacks() */ class Article { /** * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\Column(name="date", type="datetime") */ private $date; /** * @ORM\Column(name="titre", type="string", length=255) */ private $titre; /** * @ORM\Column(name="video", type="string", length=255, nullable=true) */ private $video; /** * @ORM\Column(name="contenu", type="text", nullable=true) */ private $contenu; /** * @ORM\Column(type="date", nullable=true) */ private $dateEdition; /** * @Gedmo\Slug(fields={"titre"}) * @ORM\Column(length=128, unique=true) */ private $slug; /** * @ORM\OneToOne(targetEntity="SuProfile\BlogBundle\Entity\Image", cascade={"persist", "remove"}) */ private $image; /** * @ORM\ManyToMany(targetEntity="SuProfile\BlogBundle\Entity\Categorie", cascade={"persist"}) * @ORM\JoinTable(name="article_categorie") */ private $categories; /** * @ORM\OneToMany(targetEntity="SuProfile\BlogBundle\Entity\Commentaire", mappedBy="article", cascade={"remove"}) */ private $commentaires; // Ici commentaires prend un "s", car un article a plusieurs commentaires ! /** * @ORM\OneToOne(targetEntity="SuProfile\BlogBundle\Entity\Fichier", cascade={"persist", "remove"}) */ private $fichier; /** * @ORM\ManyToOne(targetEntity="SuProfile\UserBundle\Entity\User") */ private $user; public function __construct() { $this->date = new \Datetime; $this->categories = new \Doctrine\Common\Collections\ArrayCollection(); $this->commentaires = new \Doctrine\Common\Collections\ArrayCollection(); } /** * @ORM\PreUpdate */ public function updateDate() { $this->setDateEdition(new \Datetime()); } public function getId() { return $this->id; } /** * @param datetime $date * @return Commentaire */ public function setDate(\Datetime $date) { $this->date = $date; return $this; } /** * @return datetime */ public function getDate() { return $this->date; } public function setTitre($titre) { $this->titre = $titre; } public function getTitre() { return $this->titre; } public function setVideo($video) { $this->video = $video; } public function getVideo() { return $this->video; } public function setContenu($contenu) { $this->contenu = $contenu; } public function getContenu() { return $this->contenu; } public function setImage(\SuProfile\BlogBundle\Entity\Image $image = null) { $this->image = $image; } public function getImage() { return $this->image; } public function addCategorie(\SuProfile\BlogBundle\Entity\Categorie $categorie) { $this->categories[] = $categorie; } public function removeCategorie(\SuProfile\BlogBundle\Entity\Categorie $categorie) { $this->categories->removeElement($categorie); } public function getCategories() { return $this->categories; } public function addCommentaire(\SuProfile\BlogBundle\Entity\Commentaire $commentaire) { $this->commentaires[] = $commentaire; } public function removeCommentaire(\SuProfile\BlogBundle\Entity\Commentaire $commentaire) { $this->commentaires->removeElement($commentaire); } public function getCommentaires() { return $this->commentaires; } public function setFichier(\SuProfile\BlogBundle\Entity\Fichier $fichier = null) { $this->fichier = $fichier; } public function getFichier() { return $this->fichier; } public function setDateEdition(\Datetime $dateEdition) { $this->dateEdition = $dateEdition; } public function getDateEdition() { return $this->dateEdition; } public function setSlug($slug) { $this->slug = $slug; } public function getSlug() { return $this->slug; } public function setUser(\SuProfile\UserBundle\Entity\User $user = null) { $this->user = $user; return $this; } public function getUser() { return $this->user; } }
jlafay/SuProfile
src/SuProfile/BlogBundle/Entity/Article.php
PHP
mit
4,382
import React, { Component } from 'react'; import _ from 'lodash'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { fetchPosts } from '../actions'; class PostsIndex extends Component { componentDidMount() { this.props.fetchPosts(); } renderPosts() { return _.map(this.props.posts, post => { return ( <li className="list-group-item" key={post.id}> <Link to={`/posts/${post.id}`}> {post.title} </Link> </li> ); }); } render() { return( <div> <div className="text-xs-right"> <Link className="btn btn-primary" to="/posts/new"> Add a Post </Link> </div> <h3>Posts</h3> <ul className="list-group"> {this.renderPosts()} </ul> </div> ); } } function mapStateToProps(state) { return { posts: state.posts }; } export default connect(mapStateToProps, { fetchPosts })(PostsIndex);
arianithetemi/ReactBlog
src/components/posts_index.js
JavaScript
mit
1,050
class Api::ConfirmationsController < ApplicationController def create @confirmation = Confirmation.new(confirmation_params) @confirmation.user_id = current_user.id @home = Home.find(confirmation_params[:home_id]) start_date = confirmation_params[:start_date].to_date end_date = confirmation_params[:end_date].to_date if @home.booking_conflict?(start_date, end_date) render json: "Home is unavailable on those dates", status: 422 elsif @confirmation.save render :show else render json: @confirmation.errors.full_messages, status: 422 end end def show @confirmation = Confirmation.find_by(user_id: current_user.id) if @confirmation render :show else render json: "Error", status: 422 end end def destroy @confirmation = Confirmation.find_by(user_id: current_user.id) @confirmation.destroy render :show end private def confirmation_params params.require(:confirmation).permit( :cleaning_cost, :days, :end_date, :home_id, :num_guests, :service_cost, :nightly_cost, :start_date, :total_cost, ) end end
qydchen/SafeHavn
app/controllers/api/confirmations_controller.rb
Ruby
mit
1,177
var gulp = require('gulp'), connect = require('gulp-connect'), open = require('gulp-open'), concat = require('gulp-concat'), flatten = require('gulp-flatten'), port = process.env.port || 3051; gulp.task('open', function(){ var options = { url: 'http://localhost:' + port, }; gulp.src('./app/index.html') .pipe(open('', options)); }); gulp.task('connect', function() { connect.server({ root: 'app', port: port, livereload: true }); }); gulp.task('js', function () { gulp.src('./app/dist/**/*.js') .pipe(connect.reload()); }); gulp.task('html', function () { gulp.src('./app/**/*.html') .pipe(connect.reload()); }); gulp.task('watch', function() { gulp.watch('app/index.html', ['html']); gulp.watch('app/src/**/*.js', ['concat', 'js']); }); gulp.task('bower', function() { gulp.src('bower_components/**/*.min.js') .pipe(flatten()) .pipe(gulp.dest('./app/lib/')) }); gulp.task('concat', function() { gulp.src('./app/src/**/*.js') .pipe(concat('trends.js')) .pipe(gulp.dest('./app/dist/')) }); gulp.task('default', ['concat', 'bower']); gulp.task('serve', ['default', 'connect', 'open', 'watch']);
oalami/trends
web/gulpfile.js
JavaScript
mit
1,155
import { AppState } from 'react-native'; import BackgroundTimer from 'react-native-background-timer'; import * as AppStateActionCreators from 'app/redux/shared_actions/AppStateActionCreators'; var state = AppState.currentState; export default function (store) { AppState.addEventListener('change', (nextAppState) => { if (state.match(/inactive|background/) && nextAppState === 'active') { store.dispatch(AppStateActionCreators.unlockedScreen()); } else if (state.match(/active/) && nextAppState === 'background') { store.dispatch(AppStateActionCreators.lockedScreen()); } else if (state.match(/active/) && nextAppState === 'inactive') { store.dispatch(AppStateActionCreators.multiTask()); } state = nextAppState; }); };
squatsandsciencelabs/OpenBarbellApp
app/services/AppState.js
JavaScript
mit
811
using System; using System.Collections.Generic; public class IntervalTree { private class Node { internal Interval interval; internal double max; internal Node right; internal Node left; public Node(Interval interval) { this.interval = interval; this.max = interval.Hi; } } private Node root; public void Insert(double lo, double hi) { this.root = this.Insert(this.root, lo, hi); } public void EachInOrder(Action<Interval> action) { EachInOrder(this.root, action); } public Interval SearchAny(double lo, double hi) { var current = this.root; while (current != null && !current.interval.Intersects(lo, hi)) { if (current.left != null && current.left.max > lo) { current = current.left; } else { current = current.right; } } return current?.interval; } public IEnumerable<Interval> SearchAll(double lo, double hi) { List<Interval> result = new List<Interval>(); SearchAll(this.root, lo, hi, result); return result; } private void SearchAll(Node node, double lo, double hi, List<Interval> result) { if (node == null) { return; } var goLeft = node.left != null && node.left.max > lo; var goRight = node.right != null && node.right.interval.Lo < hi; if (goLeft) { SearchAll(node.left, lo, hi, result); } if (node.interval.Intersects(lo, hi)) { result.Add(node.interval); } if (goRight) { SearchAll(node.right, lo, hi, result); } } private void EachInOrder(Node node, Action<Interval> action) { if (node == null) { return; } EachInOrder(node.left, action); action(node.interval); EachInOrder(node.right, action); } private Node Insert(Node node, double lo, double hi) { if (node == null) { return new Node(new Interval(lo, hi)); } int cmp = lo.CompareTo(node.interval.Lo); if (cmp < 0) { node.left = Insert(node.left, lo, hi); } else if (cmp > 0) { node.right = Insert(node.right, lo, hi); } this.UpdateMax(node); return node; } private void UpdateMax(Node node) { Node maxChild = this.GetMax(node.left, node.right); node.max = this.GetMax(node, maxChild).max; } private Node GetMax(Node a, Node b) { if (a == null) { return b; } if (b == null) { return a; } return a.max > b.max ? a : b; } }
metodiobetsanov/Tech-Module-CSharp
Data Structures/11. QUAD TREES, K-D TREES, INTERVAL TREES - Lab/IntervalTree/IntervalTree/IntervalTree.cs
C#
mit
2,951