code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading; using System.Threading.Tasks; namespace LinqToDB.Data { using Linq; using Common; using SqlProvider; using SqlQuery; public partial class DataConnection { IQueryRunner IDataContext.GetQueryRunner(Query query, int queryNumber, Expression expression, object[] parameters) { CheckAndThrowOnDisposed(); return new QueryRunner(query, queryNumber, this, expression, parameters); } internal class QueryRunner : QueryRunnerBase { public QueryRunner(Query query, int queryNumber, DataConnection dataConnection, Expression expression, object[] parameters) : base(query, queryNumber, dataConnection, expression, parameters) { _dataConnection = dataConnection; } readonly DataConnection _dataConnection; readonly DateTime _startedOn = DateTime.UtcNow; readonly Stopwatch _stopwatch = Stopwatch.StartNew(); bool _isAsync; Expression _mapperExpression; public override Expression MapperExpression { get => _mapperExpression; set { _mapperExpression = value; if (value != null && Common.Configuration.Linq.TraceMapperExpression && TraceSwitch.TraceInfo && _dataConnection.OnTraceConnection != null) { _dataConnection.OnTraceConnection(new TraceInfo(TraceInfoStep.MapperCreated) { TraceLevel = TraceLevel.Info, DataConnection = _dataConnection, MapperExpression = MapperExpression, StartTime = _startedOn, ExecutionTime = _stopwatch.Elapsed, IsAsync = _isAsync, }); } } } public override string GetSqlText() { SetCommand(false); var sqlProvider = _preparedQuery.SqlProvider ?? _dataConnection.DataProvider.CreateSqlBuilder(); var sb = new StringBuilder(); sb.Append("-- ").Append(_dataConnection.ConfigurationString); if (_dataConnection.ConfigurationString != _dataConnection.DataProvider.Name) sb.Append(' ').Append(_dataConnection.DataProvider.Name); if (_dataConnection.DataProvider.Name != sqlProvider.Name) sb.Append(' ').Append(sqlProvider.Name); sb.AppendLine(); sqlProvider.PrintParameters(sb, _preparedQuery.Parameters); var isFirst = true; foreach (var command in _preparedQuery.Commands) { sb.AppendLine(command); if (isFirst && _preparedQuery.QueryHints != null && _preparedQuery.QueryHints.Count > 0) { isFirst = false; while (sb[sb.Length - 1] == '\n' || sb[sb.Length - 1] == '\r') sb.Length--; sb.AppendLine(); var sql = sb.ToString(); var sqlBuilder = _dataConnection.DataProvider.CreateSqlBuilder(); sql = sqlBuilder.ApplyQueryHints(sql, _preparedQuery.QueryHints); sb = new StringBuilder(sql); } } while (sb[sb.Length - 1] == '\n' || sb[sb.Length - 1] == '\r') sb.Length--; sb.AppendLine(); return sb.ToString(); } public override void Dispose() { if (TraceSwitch.TraceInfo && _dataConnection.OnTraceConnection != null) { _dataConnection.OnTraceConnection(new TraceInfo(TraceInfoStep.Completed) { TraceLevel = TraceLevel.Info, DataConnection = _dataConnection, Command = _dataConnection.Command, MapperExpression = MapperExpression, StartTime = _startedOn, ExecutionTime = _stopwatch.Elapsed, RecordsAffected = RowsCount, IsAsync = _isAsync, }); } base.Dispose(); } public class PreparedQuery { public string[] Commands; public List<SqlParameter> SqlParameters; public IDbDataParameter[] Parameters; public SqlStatement Statement; public ISqlBuilder SqlProvider; public List<string> QueryHints; } PreparedQuery _preparedQuery; static PreparedQuery GetCommand(DataConnection dataConnection, IQueryContext query, int startIndent = 0) { if (query.Context != null) { return new PreparedQuery { Commands = (string[])query.Context, SqlParameters = query.Statement.Parameters, Statement = query.Statement, QueryHints = query.QueryHints, }; } var sql = query.Statement.ProcessParameters(dataConnection.MappingSchema); var newSql = dataConnection.ProcessQuery(sql); if (!object.ReferenceEquals(sql, newSql)) { sql = newSql; sql.IsParameterDependent = true; } var sqlProvider = dataConnection.DataProvider.CreateSqlBuilder(); var cc = sqlProvider.CommandCount(sql); var sb = new StringBuilder(); var commands = new string[cc]; for (var i = 0; i < cc; i++) { sb.Length = 0; sqlProvider.BuildSql(i, sql, sb, startIndent); commands[i] = sb.ToString(); } if (!sql.IsParameterDependent) query.Context = commands; return new PreparedQuery { Commands = commands, SqlParameters = sql.Parameters, Statement = sql, SqlProvider = sqlProvider, QueryHints = query.QueryHints, }; } static void GetParameters(DataConnection dataConnection, IQueryContext query, PreparedQuery pq) { var parameters = query.GetParameters(); if (parameters.Length == 0 && pq.SqlParameters.Count == 0) return; var ordered = dataConnection.DataProvider.SqlProviderFlags.IsParameterOrderDependent; var c = ordered ? pq.SqlParameters.Count : parameters.Length; var parms = new List<IDbDataParameter>(c); if (ordered) { for (var i = 0; i < pq.SqlParameters.Count; i++) { var sqlp = pq.SqlParameters[i]; if (sqlp.IsQueryParameter) { var parm = parameters.Length > i && object.ReferenceEquals(parameters[i], sqlp) ? parameters[i] : parameters.First(p => object.ReferenceEquals(p, sqlp)); AddParameter(dataConnection, parms, parm.Name, parm); } } } else { foreach (var parm in parameters) { if (parm.IsQueryParameter && pq.SqlParameters.Contains(parm)) AddParameter(dataConnection, parms, parm.Name, parm); } } pq.Parameters = parms.ToArray(); } static void AddParameter(DataConnection dataConnection, ICollection<IDbDataParameter> parms, string name, SqlParameter parm) { var p = dataConnection.Command.CreateParameter(); var systemType = parm.SystemType; var dataType = parm.DataType; var dbType = parm.DbType; var dbSize = parm.DbSize; var paramValue = parm.Value; if (systemType == null) { if (paramValue != null) systemType = paramValue.GetType(); } if (dataType == DataType.Undefined) { dataType = dataConnection.MappingSchema.GetDataType( parm.SystemType == typeof(object) && paramValue != null ? paramValue.GetType() : systemType).DataType; } dataConnection.DataProvider.SetParameter(p, name, new DbDataType(systemType, dataType, dbType, dbSize), paramValue); parms.Add(p); } public static PreparedQuery SetQuery(DataConnection dataConnection, IQueryContext queryContext, int startIndent = 0) { var preparedQuery = GetCommand(dataConnection, queryContext, startIndent); GetParameters(dataConnection, queryContext, preparedQuery); return preparedQuery; } protected override void SetQuery() { _preparedQuery = SetQuery(_dataConnection, Query.Queries[QueryNumber]); } void SetCommand() { SetCommand(true); _dataConnection.InitCommand(CommandType.Text, _preparedQuery.Commands[0], null, QueryHints); if (_preparedQuery.Parameters != null) foreach (var p in _preparedQuery.Parameters) _dataConnection.Command.Parameters.Add(p); } #region ExecuteNonQuery static int ExecuteNonQueryImpl(DataConnection dataConnection, PreparedQuery preparedQuery) { if (preparedQuery.Commands.Length == 1) { dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[0], null, preparedQuery.QueryHints); if (preparedQuery.Parameters != null) foreach (var p in preparedQuery.Parameters) dataConnection.Command.Parameters.Add(p); return dataConnection.ExecuteNonQuery(); } var rowsAffected = -1; for (var i = 0; i < preparedQuery.Commands.Length; i++) { dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[i], null, i == 0 ? preparedQuery.QueryHints : null); if (i == 0 && preparedQuery.Parameters != null) foreach (var p in preparedQuery.Parameters) dataConnection.Command.Parameters.Add(p); if (i < preparedQuery.Commands.Length - 1 && preparedQuery.Commands[i].StartsWith("DROP")) { try { dataConnection.ExecuteNonQuery(); } catch (Exception) { } } else { var n = dataConnection.ExecuteNonQuery(); if (i == 0) rowsAffected = n; } } return rowsAffected; } public override int ExecuteNonQuery() { SetCommand(true); return ExecuteNonQueryImpl(_dataConnection, _preparedQuery); } public static int ExecuteNonQuery(DataConnection dataConnection, IQueryContext context) { var preparedQuery = GetCommand(dataConnection, context); GetParameters(dataConnection, context, preparedQuery); return ExecuteNonQueryImpl(dataConnection, preparedQuery); } #endregion #region ExecuteScalar static object ExecuteScalarImpl(DataConnection dataConnection, PreparedQuery preparedQuery) { IDbDataParameter idParam = null; if (dataConnection.DataProvider.SqlProviderFlags.IsIdentityParameterRequired) { if (preparedQuery.Statement.NeedsIdentity()) { idParam = dataConnection.Command.CreateParameter(); idParam.ParameterName = "IDENTITY_PARAMETER"; idParam.Direction = ParameterDirection.Output; idParam.DbType = DbType.Decimal; dataConnection.Command.Parameters.Add(idParam); } } if (preparedQuery.Commands.Length == 1) { if (idParam != null) { // This is because the firebird provider does not return any parameters via ExecuteReader // the rest of the providers must support this mode dataConnection.ExecuteNonQuery(); return idParam.Value; } return dataConnection.ExecuteScalar(); } dataConnection.ExecuteNonQuery(); dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[1], null, null); return dataConnection.ExecuteScalar(); } public static object ExecuteScalar(DataConnection dataConnection, IQueryContext context) { var preparedQuery = GetCommand(dataConnection, context); GetParameters(dataConnection, context, preparedQuery); dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[0], null, preparedQuery.QueryHints); if (preparedQuery.Parameters != null) foreach (var p in preparedQuery.Parameters) dataConnection.Command.Parameters.Add(p); return ExecuteScalarImpl(dataConnection, preparedQuery); } public override object ExecuteScalar() { SetCommand(); return ExecuteScalarImpl(_dataConnection, _preparedQuery); } #endregion #region ExecuteReader public static IDataReader ExecuteReader(DataConnection dataConnection, IQueryContext context) { var preparedQuery = GetCommand(dataConnection, context); GetParameters(dataConnection, context, preparedQuery); dataConnection.InitCommand(CommandType.Text, preparedQuery.Commands[0], null, preparedQuery.QueryHints); if (preparedQuery.Parameters != null) foreach (var p in preparedQuery.Parameters) dataConnection.Command.Parameters.Add(p); return dataConnection.ExecuteReader(); } public override IDataReader ExecuteReader() { SetCommand(true); _dataConnection.InitCommand(CommandType.Text, _preparedQuery.Commands[0], null, QueryHints); if (_preparedQuery.Parameters != null) foreach (var p in _preparedQuery.Parameters) _dataConnection.Command.Parameters.Add(p); return _dataConnection.ExecuteReader(); } #endregion class DataReaderAsync : IDataReaderAsync { public DataReaderAsync(DbDataReader dataReader) { _dataReader = dataReader; } readonly DbDataReader _dataReader; public IDataReader DataReader => _dataReader; public Task<bool> ReadAsync(CancellationToken cancellationToken) { return _dataReader.ReadAsync(cancellationToken); } public void Dispose() { // call interface method, because at least MySQL provider incorrectly override // methods for .net core 1x DataReader.Dispose(); } } public override async Task<IDataReaderAsync> ExecuteReaderAsync(CancellationToken cancellationToken) { _isAsync = true; await _dataConnection.EnsureConnectionAsync(cancellationToken); base.SetCommand(true); _dataConnection.InitCommand(CommandType.Text, _preparedQuery.Commands[0], null, QueryHints); if (_preparedQuery.Parameters != null) foreach (var p in _preparedQuery.Parameters) _dataConnection.Command.Parameters.Add(p); var dataReader = await _dataConnection.ExecuteReaderAsync(_dataConnection.GetCommandBehavior(CommandBehavior.Default), cancellationToken); return new DataReaderAsync(dataReader); } public override async Task<int> ExecuteNonQueryAsync(CancellationToken cancellationToken) { _isAsync = true; await _dataConnection.EnsureConnectionAsync(cancellationToken); base.SetCommand(true); if (_preparedQuery.Commands.Length == 1) { _dataConnection.InitCommand( CommandType.Text, _preparedQuery.Commands[0], null, _preparedQuery.QueryHints); if (_preparedQuery.Parameters != null) foreach (var p in _preparedQuery.Parameters) _dataConnection.Command.Parameters.Add(p); return await _dataConnection.ExecuteNonQueryAsync(cancellationToken); } for (var i = 0; i < _preparedQuery.Commands.Length; i++) { _dataConnection.InitCommand( CommandType.Text, _preparedQuery.Commands[i], null, i == 0 ? _preparedQuery.QueryHints : null); if (i == 0 && _preparedQuery.Parameters != null) foreach (var p in _preparedQuery.Parameters) _dataConnection.Command.Parameters.Add(p); if (i < _preparedQuery.Commands.Length - 1 && _preparedQuery.Commands[i].StartsWith("DROP")) { try { await _dataConnection.ExecuteNonQueryAsync(cancellationToken); } catch { } } else { await _dataConnection.ExecuteNonQueryAsync(cancellationToken); } } return -1; } public override async Task<object> ExecuteScalarAsync(CancellationToken cancellationToken) { _isAsync = true; await _dataConnection.EnsureConnectionAsync(cancellationToken); SetCommand(); IDbDataParameter idparam = null; if (_dataConnection.DataProvider.SqlProviderFlags.IsIdentityParameterRequired) { if (_preparedQuery.Statement.NeedsIdentity()) { idparam = _dataConnection.Command.CreateParameter(); idparam.ParameterName = "IDENTITY_PARAMETER"; idparam.Direction = ParameterDirection.Output; idparam.DbType = DbType.Decimal; _dataConnection.Command.Parameters.Add(idparam); } } if (_preparedQuery.Commands.Length == 1) { if (idparam != null) { // так сделано потому, что фаерберд провайдер не возвращает никаких параметров через ExecuteReader // остальные провайдеры должны поддерживать такой режим await _dataConnection.ExecuteNonQueryAsync(cancellationToken); return idparam.Value; } return await _dataConnection.ExecuteScalarAsync(cancellationToken); } await _dataConnection.ExecuteNonQueryAsync(cancellationToken); _dataConnection.InitCommand(CommandType.Text, _preparedQuery.Commands[1], null, null); return await _dataConnection.ExecuteScalarAsync(cancellationToken); } } } }
ronnyek/linq2db
Source/LinqToDB/Data/DataConnection.QueryRunner.cs
C#
mit
17,014
# Swagger JSON This is a swagger JSON built by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. ![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-net%2Fsrc%2FSDKs%2FPostgreSQL%2FManagement.PostgreSQL%2FREADME.png)
jamestao/azure-sdk-for-net
src/SDKs/PostgreSQL/Management.PostgreSQL/README.md
Markdown
mit
288
/* * Copyright 2004 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include BOSS_WEBRTC_U_rtc_base__win32socketserver_h //original-code:"rtc_base/win32socketserver.h" #include <ws2tcpip.h> // NOLINT #include <algorithm> #include BOSS_WEBRTC_U_rtc_base__byteorder_h //original-code:"rtc_base/byteorder.h" #include BOSS_WEBRTC_U_rtc_base__checks_h //original-code:"rtc_base/checks.h" #include BOSS_WEBRTC_U_rtc_base__logging_h //original-code:"rtc_base/logging.h" #include BOSS_WEBRTC_U_rtc_base__win32window_h //original-code:"rtc_base/win32window.h" namespace rtc { /////////////////////////////////////////////////////////////////////////////// // Win32Socket /////////////////////////////////////////////////////////////////////////////// // TODO: Enable for production builds also? Use FormatMessage? #if !defined(NDEBUG) LPCSTR WSAErrorToString(int error, LPCSTR* description_result) { LPCSTR string = "Unspecified"; LPCSTR description = "Unspecified description"; switch (error) { case ERROR_SUCCESS: string = "SUCCESS"; description = "Operation succeeded"; break; case WSAEWOULDBLOCK: string = "WSAEWOULDBLOCK"; description = "Using a non-blocking socket, will notify later"; break; case WSAEACCES: string = "WSAEACCES"; description = "Access denied, or sharing violation"; break; case WSAEADDRNOTAVAIL: string = "WSAEADDRNOTAVAIL"; description = "Address is not valid in this context"; break; case WSAENETDOWN: string = "WSAENETDOWN"; description = "Network is down"; break; case WSAENETUNREACH: string = "WSAENETUNREACH"; description = "Network is up, but unreachable"; break; case WSAENETRESET: string = "WSANETRESET"; description = "Connection has been reset due to keep-alive activity"; break; case WSAECONNABORTED: string = "WSAECONNABORTED"; description = "Aborted by host"; break; case WSAECONNRESET: string = "WSAECONNRESET"; description = "Connection reset by host"; break; case WSAETIMEDOUT: string = "WSAETIMEDOUT"; description = "Timed out, host failed to respond"; break; case WSAECONNREFUSED: string = "WSAECONNREFUSED"; description = "Host actively refused connection"; break; case WSAEHOSTDOWN: string = "WSAEHOSTDOWN"; description = "Host is down"; break; case WSAEHOSTUNREACH: string = "WSAEHOSTUNREACH"; description = "Host is unreachable"; break; case WSAHOST_NOT_FOUND: string = "WSAHOST_NOT_FOUND"; description = "No such host is known"; break; } if (description_result) { *description_result = description; } return string; } void ReportWSAError(LPCSTR context, int error, const SocketAddress& address) { LPCSTR description_string; LPCSTR error_string = WSAErrorToString(error, &description_string); RTC_LOG(LS_INFO) << context << " = " << error << " (" << error_string << ":" << description_string << ") [" << address.ToString() << "]"; } #else void ReportWSAError(LPCSTR context, int error, const SocketAddress& address) {} #endif ///////////////////////////////////////////////////////////////////////////// // Win32Socket::EventSink ///////////////////////////////////////////////////////////////////////////// #define WM_SOCKETNOTIFY (WM_USER + 50) #define WM_DNSNOTIFY (WM_USER + 51) struct Win32Socket::DnsLookup { HANDLE handle; uint16_t port; char buffer[MAXGETHOSTSTRUCT]; }; class Win32Socket::EventSink : public Win32Window { public: explicit EventSink(Win32Socket* parent) : parent_(parent) {} void Dispose(); bool OnMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& result) override; void OnNcDestroy() override; private: bool OnSocketNotify(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& result); bool OnDnsNotify(WPARAM wParam, LPARAM lParam, LRESULT& result); Win32Socket* parent_; }; void Win32Socket::EventSink::Dispose() { parent_ = nullptr; if (::IsWindow(handle())) { ::DestroyWindow(handle()); } else { delete this; } } bool Win32Socket::EventSink::OnMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& result) { switch (uMsg) { case WM_SOCKETNOTIFY: case WM_TIMER: return OnSocketNotify(uMsg, wParam, lParam, result); case WM_DNSNOTIFY: return OnDnsNotify(wParam, lParam, result); } return false; } bool Win32Socket::EventSink::OnSocketNotify(UINT uMsg, WPARAM wParam, LPARAM lParam, LRESULT& result) { result = 0; int wsa_event = WSAGETSELECTEVENT(lParam); int wsa_error = WSAGETSELECTERROR(lParam); // Treat connect timeouts as close notifications if (uMsg == WM_TIMER) { wsa_event = FD_CLOSE; wsa_error = WSAETIMEDOUT; } if (parent_) parent_->OnSocketNotify(static_cast<SOCKET>(wParam), wsa_event, wsa_error); return true; } bool Win32Socket::EventSink::OnDnsNotify(WPARAM wParam, LPARAM lParam, LRESULT& result) { result = 0; int error = WSAGETASYNCERROR(lParam); if (parent_) parent_->OnDnsNotify(reinterpret_cast<HANDLE>(wParam), error); return true; } void Win32Socket::EventSink::OnNcDestroy() { if (parent_) { RTC_LOG(LS_ERROR) << "EventSink hwnd is being destroyed, but the event sink" " hasn't yet been disposed."; } else { delete this; } } ///////////////////////////////////////////////////////////////////////////// // Win32Socket ///////////////////////////////////////////////////////////////////////////// Win32Socket::Win32Socket() : socket_(INVALID_SOCKET), error_(0), state_(CS_CLOSED), connect_time_(0), closing_(false), close_error_(0), sink_(nullptr), dns_(nullptr) {} Win32Socket::~Win32Socket() { Close(); } bool Win32Socket::CreateT(int family, int type) { Close(); int proto = (SOCK_DGRAM == type) ? IPPROTO_UDP : IPPROTO_TCP; socket_ = ::WSASocket(family, type, proto, nullptr, 0, 0); if (socket_ == INVALID_SOCKET) { UpdateLastError(); return false; } if ((SOCK_DGRAM == type) && !SetAsync(FD_READ | FD_WRITE)) { return false; } return true; } int Win32Socket::Attach(SOCKET s) { RTC_DCHECK(socket_ == INVALID_SOCKET); if (socket_ != INVALID_SOCKET) return SOCKET_ERROR; RTC_DCHECK(s != INVALID_SOCKET); if (s == INVALID_SOCKET) return SOCKET_ERROR; socket_ = s; state_ = CS_CONNECTED; if (!SetAsync(FD_READ | FD_WRITE | FD_CLOSE)) return SOCKET_ERROR; return 0; } void Win32Socket::SetTimeout(int ms) { if (sink_) ::SetTimer(sink_->handle(), 1, ms, 0); } SocketAddress Win32Socket::GetLocalAddress() const { sockaddr_storage addr = {0}; socklen_t addrlen = sizeof(addr); int result = ::getsockname(socket_, reinterpret_cast<sockaddr*>(&addr), &addrlen); SocketAddress address; if (result >= 0) { SocketAddressFromSockAddrStorage(addr, &address); } else { RTC_LOG(LS_WARNING) << "GetLocalAddress: unable to get local addr, socket=" << socket_; } return address; } SocketAddress Win32Socket::GetRemoteAddress() const { sockaddr_storage addr = {0}; socklen_t addrlen = sizeof(addr); int result = ::getpeername(socket_, reinterpret_cast<sockaddr*>(&addr), &addrlen); SocketAddress address; if (result >= 0) { SocketAddressFromSockAddrStorage(addr, &address); } else { RTC_LOG(LS_WARNING) << "GetRemoteAddress: unable to get remote addr, socket=" << socket_; } return address; } int Win32Socket::Bind(const SocketAddress& addr) { RTC_DCHECK(socket_ != INVALID_SOCKET); if (socket_ == INVALID_SOCKET) return SOCKET_ERROR; sockaddr_storage saddr; size_t len = addr.ToSockAddrStorage(&saddr); int err = ::bind(socket_, reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(len)); UpdateLastError(); return err; } int Win32Socket::Connect(const SocketAddress& addr) { if (state_ != CS_CLOSED) { SetError(EALREADY); return SOCKET_ERROR; } if (!addr.IsUnresolvedIP()) { return DoConnect(addr); } RTC_LOG_F(LS_INFO) << "async dns lookup (" << addr.hostname() << ")"; DnsLookup* dns = new DnsLookup; if (!sink_) { // Explicitly create the sink ourselves here; we can't rely on SetAsync // because we don't have a socket_ yet. CreateSink(); } // TODO: Replace with IPv6 compatible lookup. dns->handle = WSAAsyncGetHostByName(sink_->handle(), WM_DNSNOTIFY, addr.hostname().c_str(), dns->buffer, sizeof(dns->buffer)); if (!dns->handle) { RTC_LOG_F(LS_ERROR) << "WSAAsyncGetHostByName error: " << WSAGetLastError(); delete dns; UpdateLastError(); Close(); return SOCKET_ERROR; } dns->port = addr.port(); dns_ = dns; state_ = CS_CONNECTING; return 0; } int Win32Socket::DoConnect(const SocketAddress& addr) { if ((socket_ == INVALID_SOCKET) && !CreateT(addr.family(), SOCK_STREAM)) { return SOCKET_ERROR; } if (!SetAsync(FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE)) { return SOCKET_ERROR; } sockaddr_storage saddr = {0}; size_t len = addr.ToSockAddrStorage(&saddr); connect_time_ = Time(); int result = connect(socket_, reinterpret_cast<SOCKADDR*>(&saddr), static_cast<int>(len)); if (result != SOCKET_ERROR) { state_ = CS_CONNECTED; } else { int code = WSAGetLastError(); if (code == WSAEWOULDBLOCK) { state_ = CS_CONNECTING; } else { ReportWSAError("WSAAsync:connect", code, addr); error_ = code; Close(); return SOCKET_ERROR; } } addr_ = addr; return 0; } int Win32Socket::GetError() const { return error_; } void Win32Socket::SetError(int error) { error_ = error; } Socket::ConnState Win32Socket::GetState() const { return state_; } int Win32Socket::GetOption(Option opt, int* value) { int slevel; int sopt; if (TranslateOption(opt, &slevel, &sopt) == -1) return -1; char* p = reinterpret_cast<char*>(value); int optlen = sizeof(value); return ::getsockopt(socket_, slevel, sopt, p, &optlen); } int Win32Socket::SetOption(Option opt, int value) { int slevel; int sopt; if (TranslateOption(opt, &slevel, &sopt) == -1) return -1; const char* p = reinterpret_cast<const char*>(&value); return ::setsockopt(socket_, slevel, sopt, p, sizeof(value)); } int Win32Socket::Send(const void* buffer, size_t length) { int sent = ::send(socket_, reinterpret_cast<const char*>(buffer), static_cast<int>(length), 0); UpdateLastError(); return sent; } int Win32Socket::SendTo(const void* buffer, size_t length, const SocketAddress& addr) { sockaddr_storage saddr; size_t addr_len = addr.ToSockAddrStorage(&saddr); int sent = ::sendto( socket_, reinterpret_cast<const char*>(buffer), static_cast<int>(length), 0, reinterpret_cast<sockaddr*>(&saddr), static_cast<int>(addr_len)); UpdateLastError(); return sent; } int Win32Socket::Recv(void* buffer, size_t length, int64_t* timestamp) { if (timestamp) { *timestamp = -1; } int received = ::recv(socket_, static_cast<char*>(buffer), static_cast<int>(length), 0); UpdateLastError(); if (closing_ && received <= static_cast<int>(length)) PostClosed(); return received; } int Win32Socket::RecvFrom(void* buffer, size_t length, SocketAddress* out_addr, int64_t* timestamp) { if (timestamp) { *timestamp = -1; } sockaddr_storage saddr; socklen_t addr_len = sizeof(saddr); int received = ::recvfrom(socket_, static_cast<char*>(buffer), static_cast<int>(length), 0, reinterpret_cast<sockaddr*>(&saddr), &addr_len); UpdateLastError(); if (received != SOCKET_ERROR) SocketAddressFromSockAddrStorage(saddr, out_addr); if (closing_ && received <= static_cast<int>(length)) PostClosed(); return received; } int Win32Socket::Listen(int backlog) { int err = ::listen(socket_, backlog); if (!SetAsync(FD_ACCEPT)) return SOCKET_ERROR; UpdateLastError(); if (err == 0) state_ = CS_CONNECTING; return err; } Win32Socket* Win32Socket::Accept(SocketAddress* out_addr) { sockaddr_storage saddr; socklen_t addr_len = sizeof(saddr); SOCKET s = ::accept(socket_, reinterpret_cast<sockaddr*>(&saddr), &addr_len); UpdateLastError(); if (s == INVALID_SOCKET) return nullptr; if (out_addr) SocketAddressFromSockAddrStorage(saddr, out_addr); Win32Socket* socket = new Win32Socket; if (0 == socket->Attach(s)) return socket; delete socket; return nullptr; } int Win32Socket::Close() { int err = 0; if (socket_ != INVALID_SOCKET) { err = ::closesocket(socket_); socket_ = INVALID_SOCKET; closing_ = false; close_error_ = 0; UpdateLastError(); } if (dns_) { WSACancelAsyncRequest(dns_->handle); delete dns_; dns_ = nullptr; } if (sink_) { sink_->Dispose(); sink_ = nullptr; } addr_.Clear(); state_ = CS_CLOSED; return err; } void Win32Socket::CreateSink() { RTC_DCHECK(nullptr == sink_); // Create window sink_ = new EventSink(this); sink_->Create(nullptr, L"EventSink", 0, 0, 0, 0, 10, 10); } bool Win32Socket::SetAsync(int events) { if (nullptr == sink_) { CreateSink(); RTC_DCHECK(nullptr != sink_); } // start the async select if (WSAAsyncSelect(socket_, sink_->handle(), WM_SOCKETNOTIFY, events) == SOCKET_ERROR) { UpdateLastError(); Close(); return false; } return true; } bool Win32Socket::HandleClosed(int close_error) { // WM_CLOSE will be received before all data has been read, so we need to // hold on to it until the read buffer has been drained. char ch; closing_ = true; close_error_ = close_error; return (::recv(socket_, &ch, 1, MSG_PEEK) <= 0); } void Win32Socket::PostClosed() { // If we see that the buffer is indeed drained, then send the close. closing_ = false; ::PostMessage(sink_->handle(), WM_SOCKETNOTIFY, socket_, WSAMAKESELECTREPLY(FD_CLOSE, close_error_)); } void Win32Socket::UpdateLastError() { error_ = WSAGetLastError(); } int Win32Socket::TranslateOption(Option opt, int* slevel, int* sopt) { switch (opt) { case OPT_DONTFRAGMENT: *slevel = IPPROTO_IP; *sopt = IP_DONTFRAGMENT; break; case OPT_RCVBUF: *slevel = SOL_SOCKET; *sopt = SO_RCVBUF; break; case OPT_SNDBUF: *slevel = SOL_SOCKET; *sopt = SO_SNDBUF; break; case OPT_NODELAY: *slevel = IPPROTO_TCP; *sopt = TCP_NODELAY; break; case OPT_DSCP: RTC_LOG(LS_WARNING) << "Socket::OPT_DSCP not supported."; return -1; default: RTC_NOTREACHED(); return -1; } return 0; } void Win32Socket::OnSocketNotify(SOCKET socket, int event, int error) { // Ignore events if we're already closed. if (socket != socket_) return; error_ = error; switch (event) { case FD_CONNECT: if (error != ERROR_SUCCESS) { ReportWSAError("WSAAsync:connect notify", error, addr_); #if !defined(NDEBUG) int64_t duration = TimeSince(connect_time_); RTC_LOG(LS_INFO) << "WSAAsync:connect error (" << duration << " ms), faking close"; #endif state_ = CS_CLOSED; // If you get an error connecting, close doesn't really do anything // and it certainly doesn't send back any close notification, but // we really only maintain a few states, so it is easiest to get // back into a known state by pretending that a close happened, even // though the connect event never did occur. SignalCloseEvent(this, error); } else { #if !defined(NDEBUG) int64_t duration = TimeSince(connect_time_); RTC_LOG(LS_INFO) << "WSAAsync:connect (" << duration << " ms)"; #endif state_ = CS_CONNECTED; SignalConnectEvent(this); } break; case FD_ACCEPT: case FD_READ: if (error != ERROR_SUCCESS) { ReportWSAError("WSAAsync:read notify", error, addr_); } else { SignalReadEvent(this); } break; case FD_WRITE: if (error != ERROR_SUCCESS) { ReportWSAError("WSAAsync:write notify", error, addr_); } else { SignalWriteEvent(this); } break; case FD_CLOSE: if (HandleClosed(error)) { ReportWSAError("WSAAsync:close notify", error, addr_); state_ = CS_CLOSED; SignalCloseEvent(this, error); } break; } } void Win32Socket::OnDnsNotify(HANDLE task, int error) { if (!dns_ || dns_->handle != task) return; uint32_t ip = 0; if (error == 0) { hostent* pHost = reinterpret_cast<hostent*>(dns_->buffer); uint32_t net_ip = *reinterpret_cast<uint32_t*>(pHost->h_addr_list[0]); ip = NetworkToHost32(net_ip); } RTC_LOG_F(LS_INFO) << "(" << IPAddress(ip).ToSensitiveString() << ", " << error << ")"; if (error == 0) { SocketAddress address(ip, dns_->port); error = DoConnect(address); } else { Close(); } if (error) { error_ = error; SignalCloseEvent(this, error_); } else { delete dns_; dns_ = nullptr; } } /////////////////////////////////////////////////////////////////////////////// // Win32SocketServer // Provides cricket base services on top of a win32 gui thread /////////////////////////////////////////////////////////////////////////////// static UINT s_wm_wakeup_id = 0; const TCHAR Win32SocketServer::kWindowName[] = L"libjingle Message Window"; Win32SocketServer::Win32SocketServer() : wnd_(this), posted_(false), hdlg_(nullptr) { if (s_wm_wakeup_id == 0) s_wm_wakeup_id = RegisterWindowMessage(L"WM_WAKEUP"); if (!wnd_.Create(nullptr, kWindowName, 0, 0, 0, 0, 0, 0)) { RTC_LOG_GLE(LS_ERROR) << "Failed to create message window."; } } Win32SocketServer::~Win32SocketServer() { if (wnd_.handle() != nullptr) { KillTimer(wnd_.handle(), 1); wnd_.Destroy(); } } Socket* Win32SocketServer::CreateSocket(int family, int type) { return CreateAsyncSocket(family, type); } AsyncSocket* Win32SocketServer::CreateAsyncSocket(int family, int type) { Win32Socket* socket = new Win32Socket; if (socket->CreateT(family, type)) { return socket; } delete socket; return nullptr; } void Win32SocketServer::SetMessageQueue(MessageQueue* queue) { message_queue_ = queue; } bool Win32SocketServer::Wait(int cms, bool process_io) { BOOL b; if (process_io) { // Spin the Win32 message pump at least once, and as long as requested. // This is the Thread::ProcessMessages case. uint32_t start = Time(); do { MSG msg; SetTimer(wnd_.handle(), 0, cms, nullptr); // Get the next available message. If we have a modeless dialog, give // give the message to IsDialogMessage, which will return true if it // was a message for the dialog that it handled internally. // Otherwise, dispatch as usual via Translate/DispatchMessage. b = GetMessage(&msg, nullptr, 0, 0); if (b == -1) { RTC_LOG_GLE(LS_ERROR) << "GetMessage failed."; return false; } else if (b) { if (!hdlg_ || !IsDialogMessage(hdlg_, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } KillTimer(wnd_.handle(), 0); } while (b && TimeSince(start) < cms); } else if (cms != 0) { // Sit and wait forever for a WakeUp. This is the Thread::Send case. RTC_DCHECK(cms == -1); MSG msg; b = GetMessage(&msg, nullptr, s_wm_wakeup_id, s_wm_wakeup_id); { CritScope scope(&cs_); posted_ = false; } } else { // No-op (cms == 0 && !process_io). This is the Pump case. b = TRUE; } return (b != FALSE); } void Win32SocketServer::WakeUp() { if (wnd_.handle()) { // Set the "message pending" flag, if not already set. { CritScope scope(&cs_); if (posted_) return; posted_ = true; } PostMessage(wnd_.handle(), s_wm_wakeup_id, 0, 0); } } void Win32SocketServer::Pump() { // Clear the "message pending" flag. { CritScope scope(&cs_); posted_ = false; } // Dispatch all the messages that are currently in our queue. If new messages // are posted during the dispatch, they will be handled in the next Pump. // We use max(1, ...) to make sure we try to dispatch at least once, since // this allow us to process "sent" messages, not included in the size() count. Message msg; for (size_t max_messages_to_process = std::max<size_t>(1, message_queue_->size()); max_messages_to_process > 0 && message_queue_->Get(&msg, 0, false); --max_messages_to_process) { message_queue_->Dispatch(&msg); } // Anything remaining? int delay = message_queue_->GetDelay(); if (delay == -1) { KillTimer(wnd_.handle(), 1); } else { SetTimer(wnd_.handle(), 1, delay, nullptr); } } bool Win32SocketServer::MessageWindow::OnMessage(UINT wm, WPARAM wp, LPARAM lp, LRESULT& lr) { bool handled = false; if (wm == s_wm_wakeup_id || (wm == WM_TIMER && wp == 1)) { ss_->Pump(); lr = 0; handled = true; } return handled; } Win32Thread::Win32Thread(SocketServer* ss) : Thread(ss), id_(0) {} Win32Thread::~Win32Thread() { Stop(); } void Win32Thread::Run() { id_ = GetCurrentThreadId(); Thread::Run(); id_ = 0; } void Win32Thread::Quit() { PostThreadMessage(id_, WM_QUIT, 0, 0); } } // namespace rtc
koobonil/Boss2D
Boss2D/addon/webrtc-jumpingyang001_for_boss/rtc_base/win32socketserver.cc
C++
mit
22,653
class R: def __init__(self, c): self.c = c self.is_star = False def match(self, c): return self.c == '.' or self.c == c class Solution(object): def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ rs = [] """:type: list[R]""" for c in p: if c == '*': rs[-1].is_star = True else: rs.append(R(c)) lr = len(rs) ls = len(s) s += '\0' dp = [[False] * (ls + 1) for _ in range(lr + 1)] dp[0][0] = True for i, r in enumerate(rs): for j in range(ls + 1): c = s[j - 1] if r.is_star: dp[i + 1][j] = dp[i][j] if j and r.match(c): dp[i + 1][j] |= dp[i + 1][j - 1] else: if j and r.match(c): dp[i + 1][j] = dp[i][j - 1] return dp[-1][-1]
SF-Zhou/LeetCode.Solutions
solutions/regular_expression_matching.py
Python
mit
1,032
# escape=` FROM mcr.microsoft.com/windows/servercore as msi SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"] ENV MONGO_VERSION 3.4.5 ENV MONGO_DOWNLOAD_URL https://downloads.mongodb.com/win32/mongodb-win32-x86_64-enterprise-windows-64-${MONGO_VERSION}-signed.msi ENV MONGO_DOWNLOAD_SHA256 cda1c8d547fc6051d7bbe2953f9a75bced846ac64a733726f8443835db5b2901 RUN Write-Host ('Downloading {0} ...' -f $env:MONGO_DOWNLOAD_URL) RUN Invoke-WebRequest -Uri $env:MONGO_DOWNLOAD_URL -OutFile 'mongodb.msi' RUN Write-Host ('Verifying sha256 ({0}) ...' -f $env:MONGO_DOWNLOAD_SHA256) RUN if ((Get-FileHash mongodb.msi -Algorithm sha256).Hash -ne $env:MONGO_DOWNLOAD_SHA256) { ` Write-Host 'FAILED!'; ` exit 1; ` } RUN Start-Process msiexec.exe -ArgumentList '/i', 'mongodb.msi', '/quiet', '/norestart', 'INSTALLLOCATION=C:\mongodb', 'ADDLOCAL=Server,Client,MonitoringTools,ImportExportTools,MiscellaneousTools' -NoNewWindow -Wait RUN Remove-Item C:\mongodb\bin\*.pdb FROM mcr.microsoft.com/windows/nanoserver:sac2016 COPY --from=msi C:\mongodb\ C:\mongodb\ COPY --from=msi C:\windows\system32\msvcp140.dll C:\windows\system32 COPY --from=msi C:\windows\system32\vcruntime140.dll C:\windows\system32 COPY --from=msi C:\windows\system32\wininet.dll C:\windows\system32 RUN mkdir C:\data\db & setx /m PATH %PATH%;C:\mongodb\bin VOLUME C:\data\db EXPOSE 27017 CMD ["mongod.exe"]
StefanScherer/dockerfiles-windows
mongo/3.4/enterprise/Dockerfile
Dockerfile
mit
1,448
namespace GameBoySharp.Domain.Contracts { public interface IContiguousMemory : IReadableMemory, IWriteableMemory { } }
taspeotis/GameBoySharp
GameBoySharp.Domain/Contracts/IContiguousMemory.cs
C#
mit
133
public class App { public static void main(String[] args) { System.out.println("Old man, look at my life..."); } }
zelark/test
src/main/java/App.java
Java
mit
119
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_102) on Thu Jan 05 15:34:48 PST 2017 --> <title>Uses of Class main.CurrentDateAndTime</title> <meta name="date" content="2017-01-05"> <link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class main.CurrentDateAndTime"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../main/package-summary.html">Package</a></li> <li><a href="../../main/CurrentDateAndTime.html" title="class in main">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-files/index-1.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../index.html?main/class-use/CurrentDateAndTime.html" target="_top">Frames</a></li> <li><a href="CurrentDateAndTime.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class main.CurrentDateAndTime" class="title">Uses of Class<br>main.CurrentDateAndTime</h2> </div> <div class="classUseContainer">No usage of main.CurrentDateAndTime</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../main/package-summary.html">Package</a></li> <li><a href="../../main/CurrentDateAndTime.html" title="class in main">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../deprecated-list.html">Deprecated</a></li> <li><a href="../../index-files/index-1.html">Index</a></li> <li><a href="../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../index.html?main/class-use/CurrentDateAndTime.html" target="_top">Frames</a></li> <li><a href="CurrentDateAndTime.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
tliang1/Java-Practice
Practice/Intro-To-Java-8th-Ed-Daniel-Y.-Liang/Chapter-5/Chapter05P24/doc/main/class-use/CurrentDateAndTime.html
HTML
mit
3,986
version https://git-lfs.github.com/spec/v1 oid sha256:83b131c4d8b0acf16d0579e177572a462b114180f95c7444ebae08cb7370e68f size 3656
yogeshsaroya/new-cdnjs
ajax/libs/pure/0.2.0/grids.css
CSS
mit
129
var score = 0; var scoreText; var map_x = 14; var map_y = 10; var game = new Phaser.Game(map_x * 16, map_y * 16, Phaser.AUTO, '', { preload: preload, create: create, update: update }); function preload() { // game.scale.maxWidth = 600; // game.scale.maxHeight = 600; game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; game.scale.setScreenSize(); game.load.image('cat', 'assets/cat.png', 16, 16); game.load.image('ground', 'assets/darkfloor.png', 16, 16); game.load.image('l_wall', 'assets/l_wall.png', 16, 16); game.load.image('r_wall', 'assets/r_wall.png', 16, 16); game.load.image('t_wall', 'assets/t_wall.png', 16, 16); game.load.image('tr_wall', 'assets/tr_wall_iso.png', 16, 16); game.load.image('tl_wall', 'assets/tl_wall_iso.png', 16, 16); game.load.image('bl_wall', 'assets/bl_wall.png', 16, 16); game.load.image('br_wall', 'assets/br_wall.png', 16, 16); game.load.image('stone_door', 'assets/door_stone.png', 16, 16); game.load.image('star', 'assets/star.png'); } function create() { game.physics.startSystem(Phaser.Physics.ARCADE); // the game world gmap = game.add.tilemap(); gmap.addTilesetImage('ground', 'ground', 16, 16, null, null, 0); gmap.addTilesetImage('l_wall', 'l_wall', 16, 16, null, null, 1); gmap.addTilesetImage('r_wall', 'r_wall', 16, 16, null, null, 2); gmap.addTilesetImage('tr_wall', 'tr_wall', 16, 16, null, null, 3); gmap.addTilesetImage('tl_wall', 'tl_wall', 16, 16, null, null, 4); gmap.addTilesetImage('br_wall', 'br_wall', 16, 16, null, null, 5); gmap.addTilesetImage('bl_wall', 'bl_wall', 16, 16, null, null, 6); gmap.addTilesetImage('t_wall', 't_wall', 16, 16, null, null, 7); gmap.addTilesetImage('stone_door', 'stone_door', 16, 16, null, null, 8); ground_layer = gmap.create('ground_layer', map_x, map_y, 16, 16); wall_layer = gmap.create('wall_layer', map_x, map_y, 16, 16); for (var i=0; i<map_x; i++) { for(var j=0; j<map_y; j++) { if (i==0 && j==0) { gmap.putTile(4, i, j, wall_layer); } else if (i==map_x/2 && j==0) { gmap.putTile(8, i, j, wall_layer); } else if (i==map_x-1 && j == map_y-1) { gmap.putTile(5, i, j, wall_layer); } else if (i==0 && j == map_y-1) { gmap.putTile(6, i, j, wall_layer); } else if (i==map_x-1 && j == 0) { gmap.putTile(3, i, j, wall_layer); } else if (i==map_x-1 && j == map_y-1) { gmap.putTile(6, i, j, wall_layer); } else if (i==0) { gmap.putTile(1, i, j, wall_layer); } else if(i==map_x-1) { gmap.putTile(2, i, j, wall_layer); } else if(j==map_y-1) { gmap.putTile(7, i, j, wall_layer); } else if(j==0) { gmap.putTile(7, i, j, wall_layer); } else { gmap.putTile(0, i, j, ground_layer); } } } wall_layer.resizeWorld(); game.physics.arcade.enable(wall_layer); gmap.setCollision(wall_layer); // the player player = game.add.sprite(32, 32, 'cat'); game.physics.arcade.enable(player); player.body.collideWorldBounds = true; // gmap.setCollisionBetween(0, 100, true, wall_layer); cursors = game.input.keyboard.createCursorKeys(); } function update() { game.physics.arcade.collide(player, wall_layer); player.body.velocity.x = 0; player.body.velocity.y = 0; if (cursors.left.isDown) { player.body.velocity.x = -150; } else if (cursors.right.isDown) { player.body.velocity.x = 150; } else if (cursors.down.isDown) { player.body.velocity.y = 150; } else if (cursors.up.isDown) { player.body.velocity.y = -150; } else { } }
henripal/henripal.github.io
game/game.js
JavaScript
mit
3,879
package com.thebluealliance.androidclient.gcm.notifications; import android.app.Notification; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.thebluealliance.androidclient.Constants; import com.thebluealliance.androidclient.R; import com.thebluealliance.androidclient.Utilities; import com.thebluealliance.androidclient.activities.ViewMatchActivity; import com.thebluealliance.androidclient.datafeed.JSONManager; import com.thebluealliance.androidclient.helpers.EventHelper; import com.thebluealliance.androidclient.helpers.MatchHelper; import com.thebluealliance.androidclient.helpers.MyTBAHelper; import com.thebluealliance.androidclient.listeners.GamedayTickerClickListener; import com.thebluealliance.androidclient.models.BasicModel; import com.thebluealliance.androidclient.models.Match; import com.thebluealliance.androidclient.models.StoredNotification; import com.thebluealliance.androidclient.views.MatchView; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; /** * Created by Nathan on 7/24/2014. */ public class ScoreNotification extends BaseNotification { private String eventName, eventKey, matchKey; private Match match; public ScoreNotification(String messageData) { super("score", messageData); } @Override public void parseMessageData() throws JsonParseException { JsonObject jsonData = JSONManager.getasJsonObject(messageData); if (!jsonData.has("match")) { throw new JsonParseException("Notification data does not contain 'match"); } JsonObject match = jsonData.get("match").getAsJsonObject(); this.match = gson.fromJson(match, Match.class); try { this.matchKey = this.match.getKey(); } catch (BasicModel.FieldNotDefinedException e) { e.printStackTrace(); } this.eventKey = MatchHelper.getEventKeyFromMatchKey(matchKey); if (!jsonData.has("event_name")) { throw new JsonParseException("Notification data does not contain 'event_name"); } eventName = jsonData.get("event_name").getAsString(); } @Override public Notification buildNotification(Context context) { Resources r = context.getResources(); String matchKey; try { matchKey = match.getKey(); this.matchKey = matchKey; } catch (BasicModel.FieldNotDefinedException e) { Log.e(getLogTag(), "Incoming Match object does not have a key. Can't post score update"); e.printStackTrace(); return null; } String matchTitle = MatchHelper.getMatchTitleFromMatchKey(context, matchKey); String matchAbbrevTitle = MatchHelper.getAbbrevMatchTitleFromMatchKey(context, matchKey); JsonObject alliances; try { alliances = match.getAlliances(); } catch (BasicModel.FieldNotDefinedException e) { Log.e(getLogTag(), "Incoming match object does not contain alliance data. Can't post score update"); e.printStackTrace(); return null; } int redScore = Match.getRedScore(alliances); ArrayList<String> redTeamKeys = new ArrayList<>(); JsonArray redTeamsJson = Match.getRedTeams(alliances); for (int i = 0; i < redTeamsJson.size(); i++) { redTeamKeys.add(redTeamsJson.get(i).getAsString()); } int blueScore = Match.getBlueScore(alliances); ArrayList<String> blueTeamKeys = new ArrayList<>(); JsonArray blueTeamsJson = Match.getBlueTeams(alliances); for (int i = 0; i < blueTeamsJson.size(); i++) { blueTeamKeys.add(blueTeamsJson.get(i).getAsString()); } // TODO filter out teams that the user doesn't want notifications about // These arrays hold the numbers of teams that the user cares about ArrayList<String> redTeams = new ArrayList<>(); ArrayList<String> blueTeams = new ArrayList<>(); for (String key : redTeamKeys) { redTeams.add(key.replace("frc", "")); } for (String key : blueTeamKeys) { blueTeams.add(key.replace("frc", "")); } // Make sure the score string is formatted properly with the winning score first String scoreString; if (redScore > blueScore) { scoreString = redScore + "-" + blueScore; } else if (redScore < blueScore) { scoreString = blueScore + "-" + redScore; } else { scoreString = redScore + "-" + redScore; } String redTeamString = Utilities.stringifyListOfStrings(context, redTeams); String blueTeamString = Utilities.stringifyListOfStrings(context, blueTeams); boolean useSpecial2015Format; try { useSpecial2015Format = match.getYear() == 2015 && match.getType() != MatchHelper.TYPE.FINAL; } catch (BasicModel.FieldNotDefinedException e) { useSpecial2015Format = false; Log.w(Constants.LOG_TAG, "Couldn't determine if we should use 2015 score format. Defaulting to no"); } String eventShortName = EventHelper.shortName(eventName); String notificationString; if (redTeams.size() == 0 && blueTeams.size() == 0) { // We must have gotten this GCM message by mistake return null; } else if (useSpecial2015Format) { /* Only for 2015 non-finals matches. Ugh */ notificationString = context.getString(R.string.notification_score_2015_no_winner, eventShortName, matchTitle, redTeamString, redScore, blueTeamString, blueScore); } else if ((redTeams.size() > 0 && blueTeams.size() == 0)) { // The user only cares about some teams on the red alliance if (redScore > blueScore) { // Red won notificationString = context.getString(R.string.notification_score_teams_won, eventShortName, redTeamString, matchTitle, scoreString); } else if (redScore < blueScore) { // Red lost notificationString = context.getString(R.string.notification_score_teams_lost, eventShortName, redTeamString, matchTitle, scoreString); } else { // Red tied notificationString = context.getString(R.string.notification_score_teams_tied, eventShortName, redTeamString, matchTitle, scoreString); } } else if ((blueTeams.size() > 0 && redTeams.size() == 0)) { // The user only cares about some teams on the blue alliance if (blueScore > redScore) { // Blue won notificationString = context.getString(R.string.notification_score_teams_won, eventShortName, blueTeamString, matchTitle, scoreString); } else if (blueScore < redScore) { // Blue lost notificationString = context.getString(R.string.notification_score_teams_lost, eventShortName, blueTeamString, matchTitle, scoreString); } else { // Blue tied notificationString = context.getString(R.string.notification_score_teams_tied, eventShortName, blueTeamString, matchTitle, scoreString); } } else if ((blueTeams.size() > 0 && redTeams.size() > 0)) { // The user cares about teams on both alliances if (blueScore > redScore) { // Blue won notificationString = context.getString(R.string.notification_score_teams_beat_teams, eventShortName, blueTeamString, redTeamString, matchTitle, scoreString); } else if (blueScore < redScore) { // Blue lost notificationString = context.getString(R.string.notification_score_teams_beat_teams, eventShortName, redTeamString, blueTeamString, matchTitle, scoreString); } else { // Blue tied notificationString = context.getString(R.string.notification_score_teams_tied_with_teams, eventShortName, redTeamString, blueTeamString, matchTitle, scoreString); } } else { // We should never, ever get here but if we do... return null; } // We can finally build the notification! Intent instance = getIntent(context); stored = new StoredNotification(); stored.setType(getNotificationType()); String eventCode = EventHelper.getEventCode(matchKey); String notificationTitle = r.getString(R.string.notification_score_title, eventCode, matchAbbrevTitle); stored.setTitle(notificationTitle); stored.setBody(notificationString); stored.setIntent(MyTBAHelper.serializeIntent(instance)); stored.setTime(Calendar.getInstance().getTime()); NotificationCompat.Builder builder = getBaseBuilder(context, instance) .setContentTitle(notificationTitle) .setContentText(notificationString) .setLargeIcon(getLargeIconFormattedForPlatform(context, R.drawable.ic_info_outline_white_24dp)); NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle().bigText(notificationString); builder.setStyle(style); return builder.build(); } @Override public void updateDataLocally(Context c) { if (match != null) { match.write(c); } } @Override public Intent getIntent(Context c) { return ViewMatchActivity.newInstance(c, matchKey); } @Override public int getNotificationId() { return (new Date().getTime() + ":" + getNotificationType() + ":" + matchKey).hashCode(); } @Override public View getView(Context c, LayoutInflater inflater, View convertView) { ViewHolder holder; if (convertView == null || !(convertView.getTag() instanceof ViewHolder)) { convertView = inflater.inflate(R.layout.list_item_notification_score, null, false); holder = new ViewHolder(); holder.header = (TextView) convertView.findViewById(R.id.card_header); holder.title = (TextView) convertView.findViewById(R.id.title); holder.matchView = (MatchView) convertView.findViewById(R.id.match_details); holder.time = (TextView) convertView.findViewById(R.id.notification_time); holder.summaryContainer = convertView.findViewById(R.id.summary_container); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.header.setText(c.getString(R.string.gameday_ticker_event_title_format, EventHelper.shortName(eventName), EventHelper.getShortCodeForEventKey(eventKey).toUpperCase())); holder.title.setText(c.getString(R.string.notification_score_gameday_title, MatchHelper.getMatchTitleFromMatchKey(c, matchKey))); holder.time.setText(getNotificationTimeString(c)); holder.summaryContainer.setOnClickListener(new GamedayTickerClickListener(c, this)); match.render(false, false, false, true).getView(c, inflater, holder.matchView); return convertView; } private class ViewHolder { public TextView header; public TextView title; public MatchView matchView; public TextView time; private View summaryContainer; } }
Adam8234/the-blue-alliance-android
android/src/main/java/com/thebluealliance/androidclient/gcm/notifications/ScoreNotification.java
Java
mit
11,766
import { expect } from 'chai'; import { Curry } from './curry'; describe('curry', () => { it('should curry the method with default arity', () => { class MyClass { @Curry() add(a: any, b?: any) { return a + b; } } const myClass = new MyClass(); const add5 = myClass.add(5); expect(add5).to.be.an.instanceOf(Function); expect(add5(10)).to.equal(15); }); it('should curry the method with default arity (paramless)', () => { class MyClass { @Curry add(a: any, b?: any) { return a + b; } } const myClass = new MyClass(); const add5 = myClass.add(5); expect(add5).to.be.an.instanceOf(Function); expect(add5(10)).to.equal(15); }); it('should curry the method with fixed arity', () => { class MyClass { @Curry(2) add(a: any, b?: any, c?: any) { return a + b * c; } } const myClass = new MyClass(); const add5 = myClass.add(5); expect(add5).to.be.an.instanceOf(Function); expect(add5(10, 2)).to.equal(25); }); it('should retain the class context', () => { class MyClass { value = 10; @Curry() add(a: any, b?: any): any { return (a + b) * this.value; } } const myClass = new MyClass(); const add5 = myClass.add(5); expect(add5(2)).to.equal(70); }); });
steelsojka/lodash-decorators
src/curry.spec.ts
TypeScript
mit
1,375
module Fog module XenServer class Compute module Models class CrashDumps < Collection model Fog::XenServer::Compute::Models::CrashDump end end end end end
fog/fog-xenserver
lib/fog/xenserver/compute/models/crash_dumps.rb
Ruby
mit
204
using UnityEngine; using UnityEngine.UI; using System.Collections; public class DebugWindow : MonoBehaviour { public Text textWindow; string freshInput; // Use this for initialization void Start () { if (textWindow == null) throw new UnityException ("Debug Window has no text box to output to."); } // Update is called once per frame void Update () { textWindow.text = "Debug:\n" + freshInput; freshInput = ""; } public void LOG(string Text) { freshInput += Text + '\n'; } }
tlsteenWoo/UnityNeedler
New Unity Project/Assets/Game/Scripts/DebugWindow.cs
C#
mit
505
// Copyright (c) Pomelo Foundation. All rights reserved. // Licensed under the MIT. See LICENSE in the project root for license information. using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Query; using Microsoft.EntityFrameworkCore.Storage; using Pomelo.EntityFrameworkCore.MySql.Query.ExpressionTranslators.Internal; using Pomelo.EntityFrameworkCore.MySql.Query.Internal; namespace Pomelo.EntityFrameworkCore.MySql.Json.Microsoft.Query.Internal { public class MySqlJsonMicrosoftMemberTranslatorPlugin : IMemberTranslatorPlugin { public MySqlJsonMicrosoftMemberTranslatorPlugin( IRelationalTypeMappingSource typeMappingSource, ISqlExpressionFactory sqlExpressionFactory, IMySqlJsonPocoTranslator jsonPocoTranslator) { var mySqlSqlExpressionFactory = (MySqlSqlExpressionFactory)sqlExpressionFactory; var mySqlJsonPocoTranslator = (MySqlJsonPocoTranslator)jsonPocoTranslator; Translators = new IMemberTranslator[] { new MySqlJsonMicrosoftDomTranslator( mySqlSqlExpressionFactory, typeMappingSource, mySqlJsonPocoTranslator), jsonPocoTranslator, }; } public virtual IEnumerable<IMemberTranslator> Translators { get; } } }
PomeloFoundation/Pomelo.EntityFrameworkCore.MySql
src/EFCore.MySql.Json.Microsoft/Query/Internal/MySqlJsonMicrosoftMemberTranslatorPlugin.cs
C#
mit
1,377
export { default } from 'ember-flexberry-gis/services/map-store';
Flexberry/ember-flexberry-gis
app/services/map-store.js
JavaScript
mit
66
from flask import Flask, render_template, flash from flask_material_lite import Material_Lite from flask_appconfig import AppConfig from flask_wtf import Form, RecaptchaField from flask_wtf.file import FileField from wtforms import TextField, HiddenField, ValidationError, RadioField,\ BooleanField, SubmitField, IntegerField, FormField, validators from wtforms.validators import Required # straight from the wtforms docs: class TelephoneForm(Form): country_code = IntegerField('Country Code', [validators.required()]) area_code = IntegerField('Area Code/Exchange', [validators.required()]) number = TextField('Number') class ExampleForm(Form): field1 = TextField('First Field', description='This is field one.') field2 = TextField('Second Field', description='This is field two.', validators=[Required()]) hidden_field = HiddenField('You cannot see this', description='Nope') recaptcha = RecaptchaField('A sample recaptcha field') radio_field = RadioField('This is a radio field', choices=[ ('head_radio', 'Head radio'), ('radio_76fm', "Radio '76 FM"), ('lips_106', 'Lips 106'), ('wctr', 'WCTR'), ]) checkbox_field = BooleanField('This is a checkbox', description='Checkboxes can be tricky.') # subforms mobile_phone = FormField(TelephoneForm) # you can change the label as well office_phone = FormField(TelephoneForm, label='Your office phone') ff = FileField('Sample upload') submit_button = SubmitField('Submit Form') def validate_hidden_field(form, field): raise ValidationError('Always wrong') def create_app(configfile=None): app = Flask(__name__) AppConfig(app, configfile) # Flask-Appconfig is not necessary, but # highly recommend =) # https://github.com/mbr/flask-appconfig Material_Lite(app) # in a real app, these should be configured through Flask-Appconfig app.config['SECRET_KEY'] = 'devkey' app.config['RECAPTCHA_PUBLIC_KEY'] = \ '6Lfol9cSAAAAADAkodaYl9wvQCwBMr3qGR_PPHcw' @app.route('/', methods=('GET', 'POST')) def index(): form = ExampleForm() form.validate_on_submit() # to get error messages to the browser flash('critical message', 'critical') flash('error message', 'error') flash('warning message', 'warning') flash('info message', 'info') flash('debug message', 'debug') flash('different message', 'different') flash('uncategorized message') return render_template('index.html', form=form) return app if __name__ == '__main__': create_app().run(debug=True)
HellerCommaA/flask-material-lite
sample_application/__init__.py
Python
mit
2,763
#!/usr/bin/env python3 from __future__ import print_function, division import numpy as np from sht.grids import standard_grid, get_cartesian_grid def test_grids(): L = 10 thetas, phis = standard_grid(L) # Can't really test much here assert thetas.size == L assert phis.size == L**2 grid = get_cartesian_grid(thetas, phis) assert grid.shape == (L**2, 3)
praveenv253/sht
tests/test_grids.py
Python
mit
386
This is an older post
TheNeikos/hemera.space
_posts/2017-03-12-old-post.md
Markdown
mit
22
var Keyboard_Space = new function(){ this.initKeyboard = function(testing){ testmode = testing; return new Keyboard(); } var Keyboard = function(){ for(var i = 0; i < numChains; i++) currentSounds.push([]); var this_obj = this; Zip_Space.loadZip(currentSongData["filename"], function() { this_obj.loadSounds(currentSongData["mappings"]["chain1"], currentSounds[0], 1); this_obj.loadSounds(currentSongData["mappings"]["chain2"], currentSounds[1], 2); this_obj.loadSounds(currentSongData["mappings"]["chain3"], currentSounds[2], 3); this_obj.loadSounds(currentSongData["mappings"]["chain4"], currentSounds[3], 4); this_obj.backend = BackendSpace.init(); this_obj.keyboardUI = Keyboard_UI_Space.initKeyboardUI(); console.log("New keyboard created"); }) } // link the keyboard and the editor Keyboard.prototype.linkEditor = function(editor){ this.editor = editor; var mainObj = this; setTimeout(function(){mainObj.editor.setBPM(currentSongData.bpm)},500); } Keyboard.prototype.getCurrentSounds = function(){ return currentSounds; } // loads sounds from srcArray for given chain into soundArr Keyboard.prototype.loadSounds = function(srcArr, soundArr, chain){ for(var i = 0; i < srcArr.length; i++) soundArr.push(null); for(var i = 0; i < srcArr.length; i++){ if(srcArr[i] == "") this.checkLoaded(); else this.requestSound(i, srcArr, soundArr, chain); } } // makes request for sounds // if offline version, gets from local files // if online version, gets from public folder Keyboard.prototype.requestSound = function(i, srcArr, soundArr, chain){ var thisObj = this; soundArr[i] = new Howl({ // for online version urls: [Zip_Space.dataArray['sounds/chain'+chain+'/'+srcArr[i]+'.mp3']], // old // urls: [currentSongData["soundUrls"]["chain"+chain][srcArr[i]].replace("www.dropbox.com","dl.dropboxusercontent.com").replace("?dl=0","")], // for offline version // urls: ["audio/chain"+chain+"/"+srcArr[i]+".mp3"], onload: function(){ thisObj.checkLoaded(); }, onloaderror: function(id, error){ console.log('error: '+id) console.log(error); console.log('sounds/chain'+chain+'/'+srcArr[i]+'.mp3'); $("#error_msg").html("There was an error. Please try clearing your browser's cache and reload the page."); } }); } // checks if all of the sounds have loaded // if they have, load the keyboard Keyboard.prototype.checkLoaded = function(){ numSoundsLoaded++; $(".soundPack").html("Loading sounds ("+numSoundsLoaded+"/"+(4*12*numChains)+")"); if(numSoundsLoaded == 4*12*numChains){ loadingSongs = false; this.keyboardUI.loadKeyboard(this, currentSongData, currentSoundPack); } } Keyboard.prototype.getKeyInd = function(kc){ var keyInd = keyPairs.indexOf(kc); if(keyInd == -1) keyInd = backupPairs.indexOf(kc); return keyInd; } Keyboard.prototype.switchSoundPackCheck = function(kc){ // up if(kc == 39){ this.switchSoundPack(3); return true; } // left else if(kc == 37){ this.switchSoundPack(0); return true; } // down else if(kc == 38){ this.switchSoundPack(1); return true; } // right else if(kc == 40){ this.switchSoundPack(2); return true; } } // switch sound pack and update pressures Keyboard.prototype.switchSoundPack = function(sp){ // release all keys for(var i = 0; i < 4; i++) for(var j = 0; j < 12; j++) if($(".button-"+(i*12+j)+"").attr("released") == "false") this.releaseKey(keyPairs[i*12+j]); // set the new soundpack currentSoundPack = sp; $(".sound_pack_button").css("background-color","white"); $(".sound_pack_button_"+(currentSoundPack+1)).css("background-color","rgb(255,160,0)"); $(".soundPack").html("Sound Pack: "+(currentSoundPack+1)); // set pressures for buttons in new sound pack for(var i = 0; i < 4; i++){ for(var j = 0; j < 12; j++){ var press = false; if(currentSongData["holdToPlay"]["chain"+(currentSoundPack+1)].indexOf((i*12+j)) != -1) press = true; $('.button-'+(i*12+j)+'').attr("pressure", ""+press+""); // holdToPlay coloring, turned off for now //$('.button-'+(i*12+j)+'').css("background-color", $('.button-'+(i*12+j)+'').attr("pressure") == "true" ? "lightgray" : "white"); } } } // key released // stop playing sound if holdToPlay Keyboard.prototype.releaseKey = function(kc){ var keyInd = this.getKeyInd(kc); if(currentSounds[currentSoundPack][keyInd] != null){ this.midiKeyUp(kc); // send key code to MIDI editor this.editor.recordKeyUp(kc); } } Keyboard.prototype.midiKeyUp = function(kc){ if(this.switchSoundPackCheck(kc)){ // do nothing } else{ var kcInd = this.getKeyInd(kc); if(currentSounds[currentSoundPack][kcInd] != null){ if($(".button-"+(kcInd)+"").attr("pressure") == "true") currentSounds[currentSoundPack][kcInd].stop(); $(".button-"+(kcInd)+"").attr("released","true"); // holdToPlay coloring, turned off for now // Removes Style Attribute to clean up HTML $(".button-"+(kcInd)+"").removeAttr("style"); if($(".button-"+(kcInd)+"").hasClass("pressed") == true) $(".button-"+(kcInd)+"").removeClass("pressed"); //$(".button-"+(kcInd)+"").css("background-color", $(".button-"+(kcInd)+"").attr("pressure") == "true" ? "lightgray" : "white"); } } } // play the key by finding the mapping, // stopping all sounds in key's linkedArea // and then playing sound Keyboard.prototype.playKey = function(kc){ var keyInd = this.getKeyInd(kc); if(currentSounds[currentSoundPack][keyInd] != null){ this.midiKeyDown(kc); // send key code to midi editor this.editor.recordKeyDown(kc); } } Keyboard.prototype.midiKeyDown = function(kc){ if(this.switchSoundPackCheck(kc)){ // do nothing } else{ var kcInd = this.getKeyInd(kc); if(currentSounds[currentSoundPack][kcInd] != null){ currentSounds[currentSoundPack][kcInd].stop(); currentSounds[currentSoundPack][kcInd].play(); // go through all linked Areas in current chain currentSongData["linkedAreas"]["chain"+(currentSoundPack+1)].forEach(function(el, ind, arr){ // for ever linked area array for(var j = 0; j < el.length; j++){ // if key code is in linked area array if(kcInd == el[j]){ // stop all other sounds in linked area array for(var k = 0; k < el.length; k++){ if(k != j) currentSounds[currentSoundPack][el[k]].stop(); } break; } } }); // set button color and attribute $(".button-"+(kcInd)+"").addClass("pressed"); $(".button-"+(kcInd)+"").attr("released","false"); //$(".button-"+(kcInd)+"").css("background-color","rgb(255,160,0)"); } } } // shows and formats all of the UI elements Keyboard.prototype.initUI = function(){ // create new editor and append it to the body element if(testmode) BasicMIDI.init("#editor_container_div", this, 170); else MIDI_Editor.init("#editor_container_div", this, 170); // info and links buttons // $(".click_button").css("display", "inline-block"); for(var s in songDatas) $("#songs_container").append("<div class='song_selection' songInd='"+s+"'>"+songDatas[s].song_name+"</div>"); $("[songInd='"+currentSongInd+"']").css("background-color","rgb(220,220,220)"); var mainObj = this; $(".song_selection").click(function() { var tempS = parseInt($(this).attr("songInd")); if(tempS != currentSongInd && !loadingSongs){ loadingSongs = true; currentSongInd = tempS currentSongData = songDatas[currentSongInd]; $(".song_selection").css("background-color","white"); $("[songInd='"+currentSongInd+"']").css("background-color","rgb(220,220,220)"); $(".button-row").remove(); for(var i = 0; i < currentSounds.length; i++){ for(var k = 0; k < currentSounds[i].length; k++){ if(currentSounds[i][k] != null) currentSounds[i][k].unload(); } } currentSounds = []; for(var i = 0; i < numChains; i++) currentSounds.push([]); mainObj.editor.notesLoaded([],-1); mainObj.editor.setBPM(currentSongData.bpm) numSoundsLoaded = 0; Zip_Space.loadZip(currentSongData["filename"], function() { mainObj.loadSounds(currentSongData["mappings"]["chain1"], currentSounds[0], 1); mainObj.loadSounds(currentSongData["mappings"]["chain2"], currentSounds[1], 2); mainObj.loadSounds(currentSongData["mappings"]["chain3"], currentSounds[2], 3); mainObj.loadSounds(currentSongData["mappings"]["chain4"], currentSounds[3], 4); }) } }); } // send request to server to save the notes to the corresponding projectId (pid) Keyboard.prototype.saveNotes = function(notes, pid){ var saveNote = []; for(var n in notes) saveNote.push({"note":notes[n].note, "beat":notes[n].beat, "length":notes[n].length}); //console.log(saveNote); this.backend.saveSong(JSON.stringify(saveNote), pid, this.editor, currentSongData.song_number); } // ask the user for the project they would like to load and then load that project from the server // send back a notes array of the loaded project with note,beat,and length and the project id Keyboard.prototype.loadNotes = function(){ this.backend.loadSongs(this.editor, currentSongData.song_number); } // current soundpack (0-3) var currentSoundPack = 0; // number of sounds loaded var numSoundsLoaded = 0; // howl objects for current song var currentSounds = []; // reference to current song data var songDatas = [equinoxData, animalsData, electroData, ghetData, kyotoData, aeroData]; var currentSongInd = 0; var currentSongData = equinoxData; // number of chains var numChains = 4; var testmode = false; var loadingSongs = true; } // Global Variables // ascii key mappings to array index var keyPairs = [49,50,51,52,53,54,55,56,57,48,189,187, 81,87,69,82,84,89,85,73,79,80,219,221, 65,83,68,70,71,72,74,75,76,186,222,13, 90,88,67,86,66,78,77,188,190,191,16,-1]; // alternate keys for firefox var backupPairs = [49,50,51,52,53,54,55,56,57,48,173,61, 81,87,69,82,84,89,85,73,79,80,219,221, 65,83,68,70,71,72,74,75,76,59,222,13, 90,88,67,86,66,78,77,188,190,191,16,-1]; // letter to show in each button var letterPairs = ["1","2","3","4","5","6","7","8","9","0","-","=", "Q","W","E","R","T","Y","U","I","O","P","[","]", "A","S","D","F","G","H","J","K","L",";","'","\\n", "Z","X","C","V","B","N","M",",",".","/","\\s","NA"];
Dan12/Launchpad
app/assets/javascripts/keyboard.js
JavaScript
mit
13,120
angular.module('booksAR') .directive('userNavbar', function(){ return{ restrict: 'E', templateUrl: './app/components/directives/user/user-navbar.html' }; }) .directive('userBooksTable', function(){ return{ restrict: 'E', templateUrl: './app/components/directives/user/user-books-table.html' }; }) .directive('userTable', function(){ return{ restrict: 'E', templateUrl: './app/components/directives/user/user-table.html' }; }) .directive('userProfileInfo', function(){ return{ restrict: 'E', templateUrl: './app/components/directives/user/user-profile-info.html' }; }) .directive('ngConfirmClick', [ function(){ return { link: function (scope, element, attr) { var msg = attr.ngConfirmClick || "Are you sure?"; var clickAction = attr.confirmedClick; element.bind('click',function (event) { if ( window.confirm(msg) ) { scope.$eval(clickAction) } }); } }; }]);
AlejandroAcostaT/TypewriterAR
frontend/app/components/directives/user/user.js
JavaScript
mit
1,158
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <div th:fragment="common-header"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <title>WickedThymeleafDemo</title> <link th:href="@{/webjars/bootstrap/3.3.7/css/bootstrap.min.css}" rel="stylesheet" media="screen"/> <link type="text/css" th:href="@{/css/styles.css}" rel="stylesheet" media="screen"/> </div> </head> <body> <div th:fragment="end-scripts"> <script th:src="@{/webjars/jquery/3.1.1/jquery.min.js}"></script> <script th:src="@{/webjars/bootstrap/3.3.7/js/bootstrap.min.js}"></script> </div> </body> </html>
WickedWitchWarsaw/ThymeleafSpringDemo
src/main/resources/templates/common/header.html
HTML
mit
662
# Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base helper :all helper_method :current_user_session, :current_user filter_parameter_logging :password, :password_confirmation layout 'application' protected def current_user_session return @current_user_session if defined?(@current_user_session) @current_user_session = UserSession.find end def current_user return @current_user if defined?(@current_user) @current_user = current_user_session && current_user_session.record end def require_user unless current_user store_location flash[:notice] = "You must be logged in to access this page" redirect_to login_url return false end end def require_no_user if current_user store_location flash[:notice] = "You must be logged out to access this page" redirect_to account_url return false end end def store_location session[:return_to] = request.request_uri end def redirect_back_or_default(default) redirect_to(session[:return_to] || default) session[:return_to] = nil end end
markbates/warp_drive
test_apps/enterprise/app/controllers/application_controller.rb
Ruby
mit
1,267
<?php namespace App\AAS_Bundle\Entity; use Doctrine\ORM\Mapping as ORM; use App\AAS_Bundle\Utils\AAS as AAS; /** * Person */ class Person { /** * @var integer */ private $id; /** * @var string */ private $surname; /** * @var string */ private $name; /** * @var string */ private $patronymic; /** * @var string */ private $position; /** * @var \App\AAS_Bundle\Entity\Witness */ private $witness; /** * @var \Doctrine\Common\Collections\Collection */ private $phone_numbers; /** * @var \App\AAS_Bundle\Entity\Team */ private $team; /** * @var \DateTime */ private $created_at; /** * @var \DateTime */ private $updated_at; /** * Constructor */ public function __construct() { $this->phone_numbers = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set surname * * @param string $surname * @return Person */ public function setSurname($surname) { $this->surname = $surname; return $this; } /** * Get surname * * @return string */ public function getSurname() { return $this->surname; } public function getSurnameSlug() { return AAS::slugify($this->getSurname()); } /** * Set name * * @param string $name * @return Person */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } public function getNameSlug() { return AAS::slugify($this->getName()); } /** * Set patronymic * * @param string $patronymic * @return Person */ public function setPatronymic($patronymic) { $this->patronymic = $patronymic; return $this; } /** * Get patronymic * * @return string */ public function getPatronymic() { return $this->patronymic; } public function getPatronymicSlug() { return AAS::slugify($this->getPatronymic()); } /** * Set created_at * * @param \DateTime $createdAt * @return Person */ public function setCreatedAt($createdAt) { $this->created_at = $createdAt; return $this; } /** * Get created_at * * @return \DateTime */ public function getCreatedAt() { return $this->created_at; } /** * Set updated_at * * @param \DateTime $updatedAt * @return Person */ public function setUpdatedAt($updatedAt) { $this->updated_at = $updatedAt; return $this; } /** * Get updated_at * * @return \DateTime */ public function getUpdatedAt() { return $this->updated_at; } /** * @ORM\PrePersist */ public function setCreatedAtValue() { if(!$this->getCreatedAt()) { $this->created_at = new \DateTime(); } } /** * @ORM\PreUpdate */ public function setUpdatedAtValue() { $this->updated_at = new \DateTime(); } /** * @var \App\AAS_Bundle\Entity\SecurityPerson */ private $security_person; /** * Set security_person * * @param \App\AAS_Bundle\Entity\SecurityPerson $securityPerson * @return Person */ public function setSecurityPerson(\App\AAS_Bundle\Entity\SecurityPerson $securityPerson = null) { $this->security_person = $securityPerson; return $this; } /** * Get security_person * * @return \App\AAS_Bundle\Entity\SecurityPerson */ public function getSecurityPerson() { return $this->security_person; } /** * Set position * * @param string $position * @return Person */ public function setPosition($position) { $this->position = $position; return $this; } /** * Get position * * @return string */ public function getPosition() { return $this->position; } /** * Set witness * * @param \App\AAS_Bundle\Entity\Witness $witness * @return Person */ public function setWitness(\App\AAS_Bundle\Entity\Witness $witness = null) { $this->witness = $witness; return $this; } /** * Get witness * * @return \App\AAS_Bundle\Entity\Witness */ public function getWitness() { return $this->witness; } /** * Add phone_numbers * * @param \App\AAS_Bundle\Entity\PhoneNumber $phoneNumbers * @return Person */ public function addPhoneNumber(\App\AAS_Bundle\Entity\PhoneNumber $phoneNumbers) { $this->phone_numbers[] = $phoneNumbers; return $this; } /** * Remove phone_numbers * * @param \App\AAS_Bundle\Entity\PhoneNumber $phoneNumbers */ public function removePhoneNumber(\App\AAS_Bundle\Entity\PhoneNumber $phoneNumbers) { $this->phone_numbers->removeElement($phoneNumbers); } /** * Get phone_numbers * * @return \Doctrine\Common\Collections\Collection */ public function getPhoneNumbers() { return $this->phone_numbers; } /** * Set team * * @param \App\AAS_Bundle\Entity\Team $team * @return Person */ public function setTeam(\App\AAS_Bundle\Entity\Team $team = null) { $this->team = $team; return $this; } /** * Get team * * @return \App\AAS_Bundle\Entity\Team */ public function getTeam() { return $this->team; } /** * @var \App\AAS_Bundle\Entity\MedicalCommission */ private $medical_commission; /** * Set medical_commission * * @param \App\AAS_Bundle\Entity\MedicalCommission $medicalCommission * @return Person */ public function setMedicalCommission(\App\AAS_Bundle\Entity\MedicalCommission $medicalCommission = null) { $this->medical_commission = $medicalCommission; return $this; } /** * Get medical_commission * * @return \App\AAS_Bundle\Entity\MedicalCommission */ public function getMedicalCommission() { return $this->medical_commission; } /** * @var \Doctrine\Common\Collections\Collection */ private $admissions; /** * Add admissions * * @param \App\AAS_Bundle\Entity\Admission $admissions * @return Person */ public function addAdmission(\App\AAS_Bundle\Entity\Admission $admissions) { $this->admissions[] = $admissions; return $this; } /** * Remove admissions * * @param \App\AAS_Bundle\Entity\Admission $admissions */ public function removeAdmission(\App\AAS_Bundle\Entity\Admission $admissions) { $this->admissions->removeElement($admissions); } /** * Get admissions * * @return \Doctrine\Common\Collections\Collection */ public function getAdmissions() { return $this->admissions; } /** * @var \App\AAS_Bundle\Entity\BusinessTripGroup */ private $business_trip_group; /** * Set business_trip_group * * @param \App\AAS_Bundle\Entity\BusinessTripGroup $businessTripGroup * @return Person */ public function setBusinessTripGroup(\App\AAS_Bundle\Entity\BusinessTripGroup $businessTripGroup = null) { $this->business_trip_group = $businessTripGroup; return $this; } /** * Get business_trip_group * * @return \App\AAS_Bundle\Entity\BusinessTripGroup */ public function getBusinessTripGroup() { return $this->business_trip_group; } }
mrkonovalov/AAS
src/App/AAS_Bundle/Entity/Person.php
PHP
mit
8,735
package me.streib.janis.nanhotline.web; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.InetSocketAddress; import org.eclipse.jetty.server.Handler; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.SessionManager; import org.eclipse.jetty.server.handler.ContextHandler; import org.eclipse.jetty.server.handler.HandlerList; import org.eclipse.jetty.server.handler.ResourceHandler; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.util.thread.QueuedThreadPool; public class Launcher { public static void main(String[] args) throws Exception { NANHotlineConfiguration conf; if (args.length != 1) { InputStream ins; File confFile = new File("conf/nanhotline.properties"); if (confFile.exists()) { ins = new FileInputStream(confFile); } else { ins = Launcher.class .getResourceAsStream("nanhotline.properties"); } conf = new NANHotlineConfiguration(ins); } else { conf = new NANHotlineConfiguration(new FileInputStream(new File( args[0]))); } DatabaseConnection.init(conf); Server s = new Server(new InetSocketAddress(conf.getHostName(), conf.getPort())); ((QueuedThreadPool) s.getThreadPool()).setMaxThreads(20); ServletContextHandler h = new ServletContextHandler( ServletContextHandler.SESSIONS); h.setInitParameter(SessionManager.__SessionCookieProperty, "DB-Session"); h.addServlet(NANHotline.class, "/*"); HandlerList hl = new HandlerList(); hl.setHandlers(new Handler[] { generateStaticContext(), h }); s.setHandler(hl); s.start(); } private static Handler generateStaticContext() { final ResourceHandler rh = new ResourceHandler(); rh.setResourceBase("static/"); ContextHandler ch = new ContextHandler("/static"); ch.setHandler(rh); return ch; } }
janisstreib/nan-hotline
webFrontend/src/me/streib/janis/nanhotline/web/Launcher.java
Java
mit
2,118
const test = require('tap').test const GF = require('core/galois-field') test('Galois Field', function (t) { t.throw(function () { GF.log(0) }, 'Should throw for log(n) with n < 1') for (let i = 1; i < 255; i++) { t.equal(GF.log(GF.exp(i)), i, 'log and exp should be one the inverse of the other') t.equal(GF.exp(GF.log(i)), i, 'exp and log should be one the inverse of the other') } t.equal(GF.mul(0, 1), 0, 'Should return 0 if first param is 0') t.equal(GF.mul(1, 0), 0, 'Should return 0 if second param is 0') t.equal(GF.mul(0, 0), 0, 'Should return 0 if both params are 0') for (let j = 1; j < 255; j++) { t.equal(GF.mul(j, 255 - j), GF.mul(255 - j, j), 'Multiplication should be commutative') } t.end() })
soldair/node-qrcode
test/unit/core/galois-field.test.js
JavaScript
mit
746
import chalk = require("chalk"); import { take, select } from "redux-saga/effects"; import path = require("path"); import moment = require("moment"); import { titleize } from "inflection"; import { parallel } from "mesh"; import { weakMemo } from "../memo"; import AnsiUp from "ansi_up"; import { reader } from "../monad"; import { noop } from "lodash"; import { ImmutableObject, createImmutableObject } from "../immutable"; import { LogLevel, LogAction, LogActionTypes, Logger } from "./base"; // beat TS type checking chalk.enabled = true; function createLogColorizer(tester: RegExp, replaceValue: any) { return function(input: string) { if (!tester.test(input)) return input; return input.replace(tester, replaceValue); } } export type ConsoleLogState = { argv?: { color?: boolean, hlog?: boolean }, log?: { level: LogLevel, prefix?: string } } const cwd = process.cwd(); const highlighters = [ createLogColorizer(/^INF/, (match) => chalk.bgCyan(match)), createLogColorizer(/^ERR/, (match) => chalk.bgRed(match)), createLogColorizer(/^DBG/, (match) => chalk.grey.bgBlack(match)), createLogColorizer(/^WRN/, (match) => chalk.bgYellow(match)), // timestamp createLogColorizer(/\[\d+\.\d+\.\d+\]/, (match, inner) => `[${chalk.grey(inner)}]`), // URL createLogColorizer(/((\w{3,}\:\/\/)|([^\/\s\("':]+)?\/)([^\/\)\s"':]+\/?)+/g, (match) => { return chalk.yellow(/\w+:\/\//.test(match) ? match : match.replace(cwd + "/", "")) }), // duration createLogColorizer(/\s\d+(\.\d+)?(s|ms|m|h|d)(\s|$)/g, (match) => chalk.bold.cyan(match)), // numbers createLogColorizer(/\b\d+(\.\d+)?\b/g, (match, inner) => `${chalk.cyan(match)}`), // strings createLogColorizer(/"(.*?)"/g, (match, inner) => `"${chalk.blue(inner)}"`), // tokens createLogColorizer(/([\:\{\}",\(\)]|->|null|undefined|Infinity)/g, (match) => chalk.grey(match)), // <<output - green (from audio again) createLogColorizer(/<<(.*)/g, (match, word) => chalk.green(word)), // >>input - magenta (from audio) createLogColorizer(/>>(.*)/g, (match, word) => chalk.magenta(word)), // **BIG EMPHASIS** createLogColorizer(/\*\*(.*?)\*\*/, (match, word) => chalk.bgBlue(word)), // *emphasis* createLogColorizer(/\*(.*?)\*/g, (match, word) => chalk.bold(word)), // ___underline___ createLogColorizer(/___(.*?)___/g, (match, word) => chalk.underline(word)), // ~de emphasis~ createLogColorizer(/~(.*?)~/g, (match, word) => chalk.grey(word)), ]; function colorize(input: string) { let output = input; for (let i = 0, n = highlighters.length; i < n; i++) output = highlighters[i](output); return output; } function styledConsoleLog(...args: any[]) { var argArray = []; if (args.length) { var startTagRe = /<span\s+style=(['"])([^'"]*)\1\s*>/gi; var endTagRe = /<\/span>/gi; var reResultArray; argArray.push(arguments[0].replace(startTagRe, '%c').replace(endTagRe, '%c')); while (reResultArray = startTagRe.exec(arguments[0])) { argArray.push(reResultArray[2]); argArray.push(''); } // pass through subsequent args since chrome dev tools does not (yet) support console.log styling of the following form: console.log('%cBlue!', 'color: blue;', '%cRed!', 'color: red;'); for (var j = 1; j < arguments.length; j++) { argArray.push(arguments[j]); } } console.log.apply(console, argArray); } // I'm against abbreviations, but it's happening here // since all of these are the same length -- saves space in stdout, and makes // logs easier to read. const PREFIXES = { [LogLevel.DEBUG]: "DBG ", [LogLevel.INFO]: "INF ", [LogLevel.WARNING]: "WRN ", [LogLevel.ERROR]: "ERR ", }; const defaultState = { level: LogLevel.ALL, prefix: "" }; export function* consoleLogSaga() { while(true) { const { log: { level: acceptedLevel, prefix }}: ConsoleLogState = (yield select()) || defaultState; let { text, level }: LogAction = (yield take(LogActionTypes.LOG)); if (!(acceptedLevel & level)) continue; const log = { [LogLevel.DEBUG]: console.log.bind(console), [LogLevel.LOG]: console.log.bind(console), [LogLevel.INFO]: console.info.bind(console), [LogLevel.WARNING]: console.warn.bind(console), [LogLevel.ERROR]: console.error.bind(console) }[level]; text = PREFIXES[level] + (prefix || "") + text; text = colorize(text); if (typeof window !== "undefined" && !window["$synthetic"]) { return styledConsoleLog(new AnsiUp().ansi_to_html(text)); } log(text); } }
crcn/aerial
packages/aerial-common2/src/log/console.ts
TypeScript
mit
4,631
<?php namespace Payname\Security; use Payname\Exception\ApiCryptoException; /** * Class Crypto * Extract from https://github.com/illuminate/encryption */ class Crypto { /** * The algorithm used for encryption. * * @var string */ private static $cipher = 'AES-128-CBC'; /** * Encrypt the given value. * * @param string $value * @param string $key * @return string */ public static function encrypt($value, $key) { $iv = openssl_random_pseudo_bytes(self::getIvSize()); $value = openssl_encrypt(serialize($value), self::$cipher, $key, 0, $iv); if ($value === false) { throw new ApiCryptoException('Could not encrypt the data.'); } $mac = self::hash($iv = base64_encode($iv), $value, $key); return base64_encode(json_encode(compact('iv', 'value', 'mac'))); } /** * Decrypt the given value. * * @param string $payload * @param string $key * @return string */ public static function decrypt($value, $key) { $payload = self::getJsonPayload($value, $key); $iv = base64_decode($payload['iv']); $decrypted = openssl_decrypt($payload['value'], self::$cipher, $key, 0, $iv); if ($decrypted === false) { throw new ApiCryptoException('Could not decrypt the data.'); } return unserialize($decrypted); } /** * Get the JSON array from the given payload. * * @param string $payload * @param string $key * @return array */ private static function getJsonPayload($payload, $key) { $payload = json_decode(base64_decode($payload), true); if (!$payload || (!is_array($payload) || !isset($payload['iv']) || !isset($payload['value']) || !isset($payload['mac']))) { throw new ApiCryptoException('The payload is invalid.'); } if (!self::validMac($payload, $key)) { throw new ApiCryptoException('The MAC is invalid.'); } return $payload; } /** * Determine if the MAC for the given payload is valid. * * @param array $payload * @param string $key * @return bool */ private static function validMac(array $payload, $key) { $bytes = null; if (function_exists('random_bytes')) { $bytes = random_bytes(16); } elseif (function_exists('openssl_random_pseudo_bytes')) { $bytes = openssl_random_pseudo_bytes(16, $strong); if ($bytes === false || $strong === false) { throw new ApiCryptoException('Unable to generate random string.'); } } else { throw new ApiCryptoException('OpenSSL extension is required for PHP 5 users.'); } $calcMac = hash_hmac('sha256', self::hash($payload['iv'], $payload['value'], $key), $bytes, true); return hash_hmac('sha256', $payload['mac'], $bytes, true) === $calcMac; } /** * Create a MAC for the given value. * * @param string $iv * @param string $value * @return string */ private static function hash($iv, $value, $key) { return hash_hmac('sha256', $iv.$value, $key); } /** * Get the IV size for the cipher. * * @return int */ private static function getIvSize() { return 16; } }
tplessis/Payname-php-sdk
src/Payname/Security/Crypto.php
PHP
mit
3,450
# Wildcard string matcher ## Requirements - PHP 5.4 or greater (recommended). ## Installation 1. [Download all libraries](https://github.com/pedzed/libs/archive/master.zip) or [specifically download this one](https://raw.githubusercontent.com/pedzed/libs/master/src/pedzed/libs/WildcardStringMatcher.php). 2. Move the file(s) to your server. 3. Include the file(s). *It's recommended to autoload them.* ## Examples ```php $strList = [ '*', '*.ipsum', 'lorem.ipsum.dolor', 'lorem.ipsum.sit.amet', 'lorem.*.amet', 'lorem.*' ]; $match = 'lorem.ipsum.sit.amet'; echo $match.'<br /><br />'; foreach($strList as $str){ echo 'String: '.$str.':<br />'; var_dump(WildcardStringMatcher::match($str, $match)); } /* OUTPUT: lorem.ipsum.sit.amet String: *: boolean true String: *.ipsum: boolean false String: lorem.ipsum.dolor: boolean false String: lorem.ipsum.sit.amet: boolean true String: lorem.*.amet: boolean true String: lorem.*: boolean true */ ``` Case-sensitivity is supported. On default, it is disabled. To enable case-sensitivity, pass a third parameter. ```php WildcardStringMatcher::match($str1, $str2, true); ```
pedzed/libs
docs/wildcard-string-matcher.md
Markdown
mit
1,166
--- layout: page title: Island Networks Seminar date: 2016-05-24 author: Sharon Gamble tags: weekly links, java status: published summary: Duis posuere erat eu orci faucibus, ac. banner: images/banner/leisure-05.jpg booking: startDate: 05/27/2017 endDate: 05/29/2017 ctyhocn: OKCBTHX groupCode: INS published: true --- Ut at tempus purus. Suspendisse potenti. Pellentesque pulvinar metus ac urna tincidunt condimentum. In hac habitasse platea dictumst. Vestibulum sollicitudin justo id metus dapibus blandit. Vestibulum sed ipsum interdum odio ultricies tristique vitae quis urna. Quisque consequat massa sit amet nunc tempus viverra. Proin lacinia condimentum interdum. Aenean ut dui dui. Phasellus ut lorem non sem viverra pellentesque et id nunc. Pellentesque fringilla eros sed erat luctus, in volutpat quam finibus. Pellentesque luctus sit amet enim vel fermentum. Aenean mollis elit libero, at porttitor turpis posuere in. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam ac ante et purus convallis feugiat. Vestibulum ornare porta aliquet. Aliquam erat volutpat. Proin ac lectus id lectus pharetra facilisis. Mauris sagittis sit amet turpis eget mattis. Donec bibendum eget mauris quis pulvinar. Sed tincidunt leo in nibh iaculis tempor. Sed sit amet laoreet mauris, et sollicitudin leo. Praesent sed auctor leo, eget dictum elit. * Cras sit amet arcu in erat vulputate iaculis ac in enim * Praesent et neque volutpat, sollicitudin erat nec, ullamcorper urna * Phasellus posuere nisi sed est venenatis placerat * Nam eleifend velit eget tristique faucibus. Donec sit amet leo a tortor fermentum lobortis nec in sapien. Quisque porta enim lorem, eu eleifend elit condimentum non. Phasellus vitae pretium velit. Suspendisse accumsan nunc vitae varius auctor. Suspendisse et sem nulla. Etiam cursus, quam eu dictum vestibulum, diam nulla malesuada mauris, et euismod erat sapien non sapien. Fusce egestas mi id volutpat laoreet. Praesent egestas, eros mollis tincidunt euismod, lorem augue feugiat ligula, ut venenatis ex purus id eros. Pellentesque vitae mauris vestibulum, auctor mauris nec, laoreet nunc. Mauris varius, tortor id eleifend fringilla, tellus tortor volutpat nibh, in elementum neque mi at ex. Phasellus ornare dui sed enim imperdiet, in porta quam interdum. Morbi a ornare velit. Quisque mollis vitae libero et rutrum. In bibendum faucibus metus at volutpat. Sed pretium ex et libero finibus, at pharetra lorem finibus. Duis venenatis laoreet sapien sit amet pharetra. Maecenas varius varius ipsum, sit amet porttitor justo consequat non. Pellentesque viverra fringilla tincidunt. Nulla turpis libero, venenatis vel magna at, finibus gravida eros. Quisque mollis mollis ante, in convallis metus consequat imperdiet. Pellentesque quis nisl at massa commodo vestibulum quis eu metus. Donec sollicitudin sed tortor et egestas.
KlishGroup/prose-pogs
pogs/O/OKCBTHX/INS/index.md
Markdown
mit
2,909
'use strict'; // Test dependencies are required and exposed in common/bootstrap.js require('../../common/bootstrap'); process.on('uncaughtException', function(err) { console.error(err.stack); }); var codeContents = 'console.log("testing deploy");'; var reference = new Buffer(codeContents); var lists = deployment.js.lists; var listRuleLength = lists.includes.length + lists.ignores.length + lists.blacklist.length; var sandbox = sinon.sandbox.create(); var FIXTURE_PATH = path.join(__dirname, '/../../../test/unit/fixtures'); exports['Deployment: JavaScript'] = { setUp(done) { this.deploy = sandbox.spy(Tessel.prototype, 'deploy'); this.appStop = sandbox.spy(commands.app, 'stop'); this.appStart = sandbox.spy(commands.app, 'start'); this.deleteFolder = sandbox.spy(commands, 'deleteFolder'); this.createFolder = sandbox.spy(commands, 'createFolder'); this.untarStdin = sandbox.spy(commands, 'untarStdin'); this.execute = sandbox.spy(commands.js, 'execute'); this.openStdinToFile = sandbox.spy(commands, 'openStdinToFile'); this.chmod = sandbox.spy(commands, 'chmod'); this.push = sandbox.spy(deploy, 'push'); this.createShellScript = sandbox.spy(deploy, 'createShellScript'); this.injectBinaryModules = sandbox.stub(deployment.js, 'injectBinaryModules').callsFake(() => Promise.resolve()); this.resolveBinaryModules = sandbox.stub(deployment.js, 'resolveBinaryModules').callsFake(() => Promise.resolve()); this.tarBundle = sandbox.stub(deployment.js, 'tarBundle').callsFake(() => Promise.resolve(reference)); this.warn = sandbox.stub(log, 'warn'); this.info = sandbox.stub(log, 'info'); this.tessel = TesselSimulator(); this.end = sandbox.spy(this.tessel._rps.stdin, 'end'); this.fetchCurrentBuildInfo = sandbox.stub(this.tessel, 'fetchCurrentBuildInfo').returns(Promise.resolve('40b2b46a62a34b5a26170c75f7e717cea673d1eb')); this.fetchNodeProcessVersions = sandbox.stub(this.tessel, 'fetchNodeProcessVersions').returns(Promise.resolve(processVersions)); this.requestBuildList = sandbox.stub(updates, 'requestBuildList').returns(Promise.resolve(tesselBuilds)); this.pWrite = sandbox.stub(Preferences, 'write').returns(Promise.resolve()); this.exists = sandbox.stub(fs, 'exists').callsFake((fpath, callback) => callback(true)); this.spinnerStart = sandbox.stub(log.spinner, 'start'); this.spinnerStop = sandbox.stub(log.spinner, 'stop'); deleteTemporaryDeployCode() .then(done); }, tearDown(done) { this.tessel.mockClose(); sandbox.restore(); deleteTemporaryDeployCode() .then(done) .catch(function(err) { throw err; }); }, bundling(test) { test.expect(1); this.tarBundle.restore(); createTemporaryDeployCode().then(() => { var tb = deployment.js.tarBundle({ target: DEPLOY_DIR_JS }); tb.then(bundle => { /* $ t2 run app.js INFO Looking for your Tessel... INFO Connected to arnold over LAN INFO Writing app.js to RAM on arnold (2.048 kB)... INFO Deployed. INFO Running app.js... testing deploy INFO Stopping script... */ test.equal(bundle.length, 2048); test.done(); }) .catch(error => { test.ok(false, error.toString()); test.done(); }); }); }, createShellScriptDefaultEntryPoint(test) { test.expect(1); var shellScript = `#!/bin/sh exec node --harmony /app/remote-script/index.js --key=value`; var opts = { lang: deployment.js, resolvedEntryPoint: 'index.js', binopts: ['--harmony'], subargs: ['--key=value'], }; this.end.restore(); this.end = sandbox.stub(this.tessel._rps.stdin, 'end').callsFake((buffer) => { test.equal(buffer.toString(), shellScript); test.done(); }); this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => { return callback(null, this.tessel._rps); }); deploy.createShellScript(this.tessel, opts); }, createShellScriptDefaultEntryPointNoSubargs(test) { test.expect(1); var shellScript = `#!/bin/sh exec node --harmony /app/remote-script/index.js`; var opts = { lang: deployment.js, resolvedEntryPoint: 'index.js', binopts: ['--harmony'], subargs: [], }; this.end.restore(); this.end = sandbox.stub(this.tessel._rps.stdin, 'end').callsFake((buffer) => { test.equal(buffer.toString(), shellScript); test.done(); }); this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => { return callback(null, this.tessel._rps); }); deploy.createShellScript(this.tessel, opts); }, createShellScriptDefaultEntryPointNoExtraargs(test) { test.expect(1); var shellScript = `#!/bin/sh exec node /app/remote-script/index.js`; var opts = { lang: deployment.js, resolvedEntryPoint: 'index.js', binopts: [], subargs: [], }; this.end.restore(); this.end = sandbox.stub(this.tessel._rps.stdin, 'end').callsFake((buffer) => { test.equal(buffer.toString(), shellScript); test.done(); }); this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => { return callback(null, this.tessel._rps); }); deploy.createShellScript(this.tessel, opts); }, createShellScriptSendsCorrectEntryPoint(test) { test.expect(1); var shellScript = `#!/bin/sh exec node /app/remote-script/index.js --key=value`; var opts = { lang: deployment.js, resolvedEntryPoint: 'index.js', binopts: [], subargs: ['--key=value'], }; this.end.restore(); this.end = sandbox.stub(this.tessel._rps.stdin, 'end').callsFake((buffer) => { test.equal(buffer.toString(), shellScript); test.done(); }); this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => { return callback(null, this.tessel._rps); }); deploy.createShellScript(this.tessel, opts); }, processCompletionOrder(test) { // Array of processes we've started but haven't completed yet var processesAwaitingCompletion = []; this.tessel._rps.on('control', (data) => { // Push new commands into the queue processesAwaitingCompletion.push(data); }); // Create the temporary folder with example code createTemporaryDeployCode() .then(() => { var closeAdvance = (event) => { // If we get an event listener for the close event of a process if (event === 'close') { // Wait some time before actually closing it setTimeout(() => { // We should only have one process waiting for completion test.equal(processesAwaitingCompletion.length, 1); // Pop that process off processesAwaitingCompletion.shift(); // Emit the close event to keep it going this.tessel._rps.emit('close'); }, 200); } }; // When we get a listener that the Tessel process needs to close before advancing this.tessel._rps.on('newListener', closeAdvance); // Actually deploy the script this.tessel.deploy({ entryPoint: path.relative(process.cwd(), DEPLOY_FILE_JS), compress: true, push: false, single: false }) // If it finishes, it was successful .then(() => { this.tessel._rps.removeListener('newListener', closeAdvance); test.done(); }) // If not, there was an issue .catch(function(err) { test.equal(err, undefined, 'We hit a catch statement that we should not have.'); }); }); } }; exports['deployment.js.compress with uglify.es.minify()'] = { setUp(done) { this.minify = sandbox.spy(uglify.es, 'minify'); this.spinnerStart = sandbox.stub(log.spinner, 'start'); this.spinnerStop = sandbox.stub(log.spinner, 'stop'); done(); }, tearDown(done) { sandbox.restore(); done(); }, minifySuccess(test) { test.expect(1); deployment.js.compress('es', 'let f = 1'); test.equal(this.minify.callCount, 1); test.done(); }, minifyFailureReturnsOriginalSource(test) { test.expect(2); const result = deployment.js.compress('es', '#$%^'); // Assert that we tried to minify test.equal(this.minify.callCount, 1); // Assert that compress just gave back // the source as-is, even though the // parser failed. test.equal(result, '#$%^'); test.done(); }, ourOptionsParse(test) { test.expect(2); const ourExplicitSettings = { toplevel: true, warnings: false, }; const ourExplicitSettingsKeys = Object.keys(ourExplicitSettings); try { // Force the acorn parse step of the // compress operation to fail. This // will ensure that that the uglify // attempt is made. deployment.js.compress('es', '#$%^'); } catch (error) { // there is nothing we can about this. } const optionsSeen = this.minify.lastCall.args[1]; ourExplicitSettingsKeys.forEach(key => { test.equal(optionsSeen[key], ourExplicitSettings[key]); }); test.done(); }, noOptionsCompress(test) { test.expect(23); const optionsCompress = { // ------ booleans: true, cascade: true, conditionals: true, comparisons: true, ecma: 6, evaluate: true, hoist_funs: true, hoist_vars: true, if_return: true, join_vars: true, loops: true, passes: 3, properties: true, sequences: true, unsafe: true, // ------ dead_code: true, unsafe_math: true, keep_infinity: true, // ------ arrows: false, keep_fargs: false, keep_fnames: false, warnings: false, drop_console: false, }; const optionsCompressKeys = Object.keys(optionsCompress); deployment.js.compress('es', 'var a = 1;', {}); const optionsSeen = this.minify.lastCall.args[1].compress; optionsCompressKeys.forEach(key => { test.equal(optionsSeen[key], optionsCompress[key]); }); test.done(); }, ourOptionsCompress(test) { test.expect(23); const ourExplicitSettings = { // ------ booleans: true, cascade: true, conditionals: true, comparisons: true, ecma: 6, evaluate: true, hoist_funs: true, hoist_vars: true, if_return: true, join_vars: true, loops: true, passes: 3, properties: true, sequences: true, unsafe: true, // ------ dead_code: true, unsafe_math: true, keep_infinity: true, // ------ arrows: false, keep_fargs: false, keep_fnames: false, warnings: false, drop_console: false, }; const ourExplicitSettingsKeys = Object.keys(ourExplicitSettings); deployment.js.compress('es', 'var a = 1;'); const optionsSeen = this.minify.lastCall.args[1].compress; ourExplicitSettingsKeys.forEach(key => { test.equal(optionsSeen[key], ourExplicitSettings[key]); }); test.done(); }, theirOptionsCompress(test) { test.expect(20); var theirExplicitSettings = { // ------ booleans: false, cascade: false, conditionals: false, comparisons: false, evaluate: false, hoist_funs: false, hoist_vars: false, if_return: false, join_vars: false, loops: false, properties: false, sequences: false, unsafe: false, // ------ dead_code: false, unsafe_math: false, keep_infinity: false, // ------ keep_fargs: true, keep_fnames: true, warnings: true, drop_console: true, }; var theirExplicitSettingsKeys = Object.keys(theirExplicitSettings); deployment.js.compress('es', 'var a = 1;', { compress: theirExplicitSettings }); const optionsSeen = this.minify.lastCall.args[1].compress; theirExplicitSettingsKeys.forEach(key => { test.equal(optionsSeen[key], theirExplicitSettings[key]); }); test.done(); }, minifyFromBuffer(test) { test.expect(1); test.equal(deployment.js.compress('es', new Buffer(codeContents)), codeContents); test.done(); }, minifyFromString(test) { test.expect(1); test.equal(deployment.js.compress('es', codeContents), codeContents); test.done(); }, minifyWithBareReturns(test) { test.expect(1); deployment.js.compress('es', 'return;'); test.equal(this.minify.lastCall.args[1].parse.bare_returns, true); test.done(); }, avoidCompleteFailure(test) { test.expect(1); this.minify.restore(); this.minify = sandbox.stub(uglify.js, 'minify').callsFake(() => { return { error: new SyntaxError('whatever') }; }); test.equal(deployment.js.compress('es', 'return;'), 'return;'); test.done(); }, }; exports['deployment.js.compress with uglify.js.minify()'] = { setUp(done) { this.minify = sandbox.spy(uglify.js, 'minify'); this.spinnerStart = sandbox.stub(log.spinner, 'start'); this.spinnerStop = sandbox.stub(log.spinner, 'stop'); done(); }, tearDown(done) { sandbox.restore(); done(); }, minifySuccess(test) { test.expect(1); deployment.js.compress('js', 'let f = 1'); test.equal(this.minify.callCount, 1); test.done(); }, minifyFailureReturnsOriginalSource(test) { test.expect(2); const result = deployment.js.compress('js', '#$%^'); // Assert that we tried to minify test.equal(this.minify.callCount, 1); // Assert that compress just gave back // the source as-is, even though the // parser failed. test.equal(result, '#$%^'); test.done(); }, ourOptionsParse(test) { test.expect(2); const ourExplicitSettings = { toplevel: true, warnings: false, }; const ourExplicitSettingsKeys = Object.keys(ourExplicitSettings); try { // Force the acorn parse step of the // compress operation to fail. This // will ensure that that the uglify // attempt is made. deployment.js.compress('js', '#$%^'); } catch (error) { // there is nothing we can about this. } const optionsSeen = this.minify.lastCall.args[1]; ourExplicitSettingsKeys.forEach(key => { test.equal(optionsSeen[key], ourExplicitSettings[key]); }); test.done(); }, noOptionsCompress(test) { test.expect(15); const optionsCompress = { // ------ booleans: true, cascade: true, conditionals: true, comparisons: true, hoist_funs: true, if_return: true, join_vars: true, loops: true, passes: 2, properties: true, sequences: true, // ------ explicitly false keep_fargs: false, keep_fnames: false, warnings: false, drop_console: false, }; const optionsCompressKeys = Object.keys(optionsCompress); deployment.js.compress('js', 'var a = 1;', {}); const optionsSeen = this.minify.lastCall.args[1].compress; optionsCompressKeys.forEach(key => { test.equal(optionsSeen[key], optionsCompress[key]); }); test.done(); }, ourOptionsCompress(test) { test.expect(15); const ourExplicitSettings = { // ------ booleans: true, cascade: true, conditionals: true, comparisons: true, hoist_funs: true, if_return: true, join_vars: true, loops: true, passes: 2, properties: true, sequences: true, // ------ explicitly false keep_fargs: false, keep_fnames: false, warnings: false, drop_console: false, }; const ourExplicitSettingsKeys = Object.keys(ourExplicitSettings); deployment.js.compress('js', 'var a = 1;'); const optionsSeen = this.minify.lastCall.args[1].compress; ourExplicitSettingsKeys.forEach(key => { test.equal(optionsSeen[key], ourExplicitSettings[key]); }); test.done(); }, theirOptionsCompress(test) { test.expect(15); var theirExplicitSettings = { // ------ booleans: true, cascade: true, conditionals: true, comparisons: true, hoist_funs: true, if_return: true, join_vars: true, loops: true, passes: 2, properties: true, sequences: true, // ------ explicitly false keep_fargs: false, keep_fnames: false, warnings: false, drop_console: false, }; var theirExplicitSettingsKeys = Object.keys(theirExplicitSettings); deployment.js.compress('js', 'var a = 1;', { compress: theirExplicitSettings }); const optionsSeen = this.minify.lastCall.args[1].compress; theirExplicitSettingsKeys.forEach(key => { test.equal(optionsSeen[key], theirExplicitSettings[key]); }); test.done(); }, minifyFromBuffer(test) { test.expect(1); test.equal(deployment.js.compress('js', new Buffer(codeContents)), codeContents); test.done(); }, minifyFromString(test) { test.expect(1); test.equal(deployment.js.compress('js', codeContents), codeContents); test.done(); }, minifyWithBareReturns(test) { test.expect(1); deployment.js.compress('js', 'return;'); test.equal(this.minify.lastCall.args[1].parse.bare_returns, true); test.done(); }, avoidCompleteFailure(test) { test.expect(1); this.minify.restore(); this.minify = sandbox.stub(uglify.js, 'minify').callsFake(() => { return { error: new SyntaxError('whatever') }; }); const result = deployment.js.compress('js', 'return;'); test.equal(result, 'return;'); test.done(); }, theReasonForUsingBothVersionsOfUglify(test) { test.expect(2); this.minify.restore(); this.es = sandbox.spy(uglify.es, 'minify'); this.js = sandbox.spy(uglify.js, 'minify'); const code = tags.stripIndents ` var Class = function() {}; Class.prototype.method = function() {}; module.exports = Class; `; deployment.js.compress('es', code); deployment.js.compress('js', code); test.equal(this.es.callCount, 1); test.equal(this.js.callCount, 1); test.done(); }, }; exports['deployment.js.tarBundle'] = { setUp(done) { this.copySync = sandbox.spy(fs, 'copySync'); this.outputFileSync = sandbox.spy(fs, 'outputFileSync'); this.writeFileSync = sandbox.spy(fs, 'writeFileSync'); this.remove = sandbox.spy(fs, 'remove'); this.readdirSync = sandbox.spy(fs, 'readdirSync'); this.globSync = sandbox.spy(glob, 'sync'); this.collect = sandbox.spy(Project.prototype, 'collect'); this.exclude = sandbox.spy(Project.prototype, 'exclude'); this.mkdirSync = sandbox.spy(fsTemp, 'mkdirSync'); this.addIgnoreRules = sandbox.spy(Ignore.prototype, 'addIgnoreRules'); this.project = sandbox.spy(deployment.js, 'project'); this.compress = sandbox.spy(deployment.js, 'compress'); this.warn = sandbox.stub(log, 'warn'); this.info = sandbox.stub(log, 'info'); this.spinnerStart = sandbox.stub(log.spinner, 'start'); this.spinnerStop = sandbox.stub(log.spinner, 'stop'); done(); }, tearDown(done) { sandbox.restore(); done(); }, actionsGlobRules(test) { test.expect(1); const target = 'test/unit/fixtures/ignore'; const rules = glob.rules(target, '.tesselignore'); test.deepEqual( rules.map(path.normalize), [ // Found in "test/unit/fixtures/ignore/.tesselignore" 'a/**/*.*', 'mock-foo.js', // Found in "test/unit/fixtures/ignore/nested/.tesselignore" 'nested/b/**/*.*', 'nested/file.js' ].map(path.normalize) ); test.done(); }, actionsGlobFiles(test) { test.expect(1); const target = 'test/unit/fixtures/ignore'; const rules = glob.rules(target, '.tesselignore'); const files = glob.files(target, rules); test.deepEqual(files, ['mock-foo.js']); test.done(); }, actionsGlobFilesNested(test) { test.expect(1); const target = 'test/unit/fixtures/ignore'; const files = glob.files(target, ['**/.tesselignore']); test.deepEqual(files, [ '.tesselignore', 'nested/.tesselignore' ]); test.done(); }, actionsGlobFilesNonNested(test) { test.expect(1); const target = 'test/unit/fixtures/ignore'; const files = glob.files(target, ['.tesselignore']); test.deepEqual(files, ['.tesselignore']); test.done(); }, noOptionsTargetFallbackToCWD(test) { test.expect(2); const target = path.normalize('test/unit/fixtures/project'); sandbox.stub(process, 'cwd').returns(target); sandbox.spy(path, 'relative'); /* project ├── .tesselignore ├── index.js ├── mock-foo.js ├── nested │   └── another.js ├── node_modules │   └── foo │   ├── .tesselignore │   ├── index.js │   └── package.json ├── other.js └── package.json 3 directories, 9 files */ deployment.js.tarBundle({ compress: true, full: true, }).then(() => { test.equal(path.relative.firstCall.args[0], path.normalize('test/unit/fixtures/project')); test.equal(path.relative.firstCall.args[1], path.normalize('test/unit/fixtures/project')); test.done(); }); }, full(test) { test.expect(8); const target = 'test/unit/fixtures/project'; /* project ├── .tesselignore ├── index.js ├── mock-foo.js ├── nested │   └── another.js ├── node_modules │   └── foo │   ├── .tesselignore │   ├── index.js │   └── package.json ├── other.js └── package.json 3 directories, 9 files */ deployment.js.tarBundle({ target: path.normalize(target), compress: true, full: true, }).then(bundle => { // One call for .tesselinclude // One call for the single rule found within // Three calls for the deploy lists // * 2 (We need all ignore rules ahead of time for ignoring binaries) test.equal(this.globSync.callCount, 5 + listRuleLength); // addIgnoreRules might be called many times, but we only // care about tracking the call that's explicitly made by // tessel's deploy operation test.deepEqual(this.addIgnoreRules.getCall(0).args[0], [ '**/.tesselignore', '**/.tesselinclude', ]); // These things don't happen in the --full path test.equal(this.project.callCount, 0); test.equal(this.exclude.callCount, 0); test.equal(this.compress.callCount, 0); test.equal(this.writeFileSync.callCount, 0); test.equal(this.remove.callCount, 0); // End // Extract and inspect the bundle... extract(bundle, (error, entries) => { if (error) { test.ok(false, error.toString()); test.done(); } test.deepEqual(entries, [ 'index.js', 'nested/another.js', 'node_modules/foo/index.js', 'package.json', ]); test.done(); }); }); }, fullHitsErrorFromFstreamIgnore(test) { test.expect(1); // Need to stub function in _actual_ fs (but we use fs-extra) const fs = require('fs'); sandbox.stub(fs, 'readFile').callsFake((file, callback) => { callback('foo'); }); const target = 'test/unit/fixtures/project'; deployment.js.tarBundle({ target: path.normalize(target), compress: true, full: true, }) .then(() => { test.ok(false, 'tarBundle should not resolve'); test.done(); }) .catch(error => { test.equal(error.toString(), 'foo'); test.done(); }); }, slim(test) { test.expect(9); const entryPoint = 'index.js'; const target = 'test/unit/fixtures/project'; /* project ├── .tesselignore ├── index.js ├── mock-foo.js ├── nested │   └── another.js ├── node_modules │   └── foo │   ├── .tesselignore │   ├── index.js │   └── package.json ├── other.js └── package.json 3 directories, 9 files */ deployment.js.tarBundle({ target: path.normalize(target), resolvedEntryPoint: entryPoint, compress: true, slim: true, }).then(bundle => { // These things happen in the --slim path test.equal(this.project.callCount, 1); test.equal(this.compress.callCount, 2); test.equal(this.mkdirSync.callCount, 1); test.equal(this.outputFileSync.callCount, 3); // End /* $ find . -type f -name .tesselignore -exec cat {} \+ mock-foo.js other.js package.json */ test.equal(this.exclude.callCount, 1); test.deepEqual(this.exclude.lastCall.args[0], [ 'mock-foo.js', 'test/unit/fixtures/project/mock-foo.js', 'other.js', 'test/unit/fixtures/project/other.js', 'node_modules/foo/package.json', 'test/unit/fixtures/project/node_modules/foo/package.json' ].map(path.normalize)); const minified = this.compress.lastCall.returnValue; test.equal(this.compress.callCount, 2); test.equal(minified.indexOf('!!mock-foo!!') === -1, true); // Extract and inspect the bundle... extract(bundle, (error, entries) => { if (error) { test.ok(false, error.toString()); test.done(); } test.deepEqual(entries, [ 'index.js', 'node_modules/foo/index.js', 'package.json' ]); test.done(); }); }); }, slimHitsErrorFromFstreamReader(test) { test.expect(1); const pipe = fstream.Reader.prototype.pipe; // Need to stub function in _actual_ fs (but we use fs-extra) this.readerPipe = sandbox.stub(fstream.Reader.prototype, 'pipe').callsFake(function() { this.emit('error', new Error('foo')); return pipe.apply(this, arguments); }); const entryPoint = 'index.js'; const target = 'test/unit/fixtures/project'; deployment.js.tarBundle({ target: path.normalize(target), resolvedEntryPoint: entryPoint, compress: true, slim: true, }) .then(() => { test.ok(false, 'tarBundle should not resolve'); test.done(); }) .catch(error => { test.equal(error.toString(), 'Error: foo'); test.done(); }); }, slimHitsErrorInfsRemove(test) { test.expect(1); this.remove.restore(); this.remove = sandbox.stub(fs, 'remove').callsFake((temp, handler) => { handler(new Error('foo')); }); const entryPoint = 'index.js'; const target = 'test/unit/fixtures/project'; deployment.js.tarBundle({ target: path.normalize(target), resolvedEntryPoint: entryPoint, compress: true, slim: true, }) .then(() => { this.remove.reset(); test.ok(false, 'tarBundle should not resolve'); test.done(); }) .catch(error => { test.equal(error.toString(), 'Error: foo'); test.done(); }); }, slimHitsErrorFromCompress(test) { test.expect(1); this.compress.restore(); this.compress = sandbox.stub(deployment.js, 'compress').callsFake(() => { throw new Error('foo'); }); const entryPoint = 'index.js'; const target = 'test/unit/fixtures/project'; deployment.js.tarBundle({ target: path.normalize(target), resolvedEntryPoint: entryPoint, compress: true, slim: true, }) .then(() => { test.ok(false, 'tarBundle should not resolve'); test.done(); }) .catch(error => { test.equal(error.toString(), 'Error: foo'); test.done(); }); }, slimHitsErrorFromProjectCollect(test) { test.expect(1); this.collect.restore(); this.collect = sandbox.stub(Project.prototype, 'collect').callsFake((handler) => { handler(new Error('foo')); }); const entryPoint = 'index.js'; const target = 'test/unit/fixtures/project'; deployment.js.tarBundle({ target: path.normalize(target), resolvedEntryPoint: entryPoint, compress: true, slim: true, }) .then(() => { test.ok(false, 'tarBundle should not resolve'); test.done(); }) .catch(error => { test.equal(error.toString(), 'Error: foo'); test.done(); }); }, slimHitsErrorFromProject(test) { test.expect(1); this.collect.restore(); this.collect = sandbox.stub(Project.prototype, 'collect').callsFake(function() { this.emit('error', new Error('foo')); }); const entryPoint = 'index.js'; const target = 'test/unit/fixtures/project'; deployment.js.tarBundle({ target: path.normalize(target), resolvedEntryPoint: entryPoint, compress: true, slim: true, }) .then(() => { test.ok(false, 'tarBundle should not resolve'); test.done(); }) .catch(error => { test.equal(error.toString(), 'Error: foo'); test.done(); }); }, compressionProducesNoErrors(test) { test.expect(1); const entryPoint = 'index.js'; const target = 'test/unit/fixtures/syntax-error'; deployment.js.tarBundle({ target: path.normalize(target), resolvedEntryPoint: entryPoint, compress: true, slim: true, }).then(bundle => { extract(bundle, (error, entries) => { if (error) { test.ok(false, error.toString()); test.done(); } test.deepEqual(entries, [ 'arrow.js', 'index.js', 'package.json', ]); test.done(); }); }).catch(() => { test.ok(false, 'Compression should not produce errors'); test.done(); }); }, compressionIsSkipped(test) { test.expect(2); const entryPoint = 'index.js'; const target = 'test/unit/fixtures/syntax-error'; deployment.js.tarBundle({ target: path.normalize(target), resolvedEntryPoint: entryPoint, compress: false, slim: true, }).then(bundle => { extract(bundle, (error, entries) => { if (error) { test.ok(false, error.toString()); test.done(); } // compression mechanism is never called when --compress=false test.equal(this.compress.callCount, 0); test.deepEqual(entries, [ 'arrow.js', 'index.js', 'package.json', ]); test.done(); }); }).catch(() => { test.ok(false, 'Compression should not produce errors'); test.done(); }); }, slimTesselInit(test) { test.expect(5); const entryPoint = 'index.js'; const target = 'test/unit/fixtures/init'; /* init ├── index.js └── package.json 0 directories, 2 files */ deployment.js.tarBundle({ target: path.normalize(target), resolvedEntryPoint: entryPoint, compress: true, slim: true, }).then(bundle => { test.equal(this.project.callCount, 1); test.equal(this.compress.callCount, 1); test.equal(this.mkdirSync.callCount, 1); const minified = this.compress.lastCall.returnValue; test.equal(minified, 'const e=require("tessel"),{2:o,3:l}=e.led;o.on(),setInterval(()=>{o.toggle(),l.toggle()},100),console.log("I\'m blinking! (Press CTRL + C to stop)");'); // Extract and inspect the bundle... extract(bundle, (error, entries) => { if (error) { test.ok(false, error.toString()); test.done(); } test.deepEqual(entries, ['index.js', 'package.json']); test.done(); }); }); }, slimSingle(test) { test.expect(4); const target = 'test/unit/fixtures/project'; const entryPoint = 'index.js'; deployment.js.tarBundle({ target: path.normalize(target), entryPoint: entryPoint, compress: true, resolvedEntryPoint: entryPoint, single: true, slim: true, }).then(bundle => { test.equal(this.project.callCount, 1); test.equal(this.compress.callCount, 1); test.equal(bundle.length, 2048); extract(bundle, (error, entries) => { if (error) { test.ok(false, error.toString()); test.done(); } test.deepEqual(entries, ['index.js']); test.done(); }); }); }, slimSingleNested(test) { test.expect(4); const target = 'test/unit/fixtures/project'; const entryPoint = 'another.js'; deployment.js.tarBundle({ target: path.normalize(target), entryPoint: entryPoint, compress: true, resolvedEntryPoint: path.join('nested', entryPoint), single: true, slim: true, }).then(bundle => { test.equal(this.project.callCount, 1); test.equal(this.compress.callCount, 1); test.equal(bundle.length, 2560); extract(bundle, (error, entries) => { if (error) { test.ok(false, error.toString()); test.done(); } test.deepEqual(entries, ['nested/another.js']); test.done(); }); }); }, fullSingle(test) { test.expect(3); const target = 'test/unit/fixtures/project'; const entryPoint = 'index.js'; deployment.js.tarBundle({ target: path.normalize(target), entryPoint: entryPoint, compress: true, resolvedEntryPoint: entryPoint, single: true, full: true, }).then(bundle => { test.equal(this.addIgnoreRules.callCount, 3); test.equal(bundle.length, 2048); extract(bundle, (error, entries) => { if (error) { test.ok(false, error.toString()); test.done(); } test.deepEqual(entries, ['index.js']); test.done(); }); }); }, fullSingleNested(test) { test.expect(2); const target = 'test/unit/fixtures/project'; const entryPoint = 'another.js'; deployment.js.tarBundle({ target: path.normalize(target), entryPoint: entryPoint, compress: true, resolvedEntryPoint: path.join('nested', entryPoint), single: true, full: true, }).then(bundle => { test.equal(bundle.length, 2560); extract(bundle, (error, entries) => { if (error) { test.ok(false, error.toString()); test.done(); } test.deepEqual(entries, ['nested/another.js']); test.done(); }); }); }, slimIncludeOverridesIgnore(test) { test.expect(9); const entryPoint = 'index.js'; const target = 'test/unit/fixtures/project-include-overrides-ignore'; /* project-include-overrides-ignore ├── .tesselignore ├── .tesselinclude ├── index.js ├── mock-foo.js ├── nested │   └── another.js ├── node_modules │   └── foo │   ├── .tesselignore │   ├── .tesselinclude │   ├── index.js │   └── package.json ├── other.js └── package.json 3 directories, 11 files */ deployment.js.tarBundle({ target: path.normalize(target), resolvedEntryPoint: entryPoint, compress: true, slim: true, }).then(bundle => { test.equal(this.globSync.callCount, 8 + listRuleLength); /* All .tesselignore rules are negated by all .tesselinclude rules: $ find . -type f -name .tesselignore -exec cat {} \+ mock-foo.js other.js package.json $ find . -type f -name .tesselinclude -exec cat {} \+ mock-foo.js other.js package.json */ // 'other.js' doesn't appear in the source, but is explicitly included test.equal(this.copySync.callCount, 1); test.equal(this.copySync.lastCall.args[0].endsWith('other.js'), true); // Called, but without any arguments test.equal(this.exclude.callCount, 1); test.equal(this.exclude.lastCall.args[0].length, 0); test.equal(this.project.callCount, 1); // 3 js files are compressed test.equal(this.compress.callCount, 3); test.equal(this.remove.callCount, 1); // Extract and inspect the bundle... extract(bundle, (error, entries) => { if (error) { test.ok(false, error.toString()); test.done(); } // Since the .tesselignore rules are ALL negated by .tesselinclude rules, // the additional files are copied into the temporary bundle dir, and // then included in the tarred bundle. test.deepEqual(entries, [ 'index.js', 'mock-foo.js', 'node_modules/foo/index.js', 'node_modules/foo/package.json', 'other.js', 'package.json', ]); test.done(); }); }); }, fullIncludeOverridesIgnore(test) { test.expect(8); const target = 'test/unit/fixtures/project-include-overrides-ignore'; /* project-include-overrides-ignore ├── .tesselignore ├── .tesselinclude ├── index.js ├── mock-foo.js ├── nested │   └── another.js ├── node_modules │   └── foo │   ├── .tesselignore │   ├── .tesselinclude │   ├── index.js │   └── package.json ├── other.js └── package.json 3 directories, 11 files */ deployment.js.tarBundle({ target: path.normalize(target), compress: true, full: true, }).then(bundle => { test.equal(this.globSync.callCount, 8 + listRuleLength); // addIgnoreRules might be called many times, but we only // care about tracking the call that's explicitly made by // tessel's deploy operation test.deepEqual(this.addIgnoreRules.getCall(0).args[0], [ '**/.tesselignore', '**/.tesselinclude', ]); /* $ find . -type f -name .tesselignore -exec cat {} \+ mock-foo.js other.js package.json */ test.equal(this.exclude.callCount, 0); // These things don't happen in the --full path test.equal(this.project.callCount, 0); test.equal(this.compress.callCount, 0); test.equal(this.writeFileSync.callCount, 0); test.equal(this.remove.callCount, 0); // End // Extract and inspect the bundle... extract(bundle, (error, entries) => { if (error) { test.ok(false, error.toString()); test.done(); } // The .tesselignore rules are ALL overridden by .tesselinclude rules test.deepEqual(entries, [ 'index.js', 'mock-foo.js', 'nested/another.js', 'node_modules/foo/index.js', 'other.js', 'package.json' ]); test.done(); }); }); }, slimIncludeWithoutIgnore(test) { test.expect(9); const entryPoint = 'index.js'; const target = 'test/unit/fixtures/project-include-without-ignore'; /* project-include-without-ignore ├── .tesselinclude ├── index.js ├── mock-foo.js ├── nested │   └── another.js ├── node_modules │   └── foo │   ├── .tesselinclude │   ├── index.js │   └── package.json ├── other.js └── package.json 3 directories, 9 files */ deployment.js.tarBundle({ target: path.normalize(target), resolvedEntryPoint: entryPoint, compress: true, slim: true, }).then(bundle => { test.equal(this.globSync.callCount, 5 + listRuleLength); /* There are NO .tesselignore rules, but there are .tesselinclude rules: $ find . -type f -name .tesselignore -exec cat {} \+ (no results) $ find . -type f -name .tesselinclude -exec cat {} \+ mock-foo.js other.js package.json */ // Called, but without any arguments test.equal(this.exclude.callCount, 1); test.equal(this.exclude.lastCall.args[0].length, 0); // 'other.js' doesn't appear in the source, but is explicitly included test.equal(this.copySync.callCount, 1); test.equal(this.copySync.lastCall.args[0].endsWith('other.js'), true); test.equal(this.project.callCount, 1); test.equal(this.compress.callCount, 3); test.equal(this.remove.callCount, 1); // Extract and inspect the bundle... extract(bundle, (error, entries) => { if (error) { test.ok(false, error.toString()); test.done(); } // There are no .tesselignore rules, all .tesselinclude rules are // respected the additional files are copied into the temporary // bundle dir, and then included in the tarred bundle. test.deepEqual(entries, [ 'index.js', 'mock-foo.js', 'node_modules/foo/index.js', 'node_modules/foo/package.json', 'other.js', 'package.json' ]); test.done(); }); }); }, fullIncludeWithoutIgnore(test) { test.expect(8); /* !! TAKE NOTE!! This is actually the default behavior. That is to say: these files would be included, whether they are listed in the .tesselinclude file or not. */ const target = 'test/unit/fixtures/project-include-without-ignore'; /* project-include-without-ignore ├── .tesselinclude ├── index.js ├── mock-foo.js ├── nested │   └── another.js ├── node_modules │   └── foo │   ├── .tesselinclude │   ├── index.js │   └── package.json ├── other.js └── package.json 3 directories, 9 files */ deployment.js.tarBundle({ target: path.normalize(target), compress: true, full: true, }).then(bundle => { test.equal(this.globSync.callCount, 5 + listRuleLength); // addIgnoreRules might be called many times, but we only // care about tracking the call that's explicitly made by // tessel's deploy operation test.deepEqual(this.addIgnoreRules.getCall(0).args[0], [ '**/.tesselignore', '**/.tesselinclude', ]); /* There are NO .tesselignore rules, but there are .tesselinclude rules: $ find . -type f -name .tesselignore -exec cat {} \+ (no results) $ find . -type f -name .tesselinclude -exec cat {} \+ mock-foo.js other.js package.json */ test.equal(this.exclude.callCount, 0); // These things don't happen in the --full path test.equal(this.project.callCount, 0); test.equal(this.compress.callCount, 0); test.equal(this.writeFileSync.callCount, 0); test.equal(this.remove.callCount, 0); // End // Extract and inspect the bundle... extract(bundle, (error, entries) => { if (error) { test.ok(false, error.toString()); test.done(); } // There are no .tesselignore rules, all .tesselinclude rules are // respected the additional files are copied into the temporary // bundle dir, and then included in the tarred bundle. test.deepEqual(entries, [ 'index.js', 'mock-foo.js', 'nested/another.js', 'node_modules/foo/index.js', 'node_modules/foo/package.json', 'other.js', 'package.json' ]); test.done(); }); }); }, slimIncludeHasNegateRules(test) { test.expect(8); const entryPoint = 'index.js'; const target = 'test/unit/fixtures/project-include-has-negate-rules'; /* project-include-has-negate-rules . ├── .tesselinclude ├── index.js ├── mock-foo.js ├── nested │   └── another.js ├── node_modules │   └── foo │   ├── .tesselinclude │   ├── index.js │   └── package.json ├── other.js └── package.json 3 directories, 9 files */ deployment.js.tarBundle({ target: path.normalize(target), resolvedEntryPoint: entryPoint, compress: true, slim: true, }).then(bundle => { test.equal(this.globSync.callCount, 6 + listRuleLength); /* There are NO .tesselignore rules, but there are .tesselinclude rules: $ find . -type f -name .tesselignore -exec cat {} \+ (no results) $ find . -type f -name .tesselinclude -exec cat {} \+ !mock-foo.js other.js package.json The negated rule will be transferred. */ test.equal(this.exclude.callCount, 1); // Called once for the extra file matching // the .tesselinclude rules test.equal(this.copySync.callCount, 1); test.equal(this.project.callCount, 1); test.equal(this.compress.callCount, 2); // The 4 files discovered and listed in the dependency graph // See bundle extraction below. test.equal(this.outputFileSync.callCount, 4); test.equal(this.remove.callCount, 1); // Extract and inspect the bundle... extract(bundle, (error, entries) => { if (error) { test.ok(false, error.toString()); test.done(); } // There are no .tesselignore rules, but the .tesselinclude rules // include a negated pattern. The additional, non-negated files // are copied into the temporary bundle dir, and then included // in the tarred bundle. test.deepEqual(entries, [ 'index.js', // mock-foo.js MUST NOT BE PRESENT 'node_modules/foo/index.js', 'node_modules/foo/package.json', 'other.js', 'package.json', ]); test.done(); }); }); }, fullIncludeHasNegateRules(test) { test.expect(8); const target = 'test/unit/fixtures/project-include-has-negate-rules'; /* project-include-has-negate-rules . ├── .tesselinclude ├── index.js ├── mock-foo.js ├── nested │   └── another.js ├── node_modules │   └── foo │   ├── .tesselinclude │   ├── index.js │   └── package.json ├── other.js └── package.json 3 directories, 9 files */ deployment.js.tarBundle({ target: path.normalize(target), compress: true, full: true, }).then(bundle => { test.equal(this.globSync.callCount, 6 + listRuleLength); // addIgnoreRules might be called many times, but we only // care about tracking the call that's explicitly made by // tessel's deploy operation test.deepEqual(this.addIgnoreRules.getCall(0).args[0], [ '**/.tesselignore', '**/.tesselinclude', ]); // This is where the negated rule is transferred. test.deepEqual(this.addIgnoreRules.getCall(1).args[0], [ // Note that the "!" was stripped from the rule 'mock-foo.js', ]); /* There are NO .tesselignore rules, but there are .tesselinclude rules: $ find . -type f -name .tesselignore -exec cat {} \+ (no results) $ find . -type f -name .tesselinclude -exec cat {} \+ !mock-foo.js other.js package.json The negated rule will be transferred. */ // These things don't happen in the --full path test.equal(this.project.callCount, 0); test.equal(this.compress.callCount, 0); test.equal(this.writeFileSync.callCount, 0); test.equal(this.remove.callCount, 0); // End // Extract and inspect the bundle... extract(bundle, (error, entries) => { if (error) { test.ok(false, error.toString()); test.done(); } // There are no .tesselignore rules, all .tesselinclude rules are // respected the additional files are copied into the temporary // bundle dir, and then included in the tarred bundle. test.deepEqual(entries, [ 'index.js', // mock-foo.js is NOT present 'nested/another.js', 'node_modules/foo/index.js', 'node_modules/foo/package.json', 'other.js', 'package.json' ]); test.done(); }); }); }, slimSingleInclude(test) { test.expect(2); const entryPoint = 'index.js'; const target = 'test/unit/fixtures/project-include-without-ignore'; /* project-include-without-ignore ├── .tesselinclude ├── index.js ├── mock-foo.js ├── nested │   └── another.js ├── node_modules │   └── foo │   ├── .tesselinclude │   ├── index.js │   └── package.json ├── other.js └── package.json 3 directories, 9 files */ deployment.js.tarBundle({ target: path.normalize(target), resolvedEntryPoint: entryPoint, compress: true, slim: true, single: true, }).then(bundle => { test.equal(this.globSync.callCount, 5 + listRuleLength); /* There are .tesselinclude rules, but the single flag is present so they don't matter. The only file sent must be the file specified. */ // Extract and inspect the bundle... extract(bundle, (error, entries) => { if (error) { test.ok(false, error.toString()); test.done(); } // Only the explicitly specified `index.js` will // be included in the deployed code. test.deepEqual(entries, [ 'index.js', ]); test.done(); }); }); }, detectAssetsWithoutInclude(test) { test.expect(4); const entryPoint = 'index.js'; const target = 'test/unit/fixtures/project-assets-without-include'; /* project-assets-without-include ├── index.js ├── mock-foo.js ├── nested │   └── another.js ├── node_modules │   └── foo │   ├── index.js │   └── package.json ├── other.js └── package.json 3 directories, 7 files */ deployment.js.tarBundle({ target: path.normalize(target), resolvedEntryPoint: entryPoint, compress: true, slim: true, }).then(() => { test.equal(this.readdirSync.callCount, 1); test.equal(this.readdirSync.lastCall.args[0], path.normalize(target)); test.equal(this.warn.callCount, 1); test.equal(this.warn.firstCall.args[0], 'Some assets in this project were not deployed (see: t2 run --help)'); test.done(); }); }, detectAssetsWithoutIncludeEliminatedByDepGraph(test) { test.expect(3); const entryPoint = 'index.js'; const target = 'test/unit/fixtures/project-assets-without-include-eliminated-by-dep-graph'; /* project-assets-without-include ├── index.js ├── mock-foo.js ├── nested │   └── another.js ├── node_modules │   └── foo │   ├── index.js │   └── package.json └── package.json 3 directories, 6 files */ deployment.js.tarBundle({ target: path.normalize(target), resolvedEntryPoint: entryPoint, compress: true, slim: true, }).then(() => { test.equal(this.readdirSync.callCount, 1); test.equal(this.readdirSync.lastCall.args[0], path.normalize(target)); test.equal(this.warn.callCount, 0); // Ultimately, all assets were accounted for, even though // no tesselinclude existed. test.done(); }); }, alwaysExplicitlyProvideProjectDirname(test) { test.expect(1); const entryPoint = 'index.js'; const target = 'test/unit/fixtures/project'; deployment.js.tarBundle({ target: path.normalize(target), resolvedEntryPoint: entryPoint, compress: true, slim: true, }).then(() => { test.deepEqual(this.project.lastCall.args[0], { entry: path.join(target, entryPoint), dirname: path.normalize(target), }); test.done(); }); }, detectAndEliminateBlacklistedAssets(test) { test.expect(1); const entryPoint = 'index.js'; const target = 'test/unit/fixtures/project-ignore-blacklisted'; /* project-ignore-blacklisted ├── index.js ├── node_modules │   └── tessel │   ├── index.js │   └── package.json └── package.json 2 directories, 4 files */ deployment.js.tarBundle({ target: path.normalize(target), resolvedEntryPoint: entryPoint, compress: true, slim: true, }).then((bundle) => { // Extract and inspect the bundle... extract(bundle, (error, entries) => { if (error) { test.ok(false, error.toString()); test.done(); } test.deepEqual(entries, [ 'index.js', 'package.json' ]); test.done(); }); }); }, iteratesBinaryModulesUsed(test) { test.expect(5); const entryPoint = 'index.js'; const target = 'test/unit/fixtures/project'; const details = { modulePath: '' }; this.minimatch = sandbox.stub(deployment.js, 'minimatch').returns(true); this.rules = sandbox.stub(glob, 'rules').callsFake(() => { return [ 'a', 'b', ]; }); this.forEach = sandbox.stub(Map.prototype, 'forEach').callsFake((handler) => { handler(details); }); deployment.js.tarBundle({ target: path.normalize(target), resolvedEntryPoint: entryPoint, compress: true, slim: true, }) .then(() => { test.equal(this.forEach.callCount, 2); test.equal(this.minimatch.callCount, 3); test.deepEqual(this.minimatch.getCall(0).args, ['', 'a', { matchBase: true, dot: true }]); test.deepEqual(this.minimatch.getCall(1).args, ['', 'b', { matchBase: true, dot: true }]); test.deepEqual(this.minimatch.getCall(2).args, ['', 'node_modules/**/tessel/**/*', { matchBase: true, dot: true }]); test.done(); }); }, }; var fixtures = { project: path.join(FIXTURE_PATH, '/find-project'), explicit: path.join(FIXTURE_PATH, '/find-project-explicit-main') }; exports['deploy.findProject'] = { setUp(done) { done(); }, tearDown(done) { sandbox.restore(); done(); }, home(test) { test.expect(1); var fake = path.normalize('/fake/test/home/dir'); this.homedir = sandbox.stub(os, 'homedir').returns(fake); this.lstatSync = sandbox.stub(fs, 'lstatSync').callsFake((file) => { return { isDirectory: () => { // naive for testing. return file.slice(-1) === '/'; } }; }); this.realpathSync = sandbox.stub(fs, 'realpathSync').callsFake((arg) => { // Ensure that "~" was transformed test.equal(arg, path.normalize('/fake/test/home/dir/foo')); test.done(); return ''; }); deploy.findProject({ lang: deployment.js, entryPoint: '~/foo/', compress: true, }); }, byFile(test) { test.expect(1); var target = 'test/unit/fixtures/find-project/index.js'; deploy.findProject({ lang: deployment.js, entryPoint: target, compress: true, }).then(project => { test.deepEqual(project, { pushdir: fixtures.project, program: path.join(fixtures.project, 'index.js'), entryPoint: 'index.js' }); test.done(); }); }, byDirectory(test) { test.expect(1); var target = 'test/unit/fixtures/find-project/'; deploy.findProject({ lang: deployment.js, entryPoint: target }).then(project => { test.deepEqual(project, { pushdir: fixtures.project, program: path.join(fixtures.project, 'index.js'), entryPoint: 'index.js' }); test.done(); }); }, byDirectoryBWExplicitMain(test) { test.expect(1); var target = 'test/unit/fixtures/find-project-explicit-main/'; deploy.findProject({ lang: deployment.js, entryPoint: target }).then(project => { test.deepEqual(project, { pushdir: fixtures.explicit, program: path.join(fixtures.explicit, 'app.js'), entryPoint: 'app.js' }); test.done(); }); }, byDirectoryMissingIndex(test) { test.expect(1); var target = 'test/unit/fixtures/find-project-no-index/index.js'; deploy.findProject({ lang: deployment.js, entryPoint: target }).then(() => { test.ok(false, 'findProject should not find a valid project here'); test.done(); }).catch(error => { test.ok(error.includes('ENOENT')); test.done(); }); }, byFileInSubDirectory(test) { test.expect(1); var target = 'test/unit/fixtures/find-project/test/index.js'; deploy.findProject({ lang: deployment.js, entryPoint: target }).then(project => { test.deepEqual(project, { pushdir: fixtures.project, program: path.join(fixtures.project, 'test/index.js'), entryPoint: path.normalize('test/index.js') }); test.done(); }); }, noPackageJsonSingle(test) { test.expect(1); var pushdir = path.normalize('test/unit/fixtures/project-no-package.json/'); var entryPoint = path.normalize('test/unit/fixtures/project-no-package.json/index.js'); var opts = { entryPoint: entryPoint, single: true, slim: true, lang: deployment.js, }; deploy.findProject(opts).then(project => { // Without the `single` flag, this would've continued upward // until it found a directory with a package.json. test.equal(project.pushdir, fs.realpathSync(pushdir)); test.done(); }); }, noPackageJsonUseProgramDirname(test) { test.expect(1); // This is no package.json here var entryPoint = path.normalize('test/unit/fixtures/project-no-package.json/index.js'); var opts = { entryPoint: entryPoint, lang: deployment.js, single: false, }; this.endOfLookup = sandbox.stub(deploy, 'endOfLookup').returns(true); deploy.findProject(opts).then(project => { test.equal(project.pushdir, path.dirname(path.join(process.cwd(), entryPoint))); test.done(); }); }, }; exports['deploy.sendBundle, error handling'] = { setUp(done) { this.tessel = TesselSimulator(); this.fetchCurrentBuildInfo = sandbox.stub(this.tessel, 'fetchCurrentBuildInfo').returns(Promise.resolve('40b2b46a62a34b5a26170c75f7e717cea673d1eb')); this.fetchNodeProcessVersions = sandbox.stub(this.tessel, 'fetchNodeProcessVersions').returns(Promise.resolve(processVersions)); this.requestBuildList = sandbox.stub(updates, 'requestBuildList').returns(Promise.resolve(tesselBuilds)); this.pathResolve = sandbox.stub(path, 'resolve'); this.failure = 'FAIL'; done(); }, tearDown(done) { this.tessel.mockClose(); sandbox.restore(); done(); }, findProject(test) { test.expect(1); this.findProject = sandbox.stub(deploy, 'findProject').callsFake(() => Promise.reject(this.failure)); deploy.sendBundle(this.tessel, { lang: deployment.js }).catch(error => { test.equal(error, this.failure); test.done(); }); }, resolveBinaryModules(test) { test.expect(1); this.pathResolve.restore(); this.pathResolve = sandbox.stub(path, 'resolve').returns(''); this.exists = sandbox.stub(fs, 'exists').callsFake((fpath, callback) => callback(true)); this.findProject = sandbox.stub(deploy, 'findProject').callsFake(() => Promise.resolve({ pushdir: '', entryPoint: '' })); this.resolveBinaryModules = sandbox.stub(deployment.js, 'resolveBinaryModules').callsFake(() => Promise.reject(this.failure)); deploy.sendBundle(this.tessel, { lang: deployment.js }).catch(error => { test.equal(error, this.failure); test.done(); }); }, tarBundle(test) { test.expect(1); this.pathResolve.restore(); this.pathResolve = sandbox.stub(path, 'resolve').returns(''); this.exists = sandbox.stub(fs, 'exists').callsFake((fpath, callback) => callback(true)); this.findProject = sandbox.stub(deploy, 'findProject').callsFake(() => Promise.resolve({ pushdir: '', entryPoint: '' })); this.resolveBinaryModules = sandbox.stub(deployment.js, 'resolveBinaryModules').callsFake(() => Promise.resolve()); this.tarBundle = sandbox.stub(deployment.js, 'tarBundle').callsFake(() => Promise.reject(this.failure)); deploy.sendBundle(this.tessel, { lang: deployment.js }).catch(error => { test.equal(error, this.failure); test.done(); }); }, }; exports['deployment.js.preBundle'] = { setUp(done) { this.tessel = TesselSimulator(); this.info = sandbox.stub(log, 'info'); this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => { callback(null, this.tessel._rps); }); this.receive = sandbox.stub(this.tessel, 'receive').callsFake((rps, callback) => { rps.emit('close'); callback(); }); this.fetchCurrentBuildInfo = sandbox.stub(this.tessel, 'fetchCurrentBuildInfo').returns(Promise.resolve('40b2b46a62a34b5a26170c75f7e717cea673d1eb')); this.fetchNodeProcessVersions = sandbox.stub(this.tessel, 'fetchNodeProcessVersions').returns(Promise.resolve(processVersions)); this.requestBuildList = sandbox.stub(updates, 'requestBuildList').returns(Promise.resolve(tesselBuilds)); this.findProject = sandbox.stub(deploy, 'findProject').returns(Promise.resolve({ pushdir: '', entryPoint: '' })); this.resolveBinaryModules = sandbox.stub(deployment.js, 'resolveBinaryModules').returns(Promise.resolve()); this.tarBundle = sandbox.stub(deployment.js, 'tarBundle').returns(Promise.resolve(new Buffer([0x00]))); this.pathResolve = sandbox.stub(path, 'resolve'); this.preBundle = sandbox.spy(deployment.js, 'preBundle'); done(); }, tearDown(done) { this.tessel.mockClose(); sandbox.restore(); done(); }, preBundleChecksForNpmrc(test) { test.expect(1); const warning = tags.stripIndents `This project is missing an ".npmrc" file! To prepare your project for deployment, use the command: t2 init Once complete, retry:`; this.exists = sandbox.stub(fs, 'exists').callsFake((fpath, callback) => callback(false)); deployment.js.preBundle({ target: '/', }).catch(error => { test.equal(error.startsWith(warning), true); test.done(); }); }, preBundleReceivesTessel(test) { test.expect(1); this.pathResolve.restore(); this.pathResolve = sandbox.stub(path, 'resolve').returns(''); this.exists = sandbox.stub(fs, 'exists').callsFake((fpath, callback) => callback(true)); deploy.sendBundle(this.tessel, { target: '/', entryPoint: 'foo.js', lang: deployment.js }).then(() => { test.equal(this.preBundle.lastCall.args[0].tessel, this.tessel); test.done(); }); }, // // We need to find a way to provde the build version directly from the // // Tessel 2 itself. This approach makes deployment slow with a network // // connection, or impossible without one. // preBundleCallsfetchCurrentBuildInfoAndForwardsResult(test) { // test.expect(4); // deploy.sendBundle(this.tessel, { // target: '/', // entryPoint: 'foo.js', // lang: deployment.js // }).then(() => { // test.equal(this.fetchCurrentBuildInfo.callCount, 1); // test.equal(this.resolveBinaryModules.callCount, 1); // var args = this.resolveBinaryModules.lastCall.args[0]; // test.equal(args.tessel, this.tessel); // test.equal(args.tessel.versions, processVersions); // test.done(); // }); // }, // preBundleCallsrequestBuildListAndForwardsResult(test) { // test.expect(4); // deploy.sendBundle(this.tessel, { // target: '/', // entryPoint: 'foo.js', // lang: deployment.js // }).then(() => { // test.equal(this.requestBuildList.callCount, 1); // test.equal(this.resolveBinaryModules.callCount, 1); // var args = this.resolveBinaryModules.lastCall.args[0]; // test.equal(args.tessel, this.tessel); // test.equal(args.tessel.versions, processVersions); // test.done(); // }); // }, // preBundleCallsfetchNodeProcessVersionsAndForwardsResult(test) { // test.expect(4); // deploy.sendBundle(this.tessel, { // target: '/', // entryPoint: 'foo.js', // lang: deployment.js // }).then(() => { // test.equal(this.fetchNodeProcessVersions.callCount, 1); // test.equal(this.resolveBinaryModules.callCount, 1); // var args = this.resolveBinaryModules.lastCall.args[0]; // test.equal(args.tessel, this.tessel); // test.equal(args.tessel.versions, processVersions); // test.done(); // }); // }, }; exports['deployment.js.resolveBinaryModules'] = { setUp(done) { this.target = path.normalize('test/unit/fixtures/project-binary-modules'); this.relative = sandbox.stub(path, 'relative').callsFake(() => { return path.join(FIXTURE_PATH, '/project-binary-modules/'); }); this.globFiles = sandbox.spy(glob, 'files'); this.globSync = sandbox.stub(glob, 'sync').callsFake(() => { return [ path.normalize('node_modules/release/build/Release/release.node'), ]; }); this.readGypFileSync = sandbox.stub(deployment.js.resolveBinaryModules, 'readGypFileSync').callsFake(() => { return '{"targets": [{"target_name": "missing"}]}'; }); this.getRoot = sandbox.stub(bindings, 'getRoot').callsFake((file) => { var pathPart = ''; if (file.includes('debug')) { pathPart = 'debug'; } if (file.includes('linked')) { pathPart = 'linked'; } if (file.includes('missing')) { pathPart = 'missing'; } if (file.includes('release')) { pathPart = 'release'; } return path.normalize(`node_modules/${pathPart}/`); }); this.ifReachable = sandbox.stub(remote, 'ifReachable').callsFake(() => Promise.resolve()); done(); }, tearDown(done) { sandbox.restore(); done(); }, bailOnSkipBinary(test) { test.expect(2); this.target = path.normalize('test/unit/fixtures/project-skip-binary'); this.relative.restore(); this.relative = sandbox.stub(path, 'relative').callsFake(() => { return path.join(FIXTURE_PATH, '/project-skip-binary/'); }); // We WANT to read the actual gyp files if necessary this.readGypFileSync.restore(); // We WANT to glob the actual target directory this.globSync.restore(); this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true); deployment.js.resolveBinaryModules({ target: this.target, tessel: { versions: { modules: 46 }, }, }).then(() => { test.equal(this.exists.callCount, 1); // test/unit/fixtures/skip-binary/ has the corresponding // dependencies for the following binary modules: // // debug-1.1.1-Debug-node-v46-linux-mipsel // release-1.1.1-Release-node-v46-linux-mipsel // // However, the latter has a "tessel.skipBinary = true" key in its package.json // // test.equal(this.exists.lastCall.args[0].endsWith(path.normalize('.tessel/binaries/debug-1.1.1-Debug-node-v46-linux-mipsel')), true); test.done(); }).catch(error => { test.ok(false, error.toString()); test.done(); }); }, buildPathExpWindow(test) { test.expect(1); let descriptor = Object.getOwnPropertyDescriptor(process, 'platform'); Object.defineProperty(process, 'platform', { value: 'win32' }); this.match = sandbox.spy(String.prototype, 'match'); this.target = path.normalize('test/unit/fixtures/project-skip-binary'); this.relative.restore(); this.relative = sandbox.stub(path, 'relative').callsFake(() => { return path.join(FIXTURE_PATH, '/project-skip-binary/'); }); this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true); deployment.js.resolveBinaryModules({ target: this.target, tessel: { versions: { modules: 46 }, }, }).then(() => { test.equal( this.match.lastCall.args[0].toString(), '/(?:build\\\\(Debug|Release|bindings)\\\\)/' ); // Restore this descriptor Object.defineProperty(process, 'platform', descriptor); test.done(); }).catch(error => { test.ok(false, error.toString()); test.done(); }); }, noOptionsTargetFallbackToCWD(test) { test.expect(3); const target = path.normalize('test/unit/fixtures/project'); sandbox.stub(process, 'cwd').returns(target); this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true); deployment.js.resolveBinaryModules({ tessel: { versions: { modules: 46 }, }, }).then(() => { test.equal(this.relative.callCount, 1); test.equal(this.relative.lastCall.args[0], target); test.equal(this.relative.lastCall.args[1], target); test.done(); }).catch(error => { test.ok(false, error.toString()); test.done(); }); }, noOptionsTargetFallbackToCWDNoRelative(test) { test.expect(1); this.relative.restore(); this.relative = sandbox.stub(path, 'relative').returns(''); this.cwd = sandbox.stub(process, 'cwd').returns(''); this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true); deployment.js.resolveBinaryModules({ tessel: { versions: { modules: 46 }, }, }).then(() => { test.ok(false, 'resolveBinaryModules should not resolve'); test.done(); }).catch(error => { // The thing to be found: // // node_modules/release/package.json // // Will not be found, because it doesn't exist, // but in this case, that's exactly what we want. test.equal(error.toString(), `Error: Cannot find module '${path.normalize('node_modules/release/package.json')}'`); test.done(); }); }, findsModulesMissingBinaryNodeFiles(test) { test.expect(2); this.globSync.restore(); this.globSync = sandbox.stub(glob, 'sync').callsFake(() => { return [ path.normalize('node_modules/release/build/Release/release.node'), path.normalize('node_modules/release/binding.gyp'), path.normalize('node_modules/missing/binding.gyp'), ]; }); this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true); deployment.js.resolveBinaryModules({ target: this.target, tessel: { versions: { modules: 46 }, }, }).then(() => { test.deepEqual( this.globFiles.lastCall.args[1], ['node_modules/**/*.node', 'node_modules/**/binding.gyp'] ); test.equal(this.readGypFileSync.callCount, 1); test.done(); }).catch(error => { test.ok(false, error.toString()); test.done(); }); }, spawnPythonScriptReturnsNull(test) { test.expect(1); this.readGypFileSync.restore(); this.readGypFileSync = sandbox.spy(deployment.js.resolveBinaryModules, 'readGypFileSync'); this.globSync.restore(); this.globSync = sandbox.stub(glob, 'sync').callsFake(() => { return [ path.normalize('node_modules/release/build/Release/release.node'), path.normalize('node_modules/release/binding.gyp'), path.normalize('node_modules/missing/binding.gyp'), ]; }); this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true); this.spawnSync = sandbox.stub(cp, 'spawnSync').callsFake(() => { return { output: null }; }); deployment.js.resolveBinaryModules({ target: this.target, tessel: { versions: { modules: 46 }, }, }).then(() => { test.equal(this.readGypFileSync.lastCall.returnValue, ''); test.done(); }).catch(error => { test.ok(false, error.toString()); test.done(); }); }, spawnPythonScript(test) { test.expect(7); this.readGypFileSync.restore(); this.readGypFileSync = sandbox.spy(deployment.js.resolveBinaryModules, 'readGypFileSync'); this.globSync.restore(); this.globSync = sandbox.stub(glob, 'sync').callsFake(() => { return [ path.normalize('node_modules/release/build/Release/release.node'), path.normalize('node_modules/release/binding.gyp'), path.normalize('node_modules/missing/binding.gyp'), ]; }); this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true); this.spawnSync = sandbox.stub(cp, 'spawnSync').callsFake(() => { return { output: [ null, new Buffer('{"targets": [{"target_name": "missing","sources": ["capture.c", "missing.cc"]}]}', 'utf8') ] }; }); deployment.js.resolveBinaryModules({ target: this.target, tessel: { versions: { modules: 46 }, }, }).then(() => { test.deepEqual( this.globFiles.lastCall.args[1], ['node_modules/**/*.node', 'node_modules/**/binding.gyp'] ); test.equal(this.readGypFileSync.callCount, 1); test.equal(this.spawnSync.callCount, 1); test.equal(this.spawnSync.lastCall.args[0], 'python'); var python = this.spawnSync.lastCall.args[1][1]; test.equal(python.startsWith('import ast, json; print json.dumps(ast.literal_eval(open('), true); test.equal(python.endsWith(').read()));'), true); test.equal(python.includes('missing'), true); test.done(); }).catch(error => { test.ok(false, error.toString()); test.done(); }); }, failsWithMessage(test) { test.expect(1); this.globSync.restore(); this.globSync = sandbox.stub(glob, 'sync').callsFake(() => { return [ path.normalize('node_modules/missing/binding.gyp'), ]; }); this.readGypFileSync.restore(); this.readGypFileSync = sandbox.stub(deployment.js.resolveBinaryModules, 'readGypFileSync').callsFake(() => { return '{"targets": [{"target_name": "missing",}]}'; // ^ // That's intentional. }); this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true); deployment.js.resolveBinaryModules({ target: this.target, tessel: { versions: { modules: 46 }, }, }).then(binaryModulesUsed => { test.equal(binaryModulesUsed.get('[email protected]').resolved, false); test.done(); }).catch(error => { test.ok(false, error.toString()); test.done(); }); }, existsInLocalCache(test) { test.expect(2); this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true); deployment.js.resolveBinaryModules({ target: this.target, tessel: { versions: { modules: 46 }, }, }).then(() => { test.equal(this.globFiles.callCount, 1); test.equal(this.exists.callCount, 1); test.done(); }).catch(error => { test.ok(false, error.toString()); test.done(); }); }, existsInLocalCacheNodeGypLinkedBinPath(test) { test.expect(1); this.readGypFileSync.restore(); this.globSync.restore(); this.globSync = sandbox.stub(glob, 'sync').callsFake(() => { return [ path.normalize('node_modules/release/build/Release/release.node'), path.normalize('node_modules/linked/build/bindings/linked.node'), ]; }); this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true); deployment.js.resolveBinaryModules({ target: this.target, tessel: { versions: { modules: 46 }, }, }).then(() => { test.equal(this.exists.callCount, 2); test.done(); }).catch(error => { test.ok(false, error.toString()); test.done(); }); }, resolveFromRealDirFixtures(test) { test.expect(5); // We WANT to read the actual gyp files if necessary this.readGypFileSync.restore(); // We WANT to glob the actual target directory this.globSync.restore(); // To avoid making an actual network request, // make the program think these things are already // cached. The test to pass is that it calls fs.existsSync // with the correct things from the project directory (this.target) this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true); deployment.js.resolveBinaryModules({ target: this.target, tessel: { versions: { modules: 46 }, }, }).then(() => { test.equal(this.exists.callCount, 4); // test/unit/fixtures/project-binary-modules/ has the corresponding // dependencies for the following binary modules: var cachedBinaryPaths = [ '.tessel/binaries/debug-1.1.1-Debug-node-v46-linux-mipsel', '.tessel/binaries/linked-1.1.1-Release-node-v46-linux-mipsel', '.tessel/binaries/release-1.1.1-Release-node-v46-linux-mipsel', '.tessel/binaries/missing-1.1.1-Release-node-v46-linux-mipsel', ]; cachedBinaryPaths.forEach((cbp, callIndex) => { test.equal(this.exists.getCall(callIndex).args[0].endsWith(path.normalize(cbp)), true); }); test.done(); }).catch(error => { test.ok(false, error.toString()); test.done(); }); }, requestsRemote(test) { test.expect(12); this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => false); this.mkdirp = sandbox.stub(fs, 'mkdirp').callsFake((dir, handler) => { handler(); }); this.transform = new Transform(); this.transform.stubsUsed = []; this.rstream = null; this.pipe = sandbox.stub(stream.Stream.prototype, 'pipe').callsFake(() => { // After the second transform is piped, emit the end // event on the request stream; if (this.pipe.callCount === 2) { process.nextTick(() => this.rstream.emit('end')); } return this.rstream; }); this.createGunzip = sandbox.stub(zlib, 'createGunzip').callsFake(() => { this.transform.stubsUsed.push('createGunzip'); return this.transform; }); this.Extract = sandbox.stub(tar, 'Extract').callsFake(() => { this.transform.stubsUsed.push('Extract'); return this.transform; }); this.request = sandbox.stub(request, 'Request').callsFake((opts) => { this.rstream = new Request(opts); return this.rstream; }); deployment.js.resolveBinaryModules({ target: this.target, tessel: { versions: { modules: 46 }, }, }).then(() => { test.equal(this.globFiles.callCount, 1); test.equal(this.exists.callCount, 1); test.equal(this.mkdirp.callCount, 1); test.equal(this.mkdirp.lastCall.args[0].endsWith(path.normalize('.tessel/binaries/release-1.1.1-Release-node-v46-linux-mipsel')), true); test.equal(this.request.callCount, 1); var requestArgs = this.request.lastCall.args[0]; test.equal(requestArgs.url, 'http://packages.tessel.io/npm/release-1.1.1-Release-node-v46-linux-mipsel.tgz'); test.equal(requestArgs.gzip, true); test.equal(this.pipe.callCount, 2); test.equal(this.createGunzip.callCount, 1); test.equal(this.Extract.callCount, 1); test.equal(this.transform.stubsUsed.length, 2); test.deepEqual(this.transform.stubsUsed, ['createGunzip', 'Extract']); test.done(); }).catch(error => { test.ok(false, error.toString()); test.done(); }); }, requestsRemoteGunzipErrors(test) { test.expect(9); this.removeSync = sandbox.stub(fs, 'removeSync'); this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => false); this.mkdirp = sandbox.stub(fs, 'mkdirp').callsFake((dir, handler) => { handler(); }); this.transform = new Transform(); this.transform.stubsUsed = []; this.rstream = null; this.pipe = sandbox.stub(stream.Stream.prototype, 'pipe').callsFake(() => { // After the second transform is piped, emit the end // event on the request stream; if (this.pipe.callCount === 2) { process.nextTick(() => this.rstream.emit('end')); } return this.rstream; }); this.createGunzip = sandbox.stub(zlib, 'createGunzip').callsFake(() => { this.transform.stubsUsed.push('createGunzip'); return this.transform; }); this.Extract = sandbox.stub(tar, 'Extract').callsFake(() => { this.transform.stubsUsed.push('Extract'); return this.transform; }); this.request = sandbox.stub(request, 'Request').callsFake((opts) => { this.rstream = new Request(opts); return this.rstream; }); // Hook into the ifReachable call to trigger an error at the gunzip stream this.ifReachable.restore(); this.ifReachable = sandbox.stub(remote, 'ifReachable').callsFake(() => { this.transform.emit('error', { code: 'Z_DATA_ERROR', }); return Promise.resolve(); }); deployment.js.resolveBinaryModules({ target: this.target, tessel: { versions: { modules: 46 }, }, }).then(() => { test.equal(this.globFiles.callCount, 1); test.equal(this.exists.callCount, 1); test.equal(this.mkdirp.callCount, 1); test.equal(this.mkdirp.lastCall.args[0].endsWith(path.normalize('.tessel/binaries/release-1.1.1-Release-node-v46-linux-mipsel')), true); // The result of gunzip emitting an error: test.equal(this.removeSync.callCount, 1); test.equal(this.removeSync.lastCall.args[0].endsWith(path.normalize('.tessel/binaries/release-1.1.1-Release-node-v46-linux-mipsel')), true); test.equal(this.request.callCount, 1); test.equal(this.createGunzip.callCount, 1); test.deepEqual(this.transform.stubsUsed, ['createGunzip', 'Extract']); test.done(); }).catch(error => { test.ok(false, error.toString()); test.done(); }); }, }; exports['deployment.js.injectBinaryModules'] = { setUp(done) { this.target = path.normalize('test/unit/fixtures/project-binary-modules'); this.relative = sandbox.stub(path, 'relative').callsFake(() => { return path.join(FIXTURE_PATH, '/project-binary-modules/'); }); this.globFiles = sandbox.spy(glob, 'files'); this.globSync = sandbox.stub(glob, 'sync').callsFake(() => { return [ path.normalize('node_modules/release/build/Release/release.node'), ]; }); this.getRoot = sandbox.stub(bindings, 'getRoot').callsFake((file) => { var pathPart = ''; if (file.includes('debug')) { pathPart = 'debug'; } if (file.includes('linked')) { pathPart = 'linked'; } if (file.includes('missing')) { pathPart = 'missing'; } if (file.includes('release')) { pathPart = 'release'; } return path.normalize(`node_modules/${pathPart}/`); }); this.globRoot = path.join(FIXTURE_PATH, '/project-binary-modules/'); this.copySync = sandbox.stub(fs, 'copySync'); this.exists = sandbox.stub(fs, 'existsSync').callsFake(() => true); done(); }, tearDown(done) { sandbox.restore(); done(); }, copies(test) { test.expect(17); this.globSync.restore(); this.globSync = sandbox.stub(glob, 'sync').callsFake(() => { return [ path.normalize('node_modules/debug/build/Debug/debug.node'), path.normalize('node_modules/debug/binding.gyp'), path.normalize('node_modules/linked/build/bindings/linked.node'), path.normalize('node_modules/linked/binding.gyp'), path.normalize('node_modules/missing/build/Release/missing.node'), path.normalize('node_modules/missing/binding.gyp'), path.normalize('node_modules/release/build/Release/release.node'), path.normalize('node_modules/release/binding.gyp'), ]; }); deployment.js.resolveBinaryModules({ target: this.target, tessel: { versions: { modules: 46 }, }, }).then(() => { deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {}).then(() => { test.equal(this.copySync.callCount, 8); var args = this.copySync.args; /* This is an abbreviated view of what should be copied by this operation: [ [ 'debug-1.1.1-Release-node-v46-linux-mipsel/Debug/debug.node', 'debug/build/Debug/debug.node' ], [ 'debug/package.json', 'debug/package.json' ], [ 'linked-1.1.1-Release-node-v46-linux-mipsel/bindings/linked.node', 'linked/build/bindings/linked.node' ], [ 'linked/package.json', 'linked/package.json' ], [ 'missing-1.1.1-Release-node-v46-linux-mipsel/Release/missing.node', 'missing/build/Release/missing.node' ], [ 'missing/package.json', 'missing/package.json' ], [ 'release-1.1.1-Release-node-v46-linux-mipsel/Release/release.node', 'release/build/Release/release.node' ], [ 'release/package.json', 'release/package.json' ] ] */ // ----- fixtures/project-binary-modules/node_modules/debug test.equal( args[0][0].endsWith(path.normalize('debug-1.1.1-Debug-node-v46-linux-mipsel/Debug/debug.node')), true ); test.equal( args[0][1].endsWith(path.normalize('debug/build/Debug/debug.node')), true ); test.equal( args[1][0].endsWith(path.normalize('debug/package.json')), true ); test.equal( args[1][1].endsWith(path.normalize('debug/package.json')), true ); // ----- fixtures/project-binary-modules/node_modules/linked test.equal( args[2][0].endsWith(path.normalize('linked-1.1.1-Release-node-v46-linux-mipsel/bindings/linked.node')), true ); test.equal( args[2][1].endsWith(path.normalize('linked/build/bindings/linked.node')), true ); test.equal( args[3][0].endsWith(path.normalize('linked/package.json')), true ); test.equal( args[3][1].endsWith(path.normalize('linked/package.json')), true ); // ----- fixtures/project-binary-modules/node_modules/missing test.equal( args[4][0].endsWith(path.normalize('missing-1.1.1-Release-node-v46-linux-mipsel/Release/missing.node')), true ); test.equal( args[4][1].endsWith(path.normalize('missing/build/Release/missing.node')), true ); test.equal( args[5][0].endsWith(path.normalize('missing/package.json')), true ); test.equal( args[5][1].endsWith(path.normalize('missing/package.json')), true ); // ----- fixtures/project-binary-modules/node_modules/release test.equal( args[6][0].endsWith(path.normalize('release-1.1.1-Release-node-v46-linux-mipsel/Release/release.node')), true ); test.equal( args[6][1].endsWith(path.normalize('release/build/Release/release.node')), true ); test.equal( args[7][0].endsWith(path.normalize('release/package.json')), true ); test.equal( args[7][1].endsWith(path.normalize('release/package.json')), true ); test.done(); }).catch(error => { test.ok(false, error.toString()); test.done(); }); }).catch(error => { test.ok(false, error.toString()); test.done(); }); }, doesNotCopyIgnoredBinaries(test) { test.expect(1); this.target = path.normalize('test/unit/fixtures/project-ignore-binary'); this.relative.restore(); this.relative = sandbox.stub(path, 'relative').callsFake(() => { return path.join(FIXTURE_PATH, '/project-ignore-binary/'); }); deployment.js.resolveBinaryModules({ target: this.target, tessel: { versions: { modules: 46 }, }, }).then(() => { deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {}).then(() => { // Nothing gets copied! test.equal(this.copySync.callCount, 0); test.done(); }); }); }, usesBinaryHighestInTreeWhenEncounteringDuplicates(test) { test.expect(6); this.target = path.normalize('test/unit/fixtures/project-binary-modules-duplicate-lower-deps'); this.relative.restore(); this.relative = sandbox.stub(path, 'relative').callsFake(() => { return path.join(FIXTURE_PATH, '/project-binary-modules-duplicate-lower-deps/'); }); // We WANT to glob the actual target directory this.globSync.restore(); this.mapHas = sandbox.spy(Map.prototype, 'has'); this.mapGet = sandbox.spy(Map.prototype, 'get'); this.mapSet = sandbox.spy(Map.prototype, 'set'); this.arrayMap = sandbox.spy(Array.prototype, 'map'); deployment.js.resolveBinaryModules({ target: this.target, tessel: { versions: { modules: 46 }, }, }).then(binaryModulesUsed => { // Ensure that 2 modules with the same name and version were found! for (var i = 0; i < this.arrayMap.callCount; i++) { let call = this.arrayMap.getCall(i); if (call.thisValue.UNRESOLVED_BINARY_LIST) { test.equal(call.thisValue.length, 2); } } test.equal(this.mapHas.callCount, 2); test.equal(this.mapHas.getCall(0).args[0], '[email protected]'); test.equal(this.mapHas.getCall(1).args[0], '[email protected]'); // Ensure that only one of the two were included in the // final list of binary modules to bundle test.equal(binaryModulesUsed.size, 1); // Ensure that the swap has occurred test.equal( path.normalize(binaryModulesUsed.get('[email protected]').globPath), path.normalize('node_modules/release/build/Release/release.node') ); test.done(); }); }, fallbackWhenOptionsMissing(test) { test.expect(1); deployment.js.resolveBinaryModules({ target: this.target, tessel: { versions: { modules: 46 }, }, }).then(binaryModulesUsed => { binaryModulesUsed.clear(); // We need something to look at... sandbox.stub(binaryModulesUsed, 'forEach'); deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync()).then(() => { test.equal(binaryModulesUsed.forEach.callCount, 1); test.done(); }); }); }, doesNotCopyWhenOptionsSingleTrue(test) { test.expect(1); // This would normally result in 8 calls to this.copySync this.globSync.restore(); this.globSync = sandbox.stub(glob, 'sync').callsFake(() => { return [ path.normalize('node_modules/debug/build/Debug/debug.node'), path.normalize('node_modules/debug/binding.gyp'), path.normalize('node_modules/linked/build/bindings/linked.node'), path.normalize('node_modules/linked/binding.gyp'), path.normalize('node_modules/missing/build/Release/missing.node'), path.normalize('node_modules/missing/binding.gyp'), path.normalize('node_modules/release/build/Release/release.node'), path.normalize('node_modules/release/binding.gyp'), ]; }); deployment.js.resolveBinaryModules({ target: this.target, tessel: { versions: { modules: 46 }, }, }).then(() => { deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), { single: true }).then(() => { // Nothing gets copied! test.equal(this.copySync.callCount, 0); test.done(); }); }); }, rewriteBinaryBuildPlatformPaths(test) { test.expect(2); this.forEach = sandbox.stub(Map.prototype, 'forEach').callsFake((handler) => { handler({ binName: 'serialport.node', buildPath: path.normalize('/build/Release/node-v46-FAKE_PLATFORM-FAKE_ARCH/'), buildType: 'Release', globPath: path.normalize('node_modules/serialport/build/Release/node-v46-FAKE_PLATFORM-FAKE_ARCH/serialport.node'), ignored: false, name: 'serialport', modulePath: path.normalize('node_modules/serialport'), resolved: true, version: '2.0.6', extractPath: path.normalize('~/.tessel/binaries/serialport-2.0.6-Release-node-v46-linux-mipsel') }); }); var find = lists.binaryPathTranslations['*'][0].find; lists.binaryPathTranslations['*'][0].find = 'FAKE_PLATFORM-FAKE_ARCH'; deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {}).then(() => { // If the replacement operation did not work, these would still be // "FAKE_PLATFORM-FAKE_ARCH" test.equal(this.copySync.firstCall.args[0].endsWith(path.normalize('linux-mipsel/serialport.node')), true); test.equal(this.copySync.firstCall.args[1].endsWith(path.normalize('linux-mipsel/serialport.node')), true); // Restore the path translation... lists.binaryPathTranslations['*'][0].find = find; test.done(); }); }, tryTheirPathAndOurPath(test) { test.expect(3); this.copySync.restore(); this.copySync = sandbox.stub(fs, 'copySync').callsFake(() => { // Fail the first try/catch on THEIR PATH if (this.copySync.callCount === 1) { throw new Error('ENOENT: no such file or directory'); } }); this.forEach = sandbox.stub(Map.prototype, 'forEach').callsFake((handler) => { handler({ binName: 'node_sqlite3.node', // This path doesn't match our precompiler's output paths. // Will result in: // ERR! Error: ENOENT: no such file or directory, stat '~/.tessel/binaries/sqlite3-3.1.4-Release/node-v46-something-else/node_sqlite3.node' buildPath: path.normalize('/lib/binding/node-v46-something-else/'), buildType: 'Release', globPath: path.normalize('node_modules/sqlite3/lib/binding/node-v46-something-else/node_sqlite3.node'), ignored: false, name: 'sqlite3', modulePath: path.normalize('node_modules/sqlite3'), resolved: true, version: '3.1.4', extractPath: path.normalize('~/.tessel/binaries/sqlite3-3.1.4-Release'), }); }); deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {}).then(() => { // 2 calls: 1 call for each try/catch fs.copySync // 1 call: copy the package.json test.equal(fs.copySync.callCount, 3); // THEIR PATH test.equal(this.copySync.getCall(0).args[0].endsWith(path.normalize('node-v46-something-else/node_sqlite3.node')), true); // OUR PATH test.equal(this.copySync.getCall(1).args[0].endsWith(path.normalize('Release/node_sqlite3.node')), true); test.done(); }); }, tryCatchTwiceAndFailGracefullyWithMissingBinaryMessage(test) { test.expect(4); this.copySync.restore(); this.copySync = sandbox.stub(fs, 'copySync').callsFake(() => { throw new Error('E_THIS_IS_NOT_REAL'); }); this.forEach = sandbox.stub(Map.prototype, 'forEach').callsFake((handler) => { handler({ binName: 'not-a-thing.node', // This path doesn't match our precompiler's output paths. // Will result in: // ERR! Error: ENOENT: no such file or directory, stat '~/.tessel/binaries/not-a-thing-3.1.4-Release/node-v46-something-else/not-a-thing.node' buildPath: path.normalize('/lib/binding/node-v46-something-else/'), buildType: 'Release', globPath: path.normalize('node_modules/not-a-thing/lib/binding/node-v46-something-else/not-a-thing.node'), ignored: false, name: 'not-a-thing', modulePath: path.normalize('node_modules/not-a-thing'), resolved: true, version: '3.1.4', extractPath: path.normalize('~/.tessel/binaries/not-a-thing-3.1.4-Release'), }); }); this.error = sandbox.stub(log, 'error'); this.logMissingBinaryModuleWarning = sandbox.stub(deployment.js, 'logMissingBinaryModuleWarning'); deployment.js.injectBinaryModules(this.globRoot, fsTemp.mkdirSync(), {}).then(() => { // 2 calls: 1 call for each try/catch fs.copySync test.equal(this.copySync.callCount, 2); // Result of failing both attempts to copy test.equal(this.logMissingBinaryModuleWarning.callCount, 1); test.equal(this.error.callCount, 1); test.equal(String(this.error.lastCall.args[0]).includes('E_THIS_IS_NOT_REAL'), true); test.done(); }); } }; exports['deploy.createShellScript'] = { setUp(done) { this.info = sandbox.stub(log, 'info'); this.tessel = TesselSimulator(); done(); }, tearDown(done) { this.tessel.mockClose(); sandbox.restore(); done(); }, remoteShellScriptPathIsNotPathNormalized(test) { test.expect(2); this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => { callback(null, this.tessel._rps); this.tessel._rps.emit('close'); }); var opts = { lang: deployment.js, resolvedEntryPoint: 'foo', binopts: [], subargs: [], }; deploy.createShellScript(this.tessel, opts).then(() => { test.deepEqual(this.exec.firstCall.args[0], ['dd', 'of=/app/start']); test.deepEqual(this.exec.lastCall.args[0], ['chmod', '+x', '/app/start']); test.done(); }); }, remoteShellScriptPathIsNotPathNormalizedWithSubargs(test) { test.expect(2); this.exec = sandbox.stub(this.tessel.connection, 'exec').callsFake((command, callback) => { callback(null, this.tessel._rps); this.tessel._rps.emit('close'); }); var opts = { lang: deployment.js, resolvedEntryPoint: 'foo', binopts: ['--harmony'], subargs: ['--key=value'], }; deploy.createShellScript(this.tessel, opts).then(() => { test.deepEqual(this.exec.firstCall.args[0], ['dd', 'of=/app/start']); test.deepEqual(this.exec.lastCall.args[0], ['chmod', '+x', '/app/start']); test.done(); }); } }; // Test dependencies are required and exposed in common/bootstrap.js exports['deployment.js.lists'] = { setUp(done) { done(); }, tearDown(done) { done(); }, checkIncludes(test) { test.expect(1); var includes = [ 'node_modules/**/aws-sdk/apis/*.json', 'node_modules/**/mime/types/*.types', 'node_modules/**/negotiator/**/*.js', 'node_modules/**/socket.io-client/socket.io.js', 'node_modules/**/socket.io-client/dist/socket.io.min.js', 'node_modules/**/socket.io-client/dist/socket.io.js', ]; test.deepEqual(lists.includes, includes); test.done(); }, checkIgnores(test) { test.expect(1); var ignores = [ 'node_modules/**/tessel/**/*', ]; test.deepEqual(lists.ignores, ignores); test.done(); }, checkCompression(test) { test.expect(1); /* This test just ensures that no one accidentally messes up the contents of the deploy-lists file, specifically for the compression options field */ var compressionOptions = { extend: { compress: { keep_fnames: true }, mangle: {} }, }; test.deepEqual(lists.compressionOptions, compressionOptions); test.done(); } }; exports['deployment.js.postRun'] = { setUp(done) { this.info = sandbox.stub(log, 'info'); this.originalProcessStdinProperties = { pipe: process.stdin.pipe, setRawMode: process.stdin.setRawMode, }; this.stdinPipe = sandbox.spy(); this.setRawMode = sandbox.spy(); process.stdin.pipe = this.stdinPipe; process.stdin.setRawMode = this.setRawMode; this.notRealTessel = { connection: { connectionType: 'LAN', }, }; done(); }, tearDown(done) { process.stdin.pipe = this.originalProcessStdinProperties.pipe; process.stdin.setRawMode = this.originalProcessStdinProperties.setRawMode; sandbox.restore(); done(); }, postRunLAN(test) { test.expect(2); deployment.js.postRun(this.notRealTessel, { remoteProcess: { stdin: null } }).then(() => { test.equal(process.stdin.pipe.callCount, 1); test.equal(process.stdin.setRawMode.callCount, 1); test.done(); }); }, postRunUSB(test) { test.expect(2); this.notRealTessel.connection.connectionType = 'USB'; deployment.js.postRun(this.notRealTessel, { remoteProcess: { stdin: null } }).then(() => { test.equal(process.stdin.pipe.callCount, 0); test.equal(process.stdin.setRawMode.callCount, 0); test.done(); }); }, }; exports['deployment.js.logMissingBinaryModuleWarning'] = { setUp(done) { this.warn = sandbox.stub(log, 'warn'); this.details = { binName: 'compiled-binary.node', buildPath: path.normalize('/build/Release/node-v46-FAKE_PLATFORM-FAKE_ARCH/'), buildType: 'Release', globPath: path.normalize('node_modules/compiled-binary/build/Release/node-v46-FAKE_PLATFORM-FAKE_ARCH/compiled-binary.node'), ignored: false, name: 'compiled-binary', modulePath: path.normalize('node_modules/compiled-binary'), resolved: true, version: '2.0.6', extractPath: path.normalize('~/.tessel/binaries/compiled-binary-2.0.6-Release-node-v46-linux-mipsel') }; done(); }, tearDown(done) { sandbox.restore(); done(); }, callsThroughToLogWarn(test) { test.expect(1); deployment.js.logMissingBinaryModuleWarning(this.details); test.equal(this.warn.callCount, 1); test.done(); }, includesModuleNameAndVersion(test) { test.expect(1); deployment.js.logMissingBinaryModuleWarning(this.details); var output = this.warn.lastCall.args[0]; test.equal(output.includes('Pre-compiled module is missing: [email protected]'), true); test.done(); }, }; exports['deployment.js.minimatch'] = { setUp(done) { done(); }, tearDown(done) { done(); }, callsThroughToMinimatch(test) { test.expect(1); const result = deployment.js.minimatch('', '', {}); test.equal(result, true); test.done(); }, };
nodebotanist/t2-cli
test/unit/deployment/javascript.js
JavaScript
mit
105,275
""" Visualize possible stitches with the outcome of the validator. """ import math import random import matplotlib.pyplot as plt import networkx as nx import numpy as np from mpl_toolkits.mplot3d import Axes3D import stitcher SPACE = 25 TYPE_FORMAT = {'a': '^', 'b': 's', 'c': 'v'} def show(graphs, request, titles, prog='neato', size=None, type_format=None, filename=None): """ Display the results using matplotlib. """ if not size: size = _get_size(len(graphs)) fig, axarr = plt.subplots(size[0], size[1], figsize=(18, 10)) fig.set_facecolor('white') x_val = 0 y_val = 0 index = 0 if size[0] == 1: axarr = np.array(axarr).reshape((1, size[1])) for candidate in graphs: # axarr[x_val, y_val].axis('off') axarr[x_val, y_val].xaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].yaxis.set_major_formatter(plt.NullFormatter()) axarr[x_val, y_val].xaxis.set_ticks([]) axarr[x_val, y_val].yaxis.set_ticks([]) axarr[x_val, y_val].set_title(titles[index]) # axarr[x_val, y_val].set_axis_bgcolor("white") if not type_format: type_format = TYPE_FORMAT _plot_subplot(candidate, request.nodes(), prog, type_format, axarr[x_val, y_val]) y_val += 1 if y_val > size[1] - 1: y_val = 0 x_val += 1 index += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_subplot(graph, new_nodes, prog, type_format, axes): """ Plot a single candidate graph. """ pos = nx.nx_agraph.graphviz_layout(graph, prog=prog) # draw the nodes for node, values in graph.nodes(data=True): shape = 'o' if values[stitcher.TYPE_ATTR] in type_format: shape = type_format[values[stitcher.TYPE_ATTR]] color = 'g' alpha = 0.8 if node in new_nodes: color = 'b' alpha = 0.2 elif 'rank' in values and values['rank'] > 7: color = 'r' elif 'rank' in values and values['rank'] < 7 and values['rank'] > 3: color = 'y' nx.draw_networkx_nodes(graph, pos, nodelist=[node], node_color=color, node_shape=shape, alpha=alpha, ax=axes) # draw the edges dotted_line = [] normal_line = [] for src, trg in graph.edges(): if src in new_nodes and trg not in new_nodes: dotted_line.append((src, trg)) else: normal_line.append((src, trg)) nx.draw_networkx_edges(graph, pos, edgelist=dotted_line, style='dotted', ax=axes) nx.draw_networkx_edges(graph, pos, edgelist=normal_line, ax=axes) # draw labels nx.draw_networkx_labels(graph, pos, ax=axes) def show_3d(graphs, request, titles, prog='neato', filename=None): """ Show the candidates in 3d - the request elevated above the container. """ fig = plt.figure(figsize=(18, 10)) fig.set_facecolor('white') i = 0 size = _get_size(len(graphs)) for graph in graphs: axes = fig.add_subplot(size[0], size[1], i+1, projection=Axes3D.name) axes.set_title(titles[i]) axes._axis3don = False _plot_3d_subplot(graph, request, prog, axes) i += 1 fig.tight_layout() if filename is not None: plt.savefig(filename) else: plt.show() plt.close() def _plot_3d_subplot(graph, request, prog, axes): """ Plot a single candidate graph in 3d. """ cache = {} tmp = graph.copy() for node in request.nodes(): tmp.remove_node(node) pos = nx.nx_agraph.graphviz_layout(tmp, prog=prog) # the container for item in tmp.nodes(): axes.plot([pos[item][0]], [pos[item][1]], [0], linestyle="None", marker="o", color='gray') axes.text(pos[item][0], pos[item][1], 0, item) for src, trg in tmp.edges(): axes.plot([pos[src][0], pos[trg][0]], [pos[src][1], pos[trg][1]], [0, 0], color='gray') # the new nodes for item in graph.nodes(): if item in request.nodes(): for nghb in graph.neighbors(item): if nghb in tmp.nodes(): x_val = pos[nghb][0] y_val = pos[nghb][1] if (x_val, y_val) in list(cache.values()): x_val = pos[nghb][0] + random.randint(10, SPACE) y_val = pos[nghb][0] + random.randint(10, SPACE) cache[item] = (x_val, y_val) # edge axes.plot([x_val, pos[nghb][0]], [y_val, pos[nghb][1]], [SPACE, 0], color='blue') axes.plot([x_val], [y_val], [SPACE], linestyle="None", marker="o", color='blue') axes.text(x_val, y_val, SPACE, item) for src, trg in request.edges(): if trg in cache and src in cache: axes.plot([cache[src][0], cache[trg][0]], [cache[src][1], cache[trg][1]], [SPACE, SPACE], color='blue') def _get_size(n_items): """ Calculate the size of the subplot layouts based on number of items. """ n_cols = math.ceil(math.sqrt(n_items)) n_rows = math.floor(math.sqrt(n_items)) if n_cols * n_rows < n_items: n_cols += 1 return int(n_rows), int(n_cols)
tmetsch/graph_stitcher
stitcher/vis.py
Python
mit
5,618
package de.verygame.surface.screen.base; import com.badlogic.gdx.InputMultiplexer; import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch; import com.badlogic.gdx.utils.viewport.Viewport; import java.util.Map; /** * @author Rico Schrage * * Context which can contain several subscreens. */ public class SubScreenContext implements ScreenContext { /** List of subScreen's plus visibility flag */ protected final ScreenSwitch screenSwitch; /** viewport of the screen (manages the glViewport) */ protected final Viewport viewport; /** True if a subScreen is visible */ protected boolean showSubScreen = false; /** * Constructs a context with the given viewport. * * @param viewport viewport viewport of the screen */ public SubScreenContext(Viewport viewport) { super(); this.viewport = viewport; this.screenSwitch = new ScreenSwitch(); } /** * Sets the dependency map of the screen switch. * * @param dependencies map of dependencies */ public void setDependencies(Map<String, Object> dependencies) { screenSwitch.setDependencyMap(dependencies); } /** * Sets the batch of the context. * * @param polygonSpriteBatch batch */ public void setBatch(PolygonSpriteBatch polygonSpriteBatch) { screenSwitch.setBatch(polygonSpriteBatch); } /** * Sets the inputHandler of the context. * * @param inputHandler inputHandler */ public void setInputHandler(InputMultiplexer inputHandler) { screenSwitch.setInputHandler(inputHandler); } public InputMultiplexer getInputHandler() { return screenSwitch.getInputHandler(); } public void onActivate(ScreenId screenKey) { if (screenSwitch.getActiveScreen() != null) { screenSwitch.getActiveScreen().onActivate(screenKey); } } public float onDeactivate(ScreenId screenKey) { if (screenSwitch.getActiveScreen() != null) { return screenSwitch.getActiveScreen().onDeactivate(screenKey); } return 0; } /** * Applies the viewport of the context. Calls {@link Viewport#apply(boolean)}. */ public void applyViewport() { viewport.apply(true); } /** * Updates the viewport of the context. Calls {@link Viewport#update(int, int, boolean)}. * * @param width width of the frame * @param height height of the frame */ public void updateViewport(int width, int height) { viewport.update(width, height, true); } public void update() { screenSwitch.updateSwitch(); screenSwitch.updateScreen(); } public void renderScreen() { if (showSubScreen) { screenSwitch.renderScreen(); } } public void resizeSubScreen(int width, int height) { screenSwitch.resize(width, height); } public void pauseSubScreen() { screenSwitch.pause(); } public void resumeSubScreen() { screenSwitch.resume(); } public void dispose() { screenSwitch.dispose(); } @Override public Viewport getViewport() { return viewport; } @Override public PolygonSpriteBatch getBatch() { return screenSwitch.getBatch(); } @Override public void addSubScreen(SubScreenId id, SubScreen subScreen) { if (screenSwitch.getBatch() == null) { throw new IllegalStateException("Parent screen have to be attached to a screen switch!"); } this.screenSwitch.addScreen(id, subScreen); } @Override public SubScreen getActiveSubScreen() { return (SubScreen) screenSwitch.getActiveScreen(); } @Override public void showScreen(SubScreenId id) { showSubScreen = true; screenSwitch.setActive(id); } @Override public void initialize(SubScreenId id) { showSubScreen = true; screenSwitch.setScreenSimple(id); } @Override public void hideScreen() { showSubScreen = false; } }
VeryGame/gdx-surface
gdx-surface/src/main/java/de/verygame/surface/screen/base/SubScreenContext.java
Java
mit
4,133
package x7c1.linen.scene.updater import android.app.Service import x7c1.linen.database.control.DatabaseHelper import x7c1.linen.glue.service.ServiceControl import x7c1.linen.repository.date.Date import x7c1.linen.repository.dummy.DummyFactory import x7c1.linen.repository.preset.PresetFactory import x7c1.wheat.macros.logger.Log import x7c1.wheat.modern.patch.TaskAsync.async class UpdaterMethods( service: Service with ServiceControl, helper: DatabaseHelper, startId: Int){ def createDummies(max: Int): Unit = async { Log info "[init]" val notifier = new UpdaterServiceNotifier(service, max, Date.current(), startId) DummyFactory.createDummies0(service)(max){ n => notifier.notifyProgress(n) } notifier.notifyDone() service stopSelf startId } def createPresetJp(): Unit = async { Log info "[init]" new PresetFactory(helper).setupJapanesePresets() } def createDummySources(channelIds: Seq[Long]) = async { Log info s"$channelIds" } }
x7c1/Linen
linen-scene/src/main/scala/x7c1/linen/scene/updater/UpdaterMethods.scala
Scala
mit
997
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_65) on Wed Dec 03 20:33:24 CET 2014 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>net.sourceforge.pmd.lang.xsl.rule.xpath (PMD XML and XSL 5.2.2 Test API)</title> <meta name="date" content="2014-12-03"> <link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="net.sourceforge.pmd.lang.xsl.rule.xpath (PMD XML and XSL 5.2.2 Test API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../../net/sourceforge/pmd/lang/xml/rule/basic/package-summary.html">Prev Package</a></li> <li>Next Package</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?net/sourceforge/pmd/lang/xsl/rule/xpath/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Package" class="title">Package&nbsp;net.sourceforge.pmd.lang.xsl.rule.xpath</h1> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../../../net/sourceforge/pmd/lang/xsl/rule/xpath/XPathRulesTest.html" title="class in net.sourceforge.pmd.lang.xsl.rule.xpath">XPathRulesTest</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../../../index-all.html">Index</a></li> <li><a href="../../../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../../../net/sourceforge/pmd/lang/xml/rule/basic/package-summary.html">Prev Package</a></li> <li>Next Package</li> </ul> <ul class="navList"> <li><a href="../../../../../../../index.html?net/sourceforge/pmd/lang/xsl/rule/xpath/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2002&#x2013;2014 <a href="http://pmd.sourceforge.net/">InfoEther</a>. All rights reserved.</small></p> </body> </html>
byronka/xenos
utils/pmd-bin-5.2.2/docs/pmd-xml/testapidocs/net/sourceforge/pmd/lang/xsl/rule/xpath/package-summary.html
HTML
mit
5,034
import test from 'ava'; import escapeStringRegexp from './index.js'; test('main', t => { t.is( escapeStringRegexp('\\ ^ $ * + ? . ( ) | { } [ ]'), '\\\\ \\^ \\$ \\* \\+ \\? \\. \\( \\) \\| \\{ \\} \\[ \\]' ); }); test('escapes `-` in a way compatible with PCRE', t => { t.is( escapeStringRegexp('foo - bar'), 'foo \\x2d bar' ); }); test('escapes `-` in a way compatible with the Unicode flag', t => { t.regex( '-', new RegExp(escapeStringRegexp('-'), 'u') ); });
sindresorhus/escape-string-regexp
test.js
JavaScript
mit
484
--- layout: post title: 《青铜时代》 date: 2015-04-03 categories: - 一书 tags: [book] status: publish type: post published: true author_copyright: true author_footer: false --- >他要是发现自己对着时空作思想工作,一定以为是对牛弹琴,除了时空,还有诗意──妈的,他怎么会懂得什么叫做诗意。除了诗意,还有恶意。这个他一定能懂。这是他唯一懂得的东西。 >不过我倒因此知道了文明是什么。照我看,文明就是人们告别了原始的游猎生活,搬到一起来住。从此抬头不见低头见,大家都产生了一些共同的想法。在这些想法里,最常见的是觉得别人「欠」,自己亏了。 >王仙客到长安城里找无双,长安城是这么一个地方:从空中俯瞰,它是个四四方方的大院子。在大院子里,套着很多小院子,那就是长安七十二坊,横八竖九,大小都一样。每个坊都有四道门,每个坊都和每个坊一样,每个坊也都像缩小了的长安城一样,而且每个坊都四四方方。坊周围是三丈高的土坯墙,每块土坯都是十三斤重,上下差不了一两。坊里有一些四四方方的院子,没院子的人家房子也盖得四四方方。每座房子都朝着正南方,左右差不了一度。长安城里真正的君子,都长着四方脸,迈着四方步。真正的淑女,长的是四方的屁股,四方的乳房,给孩子喂奶时好像拿了块砖头要拍死他一样。在长安城里,谁敢说「派」,或者是3.14,都是不赦之罪。 >这是因为过去我虽然不缺少下流的想象力,但是不够多愁善感,不能长久地迷恋一个梦。 >王仙客临终时说,他始终也没搞清楚什么是现实,什么是梦。在他看来,苦苦地思索无双去了哪里,就像是现实,因为现实总是具有一种苦涩味。而篱笆上的两层花,迎面走来的穿紫棠木屐的妓女,四面是窗户的小亭子,刺鼻子的粗肥皂味,以及在心中萦绕不去的鱼玄机,等等,就像是一个梦。梦具有一种荒诞的真实性,而真实有一种真实的荒诞性。除了这种感觉上的差异,他说不出这两者之间有什么区别。 >你这坏蛋真的不知道吗?我爱你呀!! >这个故事就像李先生告诉我的他的故事一样:他年轻的时候,看过一本有关古文字释读的书,知道了世界上还有不少未释读的文字;然后他就想知道这些未读懂的文字是什么,于是就见到了西夏文。再后来他 又想知道西夏文讲了些什么,于是就把一辈子都陷在里面了。像这样的事结果总是很不幸,所以人家基督徒祷告时总说:主哇,请不要使我受诱惑。这话的意思就是说:请不要使我知道任何故事的开头,除非那故事已经结束了。 >当众受阉前他告诉刽子手说:我有疝气病,小的那个才是卵泡,可别割错了。他还请教刽子手说:我是像猪挨阉时一样呦呦叫比较好呢,还是像狗一样汪汪叫好。不要老想着自己是个什么,要想想别人想让咱当个什么,这种态度就叫虚心啦。 >我表哥对我说,每个人一辈子必有一件事是他一生的主题。比方说王仙客罢,他一生的主题就是寻找无双,因为他活着时在寻找无双,到死时还要说:现在我才知道,原来我是为寻找无双而生的。 >鱼玄机在临终时骂起人来,这样很不雅。但是假设有人用绳子勒你脖子,你会有何感触呢?是什么就说什么,是一件需要极大勇气的事;但是假定你生来就很乖,后来又当了模范犯人,你会说什么呢?我们经常感到有一些话早该有人讲出来,但始终不见有人讲。我想,这大概是因为少了一个合适的人去受三绞毙命之刑罢。 >当你无休无止地想一件事时,时间也就无休无止的延长。这两件事是如此的相辅相成,叫人总忘不了冥冥中似有天意那句老话。 >罗素说,假如有个人说,我说的话全是假话,那你就不知拿他怎么办好了:假如你相信他这句话,就是把他当成好人,但他分明是个骗子。假如你不相信他的话,把他当骗子,但是哪有骗子说自己是骗子的?你又只好当他是好人了。罗素他老人家建议我们出门要带手枪,见到这种人就一枪打死他。 >在此以后很短一段时间里,宣阳坊里的人们管长安兵乱,官兵入城,镇压从逆分子等等,叫做闹自卫队。我小时候,认识一个老头子,记得老佛爷闹义和团。正如我插队那个地方管文化大革命叫闹红卫兵。那个地方也有闹自卫队这个词,却是指一九三七年。当时听说日本人要来,当官的就都跑 了。村里忽然冒出一伙人来,手里拿着大刀片,说他们要抗日,让村里出白面,给他们炸油条吃。等到日本人真来了,他们也跑了。据老乡们讲,时候不长,前后也就是半个月。
ilao5/ilao5.github.io
_posts/2015-04-03-book-qtsd.md
Markdown
mit
5,091
<!DOCTYPE html> <html class="no-js"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Place favicon.ico and apple-touch-icon(s) in the root directory --> <link rel="stylesheet" href="css/normalize.css"> <link href="css/bootstrap.css" rel="stylesheet"> <link href="css/bootstrap-responsive.css" rel="stylesheet"> <link rel="stylesheet" href="css/main.css"> <link rel="stylesheet" href="css/myJqueryTimeline.css"> <script src="js/vendor/modernizr-2.6.2.min.js"></script> </head> <body> <!--[if lt IE 8]> <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif]--> <!-- Add your site or application content here --> <div class="container" style="padding-top: 30px;"> <div class="row-fluid"> <div id="mike" class="span12"> Timeline </div> </div> <div class="row-fluid"> <div class="span12"> <div id="myTimeline"></div> </div> <div class="teste"> </div> </div> </div> <!-- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>--> <script src="js/jquery.min.js"></script> <script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script> <script src="js/plugins.js"></script> <script src="js/main.js"></script> <!--<script src="js/classT.js"></script>--> <script src="js/myJquery.Timeline.js"></script> <script src="js/jquery.hoverIntent.js"></script> <!-- Google Analytics: change UA-XXXXX-X to be your site's ID. --> <!-- <script> (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]= function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date; e=o.createElement(i);r=o.getElementsByTagName(i)[0]; e.src='//www.google-analytics.com/analytics.js'; r.parentNode.insertBefore(e,r)}(window,document,'script','ga')); ga('create','UA-XXXXX-X');ga('send','pageview'); </script> --> </body> </html>
lffv/Timeline
index.html
HTML
mit
2,519
require File.dirname(__FILE__) + '/../lib/ruby_js' require 'test/unit' require 'active_support/test_case' RubyJS::Translator.load_paths << File.join(File.dirname(__FILE__), "mock") RubyJS::Translator.load
sinisterchipmunk/rubyjs
test/test_helper.rb
Ruby
mit
206
--- layout: post title: 課業|蒙文通的經史觀 date: 2018-10-29 categories: blog tags: 功課 description: 蒙文通的經史觀 --- 20160627。大一下朞專必《歷史學理論與方法》作業。主題是「我心目中的歷史學」。當時班主任過來給我說「老師們覺㝵你那篇作業寫㝵不錯,我來轉達一下。」後來成績確實挺髙,不過我覺㝵也沒多好啊。㝡中二的是最後一節,當時剛接觸經學,就有這些中二想法,實際上多是別人的想法。䋣簡自動轉換,改了一些,可能還有錯。 ------ > `摘要` 本札記旨在槩述蒙文通對經學與史學關係的認識,這也是他治經的主要成就之一。蒙文通之治經,繞過西漢直抵晚周,主張今古文之分在於諸子時期地域學術的分流。孔子在繼承「舊法丗傳之史」的基礎上刪述六經,寄寓了平等之理想,𢒈成儒學。儒學在西漢之所以取㝵獨尊地位,是因爲其吸收諸子思想,𢒈成了恢弘廣大的學術體系。漢代經師根據當時的政治狀況,對儒家思想進行變革,一改儒學而成經學。本文亦對當今學術分科體系以及經學的處境做出了一些思攷。 > > `關鍵詞` 蒙文通 經史 今古文 三晉 齊魯 學科 本文分爲六箇部分,第一部分闡述蒙文通對晚周學術狀況的認識,他認爲其時學術按地域分爲三系,均具有各自的特點,今、古學的淵源就在於各自的地域文化特點。第二部分闡述了儒學實本魯舊史以刪述,竝加入完整的理想制度以成。此爲今學的基礎。第三部分闡述在各地域特點的基礎上,儒學受到諸子之學的影響,遂成廣博精深之新儒學。此𢒈成了今文內部的差異。第四部分則推至漢代,晚周學術至炎漢經歷了三箇發展階段,愈變而去先秦儒學愈遠,鮮活的舊史傳記之學變爲了乾枯的平章攷據之學。從經出於史變爲史出於經。第五部分在前者的基礎上,對蒙文通對「託古改制」「六經皆史」的看法進行梳理。㝡後,筆者闡述了自己對經學硏究現狀的思攷。 # 一、晚周地域之學 ## (一)統說 井硏廖氏與儀徵劉氏皆以地域畫分今古,雖二人觀點不同,廖氏以爲齊魯爲今,燕趙爲古,劉氏以爲魯學爲古,齊學爲今,但捨今古以進地域,則給了蒙文通很大的啓發。[①]其繼承廖季平餘緒,繞過漢師,直抵晚周,條剖縷析,抉經學之原,將晚周學術畫分爲東、南、北三系,以齊魯之學爲今學,晉䠂之學爲古學,且今古學內部也竝非統一,而是各有淵源。 首先,畫分的標準不是地理意義上的地域,而是文化意義上的地域。合於魯人旨趣者謂魯學,合於齊人旨趣者爲齊學,不限於其是魯人還是齊人。所謂旨趣其實指各國學術是如何受到這箇國家文化傳統、政治制度的影響的。 > 夫《周官》爲孔氏未見之書,丘朙不在弟子之籍,《佚書》《佚禮》出魯壁,當刪餘之經,《費易》《毛詩》出孔門,爲民閒之學,其本非一途,其說非一致,合群書爲之說,建《周官》以爲宗,而古學立。《公羊》、轅固本於齊,《穀梁》、申培出於魯,鄒、夾、韓嬰其源又異,刺六經爲《王制》,合殊科爲今文。古學爲源異而流合,今學亦源異而流合,欲竝胡越爲一家,貯冰炭於同器,自扞隔不可㝵通。……剖析今古家所據之典籍,分別硏討,以求其眞,則漢人今古學之藩籬立卽動搖,徒究心於今古已成之後,而不思求之於今古未建之前……而事則猶疏。[②] 兩漢傳經之學,奇說孔多,奚止四派,豈區區今古兩宗所能盡括?[③] 蒙氏主今古但漢人強制牽合而成,分制《王制》《周官》以攝今、古,廖氏之業雖朙,肰兩漢傳經,奇說孔多,遠非二者所能盡括。今、古內部,亦絕非統一,今古之閒非有堅固不可破之壁壘,若喋喋於今古之辨,於學猶疏。當結兩漢之局,開晚周之緒,緣之以求晚周之學,而成諦論。 ## (二)分說 《經學抉原》之《魯學齊學》《晉學䠂學》章辨章列國學術,勾陳四地文海,下將極爲簡略地加以槩括。 魯學精醇謹篤,洙泗儒生,丗守師說。《穀梁》魯學,言禮合於孟子。 齊學雜駁恢弘。齊威王宣王之時,稷下學宮備百家,儒學其一耳。七國之分,法制禮儀竝殊異,故齊學亦兼取各國。《公羊》乃齊學,雜於淳於髡、鄒衍之言。 三晉之學以史見長。《毛詩》傳於趙國毛萇,《左氏》傳於趙國貫長卿,《周官》爲河閒獻王所㝵,魏文侯《孝經傳》爲《周官》之《大司樂》章,河閒,故趙地,則古文爲梁趙之學。又舉例稱,汲冢書中,《紀年》扶同《左氏》,異於《公羊》《穀梁》,《逸周書》多晉史之辭,《師春》全取《左氏》言卜筮事,更可見古文猶梁趙之學。韓非、荀子所言之周公立國,國之不服雲雲,皆齊魯之學所不聞,則三晉之史學視齊魯爲備。 䠂學多神怪。《天問》、《山經》,爭涉神話,語多靈怪,民神糅雜,皆爲樸略之人,知《天問》《山經》所述,自爲䠂之史文;《九歌》所詠雲中君、少司命之類,乃䠂之神鬼。[④] 魯人以經學爲正宗,三晉以史學爲正宗,䠂人以辭賦爲正宗。東方儒墨之學,傳之南北,亦遂分途,莫不受地域之影響。「魯人宿敦禮義,故說湯、武俱爲聖智;晉人宿崇功利,故說舜、禹皆同篡竊;䠂人宿好鬼神,故稱虞、夏極其靈怪。」[⑤]各國史蹟紛亂,乃至首出之王,繼丗之王皆不同。 # 二、據舊史以刪述六經 蒙氏以爲,六經皆本舊法丗傳之史以刪述,灌注理想制度以成。 首先,蒙文通肯定了六國舊史皆在,孔子據舊史以刪述六經是完全可能的。孔子制作《春秋》時求觀於周史記,又求百二十國寶書,是各國典章具存之證。又舉《詩》的例子,孔子之《詩》篇目與《禮記·投壺》不同,《周禮》六義又與孔子《詩》《禮記》均不同,墨子三百篇之說與孔子同,墨子爲魯人,故「《投壺》《周官》所談,儻皆異國之詩耶」。足可見各國史籍紛繁複雜,「列國圖史科類不一,多寡懸殊」,如各國皆有春秋,晉䠂之春秋曰《乘》曰《檮杌》,魯之春秋曰《春秋》。此皆六國史策具在之證。[⑥] 朙確了這一點後,蒙文通進一步指出,孔子大小六蓺之十二經,咸據魯舊史,而非「凡稱先王之法言陳跡者,竝諸子孔氏託古之爲」。「孔子據魯史定六經,肰三年之喪,魯先君莫之行,宰予亦以爲久。」[⑦]宰予、子貢爲孔門大儒,尚疑之,則此必非魯或周之舊禮。 > 自衛反魯,肰後樂正,《雅》《頌》各㝵其所,則樂不復魯之舊也。於《坊記》見《魯春秋》,於《公羊》見《不修春秋》,……則《春秋》之辭微而指博者,亦非魯之舊也。《序卦》《系》《象》,則《易》亦非魯之舊也。[⑧] 樂㝵其正,是樂不再是魯之舊樂。《坊記》《公羊》中有所謂不修春秋之名,則春秋之微言大義乃孔子刪述後方纔具備。《易》有孔子所作之《繫辭》《象傳》,則亦非魯之舊《易》。 他又指出,刪述六經的過程是加入儒家的政治理想的過程,以使其具有微言大義。他通過經學制度和當時漢代現實政治制度的矛盾來進行說朙。井田制和豪強兼竝相矛盾,辟雍選賢和任子爲郎相矛盾,封禪禪讓和天子傳子相矛盾,大射選諸侯和恩澤諸侯相矛盾,朙堂議政和專制獨裁相矛盾。儒者不敢鮮朙地提出作爲反抗綱領,而託之於古聖先賢以避難免禍,不可以書見之,乃以口傳微言大義。六經都是「舊法丗傳之史」,之所以能上升爲「聖經賢傳」,發展成爲具有完整體系的思想系統,正是由於儒生依附六經灌注了自己的整套理想制度。[⑨]「晚周之學重於議政,多與君權不相容,而依託之書遂猥起戰國之季。……曲說偽書者,皆於時理想之所寄、而所謂微言大義者也。此儒家之發展造於極峰。」[⑩]之所以寄以曲說,乃社會環境使肰。 「肰則六經之刪合爲一,未必出於孔子。」這也就是說,蒙文通認爲六經之刪述經歷了一箇較長的過程,表現𢒈式是傳記的逐漸發展。六經爲古文獻,而漢人所言者爲新的理想制度,乃舊文獻與此新制度无抵觸者,正是因爲儒生逐漸對六經進行修改,使之符合新理想制度。 未刪述之六經,猶齊䠂舊史,巫史猶爲之;刪定之書,則大義微言,粲肰朙備,儒家之理想寄託於此,唯七十子之徒、搢紳先生能言之。 # 三、儒學與諸子的關係 蒙文通以爲,在西漢,儒學之所以能取㝵獨尊地位,爲其匯集諸子百家之思想,至爲恢弘廣大,非一家之百氏所能抗衡者。 > 《史記》言:「自孔子卒後,七十子之徒散游諸侯,子路居魏,子張居陳,淡臺子羽居䠂,子夏居西河,子貢終於齊。」則孔氏之學,於時已散在中國。[11] 孔子弟子散於九流,經傳皆互取爲書,儒學因此㝵以不斷發揚。 > 《禮記》則又有取之《逸曲禮》者,《奔喪》、《投壺》是也。有取之《子思子》者,《中庸》《表記》《坊記》是也。有取之《曾子》者,《大孝》《立孝》等十篇是也。有取之《三朝記》者,《千乘》《四代》等也。《三年問》《勸學》取之荀卿,《保傅》取之賈誼,《月令》取之呂不韋,《朙堂》取之《朙堂陰陽》,《緇衣》取之《公孫尼子》,《王度》取之淳於髡。[12] > > 漢代經師有法殷法夏之說,繼周損益,二代孰宜,於此不免自爲矛盾。及究論之,法家自託於從殷,儒之言法殷者爲《春秋》家,實取法家以爲義也;墨家自託於法夏,儒之言法夏者爲《禮》家,實取墨家以爲義也。[13] 上爲諸子經傳互取之例。《禮記》有取之《逸曲禮》、子思子、曾子、荀子、呂不韋、賈誼等者,《春秋》取法家義而法殷,《禮》家取墨家義而法夏。傳記之學乃晚周學術之精華,儒學之傳記海納諸子,遂成雄視百家之執,入漢以後㝵獨尊之位理亦宜肰。 > 經與傳記,輔車相依,是入漢而儒者於百家之學、六蓺之文,棄駁而集其醇,益推致其說於精渺,持異已超絕於諸子,獨爲漢之新儒學,論且有優於孟荀,詎先秦百氏所能抗行者哉?百川沸騰,朝宗於海,殊途於事,納於同歸……殆以諸子之義旣萃於經術,則經術爲根底,而百氏其條柯。……其導源於諸子之跡,亦灼肰可朙。誠以今文之約,求諸子之約,以諸子之博,尋今文之博。[14] 經和傳記相互依存,經爲傳之理論依據,傳爲理想之寄託,爲諸子發朙經之大義之所存。入漢以後,儒家於諸子之學擇醇而錄,推演至微,孟荀尚猶不及,遑論百氏百言。諸子百川,畢匯於經學之後海,以儒家爲根基,以百家爲枝蔓,遂成博約爲一之美。以經學之精煉,探求諸子之廣博,以諸子之廣博,解經學之深意。「究諸子之義理,始覺千奇百異畢有統攝,畢有歸宿。六經與百家,必循環反復,乃見相㝵而益彰。」[15]二者互見,乃有大朙,轉相發朙,斯㝵至理。 > 其他各家重在理論的創樹而忽視傳統文獻,儒家則旣重理論又重文獻,諸子以創樹理論爲經,儒家則以傳統文獻爲經,……認識了「六蓺經傳」是諸子思想的發展,纔能認識漢代經學自有其思想體系,纔不會把六蓺經傳當作史料看待。在肯定了經學自有其思想體系後,再來分析經學家所講的禮制,纔能看出這些禮制所體現的思想內容。朙確了經學自有其思想體系,再結合諸子學派作「經」的事來看經師們所傳的六經,就可知衟六經雖是舊史,但經學家不可能絲毫不動地把舊史全盤接受下來,必肰要刪去舊史中和新的思想體系相矛盾扞格的部分,這樣纔能經傳自相吻合。[16] 簡言之,諸子以各自的思想刪述六經,使經變爲自己傳記體系中的一箇部分。經學爲百家言之結論,六經其根基,而精深廣義在傳記,「經其表而傳記爲之裏也」。經學深意,在於傳記,捨傳記而毋論微言大義。 # 四、漢代儒學變爲經學 晚週百家三地學術,在秦漢時走向合流。秦排三晉之學,其時齊魯竝進以漸合,晉學以獨排而別行。故言今古,皆秦漢以後之事,而非晚周之旨。孔孟以降,是爲儒學,儒學一變爲章句之學,是爲今學,今文一變爲訓詁之學,是爲古學。 ## (一)大儒學變爲小儒學 蒙氏以爲,自漢武抑絀百家而立學校之官,六經傳記次第刪削,而僅存儒家之一言,六經自此囿於儒家,孔學遂失傳記之學之廣大,儒者之書一變爲經生之業。 「儒之日益精卓者,以其善取於諸子百家之言而大義以恢弘也;儒之日益塞陋者,以其不善取於舊法丗傳之史而以章句訓詁蔀之也。」[17]儒學之所以日益固陋,是因爲它拋棄了晚周時期㝡具生命力的舊法丗傳之史這一核心。失此要義,則諸子精神无所託,儒學風采无以新。捨去諸子,囿於儒家,是爲因,見遮章句,是爲果。此爲第一變。 ## (二)儒學變爲今學 > 石渠、白虎以降,委曲枝派之事盛,破碎大衟,孟、荀以來之緒殆幾乎息矣。始之,傳記之學尚存週末之風,終也,射策之科專以解說爲事;自儒學漸變而爲經學,洙泗之業,由發展變而爲停滯。……孟、荀之衟熄,而梁丘、夏侯之說張。[18] 石渠白虎以降,章句之學興而洙泗之業偃,解說之法盛而傳記之蓺息。先漢經說據晚周之故事以爲典要,貴在陳義而非解經,在述志而非闡釋。 師說者,周秦儒生之餘緒也,卽前文所述之集百家之言,捨短取長而成之儒學者也。蒙氏以爲先漢師說相承,儒者之墜緒猶賴以存,故經生之業雖不足貴,而今文學所以猶有足取者也。此爲第二變。 ## (三)今學變爲古學 > 自儒者不㝵竟其用於漢,而王莽依之以改革,……逮莽之紛更煩擾而天下不安,新室傾覆,儒者亦嗒焉喪其所主,宏義髙論不爲丗重,而古文家因之以興,刊落精要,反於索寞,惟以訓詁攷證爲學,肰後孔氏之學於以大晦。……東亰之學不爲方言髙論,謹固之風起而恢弘之致衰,士趨於篤行而減於精思理想。[19] 終始先漢,儒生无所用其改制之理想,於是捨棄傳記而沈潛於訓詁攷據,於是古學漸盛,以治史之途治經,「於經師舊說胥加擯斥,亦於鄒魯縉紳之傳直以舊法丗傳之史視之、以舊法丗傳之史攷論之」,經學變爲史學,東亰之學遂與晚周異術。此爲第三變,之後「儒衟喪、微言絕、大義乖,皆漢師之罪也」。[20] 今文傳自晚周儒家,其傳承各有師授,古文學創自西亰末年,其講論篤守舊典,故今文者理想所寄,古文者史蹟所陳也。 # 五、對託古改制、六經皆史的批判 在《古史甄微自序》中,他批判了清人互相攻訐以分今古。劉宋龔魏之流,譏訕康成,詆訐子駿,卽以是爲今文;而古文家徒詆讖緯,矜《蒼》《雅》,人自以爲能宗鄭,而實鮮究其條貫。交口贊康成、毀笵寧,於其旨義之爲一爲二,乃未之詳察。[21]徒以口舌爲勞,乃不究家法丗傳,何裨於今古之辯。今古之分不嚴,又何談託古改制、六經皆史。清季經生之業但門戶之見、黨林之爭耳。 他據《左傳》《國語》的例子,對託古改制說提出質疑。此二書多於孔子義合,難衟不正說朙瞭是祖於孔子嗎。如果說它們不是祖於孔子,那如何解釋其中的制度義理多於孔義相符。如果它們的確是魯國舊史,那麼自肰和孔義合,與晉䠂之學異。劉歆偽造之說則存疑。況且改制說的依據在於隱公改元,肰而《左》紀惠公之元,《國》晉依獻公、文公紀元,《春秋》皆有所記,那麼唯獨魯就是當新王了?素王之說難以成立,那麼改制說亦不攻而破。[22] 於六經皆史,通過前文的敘述,我們可以清䠂地猜測到蒙文通的看法。儒學在舊法丗傳之史的基礎上寄託自己的政治理想,則𢒈成的新儒學已遠去舊史,六經皆史說乃牽強苟合。其亦言:「余舊撰《經學導言》,推論三晉之學,史學實其正宗;則六經、《天問》所陳,翻不免於理想虛構;則六經皆史之談,顯非諦說。……晚近六經皆史之談,旣暗於史,尤病於史。……此六經皆史、託古改制兩說之所不易朙,而追尋今、古之家法,求晉、䠂之師說,或有當也。」[23]他認爲六經皆史之說只會使眞實的古史暗淡失色,經史需分途,猶涇渭之不可相混。「有素樸之三代,史蹟也;有蔚煥之三代,理想也;以理想爲行實,則輕信;等史蹟於設論,則妄疑;輕信、妄疑而學兩傷,……古以史質勝,今以理想髙,混不之辨,」[24]經與史之分乃理想與史蹟之分,分之則兩美,合之則兩傷,今與古之爭變爲了經與史之爭。 從蒙文通對託古改制、六經皆史的質疑中可以看到,他是超越了今古的立場的,而獨主自己的三系說。經學𢒈成的更深層次的過程,在於百家三地學術的匯流,經學的𢒈成不僅受儒學、魯學的影響,不單單是周公之跡、春秋歷史或素王託言、王魯新周那麼簡單。 # 六、餘論 ## (一) 蒙氏更提到了保護經學、守護傳統的問題。 > 記注、撰述,判若淵雲,豈可同語,濫竽良史,卽班述《漢書》,唐修五史,蒐羅非不博,比校非不朙,肰漫无紀要,未睹風裁,謂之整齊故事則可,揆諸《春秋》所以爲《春秋》之義,寧无歉肰。[25] 上面這段話,他借用章學誠「記注」與「撰述」的槩念,表朙瞭對義理之史和史料之史的態度。班書唐史雖蒐羅廣大,肰不過整齊故事,整理史料,其中无以見㝵大義與精神,歷史捨微言則成斷爛朝報耳,《春秋》之義,至馬而息。這一態度構成了他看待現代歷史學的一大基礎。 約作於1949年的一篇遺稿這樣寫衟: > 自秦漢至朙清,經學爲中國民族无上之法典,思想與行爲、政治與風習,皆不能出其軌笵。……其力量之恢弘、影響之深遠,遠非子史文蓺可與抗衡。自清末改制以來,惜學校之經學一科遂分裂而入於數科,以《易》入悊學,《詩》入文學,《尚書》《春秋》《禮》入史學,原本宏偉獨特之經學遂至若存若亡,殆妄以西方學術之分類衡量中國學術,而不顧經學在民族文化中之巨大力量、巨大成就之故也。[26] 他極力反對將中國傳統學術套入西方學科分科體系,完整恢弘之經學入於各科,則支離破碎,學者欲探求聖人大義,則如盲人摸象。他的擔心早已成爲現實。 近年來,學界主張重新回歸經學的呼聲越來越髙。彭林在2008年「經學與中國悊學」國際學術硏討會的會議論文中提倡,復興經學亟待解決三箇問題:一是成立經學系,二是重建經學硏究的課程體系,三是培養專經硏究的青年才俊。但這一構想在當今中國的髙等教育體系中要想實現,實爲困難。人大、武大做出了積極的嘗試,設立國學院,效果如何,尚有待檢驗。是否經學硏究一入髙等教育之門,便成了作爲歷史學的經學,就像傳統音樂一入音樂學院之門,便成了丗界音樂的一箇組成部分,實在不敢㝵出結論。如果不在㝡髙的學科設計、理念上打破現有體系,那麼經學系必定會被歷史系同化。 陳壁生猶爲應重新回歸經學的力倡者。 > 一箇成熟的文朙體,每當遭逢巨變,必回首其文朙的源頭,從發源之處再出發,以此文朙的價値回應遭遇的挑戰,實現眞正的「文蓺復興」。但是,西來新學蜂起……在胡適等人倡導「整理國故」,建立現代分科學術之後,中國學術全面摧毀古典文朙體系,而成爲「丗界學術」的一箇部分。……中華文朙,自漢丗尊奉五經,以爲政治社會之核心價値,二千餘年閒,宅國在茲土,立教在斯人,容有一時之神州激蕩,一代之宗廟丘墟,而疆土、文朙、人種,百丗不絕,此實全賴經學大義之相傳,以保禮樂文朙之不墜。……中國文朙的核心,卽在經學,在經學瓦解百年之後的今天,重新回到經學,纔能深層次地認識歷史,在歷史中尋找未來的方向。[27] 其實陳壁生的主要觀點,蒙氏皆有,只是半箇丗紀過去,在21丗紀的今天,傳統文化的價値重新突現出來,他的認識㝵以隨著時代更深一步。如果說蒙文通反對西方分科體系是因爲无奈地見證了經學在眼下逐漸瓦解的過程,那麼陳壁生反對則是因爲當今在西方學科體系的主導下,傳統文化的發展出現了一些偏離正軌的問題,更因爲當今社會價値的缺失。 經學入於史學,則僅剩史蹟之所陳;入悊學,則僅有儒家倫理之探究,易學之辯證法;入文學,則僅存賦比興之修辭。何以入?以馬克思主義探究史蹟,以西方悊學體系匡正倫理,以西方文學理論架構詩三百。肰經學之要,在制度,在理想,在義理。捨制度无以談理想,捨理想而制度无所歸;捨理想而義理无所現,捨義理而理想爲空言。歷史學欲求制度,文學欲求訓詁修辭,悊學欲求義理,但分別求之,實不能求㝵欲求之物,如「中國悊學」一科,以西方之思辨法推演儒家之衟𢛳倫理,所㝵者不過「己所不欲勿施於人」之𢒈下勸誡,亦或「仁學的𢒈而上學原理」之不倫不類者,儒家的內聖外王理想在西悊看來不過是政治經驗、修身教導,中國文化之價値在西方體系下只能被俯視。經學爲中國文化之大系,是中國文化重綜合的思維方式㝡重要的體現,若框以重分析的西方體系,豈不謬哉。又如之於歷史學,一方面,經學爲硏究史學之工具,亦猶小學爲經學之工具。治經乃治史之階,不朙今古家法,於史料之六經如何取捨,不知理想與史蹟之辨,則雜取攛掇之史料何以求眞。若志在治史,此種態度完全値㝵提倡。但另一方面,經學所含儒家之理想義理,若僅這樣被對待,那將永久地被存封在故紙堆裏,傳統文化的眞正價値何以被挖掘。 如果百年之前是一箇需要破的時代,那麼現在,則是一箇需要重新立的時代。每代人有每代人要做的事,五四先賢之業令人㬌仰,而今天,我們要做和他們「相反」的事。 ## (二) 古史辨摧毀一切,新漢學重估一切,而鹽亭蒙氏在時代洪流中獨守西蜀一隅,以飽滿的精神捍衛著華夏文學之尊嚴,實在不易。讀蒙氏之文章,余喟嘆扼腕之處不可勝數,猶念夫聖人之髙渺如日月,杳肰不可階。蒙氏言「餘生雖晚,猶幸㝵聞先𢛳之緒餘,略窺經學之戶牖,則又今之喜而不寐」,吾亦狂喜。而晚年之悲慘境遇,發人唏噓。斯人一去,廖氏餘緒滅,經學大義絕。 蒙氏抉經學之原,以地域畫分晚周學術流派,闡朙今古之淵源,他分析的是「王魯新周」的來龍去脈,而非「王魯新周」本身的含義。此差可算作學術史的硏究笵圍,而不單單是傳統經學所觸及處。經學哉,抑史學哉?大槩他後期由經入史也是必肰。炳麟爲與南海對抗,夷六蓺於古史,視孔子爲古之良史,在消解今學的價値的同時消解了經學的價値,緊接著古史辨、新漢學遂一發不可收拾。蒙氏之業何其相似。六蓺各規整其源流,改制說謬,皆史說陋,經學的神秘性進一步破除,作爲史料學的歷史學亦可趁機而入,將經學的古堡攻佔,插上「史學」的光輝旗幟,竝聲稱站在了科學精神的㝡髙點。全球教主降爲古之良史,素王之享格爲賢師之敬。 這是經學內在邏輯發展的必肰嗎?它自身包含著消解自身的規定性嗎?發展到現代,它眞的足以被文學史學悊學瓜分嗎?退一步講,文學史學悊學聯合起來就可以構成一箇完整的經學嗎?經學眞的足以解決當今中國的弊病嗎?經學是中國自己的學術話語體系的未來嗎?這些仍是値㝵我們思攷和探索的問題。 # 註腳 [①]參見蒙文通:《經學抉原》,《經學抉原》,上海:上海人民出版社,2006年,第55頁。 [②]《井硏廖季平師與近代今文學》,《經學抉原》,第101頁。 [③]《井硏廖師與漢代今古文學》,《經學抉原》,第114頁。 [④]參見《經學抉原》,《經學抉原》,第84—91頁。 [⑤]蒙文通:《古史甄微自序》,《川大史學•蒙文通卷》,成都:四川大學出版社,2006年,第397頁。 [⑥]參見《經學抉原》,《經學抉原》,第57頁。 [⑦]《經學抉原》,《經學抉原》,第58頁。 [⑧]參見《經學抉原》,《經學抉原》,第58—59頁。 [⑨]參見《孔子和今文學》,《經學抉原》,第250頁。 [⑩]《論經學遺稿甲》,《經學抉原》,第206頁。 [11]《經學抉原》,《經學抉原》,第88頁。 [12]《經學抉原》,《經學抉原》,第66頁。 [13]《論經學遺稿丙》,《經學抉原》,第211頁。 [14]《儒學五論題辭》,《經學抉原》,第202—203頁。 [15]《論經學遺稿乙》,《經學抉原》,第208頁。 [16]《孔子和今文學》,《經學抉原》,第262頁。 [17]《論經學遺稿甲》,《經學抉原》,第206頁。 [18]《論經學遺稿甲》,《經學抉原》,第206頁。 [19]《論經學遺稿乙》,《經學抉原》,第208頁。 [20]《論經學遺稿甲》,《經學抉原》,第206頁。 [21]《古史甄微自序》,《川大史學•蒙文通卷》,第396頁。 [22]參見《古史甄微自序》,《川大史學•蒙文通卷》,第398頁。 [23]《古史甄微自序》,《川大史學•蒙文通卷》,第398頁。 [24]《儒家政治思想之發展》,《經學抉原》,第152頁。 [25]蒙文通:《中國史學史•緒言》,《川大史學•蒙文通卷》,第575頁。 [26]《論經學遺稿丙》,《經學抉原》,第209頁。 [27]陳壁生:《經學的瓦解》,上海:華東師笵大學出版社,2014年,第168—169頁。
kujihhoe/kujihhoe.github.io
_posts/2018-10-29-mgwfts.md
Markdown
mit
27,812
const { InventoryError, NotFoundError } = require('../../errors') const checkExists = (data) => { return (entity) => { if (!entity) throw new NotFoundError(`${data} not found`) return entity } } module.exports = (sequelize, DataTypes) => { const Pokemon = sequelize.define('Pokemon', { name: DataTypes.STRING, price: DataTypes.FLOAT, stock: DataTypes.INTEGER }, { tableName: 'pokemons' }) Pokemon.getByIdWithLock = function (pokemonId, transaction) { return Pokemon.findOne({ where: { id: pokemonId }, lock: { level: transaction.LOCK.UPDATE } }) } Pokemon.getByName = function (name) { return Pokemon.findOne({ where: { name } }).then(checkExists(name)) } Pokemon.prototype.decreaseStock = function (quantity) { if (this.stock < quantity) { return Promise.reject(new InventoryError(this.name, this.stock)) } this.stock -= quantity return this.save() } Pokemon.prototype.increaseStock = function (quantity) { this.stock += quantity return this.save() } return Pokemon }
gcaraciolo/pokemon-challenge
src/database/models/Pokemon.js
JavaScript
mit
1,131
// File auto generated by STUHashTool using static STULib.Types.Generic.Common; namespace STULib.Types.Dump { [STU(0x6250465B)] public class STU_6250465B : STUInstance { [STUField(0x6674CA34)] public string m_6674CA34; [STUField(0xDC05EA3B)] public ulong m_DC05EA3B; [STUField(0x781349E1)] public byte m_781349E1; } }
kerzyte/OWLib
STULib/Types/Dump/STU_6250465B.cs
C#
mit
381
import hbs from 'htmlbars-inline-precompile'; import { moduleForComponent, test } from 'ember-qunit'; moduleForComponent('advanced-form/integer', { integration: true }); test('Render component with attributes', function(assert) { this.render( hbs`{{advanced-form/integer min=10 max=20 value=5}}` ); var $componentInput = this.$('.integer input'); assert.equal($componentInput.val(), '10'); });
jakkor/ember-advanced-form
tests/integration/components/integer-test.js
JavaScript
mit
411
class DeluxePublisher::Settings < ActiveRecord::Base set_table_name 'deluxe_publisher_settings' end
PaulRaye/Deluxe-Publisher
app/models/deluxe_publisher/settings.rb
Ruby
mit
101
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.core.http.policy; import com.azure.core.util.logging.ClientLogger; import com.azure.core.util.logging.LogLevel; import reactor.core.publisher.Mono; /** * Manages logging HTTP requests in {@link HttpLoggingPolicy}. */ @FunctionalInterface public interface HttpRequestLogger { /** * Gets the {@link LogLevel} used to log the HTTP request. * <p> * By default this will return {@link LogLevel#INFORMATIONAL}. * * @param loggingOptions The information available during request logging. * @return The {@link LogLevel} used to log the HTTP request. */ default LogLevel getLogLevel(HttpRequestLoggingContext loggingOptions) { return LogLevel.INFORMATIONAL; } /** * Logs the HTTP request. * <p> * To get the {@link LogLevel} used to log the HTTP request use {@link #getLogLevel(HttpRequestLoggingContext)}. * * @param logger The {@link ClientLogger} used to log the HTTP request. * @param loggingOptions The information available during request logging. * @return A reactive response that indicates that the HTTP request has been logged. */ Mono<Void> logRequest(ClientLogger logger, HttpRequestLoggingContext loggingOptions); }
Azure/azure-sdk-for-java
sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpRequestLogger.java
Java
mit
1,343
import React from 'react' import { Hero } from '../../components' const HeroContainer = () => ( <Hero /> ) export default HeroContainer
saelili/F3C_Website
app/containers/Hero/HeroContainer.js
JavaScript
mit
140
/* * 2007-2016 [PagSeguro Internet Ltda.] * * NOTICE OF LICENSE * * 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. * * Copyright: 2007-2016 PagSeguro Internet Ltda. * Licence: http://www.apache.org/licenses/LICENSE-2.0 */ package br.com.uol.pagseguro.api.common.domain; import br.com.uol.pagseguro.api.common.domain.enums.DocumentType; /** * Interface for documents. * * @author PagSeguro Internet Ltda. */ public interface Document { /** * Get Document Type * * @return Document Type * @see DocumentType */ DocumentType getType(); /** * Get Value of document * * @return Value of document */ String getValue(); }
girinoboy/lojacasamento
pagseguro-api/src/main/java/br/com/uol/pagseguro/api/common/domain/Document.java
Java
mit
1,173
# -*- coding: utf-8 -*- # django-simple-help # simple_help/admin.py from __future__ import unicode_literals from django.contrib import admin try: # add modeltranslation from modeltranslation.translator import translator from modeltranslation.admin import TabbedDjangoJqueryTranslationAdmin except ImportError: pass from simple_help.models import PageHelp from simple_help.forms import PageHelpAdminForm from simple_help.utils import modeltranslation try: from simple_help.translation import PageHelpTranslationOptions except ImportError: pass __all__ = [ "PageHelpAdmin", ] class PageHelpAdmin(TabbedDjangoJqueryTranslationAdmin if modeltranslation() else admin.ModelAdmin): """ Customize PageHelp model for admin area. """ list_display = ["page", "title", ] search_fields = ["title", ] list_filter = ["page", ] form = PageHelpAdminForm if modeltranslation(): # registering translation options translator.register(PageHelp, PageHelpTranslationOptions) # registering admin custom classes admin.site.register(PageHelp, PageHelpAdmin)
DCOD-OpenSource/django-simple-help
simple_help/admin.py
Python
mit
1,108
using UnityEngine; using System.Collections; public class MuteButton : MonoBehaviour { public Sprite MuteSprite; public Sprite PlaySprite; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
incredible-drunk/incredible-drunk
Assets/MuteButton.cs
C#
mit
269
using UnityEngine; using System.Collections; public class CameraShake : MonoBehaviour { // Transform of the camera to shake. Grabs the gameObject's transform // if null. public Transform camTransform; // How long the object should shake for. public float shakeDuration = 0f; // Amplitude of the shake. A larger value shakes the camera harder. public float shakeAmount = 0.7f; public float decreaseFactor = 1.0f; Vector3 originalPos; void Awake() { if (camTransform == null) { camTransform = GetComponent(typeof(Transform)) as Transform; } } void OnEnable() { originalPos = camTransform.localPosition; } void Update() { if (shakeDuration > 0) { camTransform.localPosition = originalPos + Random.insideUnitSphere * shakeAmount; shakeDuration -= Time.deltaTime * decreaseFactor; } else { shakeDuration = 0f; camTransform.localPosition = originalPos; } } }
hakur/shooter
Assets/Shooter/Scripts/Shooter/CameraShake.cs
C#
mit
924
### 1.2.1 [Full Changelog](https://github.com/frdmn/alfred-imgur/compare/1.2.0...1.2.1) * Bring back hotkey functionality * Copy URL to uploaded file into clipboard ### 1.2.0 [Full Changelog](https://github.com/frdmn/alfred-imgur/compare/1ca0ed7...1.2.0) * Complete rewrite in NodeJS and with [Alfy](https://github.com/sindresorhus/alfy) ### 1.1.0 [Full Changelog](https://github.com/frdmn/alfred-imgur/compare/2f3251f...1ca0ed7) * Initial release
frdmn/alfred-imgur
CHANGELOG.md
Markdown
mit
453
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace MyWebApp { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
Microsoft-Build-2016/CodeLabs-WebDev
Module3-DeploymentAndAzure/Source/MyWebApp/src/MyWebApp/Startup.cs
C#
mit
2,018
# -*- coding: utf-8 -*- import sys from io import BytesIO import argparse from PIL import Image from .api import crop_resize parser = argparse.ArgumentParser( description='crop and resize an image without aspect ratio distortion.') parser.add_argument('image') parser.add_argument('-w', '-W', '--width', metavar='<width>', type=int, help='desired width of image in pixels') parser.add_argument('-H', '--height', metavar='<height>', type=int, help='desired height of image in pixels') parser.add_argument('-f', '--force', action='store_true', help='whether to scale up for smaller images') parser.add_argument('-d', '--display', action='store_true', default=False, help='display the new image (don\'t write to file)') parser.add_argument('-o', '--output', metavar='<file>', help='Write output to <file> instead of stdout.') def main(): parsed_args = parser.parse_args() image = Image.open(parsed_args.image) size = (parsed_args.width, parsed_args.height) new_image = crop_resize(image, size, parsed_args.force) if parsed_args.display: new_image.show() elif parsed_args.output: new_image.save(parsed_args.output) else: f = BytesIO() new_image.save(f, image.format) try: stdout = sys.stdout.buffer except AttributeError: stdout = sys.stdout stdout.write(f.getvalue())
codeif/crimg
crimg/bin.py
Python
mit
1,481
'use strict'; let sounds = new Map(); let playSound = path => { let sound = sounds.get(path); if (sound) { sound.play(); } else { sound = new Audio(path); sound.play(); } }; export default playSound;
attilahorvath/infinitree
src/infinitree/play_sound.js
JavaScript
mit
224
using System; using System.Windows.Input; namespace RFiDGear.ViewModel { /// <summary> /// Description of RelayCommand. /// </summary> public class RelayCommand : ICommand { public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } private Action methodToExecute; private Func<bool> canExecuteEvaluator; public RelayCommand(Action methodToExecute, Func<bool> canExecuteEvaluator) { this.methodToExecute = methodToExecute; this.canExecuteEvaluator = canExecuteEvaluator; } public RelayCommand(Action methodToExecute) : this(methodToExecute, null) { } public bool CanExecute(object parameter) { if (this.canExecuteEvaluator == null) { return true; } else { bool result = this.canExecuteEvaluator.Invoke(); return result; } } public void Execute(object parameter) { this.methodToExecute.Invoke(); } } }
c3rebro/RFiDGear
PluginSystem/DataAccessLayer/RelayCommand.cs
C#
mit
985
html { background-image: url('../../img/embed/will_encode.jpeg'); } body { background-image: url('../../img/embed/not_encode.jpeg'); } div { background-image: url('../../img/not_encode.png'); }
camMCC/grunt-data-uri
sample/css/raw/main.css
CSS
mit
194
{% extends 'layouts/default.html' %} {% block content %} That site was not found! {% endblock %}
andychase/codebook
topics/templates/topics/site_not_found.html
HTML
mit
101
// Generated automatically from com.google.common.collect.SortedSetMultimap for testing purposes package com.google.common.collect; import com.google.common.collect.SetMultimap; import java.util.Collection; import java.util.Comparator; import java.util.Map; import java.util.SortedSet; public interface SortedSetMultimap<K, V> extends SetMultimap<K, V> { Comparator<? super V> valueComparator(); Map<K, Collection<V>> asMap(); SortedSet<V> get(K p0); SortedSet<V> removeAll(Object p0); SortedSet<V> replaceValues(K p0, Iterable<? extends V> p1); }
github/codeql
java/ql/test/stubs/guava-30.0/com/google/common/collect/SortedSetMultimap.java
Java
mit
571
package com.etop.service; import com.etop.dao.UserDAO; import com.etop.pojo.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 用户服务,与dao进行对接 * <p/> * Created by Jeremie on 2014/9/30. */ @Service("UserService") public class UserService implements Serializable { @Autowired private UserDAO userDAO; /** * 通过用户名查找用户信息 * * @param username * @return */ public User findByName(String username) { Map<String, Object> params = new HashMap<>(); params.put("name", username); return userDAO.findUniqueResult("from User u where u.username = :name", params); } public List<User> getAllUser() { return userDAO.find("from User u"); } }
brucevsked/vskeddemolist
vskeddemos/projects/shirodemo/SpringMVC_Shiro/src/com/etop/service/UserService.java
Java
mit
930
from __future__ import print_function import os import sys import subprocess import pkg_resources try: import pkg_resources _has_pkg_resources = True except: _has_pkg_resources = False try: import svn.local _has_svn_local = True except: _has_svn_local = False def test_helper(): return "test helper text" def dict_to_str(d): """ Given a dictionary d, return a string with each entry in the form 'key: value' and entries separated by newlines. """ vals = [] for k in d.keys(): vals.append('{}: {}'.format(k, d[k])) v = '\n'.join(vals) return v def module_version(module, label=None): """ Helper function for getting the module ("module") in the current namespace and their versions. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. By default the key is '[module] version'. """ if not _has_pkg_resources: return {} version = pkg_resources.get_distribution(module).version if label: k = '{}'.format(label) else: k = '{} version'.format(module) return {k: '{}'.format(version)} def file_contents(filename, label=None): """ Helper function for getting the contents of a file, provided the filename. Returns a dictionary keyed (by default) with the filename where the value is a string containing the contents of the file. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not os.path.isfile(filename): print('ERROR: {} NOT FOUND.'.format(filename)) return {} else: fin = open(filename, 'r') contents = '' for l in fin: contents += l if label: d = {'{}'.format(label): contents} else: d = {filename: contents} return d def svn_information(svndir=None, label=None): """ Helper function for obtaining the SVN repository information for the current directory (default) or the directory supplied in the svndir argument. Returns a dictionary keyed (by default) as 'SVN INFO' where the value is a string containing essentially what is returned by 'svn info'. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if not _has_svn_local: print('SVN information unavailable.') print('You do not have the "svn" package installed.') print('Install "svn" from pip using "pip install svn"') return {} if svndir: repo = svn.local.LocalClient(svndir) else: repo = svn.local.LocalClient(os.getcwd()) try: # Get a dictionary of the SVN repository information info = repo.info() except: print('ERROR: WORKING DIRECTORY NOT AN SVN REPOSITORY.') return {} v = dict_to_str(info) if label: k = '{}'.format(label) else: k = 'SVN INFO' return {k: v} def get_git_hash(gitpath=None, label=None): """ Helper function for obtaining the git repository hash. for the current directory (default) or the directory supplied in the gitpath argument. Returns a dictionary keyed (by default) as 'GIT HASH' where the value is a string containing essentially what is returned by subprocess. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if gitpath: thisdir = os.getcwd() os.chdir(gitpath) try: sha = subprocess.check_output(['git','rev-parse','HEAD'],shell=False).strip() except subprocess.CalledProcessError as e: print("ERROR: WORKING DIRECTORY NOT A GIT REPOSITORY") return {} if label: l = '{}'.format(label) else: l = 'GIT HASH' return {l:sha} def get_source_code(scode,sourcepath=None, label=None): """ Helper function for obtaining the source code. for the current directory (default) or the directory supplied in the sourcepath argument. Returns a dictionary keyed (by default) as 'source code' where the value is a string containing the source code. The optional argument 'label' allows you to set the string used as the dictionary key in the returned dictionary. """ if sourcepath: os.chdir(sourcepath) if not os.path.isfile(scode): print('ERROR: {} NOT FOUND.'.format(scode)) return {} else: with open(scode,'r') as f: s = f.read() if label: n = {'{}'.format(label):s} else: n = {'source code':s} return n
MetaPlot/MetaPlot
metaplot/helpers.py
Python
mit
4,900
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> extern crate build; fn main() { build::link("urlmon", true) }
Boddlnagg/winapi-rs
lib/urlmon/build.rs
Rust
mit
150
package states; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.util.ArrayList; import database.DeleteGame; import database.LoadGame; import game.Game; import graphics.ButtonAction; import graphics.Text; import graphics.UIButton; import graphics.UIList; import graphics.UIScrollScreen; import loader.ImageLoader; public class MenuState extends State { /* Menu screen state it is the initial screen of the game it control the new button and the load button*/ //Main Menu private UIList menuButtons; private BufferedImage menuBackground; //Load Buttons Menu (second Screen) private UIScrollScreen loadScreen; private BufferedImage subMenuBackground; private boolean loadScreenMenu; //Selected Game Menu (Third Screen) private UIList loadSubMenu; private BufferedImage gameSelectedBackground; private boolean gameSelected; public MenuState(Game game) { super(game); State.loadMenuState = true; } @Override public UIList getUIButtons() { /*Control of active buttons*/ if (!gameSelected) { return menuButtons; } else { return loadSubMenu; } } @Override public UIScrollScreen getScreen() { /*control if scroll buttons are active*/ if (loadScreenMenu) return loadScreen; else return null; } @Override public void tick() { // If ESC is clicked on the menu screen then the game closes if(State.loadMenuState) { //loadMenuState is true then init menu screen initMenuScreen(); State.loadMenuState = false; } if (game.getKeyboard().mESC == true) { //If esc was pressed if (loadScreenMenu) { //Release loadScreen memory loadScreenMenu = false; loadScreen.getButtons().clear(); loadScreen = null; subMenuBackground = null; } else if(gameSelected) { //Release memory of the screen after choose a saved game gameSelected = false; loadSubMenu.getButtons().clear(); loadSubMenu = null; gameSelectedBackground = null; } else { // If esc was clicked on menu then close game game.stop(); } game.getKeyboard().mESC = false; } if(State.loadGame || State.newGame) // If load or new game true then it will change to gameState so release menu memory and changes state { menuButtons.getButtons().clear(); menuButtons = null; menuBackground = null; State.setCurrentState(game.getGameState()); } } @Override public void render(Graphics graph) { if(State.loadMenuState) // Make sure that only render after menu was loaded return; // Draw the menu background image and render the UI buttons graph.drawImage(menuBackground, 0, 0, game.getWidth(), game.getHeight(), null); menuButtons.render(graph); if (loadScreenMenu) { //Draw subMenu background and render buttons graph.drawImage(subMenuBackground, 0, 0, game.getWidth(), game.getHeight(), null); loadScreen.render(graph); } else if (gameSelected) { //Draw gameSelected background and render buttons graph.drawImage(gameSelectedBackground, 0, 0, game.getWidth(), game.getHeight(), null); loadSubMenu.render(graph); } } private void initMenuScreen() { /*Initialize the screen and buttons of the first menu screen*/ menuBackground = ImageLoader.loadImage("/background/menu_backgroud.png"); try { initMenuButtons(); } catch (Exception e) { e.printStackTrace(); } } private void initLoadScreen() { /*Initialize the screen and buttons of the second menu screen (list of saved games)*/ subMenuBackground = ImageLoader.loadImage("/background/submenu_background.png"); initLoadScreenButtons(); } private void initGameSelectedScreen() { /*Initialize the screen and of the third menu screen (game selected)*/ gameSelectedBackground = ImageLoader.loadImage("/background/load_submenu_background.png"); initGameSelectedButtons(); } private void initGameSelectedButtons() { /*Init buttons of the selected game load, delete and cancel*/ BufferedImage loadSaveButton[] = new BufferedImage[2]; BufferedImage deleteSaveButton[] = new BufferedImage[2]; BufferedImage cancelButton[] = new BufferedImage[2]; loadSubMenu = new UIList(); loadSaveButton[0] = ImageLoader.loadImage("/button/load_submenu_d.png"); loadSaveButton[1] = ImageLoader.loadImage("/button/load_submenu_s.png"); int buttonWidth = (int) (loadSaveButton[0].getWidth() * game.getScale()); int buttonHeight = (int) (loadSaveButton[0].getHeight() * game.getScale()); //Load a saved game loadSubMenu.getButtons().add(new UIButton((int) (50 * game.getScale()), (int)(300 * game.getScale()), buttonWidth, buttonHeight, loadSaveButton, -1, new ButtonAction() { @Override public void action() { State.loadGame = true; // Tells gameState to load a game game.getKeyboard().mESC = true; // Set esc true to release memory from this screen (GameSelected screen) } })); deleteSaveButton[0] = ImageLoader.loadImage("/button/delete_submenu_d.png"); deleteSaveButton[1] = ImageLoader.loadImage("/button/delete_submenu_s.png"); //Delete a saved game loadSubMenu.getButtons().add(new UIButton((int)(50 * game.getScale()), (int)(430 * game.getScale()), buttonWidth, buttonHeight, deleteSaveButton, -1, new ButtonAction() { @Override public void action() { try { DeleteGame.Delete(State.savedGames.get(lastButtonIndex).split(" ")[0]); //Get the name of the button pressed and removes from database } catch (Exception e) { e.printStackTrace(); } State.savedGames.clear(); //Clear database name loaded State.savedGames = null; game.getKeyboard().mESC = true; //Release memory from this screen (GameSelected screen) } })); cancelButton[0] = ImageLoader.loadImage("/button/cancel_submenu_d.png"); cancelButton[1] = ImageLoader.loadImage("/button/cancel_submenu_s.png"); //Cancel operation and goes back to the first menu screen loadSubMenu.getButtons().add(new UIButton((int)(50 * game.getScale()), (int)(550 * game.getScale()), buttonWidth, buttonHeight, cancelButton, -1, new ButtonAction() { @Override public void action() { State.savedGames.clear(); //Clear database name loaded State.savedGames = null; game.getKeyboard().mESC = true; //Release memory from this screen (GameSelected screen) } })); } private void initLoadScreenButtons() { /*Initialize all load screen buttons*/ BufferedImage loadScreenImage = ImageLoader.loadImage("/background/scrollScreen.png"); BufferedImage loadButton[] = new BufferedImage[2]; int scrollSpeed = 10; //Init load screen loadScreen = new UIScrollScreen(loadScreenImage, (int)(31 * game.getScale()), (int)(132 * game.getScale()), (int)(loadScreenImage.getWidth() * game.getScale()), (int)(loadScreenImage.getHeight() * game.getScale()), scrollSpeed); loadButton[0] = ImageLoader.loadImage("/button/submenu_button_d.png"); loadButton[1] = ImageLoader.loadImage("/button/submenu_button_s.png"); float buttonWidth = loadButton[0].getWidth() * game.getScale(); float buttonHeight = loadButton[0].getHeight() * game.getScale(); Font font = new Font("Castellar", Font.PLAIN, (int)(25 * game.getScale())); for (int i = 0, accumulator = (int) loadScreen.getScreen().getY(); (int) i < savedGames.size(); i++) { //Accumulator controls the button position on the screen String split[] = savedGames.get(i).split(" "); //split the name that came from the database float buttonX = (float) (loadScreen.getScreen().getX() + 3); Text text[] = new Text[2]; //Initialize both colors of the text and create the visible buttons text[0] = new Text("SaveGame " + (i+1) + " - " + split[split.length - 1], font, Color.black, (int) (buttonX - (25 * game.getScale()) + buttonWidth/4), accumulator + (int) (buttonHeight / 2)); text[1] = new Text("SaveGame " + (i+1) + " - " + split[split.length - 1], font, Color.white, (int) (buttonX - (25 * game.getScale()) + buttonWidth/4), accumulator + (int) (buttonHeight / 2)); loadScreen.getButtons().add(new UIButton((int) buttonX, accumulator, (int) (buttonWidth), (int) buttonHeight, loadButton, i, text, new ButtonAction() { public void action() { initGameSelectedScreen(); //Initialize gameSelect screen and buttons gameSelected = true; game.getKeyboard().mESC = true; // Select true to free memory used by the loadScreen } })); accumulator += (buttonHeight); } } private void initMenuButtons() throws Exception{ // Resize the button depending of the scale attribute of the game class BufferedImage[] buttonNewGame = new BufferedImage[2]; BufferedImage[] buttonLoadGame = new BufferedImage[2]; buttonNewGame[0] = ImageLoader.loadImage("/button/new_game.png"); buttonNewGame[1] = ImageLoader.loadImage("/button/new_game_b.png"); buttonLoadGame[0] = ImageLoader.loadImage("/button/load_game.png"); buttonLoadGame[1] = ImageLoader.loadImage("/button/load_game_b.png"); menuButtons = new UIList(); /* * Creates the load button and add to the UI button list, the first two * parameters has the position of the button on the screen it uses the * game.width to centralize the button and the game.height to control * the y position on the screen for every button a Button action is * defined when passing the argument, this way is possible to program * the button when creating it */ float buttonWidth = buttonLoadGame[0].getWidth() * game.getScale(); float buttonHeight = buttonLoadGame[0].getHeight() * game.getScale(); menuButtons.getButtons().add(new UIButton((int) ((game.getWidth() / 2) - (buttonWidth / 2)), (int) ((game.getHeight() - game.getHeight() / 3) + buttonHeight), (int) (buttonWidth), (int) buttonHeight, buttonLoadGame, -1, new ButtonAction() { public void action() { savedGames = new ArrayList<>(); try { savedGames = LoadGame.loadNames(); } catch (Exception e) { e.printStackTrace(); } initLoadScreen(); loadScreenMenu = true; } })); /* * Creates the game button and add to the UI button list, the first two * parameters has the position of the button on the screen it uses the * game.width to centralize the button and the game.height to control * the y position on the screen for every button a Button action is * defined when passing the argument, this way is possible to program * the button when creating it */ // Resize the button depending of the scale attribute of the game class buttonWidth = buttonNewGame[0].getWidth() * game.getScale(); buttonHeight = buttonNewGame[0].getHeight() * game.getScale(); menuButtons.getButtons() .add(new UIButton((int) ((game.getWidth() / 2) - (buttonWidth / 2)), (int) ((game.getHeight() - game.getHeight() / 3)), (int) (buttonWidth), (int) (buttonHeight), buttonNewGame, -1, new ButtonAction() { public void action() { State.newGame = true; } })); } }
BrunoMarchi/Chess_Game-LCP_2017
ChessGame/src/states/MenuState.java
Java
mit
11,128
<?php declare(strict_types = 1); use PHPUnit\Framework\TestCase; use Sop\JWX\JWA\JWA; use Sop\JWX\JWS\Algorithm\NoneAlgorithm; use Sop\JWX\JWT\Parameter\AlgorithmParameter; use Sop\JWX\JWT\Parameter\JWTParameter; /** * @group jwt * @group parameter * * @internal */ class JWTAlgorithmParameterTest extends TestCase { public function testCreate() { $param = new AlgorithmParameter(JWA::ALGO_NONE); $this->assertInstanceOf(AlgorithmParameter::class, $param); return $param; } /** * @depends testCreate */ public function testParamName(JWTParameter $param) { $this->assertEquals(JWTParameter::PARAM_ALGORITHM, $param->name()); } public function testFromAlgo() { $param = AlgorithmParameter::fromAlgorithm(new NoneAlgorithm()); $this->assertInstanceOf(AlgorithmParameter::class, $param); } }
sop/jwx
test/unit/jwt/parameter/AlgorithmTest.php
PHP
mit
896
# frozen_string_literal: true module HelperFunctions def log_in email = '[email protected]' password = 'password' User.create! email: email, password: password visit '/users/sign_in' fill_in 'user_email', with: email fill_in 'user_password', with: password click_button 'Log in' end def create_tags Tag.create!([ { tag_name: '*Welcome_Sequence', actionkit_uri: '/rest/v1/tag/1000/' }, { tag_name: '#Animal_Rights', actionkit_uri: '/rest/v1/tag/944/' }, { tag_name: '#Net_Neutrality', actionkit_uri: '/rest/v1/tag/1078/' }, { tag_name: '*FYI_and_VIP', actionkit_uri: '/rest/v1/tag/980/' }, { tag_name: '@Germany', actionkit_uri: '/rest/v1/tag/1036/' }, { tag_name: '@NewZealand', actionkit_uri: '/rest/v1/tag/1140/' }, { tag_name: '@France', actionkit_uri: '/rest/v1/tag/1128/' }, { tag_name: '#Sexism', actionkit_uri: '/rest/v1/tag/1208/' }, { tag_name: '#Disability_Rights', actionkit_uri: '/rest/v1/tag/1040/' }, { tag_name: '@Austria', actionkit_uri: '/rest/v1/tag/1042/' } ]) end def error_messages_from_response(response) JSON.parse(response.body)['errors'].inject([]) { |memo, error| memo << error['message'] }.uniq end end
SumOfUs/Champaign
spec/support/helper_functions.rb
Ruby
mit
1,244
import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core'; import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn, Validators } from '@angular/forms'; export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn { return (control: AbstractControl): {[key: string]: any} => { const name = control.value; const no = nameRe.test(name); return no ? {forbiddenName: {name}} : null; }; } @Directive({ selector: '[forbiddenName]', providers: [{provide: NG_VALIDATORS, useExisting: ForbiddenValidatorDirective, multi: true}] }) export class ForbiddenValidatorDirective implements Validator, OnChanges { @Input() public forbiddenName: string; private valFn = Validators.nullValidator; public ngOnChanges(changes: SimpleChanges): void { // const change = changes['forbiddenName']; // if (change) { // const val: string | RegExp = change.currentValue; // const re = val instanceof RegExp ? val : new RegExp(val, 'i'); // this.valFn = forbiddenNameValidator(re); // } else { // this.valFn = Validators.nullValidator; // } } public validate(control: AbstractControl): {[key: string]: any} { return this.valFn(control); } }
TaylorPzreal/curriculum-vitae
src/app/func/sign-up/forbidden-name.directive.ts
TypeScript
mit
1,223
namespace TransferCavityLock2012 { partial class LockControlPanel { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.lockParams = new System.Windows.Forms.GroupBox(); this.lockedLED = new NationalInstruments.UI.WindowsForms.Led(); this.label10 = new System.Windows.Forms.Label(); this.setPointIncrementBox = new System.Windows.Forms.TextBox(); this.GainTextbox = new System.Windows.Forms.TextBox(); this.VoltageToLaserTextBox = new System.Windows.Forms.TextBox(); this.setPointAdjustMinusButton = new System.Windows.Forms.Button(); this.setPointAdjustPlusButton = new System.Windows.Forms.Button(); this.LaserSetPointTextBox = new System.Windows.Forms.TextBox(); this.lockEnableCheck = new System.Windows.Forms.CheckBox(); this.label4 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.SlaveLaserIntensityScatterGraph = new NationalInstruments.UI.WindowsForms.ScatterGraph(); this.SlaveDataPlot = new NationalInstruments.UI.ScatterPlot(); this.xAxis1 = new NationalInstruments.UI.XAxis(); this.yAxis1 = new NationalInstruments.UI.YAxis(); this.SlaveFitPlot = new NationalInstruments.UI.ScatterPlot(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.ErrorScatterGraph = new NationalInstruments.UI.WindowsForms.ScatterGraph(); this.ErrorPlot = new NationalInstruments.UI.ScatterPlot(); this.xAxis2 = new NationalInstruments.UI.XAxis(); this.yAxis2 = new NationalInstruments.UI.YAxis(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.slErrorResetButton = new System.Windows.Forms.Button(); this.VoltageTrackBar = new System.Windows.Forms.TrackBar(); this.lockParams.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.lockedLED)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.SlaveLaserIntensityScatterGraph)).BeginInit(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.ErrorScatterGraph)).BeginInit(); this.groupBox2.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.VoltageTrackBar)).BeginInit(); this.SuspendLayout(); // // lockParams // this.lockParams.Controls.Add(this.lockedLED); this.lockParams.Controls.Add(this.label10); this.lockParams.Controls.Add(this.setPointIncrementBox); this.lockParams.Controls.Add(this.GainTextbox); this.lockParams.Controls.Add(this.VoltageToLaserTextBox); this.lockParams.Controls.Add(this.setPointAdjustMinusButton); this.lockParams.Controls.Add(this.setPointAdjustPlusButton); this.lockParams.Controls.Add(this.LaserSetPointTextBox); this.lockParams.Controls.Add(this.lockEnableCheck); this.lockParams.Controls.Add(this.label4); this.lockParams.Controls.Add(this.label2); this.lockParams.Controls.Add(this.label3); this.lockParams.Controls.Add(this.VoltageTrackBar); this.lockParams.Location = new System.Drawing.Point(589, 3); this.lockParams.Name = "lockParams"; this.lockParams.Size = new System.Drawing.Size(355, 162); this.lockParams.TabIndex = 13; this.lockParams.TabStop = false; this.lockParams.Text = "Lock Parameters"; // // lockedLED // this.lockedLED.LedStyle = NationalInstruments.UI.LedStyle.Round3D; this.lockedLED.Location = new System.Drawing.Point(310, 6); this.lockedLED.Name = "lockedLED"; this.lockedLED.Size = new System.Drawing.Size(32, 30); this.lockedLED.TabIndex = 34; // // label10 // this.label10.AutoSize = true; this.label10.Location = new System.Drawing.Point(6, 66); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(123, 13); this.label10.TabIndex = 33; this.label10.Text = "Set Point Increment Size"; // // setPointIncrementBox // this.setPointIncrementBox.Location = new System.Drawing.Point(168, 63); this.setPointIncrementBox.Name = "setPointIncrementBox"; this.setPointIncrementBox.Size = new System.Drawing.Size(55, 20); this.setPointIncrementBox.TabIndex = 32; this.setPointIncrementBox.Text = "0.01"; this.setPointIncrementBox.TextChanged += new System.EventHandler(this.setPointIncrementBox_TextChanged); // // GainTextbox // this.GainTextbox.Location = new System.Drawing.Point(167, 15); this.GainTextbox.Name = "GainTextbox"; this.GainTextbox.Size = new System.Drawing.Size(81, 20); this.GainTextbox.TabIndex = 31; this.GainTextbox.Text = "0.5"; this.GainTextbox.TextChanged += new System.EventHandler(this.GainChanged); // // VoltageToLaserTextBox // this.VoltageToLaserTextBox.Location = new System.Drawing.Point(167, 89); this.VoltageToLaserTextBox.Name = "VoltageToLaserTextBox"; this.VoltageToLaserTextBox.Size = new System.Drawing.Size(100, 20); this.VoltageToLaserTextBox.TabIndex = 30; this.VoltageToLaserTextBox.Text = "0"; this.VoltageToLaserTextBox.TextChanged += new System.EventHandler(this.VoltageToLaserChanged); // // setPointAdjustMinusButton // this.setPointAdjustMinusButton.Location = new System.Drawing.Point(124, 37); this.setPointAdjustMinusButton.Name = "setPointAdjustMinusButton"; this.setPointAdjustMinusButton.Size = new System.Drawing.Size(37, 23); this.setPointAdjustMinusButton.TabIndex = 29; this.setPointAdjustMinusButton.Text = "-"; this.setPointAdjustMinusButton.UseVisualStyleBackColor = true; this.setPointAdjustMinusButton.Click += new System.EventHandler(this.setPointAdjustMinusButton_Click); // // setPointAdjustPlusButton // this.setPointAdjustPlusButton.Location = new System.Drawing.Point(81, 37); this.setPointAdjustPlusButton.Name = "setPointAdjustPlusButton"; this.setPointAdjustPlusButton.Size = new System.Drawing.Size(37, 23); this.setPointAdjustPlusButton.TabIndex = 28; this.setPointAdjustPlusButton.Text = "+"; this.setPointAdjustPlusButton.UseVisualStyleBackColor = true; this.setPointAdjustPlusButton.Click += new System.EventHandler(this.setPointAdjustPlusButton_Click); // // LaserSetPointTextBox // this.LaserSetPointTextBox.AcceptsReturn = true; this.LaserSetPointTextBox.Location = new System.Drawing.Point(167, 39); this.LaserSetPointTextBox.Name = "LaserSetPointTextBox"; this.LaserSetPointTextBox.Size = new System.Drawing.Size(57, 20); this.LaserSetPointTextBox.TabIndex = 27; this.LaserSetPointTextBox.Text = "0"; // // lockEnableCheck // this.lockEnableCheck.AutoSize = true; this.lockEnableCheck.Location = new System.Drawing.Point(254, 17); this.lockEnableCheck.Name = "lockEnableCheck"; this.lockEnableCheck.Size = new System.Drawing.Size(50, 17); this.lockEnableCheck.TabIndex = 9; this.lockEnableCheck.Text = "Lock"; this.lockEnableCheck.UseVisualStyleBackColor = true; this.lockEnableCheck.CheckedChanged += new System.EventHandler(this.lockEnableCheck_CheckedChanged); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(6, 18); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(29, 13); this.label4.TabIndex = 20; this.label4.Text = "Gain"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(6, 92); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(122, 13); this.label2.TabIndex = 17; this.label2.Text = "Voltage sent to laser (V):"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(6, 42); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(69, 13); this.label3.TabIndex = 13; this.label3.Text = "Set Point (V):"; // // SlaveLaserIntensityScatterGraph // this.SlaveLaserIntensityScatterGraph.Location = new System.Drawing.Point(9, 17); this.SlaveLaserIntensityScatterGraph.Name = "SlaveLaserIntensityScatterGraph"; this.SlaveLaserIntensityScatterGraph.Plots.AddRange(new NationalInstruments.UI.ScatterPlot[] { this.SlaveDataPlot, this.SlaveFitPlot}); this.SlaveLaserIntensityScatterGraph.Size = new System.Drawing.Size(567, 132); this.SlaveLaserIntensityScatterGraph.TabIndex = 12; this.SlaveLaserIntensityScatterGraph.XAxes.AddRange(new NationalInstruments.UI.XAxis[] { this.xAxis1}); this.SlaveLaserIntensityScatterGraph.YAxes.AddRange(new NationalInstruments.UI.YAxis[] { this.yAxis1}); // // SlaveDataPlot // this.SlaveDataPlot.LineStyle = NationalInstruments.UI.LineStyle.None; this.SlaveDataPlot.PointSize = new System.Drawing.Size(3, 3); this.SlaveDataPlot.PointStyle = NationalInstruments.UI.PointStyle.SolidCircle; this.SlaveDataPlot.XAxis = this.xAxis1; this.SlaveDataPlot.YAxis = this.yAxis1; // // SlaveFitPlot // this.SlaveFitPlot.LineStyle = NationalInstruments.UI.LineStyle.None; this.SlaveFitPlot.PointColor = System.Drawing.Color.LawnGreen; this.SlaveFitPlot.PointStyle = NationalInstruments.UI.PointStyle.EmptyTriangleUp; this.SlaveFitPlot.XAxis = this.xAxis1; this.SlaveFitPlot.YAxis = this.yAxis1; // // groupBox1 // this.groupBox1.Controls.Add(this.ErrorScatterGraph); this.groupBox1.Controls.Add(this.SlaveLaserIntensityScatterGraph); this.groupBox1.Location = new System.Drawing.Point(4, 3); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(582, 286); this.groupBox1.TabIndex = 15; this.groupBox1.TabStop = false; this.groupBox1.Text = "Slave laser"; // // ErrorScatterGraph // this.ErrorScatterGraph.Location = new System.Drawing.Point(6, 155); this.ErrorScatterGraph.Name = "ErrorScatterGraph"; this.ErrorScatterGraph.Plots.AddRange(new NationalInstruments.UI.ScatterPlot[] { this.ErrorPlot}); this.ErrorScatterGraph.Size = new System.Drawing.Size(570, 125); this.ErrorScatterGraph.TabIndex = 13; this.ErrorScatterGraph.UseColorGenerator = true; this.ErrorScatterGraph.XAxes.AddRange(new NationalInstruments.UI.XAxis[] { this.xAxis2}); this.ErrorScatterGraph.YAxes.AddRange(new NationalInstruments.UI.YAxis[] { this.yAxis2}); // // ErrorPlot // this.ErrorPlot.LineColor = System.Drawing.Color.Red; this.ErrorPlot.LineColorPrecedence = NationalInstruments.UI.ColorPrecedence.UserDefinedColor; this.ErrorPlot.XAxis = this.xAxis2; this.ErrorPlot.YAxis = this.yAxis2; // // xAxis2 // this.xAxis2.Mode = NationalInstruments.UI.AxisMode.StripChart; this.xAxis2.Range = new NationalInstruments.UI.Range(0D, 500D); // // groupBox2 // this.groupBox2.Controls.Add(this.slErrorResetButton); this.groupBox2.Location = new System.Drawing.Point(589, 171); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(355, 118); this.groupBox2.TabIndex = 16; this.groupBox2.TabStop = false; this.groupBox2.Text = "Error Signal Parameters"; // // slErrorResetButton // this.slErrorResetButton.Location = new System.Drawing.Point(9, 19); this.slErrorResetButton.Name = "slErrorResetButton"; this.slErrorResetButton.Size = new System.Drawing.Size(109, 23); this.slErrorResetButton.TabIndex = 29; this.slErrorResetButton.Text = "Reset Graph"; this.slErrorResetButton.UseVisualStyleBackColor = true; this.slErrorResetButton.Click += new System.EventHandler(this.slErrorResetButton_Click); // // VoltageTrackBar // this.VoltageTrackBar.BackColor = System.Drawing.SystemColors.ButtonFace; this.VoltageTrackBar.Location = new System.Drawing.Point(6, 114); this.VoltageTrackBar.Maximum = 1000; this.VoltageTrackBar.Name = "VoltageTrackBar"; this.VoltageTrackBar.RightToLeft = System.Windows.Forms.RightToLeft.No; this.VoltageTrackBar.Size = new System.Drawing.Size(343, 45); this.VoltageTrackBar.TabIndex = 53; this.VoltageTrackBar.Value = 100; this.VoltageTrackBar.Scroll += new System.EventHandler(this.VoltageTrackBar_Scroll); // // LockControlPanel // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSize = true; this.Controls.Add(this.lockParams); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Name = "LockControlPanel"; this.Size = new System.Drawing.Size(952, 294); this.lockParams.ResumeLayout(false); this.lockParams.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.lockedLED)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.SlaveLaserIntensityScatterGraph)).EndInit(); this.groupBox1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.ErrorScatterGraph)).EndInit(); this.groupBox2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.VoltageTrackBar)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox lockParams; private System.Windows.Forms.Label label10; private System.Windows.Forms.TextBox setPointIncrementBox; private System.Windows.Forms.TextBox GainTextbox; private System.Windows.Forms.TextBox VoltageToLaserTextBox; private System.Windows.Forms.Button setPointAdjustMinusButton; private System.Windows.Forms.Button setPointAdjustPlusButton; private System.Windows.Forms.TextBox LaserSetPointTextBox; private System.Windows.Forms.CheckBox lockEnableCheck; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; public NationalInstruments.UI.WindowsForms.ScatterGraph SlaveLaserIntensityScatterGraph; public NationalInstruments.UI.ScatterPlot SlaveDataPlot; private NationalInstruments.UI.XAxis xAxis1; private NationalInstruments.UI.YAxis yAxis1; public NationalInstruments.UI.ScatterPlot SlaveFitPlot; private System.Windows.Forms.GroupBox groupBox1; private NationalInstruments.UI.WindowsForms.Led lockedLED; private NationalInstruments.UI.WindowsForms.ScatterGraph ErrorScatterGraph; private NationalInstruments.UI.ScatterPlot ErrorPlot; private NationalInstruments.UI.XAxis xAxis2; private NationalInstruments.UI.YAxis yAxis2; private System.Windows.Forms.GroupBox groupBox2; private System.Windows.Forms.Button slErrorResetButton; public System.Windows.Forms.TrackBar VoltageTrackBar; } }
jstammers/EDMSuite
TransferCavityLock2012/LockControlPanel.Designer.cs
C#
mit
18,415
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using BasicInfrastructureWeb.DependencyResolution; using IoC = LiveScore.App_Start.IoC; namespace LiveScore { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { ControllerConvention.Register(IoC.Initialize()); AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); } } }
thiagosgarcia/RSSS-ReallySimpleScoreStreaming
LiveScore/Global.asax.cs
C#
mit
749
#include "..\stdafx.h" #pragma once class CMutex { private: HANDLE m_mutex; bool m_isLocked; void Lock() { WaitForSingleObject(this->m_mutex, INFINITE); } void Unlock() { if (this->m_isLocked) { this->m_isLocked = false; ReleaseMutex(this->m_mutex); } } public: CMutex() { this->m_mutex = CreateMutex(NULL, FALSE, NULL); } ~CMutex() { CloseHandle(this->m_mutex); } friend class CMutexLock; }; class CMutexLock { private: CMutex* m_mutexObj; public: CMutexLock(CMutex* mutex) { this->m_mutexObj = mutex; this->m_mutexObj->Lock(); } ~CMutexLock() { this->m_mutexObj->Unlock(); } };
fieryorc/gitprompt
cache/Utils/Mutex.h
C
mit
637
/** * Wheel, copyright (c) 2017 - present by Arno van der Vegt * Distributed under an MIT license: https://arnovandervegt.github.io/wheel/license.txt **/ const testLogs = require('../../utils').testLogs; describe( 'Test repeat', () => { testLogs( it, 'Should repeat ten times', [ 'proc main()', ' number i', ' i = 0', ' repeat', ' addr i', ' mod 0, 1', ' i += 1', ' if i > 9', ' break', ' end', ' end', 'end' ], [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] ); testLogs( it, 'Should break to outer loop', [ 'proc main()', ' number x = 0', ' repeat loop', ' x += 1', ' repeat', ' x += 1', ' if (x > 10)', ' break loop', ' end', ' addr x', ' mod 0, 1', ' end', ' end', 'end' ], [ 2, 3, 4, 5, 6, 7, 8, 9, 10 ] ); } );
ArnoVanDerVegt/wheel
test/compiler/loop/testRepeat.js
JavaScript
mit
1,499
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>tlc: 2 m 40 s</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">dev / tlc - 20200328</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> tlc <small> 20200328 <span class="label label-success">2 m 40 s</span> </small> </h1> <p><em><script>document.write(moment("2020-04-14 10:21:03 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-04-14 10:21:03 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq dev Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.10.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.10.0 Official release 4.10.0 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/charguer/tlc&quot; dev-repo: &quot;git+https://github.com/charguer/tlc.git&quot; bug-reports: &quot;https://github.com/charguer/tlc/issues&quot; license: &quot;MIT&quot; synopsis: &quot;TLC: A Library for Classical Coq &quot; description: &quot;&quot;&quot; Provides an alternative to the core of the Coq standard library, using classic definitions. &quot;&quot;&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] depends: [ &quot;coq&quot; { &gt;= &quot;8.10&quot; } ] tags: [ &quot;category:Miscellaneous/Coq Extensions&quot; &quot;date:2020-03-28&quot; &quot;keyword:library&quot; &quot;keyword:classic&quot; &quot;logpath:TLC&quot; ] authors: [ &quot;Arthur Charguéraud&quot; ] url { src: &quot;https://github.com/charguer/tlc/archive/20200328.tar.gz&quot; checksum: [ &quot;md5=c62a434ed2d771d0d1814d0877d9a147&quot; &quot;sha512=33996475d9b3adc1752fd91ddbac5ebbe5bd7f22583c788807dd7ca9cd0363476621135884cf2603c1003c9c280811633a5a66ab2a279bf21cb1b39e60ae47a3&quot; ] } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-tlc.20200328 coq.dev</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 4000000; timeout 2h opam install -y --deps-only coq-tlc.20200328 coq.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>5 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 16000000; timeout 2h opam install -y -v coq-tlc.20200328 coq.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>2 m 40 s</dd> </dl> <h2>Installation size</h2> <p>Total: 9 M</p> <ul> <li>951 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibList.vo</code></li> <li>591 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibTactics.vo</code></li> <li>389 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFix.vo</code></li> <li>348 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibList.glob</code></li> <li>343 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFixDemos.vo</code></li> <li>307 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFix.glob</code></li> <li>276 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibContainer.vo</code></li> <li>245 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibRelation.vo</code></li> <li>241 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListZ.vo</code></li> <li>224 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOrder.vo</code></li> <li>193 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibEnv.vo</code></li> <li>188 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibTactics.v</code></li> <li>180 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibRelation.glob</code></li> <li>179 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibSet.vo</code></li> <li>178 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMap.vo</code></li> <li>137 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMultiset.vo</code></li> <li>135 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibPer.vo</code></li> <li>135 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibLogic.vo</code></li> <li>127 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFixDemos.glob</code></li> <li>120 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibTactics.glob</code></li> <li>120 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibEqual.vo</code></li> <li>116 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibTacticsDemos.vo</code></li> <li>111 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibInt.vo</code></li> <li>110 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListZ.glob</code></li> <li>100 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibEnv.glob</code></li> <li>100 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibList.v</code></li> <li>99 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibWf.vo</code></li> <li>93 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibStream.vo</code></li> <li>93 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibContainer.glob</code></li> <li>87 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibSet.glob</code></li> <li>86 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibLogic.glob</code></li> <li>84 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFset.vo</code></li> <li>83 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibEqual.glob</code></li> <li>83 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibVar.vo</code></li> <li>83 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibTacticsDemos.glob</code></li> <li>82 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFix.v</code></li> <li>79 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOrder.glob</code></li> <li>78 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMap.glob</code></li> <li>77 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibNat.vo</code></li> <li>72 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMin.vo</code></li> <li>71 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFun.vo</code></li> <li>71 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOtherDemos.vo</code></li> <li>69 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibProd.vo</code></li> <li>68 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibReflect.vo</code></li> <li>68 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMultiset.glob</code></li> <li>65 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListSub.vo</code></li> <li>60 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListAssoc.vo</code></li> <li>59 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibRelation.v</code></li> <li>56 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibGraph.vo</code></li> <li>55 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibBool.vo</code></li> <li>52 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibInt.glob</code></li> <li>52 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibLN.vo</code></li> <li>50 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListExec.vo</code></li> <li>48 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibEpsilon.vo</code></li> <li>48 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibContainerDemos.vo</code></li> <li>46 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibProd.glob</code></li> <li>46 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibChoice.vo</code></li> <li>46 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOption.vo</code></li> <li>45 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMonoid.vo</code></li> <li>45 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOld.v</code></li> <li>45 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFixDemos.v</code></li> <li>43 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOperation.vo</code></li> <li>42 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListAssocExec.vo</code></li> <li>42 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFset.glob</code></li> <li>39 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibIntTactics.vo</code></li> <li>38 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibSum.vo</code></li> <li>38 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibTacticsDemos.v</code></li> <li>34 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibEnv.v</code></li> <li>33 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOtherDemos.glob</code></li> <li>32 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListZ.v</code></li> <li>32 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibCore.vo</code></li> <li>31 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibLogic.v</code></li> <li>31 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibUnit.vo</code></li> <li>31 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOrder.v</code></li> <li>31 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibString.vo</code></li> <li>30 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibSet.v</code></li> <li>30 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibVar.glob</code></li> <li>29 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibContainer.v</code></li> <li>27 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibEqual.v</code></li> <li>25 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibReflect.glob</code></li> <li>25 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibWf.glob</code></li> <li>24 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibInt.v</code></li> <li>23 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFun.glob</code></li> <li>23 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMap.v</code></li> <li>21 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMultiset.v</code></li> <li>19 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibChoice.glob</code></li> <li>18 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListAssoc.glob</code></li> <li>18 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListSort.v</code></li> <li>18 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListSub.glob</code></li> <li>15 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibWf.v</code></li> <li>15 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibStream.glob</code></li> <li>14 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibVar.v</code></li> <li>14 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibExec.v</code></li> <li>14 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMin.glob</code></li> <li>13 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibReflect.v</code></li> <li>13 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibEpsilon.glob</code></li> <li>12 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibPer.glob</code></li> <li>12 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibBool.glob</code></li> <li>12 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFset.v</code></li> <li>11 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOtherDemos.v</code></li> <li>11 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOperation.glob</code></li> <li>11 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibGraph.glob</code></li> <li>10 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibNat.glob</code></li> <li>10 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibBool.v</code></li> <li>9 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOption.glob</code></li> <li>9 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibProd.v</code></li> <li>9 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListSub.v</code></li> <li>9 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibContainerDemos.glob</code></li> <li>8 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibLN.v</code></li> <li>8 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListExec.glob</code></li> <li>8 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibContainerDemos.v</code></li> <li>8 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMin.v</code></li> <li>8 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibStream.v</code></li> <li>7 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibFun.v</code></li> <li>7 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibNat.v</code></li> <li>7 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibChoice.v</code></li> <li>7 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibEpsilon.v</code></li> <li>6 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibLN.glob</code></li> <li>5 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListAssoc.v</code></li> <li>5 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibPer.v</code></li> <li>5 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/Makefile.coq</code></li> <li>5 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibIntTactics.v</code></li> <li>5 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibLogicCore.v</code></li> <li>5 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListAssocExec.glob</code></li> <li>5 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibSum.glob</code></li> <li>4 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOperation.v</code></li> <li>4 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOption.v</code></li> <li>4 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListExec.v</code></li> <li>4 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMonoid.glob</code></li> <li>3 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibMonoid.v</code></li> <li>3 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibGraph.v</code></li> <li>3 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibSum.v</code></li> <li>2 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibAxioms.vo</code></li> <li>2 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibAxioms.v</code></li> <li>2 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibIntTactics.glob</code></li> <li>2 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListAssocExec.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/Makefile</code></li> <li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibAxioms.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibLogicCore.vo</code></li> <li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListSort.vo</code></li> <li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibExec.vo</code></li> <li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOld.vo</code></li> <li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibUnit.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibUnit.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibCore.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibString.v</code></li> <li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibCore.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibString.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibLogicCore.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibListSort.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibExec.glob</code></li> <li>1 K <code>../ocaml-base-compiler.4.10.0/lib/coq/user-contrib/TLC/LibOld.glob</code></li> </ul> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq-tlc.20200328</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.10.0-2.0.6/extra-dev/dev/tlc/20200328.html
HTML
mit
23,112
from django.db import models from .workflow import TestStateMachine class TestModel(models.Model): name = models.CharField(max_length=100) state = models.CharField(max_length=20, null=True, blank=True) state_num = models.IntegerField(null=True, blank=True) other_state = models.CharField(max_length=20, null=True, blank=True) message = models.CharField(max_length=250, null=True, blank=True) class Meta: permissions = TestStateMachine.get_permissions('testmodel', 'Test')
andrewebdev/django-ostinato
ostinato/tests/statemachine/models.py
Python
mit
509
<?php namespace Fisharebest\Localization\Locale; use Fisharebest\Localization\Territory\TerritoryNi; /** * Class LocaleEsNi * * @author Greg Roach <[email protected]> * @copyright (c) 2015 Greg Roach * @license GPLv3+ */ class LocaleEsNi extends LocaleEs { public function territory() { return new TerritoryNi; } }
fweber1/Annies-Ancestors
webtrees/vendor/fisharebest/localization/src/Locale/LocaleEsNi.php
PHP
mit
344
use internal; #[repr(C)] #[derive(Debug, PartialEq, PartialOrd, Copy, Clone)] #[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))] pub struct Size { pub width: f32, pub height: f32, } impl From<Size> for internal::YGSize { fn from(s: Size) -> internal::YGSize { internal::YGSize { width: s.width, height: s.height, } } }
bschwind/yoga-rs
src/ffi_types/size.rs
Rust
mit
355
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>bignums: 1 m 56 s 🏆</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">8.10.0 / bignums - 8.10+beta1</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> bignums <small> 8.10+beta1 <span class="label label-success">1 m 56 s 🏆</span> </small> </h1> <p>📅 <em><script>document.write(moment("2020-07-29 03:23:42 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-29 03:23:42 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.10.0 Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.08.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.08.1 Official release 4.08.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; homepage: &quot;https://github.com/coq/bignums&quot; dev-repo: &quot;git+https://github.com/coq/bignums.git&quot; bug-reports: &quot;https://github.com/coq/bignums/issues&quot; authors: [ &quot;Laurent Théry&quot; &quot;Benjamin Grégoire&quot; &quot;Arnaud Spiwack&quot; &quot;Evgeny Makarov&quot; &quot;Pierre Letouzey&quot; ] license: &quot;LGPL 2&quot; build: [ [make &quot;-j%{jobs}%&quot;] ] install: [ [make &quot;install&quot;] ] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.10&quot; &amp; &lt; &quot;8.11~&quot;} ] tags: [ &quot;keyword:integer numbers&quot; &quot;keyword:rational numbers&quot; &quot;keyword:arithmetic&quot; &quot;keyword:arbitrary-precision&quot; &quot;category:Miscellaneous/Coq Extensions&quot; &quot;category:Mathematics/Arithmetic and Number Theory/Number theory&quot; &quot;category:Mathematics/Arithmetic and Number Theory/Rational numbers&quot; &quot;logpath:Bignums&quot; ] synopsis: &quot;Bignums, the Coq library of arbitrary large numbers&quot; description: &quot;Provides BigN, BigZ, BigQ that used to be part of Coq standard library &lt; 8.7.&quot; url { src: &quot;https://github.com/coq/bignums/archive/V8.10+beta1.tar.gz&quot; checksum: &quot;md5=7389fc52776af64717fc6b4550066aa8&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-bignums.8.10+beta1 coq.8.10.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 4000000; timeout 2h opam install -y --deps-only coq-bignums.8.10+beta1 coq.8.10.0</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>2 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam list; echo; ulimit -Sv 16000000; timeout 2h opam install -y coq-bignums.8.10+beta1 coq.8.10.0</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>1 m 56 s</dd> </dl> <h2>Installation size</h2> <p>Total: 10 M</p> <ul> <li>899 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/BigN.vo</code></li> <li>786 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDiv.vo</code></li> <li>715 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSqrt.vo</code></li> <li>564 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/NMake.vo</code></li> <li>554 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDiv.glob</code></li> <li>535 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigZ/BigZ.vo</code></li> <li>372 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleMul.vo</code></li> <li>346 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSqrt.glob</code></li> <li>317 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigQ/QMake.vo</code></li> <li>300 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDivn1.vo</code></li> <li>289 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/NMake_gen.vo</code></li> <li>286 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleLift.vo</code></li> <li>274 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleCyclic.vo</code></li> <li>264 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/NMake.glob</code></li> <li>201 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDivn1.glob</code></li> <li>198 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleCyclic.glob</code></li> <li>197 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/NMake_gen.glob</code></li> <li>186 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSigNAxioms.vo</code></li> <li>185 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigZ/ZMake.vo</code></li> <li>185 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSigZAxioms.vo</code></li> <li>182 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleMul.glob</code></li> <li>168 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigQ/BigQ.vo</code></li> <li>152 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleLift.glob</code></li> <li>145 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigQ/QMake.glob</code></li> <li>124 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigNumPrelude.vo</code></li> <li>118 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaQ/QSig.vo</code></li> <li>116 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigZ/ZMake.glob</code></li> <li>109 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/Nbasic.vo</code></li> <li>104 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSub.vo</code></li> <li>99 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleBase.vo</code></li> <li>88 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleAdd.vo</code></li> <li>88 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSub.glob</code></li> <li>74 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleBase.glob</code></li> <li>72 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleAdd.glob</code></li> <li>70 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/Nbasic.glob</code></li> <li>68 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigNumPrelude.glob</code></li> <li>63 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/bignums_syntax_plugin.cmxs</code></li> <li>62 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSigNAxioms.glob</code></li> <li>62 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSigZAxioms.glob</code></li> <li>56 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSig.vo</code></li> <li>55 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDiv.v</code></li> <li>52 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/NMake.v</code></li> <li>52 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSig.vo</code></li> <li>48 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSqrt.v</code></li> <li>37 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaQ/QSig.glob</code></li> <li>35 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSig.glob</code></li> <li>35 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigQ/QMake.v</code></li> <li>33 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/NMake_gen.v</code></li> <li>31 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSig.glob</code></li> <li>28 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleCyclic.v</code></li> <li>24 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleMul.v</code></li> <li>21 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigZ/ZMake.v</code></li> <li>20 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleDivn1.v</code></li> <li>19 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleLift.v</code></li> <li>16 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/Nbasic.v</code></li> <li>16 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigZ/BigZ.glob</code></li> <li>13 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/BigN.glob</code></li> <li>13 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleBase.v</code></li> <li>13 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigNumPrelude.v</code></li> <li>12 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleSub.v</code></li> <li>12 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSigZAxioms.v</code></li> <li>12 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigQ/BigQ.glob</code></li> <li>12 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSigNAxioms.v</code></li> <li>11 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/CyclicDouble/DoubleAdd.v</code></li> <li>9 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/bignums_syntax_plugin.cmi</code></li> <li>8 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/bignums_syntax_plugin.cmx</code></li> <li>7 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaQ/QSig.v</code></li> <li>6 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigZ/BigZ.v</code></li> <li>6 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigN/BigN.v</code></li> <li>5 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/ZSig.v</code></li> <li>5 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/BigQ/BigQ.v</code></li> <li>5 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/SpecViaZ/NSig.v</code></li> <li>4 K <code>../ocaml-base-compiler.4.08.1/lib/coq/user-contrib/Bignums/bignums_syntax_plugin.cmxa</code></li> </ul> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq-bignums.8.10+beta1</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.08.1-2.0.5/extra-dev/8.10.0/bignums/8.10+beta1.html
HTML
mit
15,698
require 'builder' module MWS module API class Fulfillment < Base include Feeds ## Takes an array of hash AmazonOrderID,FulfillmentDate,CarrierName,ShipperTrackingNumber,sku,quantity ## Returns true if all the orders were updated successfully ## Otherwise raises an exception def post_ship_confirmation(merchant_id, ship_info) # Shipping Confirmation is done by sending an XML "feed" to Amazon xml = "" builder = Builder::XmlMarkup.new(:indent => 2, :target => xml) builder.instruct! # <?xml version="1.0" encoding="UTF-8"?> builder.AmazonEnvelope(:"xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance", :"xsi:noNamespaceSchemaLocation" => "amzn-envelope.xsd") do |env| env.Header do |head| head.DocumentVersion('1.01') head.MerchantIdentifier(merchant_id) end env.MessageType('OrderFulfillment') i = 0 ship_info.each do |shp| env.Message do |msg| msg.MessageID(i += 1) msg.OrderFulfillment do |orf| orf.AmazonOrderID(shp.AmazonOrderID) orf.FulfillmentDate(shp.FulfillmentDate.to_time.iso8601) orf.FulfillmentData do |fd| fd.CarrierCode(shp.CarrierCode) fd.ShippingMethod() fd.ShipperTrackingNumber(shp.ShipperTrackingNumber) end if shp.sku != '' orf.Item do |itm| itm.MerchantOrderItemID(shp.sku) itm.MerchantFulfillmentItemID(shp.sku) itm.Quantity(shp.quantity) end end end end end end submit_feed('_POST_ORDER_FULFILLMENT_DATA_', xml) end end end end
tinabme/ruby-mws
lib/ruby-mws/api/fulfillment.rb
Ruby
mit
1,850
import { NgModule } from '@angular/core'; import { SharedModule } from '../shared/shared.module'; import { HelloRoutingModule } from './hello-routing.module'; import { HelloComponent } from './hello.component'; @NgModule({ imports: [ SharedModule, HelloRoutingModule, ], declarations: [ HelloComponent, ], }) export class HelloModule { }
rangle/angular2-starter
src/app/hello/hello.module.ts
TypeScript
mit
361
package de.espend.idea.shopware.util.dict; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.PsiRecursiveElementWalkingVisitor; import com.intellij.psi.util.PsiTreeUtil; import com.jetbrains.php.lang.psi.elements.Method; import com.jetbrains.php.lang.psi.elements.MethodReference; import com.jetbrains.php.lang.psi.elements.PhpClass; import com.jetbrains.php.lang.psi.elements.StringLiteralExpression; import fr.adrienbrault.idea.symfony2plugin.Symfony2InterfacesUtil; import fr.adrienbrault.idea.symfony2plugin.util.PhpElementsUtil; import org.apache.commons.lang.StringUtils; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; public class PsiParameterStorageRunnable implements Runnable { private final Project project; private final VirtualFile virtualFile; private final Map<String, Collection<String>> events; private final Set<String> configs; public PsiParameterStorageRunnable(Project project, VirtualFile virtualFile, Map<String, Collection<String>> events, Set<String> configs) { this.project = project; this.virtualFile = virtualFile; this.events = events; this.configs = configs; } public void run() { final PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile); if (psiFile != null) { psiFile.acceptChildren(new MyPsiRecursiveElementWalkingVisitor()); } } private class MyPsiRecursiveElementWalkingVisitor extends PsiRecursiveElementWalkingVisitor { @Override public void visitElement(PsiElement element) { if (element instanceof MethodReference) { visitMethodReference((MethodReference) element); } super.visitElement(element); } private void visitMethodReference(MethodReference methodReference) { String name = methodReference.getName(); if (name != null && ("notify".equals(name) || "notifyUntil".equals(name) || "filter".equals(name))) { PsiElement[] parameters = methodReference.getParameters(); if(parameters.length > 1) { if(parameters[0] instanceof StringLiteralExpression) { PsiElement method = methodReference.resolve(); if(method instanceof Method) { PhpClass phpClass = ((Method) method).getContainingClass(); if(phpClass != null && new Symfony2InterfacesUtil().isInstanceOf(phpClass, "\\Enlight_Event_EventManager")) { String content = PhpElementsUtil.getStringValue(parameters[0]); if(StringUtils.isNotBlank(content)) { if(!events.containsKey(content)) { events.put(content, new HashSet<String>()); } Collection<String> data = events.get(content); Method parentOfType = PsiTreeUtil.getParentOfType(parameters[0], Method.class); if(parentOfType != null && parentOfType.getContainingClass() != null) { String methodName = parentOfType.getName(); String presentableFQN = parentOfType.getContainingClass().getPresentableFQN(); data.add(presentableFQN + '.' + methodName); events.put(content, data); } } } } } } } if (name != null && ("addElement".equals(name) || "setElement".equals(name))) { PsiElement[] parameters = methodReference.getParameters(); if(parameters.length > 2) { if(parameters[1] instanceof StringLiteralExpression) { PsiElement method = methodReference.resolve(); if(method instanceof Method) { PhpClass phpClass = ((Method) method).getContainingClass(); if(phpClass != null && new Symfony2InterfacesUtil().isInstanceOf(phpClass, "\\Shopware\\Models\\Config\\Form")) { String content = ((StringLiteralExpression) parameters[1]).getContents(); if(StringUtils.isNotBlank(content)) { configs.add(content); } } } } } } } } }
ShopwareHackathon/idea-php-shopware-plugin
src/de/espend/idea/shopware/util/dict/PsiParameterStorageRunnable.java
Java
mit
5,005
/******************************************************************************** * The MIT License (MIT) * * * * Copyright (C) 2016 Alex Nolasco * * * *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. * *********************************************************************************/ #import <Foundation/Foundation.h> #import "HL7SummaryProtocol.h" @class HL7PatientSummary; @class HL7ClinicalDocumentSummary; typedef NSDictionary<NSString *, id<HL7SummaryProtocol>> NSDictionaryTemplateIdToSummary; @interface HL7CCDSummary : NSObject <NSCopying, NSCoding> - (HL7ClinicalDocumentSummary *_Nullable)document; - (HL7PatientSummary *_Nullable)patient; - (NSDictionaryTemplateIdToSummary *_Nullable)summaries; - (id<HL7SummaryProtocol> _Nullable)getSummaryByClass:(Class _Nonnull)className; @end
alexandern/ccdaviewer
ccdaparser/ccdaparser/model/summary/HL7CCDSummary.h
C
mit
2,319
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('geokey_sapelli', '0005_sapellifield_truefalse'), ] operations = [ migrations.AddField( model_name='sapelliproject', name='sapelli_fingerprint', field=models.IntegerField(default=-1), preserve_default=False, ), ]
ExCiteS/geokey-sapelli
geokey_sapelli/migrations/0006_sapelliproject_sapelli_fingerprint.py
Python
mit
468
using UnityEngine; using System.Collections; public class HurtSusukeOnContact : MonoBehaviour { public int damageToGive; public float bounceOnEnemy; private Rigidbody2D myRigidbody2D; // Use this for initialization void Start () { myRigidbody2D = transform.parent.GetComponent<Rigidbody2D> (); } // Update is called once per frame void Update () { } void OnTriggerEnter2D(Collider2D other) { if (other.tag == "Susuke") { other.GetComponent<EnemyHealthManager>().giveDamage(damageToGive); myRigidbody2D.velocity = new Vector2 (myRigidbody2D.velocity.x, bounceOnEnemy); } } }
SafeRamen/Nerd-Quest
Nerd Quest/Assets/Scripts/HurtSusukeOnContact.cs
C#
mit
611
# lsyncd Docker image allowing you to use lsyncd as a docker command ## Usage ``` docker run -d -v /docker/lsyncd/src:/src -v /docker/lsyncd/target:/target -v /docker/lsyncd/lrsync.lua:/etc/lrsync/lrsync.lua zeroboh/lsyncd:2.1-alpine ```
egobude/docker
lsyncd/2.1-alpine/README.md
Markdown
mit
241
 #include "Internal.hpp" #include <LuminoEngine/Graphics/Texture.hpp> #include <LuminoEngine/Rendering/Material.hpp> #include <LuminoEngine/Mesh/Mesh.hpp> #include <LuminoEngine/Visual/StaticMeshComponent.hpp> namespace ln { //============================================================================= // StaticMeshComponent StaticMeshComponent::StaticMeshComponent() : m_model(nullptr) { } StaticMeshComponent::~StaticMeshComponent() { } void StaticMeshComponent::init() { VisualComponent::init(); } void StaticMeshComponent::setModel(StaticMeshModel* model) { m_model = model; } StaticMeshModel* StaticMeshComponent::model() const { return m_model; } void StaticMeshComponent::onRender(RenderingContext* context) { const auto& containers = m_model->meshContainers(); for (int iContainer = 0; iContainer < containers.size(); iContainer++) { const auto& meshContainer = containers[iContainer]; MeshResource* meshResource = meshContainer->meshResource(); if (meshResource) { for (int iSection = 0; iSection < meshResource->sections().size(); iSection++) { context->setMaterial(m_model->materials()[meshResource->sections()[iSection].materialIndex]); context->drawMesh(meshResource, iSection); } } //Mesh* mesh = meshContainer->mesh(); //if (mesh) { // for (int iSection = 0; iSection < mesh->sections().size(); iSection++) { // context->setMaterial(m_model->materials()[mesh->sections()[iSection].materialIndex]); // context->drawMesh(mesh, iSection); // } //} } for (const auto& node : m_model->meshNodes()) { if (node->meshContainerIndex() >= 0) { context->setTransfrom(m_model->nodeGlobalTransform(node->index())); const auto& meshContainer = m_model->meshContainers()[node->meshContainerIndex()]; Mesh* mesh = meshContainer->mesh(); if (mesh) { for (int iSection = 0; iSection < mesh->sections().size(); iSection++) { context->setMaterial(m_model->materials()[mesh->sections()[iSection].materialIndex]); context->drawMesh(mesh, iSection); } } } } } } // namespace ln
lriki/Lumino
src/LuminoEngine/src/Visual/StaticMeshComponent.cpp
C++
mit
2,432
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="../../lib/vue.js"></script> <title>vue test</title> </head> <body> <div id="app"> {{ message }} <span id="test-1">message-2:{{getMemo}}</span> </div> <text></text> </body> <script> import text from './Text' export default { data(){ return { a:1, b:2 } }, created(){ console.log(this) }, computed:{ getMemo(){ return `this is query params ${this.message}` } }, components: { text }, } </script> </html>
lian01chen/navigator
vueCode/vueTest/Vue.html
HTML
mit
912
<!DOCTYPE html> <html class="no-js" lang="es"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="p5.js a JS client-side library for creating graphic and interactive experiences, based on the core principles of Processing."> <title tabindex="1">examples | p5.js</title> <link rel="stylesheet" href="/assets/css/all.css?v=db3be6"> <link href="https://fonts.googleapis.com/css?family=Montserrat&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Inconsolata&display=swap" rel="stylesheet"> <link rel="shortcut icon" href="/../../assets/img/favicon.ico"> <link rel="icon" href="/../../assets/img/favicon.ico"> <script src="/../../assets/js/vendor/jquery-1.12.4.min.js"></script> <script src="/../../assets/js/vendor/ace-nc/ace.js"></script> <script src="/../../assets/js/vendor/ace-nc/mode-javascript.js"></script> <script src="/../../assets/js/vendor/prism.js"></script> <script src="/assets/js/init.js?v=af215d"></script> </head> <body> <a href="#content" class="sr-only">Ir al contenido</a> <!-- p5*js language buttons --> <div id="i18n-btn"> <h2 id="i18n-settings" class="sr-only">Preferencias de idioma</h2> <ul id="i18n-buttons" aria-labelledby="i18n-settings"> <li><a href='#' lang='en' data-lang='en'>English</a></li> <li><a href='#' lang='es' data-lang='es'>Español</a></li> <li><a href='#' lang='zh-Hans' data-lang='zh-Hans'>简体中文</a></li> <li><a href='#' lang='ko' data-lang='ko'>한국어</a></li> </ul> </div> <!-- .container --> <div class="container"> <!-- logo --> <header id="lockup"> <a href="/es/"> <img src="/../../assets/img/p5js.svg" alt="p5 homepage" id="logo_image" class="logo" /> <div id="p5_logo"></div> </a> </header> <!-- close logo --> <div id="examples-page"> <!-- site navigation --> <div class="column-span"> <nav class="sidebar-menu-nav-element"> <h2 id="menu-title" class="sr-only">Navegación del sitio</h2> <input class="sidebar-menu-btn" type="checkbox" id="sidebar-menu-btn" /> <label class="sidebar-menu-icon" for="sidebar-menu-btn"><span class="sidebar-nav-icon"></span></label> <ul id="menu" class="sidebar-menu" aria-labelledby="menu-title"> <li><a href="/es/">Inicio</a></li> <li><a href="https://editor.p5js.org">Editor</a></li> <li><a href="/es/download/">Descargar</a></li> <li><a href="/es/download/support.html">Donar</a></li> <li><a href="/es/get-started/">Empezar</a></li> <li><a href="/es/reference/">Referencia</a></li> <li><a href="/es/libraries/">Bibliotecas</a></li> <li><a href="/es/learn/">Aprender</a></li> <li><a href="/es/examples/">Ejemplos</a></li> <li><a href="/es/books/">Libros</a></li> <li><a href="/es/community/">Comunidad</a></li> <li><a href="https://showcase.p5js.org">Showcase</a></li> <li><a href="https://discourse.processing.org/c/p5js" target=_blank class="other-link">Foro</a></li> <li><a href="http://github.com/processing/p5.js" target=_blank class="other-link">GitHub</a></li> <li><a href="http://twitter.com/p5xjs" target=_blank class="other-link">Twitter</a></li> </ul> </nav> </div> <div class="column-span"> <main id="content" > <p id="backlink"><a href="./">&lt; Volver a Ejemplos</a></p> <h1 id='example-name'>example name placeholder</h1> <p id='example-desc'>example description placeholder</p> <div id="exampleDisplay"> <div class="edit_space"> <button id="toggleTextOutput" class="sr-only">toggle text output</button> <button id="runButton" class="edit_button">run</button> <button id="resetButton" class="reset_button">reset</button> <button id="copyButton" class="copy_button">copy</button> </div> <div id="exampleEditor"></div> <iframe id="exampleFrame" src="../../assets/examples/example.html" ></iframe> </div> <p><a style="border-bottom:none !important;" href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target=_blank><img src="https://licensebuttons.net/l/by-nc-sa/4.0/88x31.png" alt="creative commons license" style="width:88px"/></a></p> </main> <footer> <h2 class="sr-only">Créditos</h2> <p> p5.js actualmente está dirigido por <a href='https://github.com/mcturner1995' target="_blank">Moira Turner</a>y fue creado por<a href='http://lauren-mccarthy.com' target="_blank">Lauren McCarthy</a> p5.js es desarrollado por una comunidad de colaboradores, con apoyo de <a href="http://processing.org/foundation/" target="_blank">Processing Foundation</a> y <a href="http://itp.nyu.edu/itp/" target="_blank">NYU ITP</a>. Identidad y diseño gráfico por <a href="http://jereljohnson.com/" target="_blank">Jerel Johnson</a>. <a href="/es/copyright.html">&copy; Info.</a></p> </footer> </div> <!-- end column-span --> <!-- outside of column for footer to go across both --> <p class="clearfix"> &nbsp; </p> <object type="image/svg+xml" data="../../assets/img/thick-asterisk-alone.svg" id="asterisk-design-element" aria-hidden="true"> </object> <!-- <script src="../../assets/js/vendor/ace-nc/ace.js"></script> <script src="../../assets/js/examples.js"></script> --> <script> window._p5jsExample = '../../assets/examples/es/09_Simulate/05_MultipleParticleSystems.js'; window.addEventListener('load', function() { // examples.init('../../assets/examples/es/09_Simulate/05_MultipleParticleSystems.js'); if (false) { var isMobile = window.matchMedia("only screen and (max-width: 767px)"); // isMobile is true if viewport is less than 768 pixels wide document.getElementById('exampleFrame').style.display = 'none'; if (isMobile.matches) { document.getElementById('notMobile-message').style.display = 'none'; document.getElementById('isMobile-displayButton').style.display = 'block'; } else { document.getElementById('notMobile-message').style.display = 'block'; document.getElementById('isMobile-displayButton').style.display = 'none'; document.getElementById('runButton').style.display = 'none'; document.getElementById('resetButton').style.display = 'none'; document.getElementById('copyButton').style.display = 'none'; } } }, true); </script> </div><!-- end id="get-started-page" --> <script src="/../../assets/js/examples.js"></script> </div> <!-- close class='container'--> <nav id="family" aria-labelledby="processing-sites-heading"> <h2 id="processing-sites-heading" class="sr-only">Processing Sister Sites</h2> <ul id="processing-sites" aria-labelledby="processing-sites-heading"> <li><a href="http://processing.org">Processing</a></li> <li><a class="here" href="/es/">p5.js</a></li> <li><a href="http://py.processing.org/">Processing.py</a></li> <li><a href="http://android.processing.org/">Processing for Android</a></li> <li><a href="http://pi.processing.org/">Processing for Pi</a></li> <li><a href="https://processingfoundation.org/">Processing Foundation</a></li> </ul> <a tabindex="1" href="#content" id="skip-to-content">Skip to main content</a> <!-- <a id="promo-link" href="https://donorbox.org/supportpf2019-fundraising-campaign" target="_blank"><div id="promo">This season, we need your help! Click here to #SupportP5!</div></a> --> </nav> <script> var langs = ["en","es","ko","zh-Hans"]; (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-53383000-1', 'auto'); ga('send', 'pageview'); $(window).ready(function() { if (window.location.pathname !== '/' && window.location.pathname !== '/index.html') { $('#top').remove(); } else { $('#top').show(); } }); </script> </body> </html>
mayaman/p5js-website
es/examples/simulate-multiple-particle-systems.html
HTML
mit
8,643
--- layout: tagpage tag: quartz ---
Abel-Liu/Abel-Liu.github.io
tag/quartz.md
Markdown
mit
35
#!/usr/bin/env bats ## tests with https://github.com/sstephenson/bats die() { echo "$@" >/dev/stderr exit 1 } export DOCKHACK_SKIP_UID_CHECK=1 ################################################################################ ## mocked docker command #which docker &>/dev/null || die "ERROR: docker must be installed to run tests" source $BATS_TEST_DIRNAME/mock_docker # for test fixture variables export mock_docker="$BATS_TEST_DIRNAME/mock_docker" docker() { "$mock_docker" "$@" } export -f docker ################################################################################ @test "running with no args prints usage & exit code 2." { run ./dockhack [ "$status" -eq 2 ] # can't distinguish between stdout/err yet https://github.com/sstephenson/bats/pull/55 [[ "$output" =~ "Usage" ]] } @test "-h/--help print usage & exit code 0." { run ./dockhack -h [ "$status" -eq 0 ] [[ "$output" =~ "Usage" ]] run ./dockhack --help [ "$status" -eq 0 ] [[ "$output" =~ "Usage" ]] } @test "'dockhack lib' is a no-op" { run ./dockhack lib [ "$status" -eq 0 ] [[ "$output" = "" ]] } @test "'get_id last' == 'get_id l' == 'id last'" { local -a commands=('get_id last' 'get_id l' 'id last') for com in "${commands[@]}"; do eval "run ./dockhack $com" echo ">> $com : $output" [[ "$status" -eq 0 ]] [[ "$output" = "$TEST_ID" ]] || die "bad out" done } @test "'get_id $TEST_NAME' == 'id $TEST_NAME'" { local -a commands=("get_id $TEST_NAME" "id $TEST_NAME") for com in "${commands[@]}"; do eval "run ./dockhack $com" [[ "$status" -eq 0 ]] [[ "$output" = "$TEST_ID" ]] || die "bad out" done } @test "dummy test" { true }
tavisrudd/dockhack
tests.bat
Batchfile
mit
1,708
<?php namespace App\Controllers\Admin; use BaseController; use DB, View, Datatables, Input, Redirect, Str, Validator, Image, File; use App\Models\Music; class MusicController extends BaseController { private $upload_path = "uploads/music/"; public function getList() { $music_count = Music::count(); $data = array(); if($music_count > 0){ $data['formProcess'] = "editProcess"; $musicRecord = Music::orderBy('id', 'DESC')->first(); $id = $musicRecord->id; $data['input'] = Music::find($id); } return View::make('admin.site.music',$data); } public function postSubmit(){ if(Input::get('_action') == 'addProcess'){ $validator = Validator::make( array( 'Title' => Input::get('title'), 'MP3 File' => Input::file('file_name') ), array( 'Title' => 'required', 'MP3 File' => 'required' ) ); $mime = Input::file('file_name')->getMimeType(); if ($validator->fails()){ return Redirect::route('admin.music')->withErrors($validator)->withInput(); } // if($mime !== 'audio/mpeg'){ // $error = "You have to input audio MP3 file"; // return Redirect::route('admin.music')->withErrors($error)->withInput(); // } $music = new Music; $music->title = Input::get('title'); if(!file_exists($this->upload_path)) { mkdir($this->upload_path, 0777, true); } if(!is_null(Input::file('file_name'))){ $file = Input::file('file_name'); if($file->isValid()){ $filename = "subud_".str_random(10); $extension = $file->getClientOriginalExtension(); $upload_name = $filename.".".$extension; $upload_success = $file->move($this->upload_path, $upload_name); if( $upload_success ) { $music->file_name = $this->upload_path.$upload_name; } else { $error = "Failed uploading file"; return Redirect::route('admin.music')->withErrors($error)->withInput(); } $music->save(); } else { $error = "Invalid file"; return Redirect::route('admin.music')->withErrors($error)->withInput(); } } else { $error = "Null file input"; return Redirect::route('admin.music')->withErrors($error)->withInput(); } } elseif(Input::get('_action') == 'editProcess'){ if(Input::has('id')){ $validator = Validator::make( array( 'Title' => Input::get('title') ), array( 'Title' => 'required' ) ); if ($validator->fails()){ return Redirect::route('admin.music')->withErrors($validator)->withInput(); } $music = Music::find(Input::get('id')); $music->title = Input::get('title'); if(!is_null(Input::file('file_name'))){ $mime = Input::file('file_name')->getMimeType(); if($mime !== 'audio/mpeg'){ $error = "You have to input audio MP3 file"; return Redirect::route('admin.music')->withErrors($error)->withInput(); } if(!file_exists($this->upload_path)) { mkdir($this->upload_path, 0777, true); } $file = Input::file('file_name'); if($file->isValid()){ $filename = "subud_".str_random(10); $extension = $file->getClientOriginalExtension(); $upload_name = $filename.".".$extension; $upload_success = $file->move($this->upload_path, $upload_name); if( $upload_success ) { $music->file_name = $this->upload_path.$upload_name; } else { $error = "Failed uploading file"; return Redirect::route('admin.music')->withErrors($error)->withInput(); } $music->save(); } else { $error = "Invalid file"; return Redirect::route('admin.music')->withErrors($error)->withInput(); } } $music->save(); } } return Redirect::route('admin.music'); } }
benhanks040888/subud
app/controllers/admin/MusicController.php
PHP
mit
3,793
package org.jabref.logic.importer.fetcher; import java.io.IOException; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.Optional; import org.jabref.logic.formatter.bibtexfields.ClearFormatter; import org.jabref.logic.formatter.bibtexfields.NormalizePagesFormatter; import org.jabref.logic.help.HelpFile; import org.jabref.logic.importer.EntryBasedFetcher; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.IdBasedFetcher; import org.jabref.logic.importer.ImportFormatPreferences; import org.jabref.logic.importer.ParseException; import org.jabref.logic.importer.fileformat.BibtexParser; import org.jabref.logic.l10n.Localization; import org.jabref.logic.net.URLDownload; import org.jabref.model.cleanup.FieldFormatterCleanup; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.field.StandardField; import org.jabref.model.entry.identifier.DOI; import org.jabref.model.util.DummyFileUpdateMonitor; import org.jabref.model.util.OptionalUtil; public class DoiFetcher implements IdBasedFetcher, EntryBasedFetcher { public static final String NAME = "DOI"; private final ImportFormatPreferences preferences; public DoiFetcher(ImportFormatPreferences preferences) { this.preferences = preferences; } @Override public String getName() { return DoiFetcher.NAME; } @Override public Optional<HelpFile> getHelpPage() { return Optional.of(HelpFile.FETCHER_DOI); } @Override public Optional<BibEntry> performSearchById(String identifier) throws FetcherException { Optional<DOI> doi = DOI.parse(identifier); try { if (doi.isPresent()) { URL doiURL = new URL(doi.get().getURIAsASCIIString()); // BibTeX data URLDownload download = new URLDownload(doiURL); download.addHeader("Accept", "application/x-bibtex"); String bibtexString = download.asString(); // BibTeX entry Optional<BibEntry> fetchedEntry = BibtexParser.singleFromString(bibtexString, preferences, new DummyFileUpdateMonitor()); fetchedEntry.ifPresent(this::doPostCleanup); return fetchedEntry; } else { throw new FetcherException(Localization.lang("Invalid DOI: '%0'.", identifier)); } } catch (IOException e) { throw new FetcherException(Localization.lang("Connection error"), e); } catch (ParseException e) { throw new FetcherException("Could not parse BibTeX entry", e); } } private void doPostCleanup(BibEntry entry) { new FieldFormatterCleanup(StandardField.PAGES, new NormalizePagesFormatter()).cleanup(entry); new FieldFormatterCleanup(StandardField.URL, new ClearFormatter()).cleanup(entry); } @Override public List<BibEntry> performSearch(BibEntry entry) throws FetcherException { Optional<String> doi = entry.getField(StandardField.DOI); if (doi.isPresent()) { return OptionalUtil.toList(performSearchById(doi.get())); } else { return Collections.emptyList(); } } }
zellerdev/jabref
src/main/java/org/jabref/logic/importer/fetcher/DoiFetcher.java
Java
mit
3,259
from __future__ import division, print_function #, unicode_literals """ Multiples of 3 and 5 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ import numpy as np # Setup. num_max = 1000 basis = [3, 5] factors = [] for i in range(num_max): for k in basis: if not i % k: factors.append(i) break print('\nRange: {:d}'.format(num_max)) print('Number of factors: {:d}'.format(len(factors))) print('The answer: {:d}'.format(np.sum(factors))) # Done.
Who8MyLunch/euler
problem_001.py
Python
mit
632
<# Microsoft provides programming examples for illustration only, without warranty either expressed or implied, including, but not limited to, the implied warranties of merchantability and/or fitness for a particular purpose. This sample assumes that you are familiar with the programming language being demonstrated and the tools used to create and debug procedures. Microsoft support professionals can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific needs. if you have limited programming experience, you may want to contact a Microsoft Certified Partner or the Microsoft fee-based consulting line at (800) 936-5200. HISTORY 08-28-2017 - Created ==============================================================#> Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue | Out-Null function Get-CustomResultSource { <# .SYNOPSIS This cmdlet will return Site Url, Web Url, Name, Creation Date, Status and IsDefault value for each custom search resource source for the specificed site collection. .EXAMPLE Get-CustomResultSource -Site $site -SearchServiceApplication $ssa .FUNCTIONALITY PowerShell Language #> [cmdletbinding()] [OutputType([object[]])] param ( # SPSite to search for custom result sources [Parameter(Mandatory=$true)][Microsoft.SharePoint.SPSite]$Site, # SearchServiceApplication associated with the site collection [Parameter(Mandatory=$true)][Microsoft.Office.Server.Search.Administration.SearchServiceApplication]$SearchServiceApplication ) begin { $siteLevel = [Microsoft.Office.Server.Search.Administration.SearchObjectLevel]::SPSite $webLevel = [Microsoft.Office.Server.Search.Administration.SearchObjectLevel]::SPWeb $defaultSource = $null } process { # we can't read from readlocked sites, so skip them if (-not $site.IsReadLocked ) { $owner = New-Object Microsoft.Office.Server.Search.Administration.SearchObjectOwner( $siteLevel, $site.RootWeb ) $filter = New-Object Microsoft.Office.Server.Search.Administration.SearchObjectFilter( $owner ) $filter.IncludeHigherLevel = $false $federationManager = New-Object Microsoft.Office.Server.Search.Administration.Query.FederationManager($SearchServiceApplication) $siteSources = $federationManager.ListSourcesWithDefault( $filter, $false, [ref]$defaultSource ) # filter out all built in and non-site level result sources $siteSources | ? { -not $_.BuiltIn -and $_.Owner.Level -eq $siteLevel } | SELECT @{ Name="SiteUrl"; Expression={ $site.Url}}, @{ Name="WebUrl"; Expression={ $site.Url}}, Name, CreatedDate, @{ Name="Status"; Expression={ if ($_.Active) { return "Active"}else{ return "Inactive"} }}, @{ Name="IsDefault"; Expression={ $_.Id -eq $defaultSource.Id}} foreach ($web in $site.AllWebs | ? { -not $_.IsAppWeb }) { $owner = New-Object Microsoft.Office.Server.Search.Administration.SearchObjectOwner( $webLevel, $web ) $filter = New-Object Microsoft.Office.Server.Search.Administration.SearchObjectFilter( $owner ) $filter.IncludeHigherLevel = $false $federationManager = New-Object Microsoft.Office.Server.Search.Administration.Query.FederationManager($SearchServiceApplication) $webSources = $federationManager.ListSourcesWithDefault( $filter, $false, [ref]$defaultSource ) # filter out all built in and non-web level result sources $webSources | ? { -not $_.BuiltIn -and $_.Owner.Level -eq $webLevel } | SELECT @{ Name="SiteUrl"; Expression={ $site.Url}}, @{ Name="WebUrl"; Expression={ $web.Url}}, Name, CreatedDate, @{ Name="Status"; Expression={ if ($_.Active) { return "Active"}else{ return "Inactive"} }}, @{ Name="IsDefault"; Expression={ $_.Id -eq $defaultSource.Id}} } } } end { } } # array to store results $customResultSources = @() # get the search service $ssa = Get-SPEnterpriseSearchServiceApplication | SELECT -First 1 # get the custom result sources for all sites in the farm Get-SPSite -Limit All | % { $customResultSources += Get-CustomResultSource -Site $_ -SearchServiceApplication $ssa } # save the results to the ULS logs directory in CSV format $customResultSources | Export-Csv -Path "$($(Get-SPDiagnosticConfig).LogLocation)\CustomResultSources$($(Get-Date).ToString('yyyyMMdd')).csv" -NoTypeInformation
joerodgers/powershell
SharePoint/ServiceApplications/Search/Get-CustomResultSource.ps1
PowerShell
mit
4,744
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>ordinal: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.11.2 / ordinal - 0.5.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> ordinal <small> 0.5.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2021-12-09 02:26:46 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-12-09 02:26:46 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils coq 8.11.2 Formal proof management system num 1.4 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.08.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.08.1 Official release 4.08.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;[email protected]&quot; synopsis: &quot;Ordinal Numbers in Coq&quot; homepage: &quot;https://github.com/minkiminki/Ordinal&quot; dev-repo: &quot;git+https://github.com/minkiminki/Ordinal&quot; bug-reports: &quot;https://github.com/minkiminki/Ordinal/issues&quot; authors: [ &quot;Minki Cho &lt;[email protected]&gt;&quot; ] license: &quot;MIT&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;-f&quot; &quot;Makefile.coq&quot; &quot;install&quot;] depends: [ &quot;coq&quot; {&gt;= &quot;8.12&quot; &amp; &lt; &quot;8.14~&quot;} ] tags: [ &quot;date:2021-06-15&quot; &quot;category:Mathematics/Logic&quot; &quot;keyword:ordinal number&quot; &quot;keyword:set theory&quot; &quot;logpath:Ordinal&quot; ] url { http: &quot;https://github.com/minkiminki/Ordinal/archive/refs/tags/v0.5.0.tar.gz&quot; checksum: &quot;2fcc5d5a6ba96850341e13f16430b255&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-ordinal.0.5.0 coq.8.11.2</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.11.2). The following dependencies couldn&#39;t be met: - coq-ordinal -&gt; coq &gt;= 8.12 Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-ordinal.0.5.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.08.1-2.0.5/released/8.11.2/ordinal/0.5.0.html
HTML
mit
6,503
RSpec.configure do |config| config.before(:suite) do DatabaseCleaner.clean_with(:deletion) end config.before(:each) do DatabaseCleaner.strategy = :transaction end config.before(:each, :js => true) do DatabaseCleaner.strategy = :deletion end config.before(:each) do DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean end end
osulp/valley-rails-generator
templates/database_cleaner_rspec.rb
Ruby
mit
387
s="the quick brown fox jumped over the lazy dog" t = s.split(" ") for v in t: print(v) r = s.split("e") for v in r: print(v) x = s.split() for v in x: print(v) # 2-arg version of split not supported # y = s.split(" ",7) # for v in y: # print v
naitoh/py2rb
tests/strings/split.py
Python
mit
266
<!DOCTYPE html> <html> <head> <title>Zefu Li</title> <link rel="stylesheet" type="text/css" href="official.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <script src="official.js"></script> </head> <body> <ul> <li><a href="#home">Home</a></li> <li><a href="#about">About</a></li> <li><a href="#blog">Blog</a></li> <li><a href="#contact">Contact</a></li> </ul> <header class="header"> <div id="home"><a href="home"></a>Home</div> <div id="text">Hi, I am Zefu Li</marquee></div> <img class="human"src="http://www.newdesignfile.com/postpic/2016/04/human-head-silhouette-vector_396827.png" width="600px" height="600px"> <div class="wifi"><i class="fa fa-feed" aria-hidden="true"></i></div> <div class="questionmark"><i class="fa fa-question" aria-hidden="true"></i></div> <div class="exclamationmark"><i class="fa fa-exclamation" aria-hidden="true"></i></div> </header> <div id="about"><a href="about"></a>About <p>I am currently a senior at Oakland Charter High School. I am passionate about technology especially when it comes to computer science, I also like to solve problems and I will keep thinking about the solutions unless I solved them, I guess I am a little stubborn. Information Technology has started a significant revolution and influenced the world over a decade, therefore I decided to pursue a computer science degree. Technology will keep changing the world and moving us forward, that’s what I believe and I am so glad that I am part of the next generation of tech talent. </p></div> <div id="blog"><a href="blog"></a>Blog <h1>My Journey In dev/Mission</h1> <h2>Coming Soon</h2> </div> <div id="contact"><a href="contact"></a>Contact <a id="Linkedin" href="https://www.linkedin.com/in/zefu-li-23866b140/"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/ca/LinkedIn_logo_initials.png/768px-LinkedIn_logo_initials.png" height="30" width="30"></a> <a id="github" href="https://github.com/seriouswork/seriouswork.github.io"><img src="https://image.flaticon.com/icons/svg/25/25231.svg" height="30" width="30"></a> </div> </body> </html>
seriouswork/seriouswork.github.io
official.html
HTML
mit
2,378
module Xronor class DSL module Checker class ValidationError < StandardError end def required(name, value) invalid = false if value case value when String invalid = value.strip.empty? when Array, Hash invalid = value.empty? end else invalid = true end raise ValidationError.new("'#{name}' is required") if invalid end end end end
dtan4/xronor
lib/xronor/dsl/checker.rb
Ruby
mit
483
var mongoose = require('mongoose'); var statuses = ['open', 'closed', 'as_expected']; var priorities = ['major','regular','minor','enhancement']; var Comment = new mongoose.Schema( { comment: String, username: String, name: String, dca: {type: Date, default: Date.now} } ); var Bug = new mongoose.Schema( { id: {type: String}, name: {type: String, required: true}, desc: String, status: {type: String, default: 'open'}, priority: {type: String, default: 'regular'}, username: { type: String, required: true}, reported_by: {type: String}, company: {type: String, required: true}, comments: [Comment], dca: {type: Date, default: Date.now}, dua: Date } ); Bug.pre('save', function(next) { if (this.id === undefined) { this.id = (new Date()).getTime().toString(); } now = new Date(); this.dua = now; next(); }); module.exports = mongoose.model('Bug', Bug);
baliganikhil/Storm
models/bug.js
JavaScript
mit
1,110
#include "EngineImplDefine.h" void BlendColor::Init(D3DCOLOR defaultColor, D3DCOLOR disabledColor, D3DCOLOR hiddenColor) { for (decltype(States.size()) i = 0; i != States.size(); ++i) { States[i] = defaultColor; } States[STATE_DISABLED] = disabledColor; States[STATE_HIDDEN] = hiddenColor; Current = hiddenColor; } void BlendColor::Blend(CONTROL_STATE iState, float fElapsedTime, float fRate) { D3DXCOLOR destColor = States[iState]; D3DXColorLerp(&Current, &Current, &destColor, 1.0f - powf(fRate, 30 * fElapsedTime)); } void FontTexElement::SetTexture(UINT iTexture, RECT * prcTexture, D3DCOLOR defaultTextureColor) { this->iTexture = iTexture; if (prcTexture) rcTexture = *prcTexture; else SetRectEmpty(&rcTexture); TextureColor.Init(defaultTextureColor); } void FontTexElement::SetFont(UINT iFont, D3DCOLOR defaultFontColor, DWORD dwTextFormat) { this->iFont = iFont; this->dwTextFormat = dwTextFormat; FontColor.Init(defaultFontColor); } void FontTexElement::Refresh() { TextureColor.Current = TextureColor.States[STATE_HIDDEN]; FontColor.Current = FontColor.States[STATE_HIDDEN]; }
ss-torres/UI-Editor
UI Editor/DrawEngine/EngineImplDefine.cpp
C++
mit
1,118
class AddColumnToRequestSchema < ActiveRecord::Migration def change add_column :request_schemata, :name, :string, null: false, default: "" end end
opentie/opentie-app
db/migrate/20150502043108_add_column_to_request_schema.rb
Ruby
mit
155
ActionController::Routing::Routes.draw do |map| map.resources :companies, :member => { :filter_available_members => :get, :delete_member => :post, :add_members => :post, :filter_available_projects => :get, :delete_project => :post, :add_projects => :post } end
splendeo/chiliproject_companies
config/routes.rb
Ruby
mit
283
// // ViewController.h // MKDevice // // Created by Michal Konturek on 18/11/2013. // Copyright (c) 2013 Michal Konturek. All rights reserved. // #import <UIKit/UIKit.h> @interface ViewController : UIViewController @property (nonatomic, strong) IBOutlet UIButton *button; - (IBAction)onAction:(id)sender; @end
michalkonturek/MKDevice
Example/MKDevice/Demo/ViewController.h
C
mit
319