text
stringlengths
2
1.04M
meta
dict
layout: leaf-node title: "Facilitation of formative assessments using clickers in a university physics course" title-url: "http://www.editlib.org/p/44726/article_44726.pdf" author: ["David Majerich","Judith Stull","Susan Varnum","Tiffany Gilles","Joseph Ducette","Judith Stull"] groups: pedagogical-styles categories: formative-assessment topics: scholarly-readings summary: > The paper reports taking a multiple choice test and reviewing the results of the test (formative assessment) improved student grades for every review episode they participated in vs. those in the control group who did not participate. A clicker, btw, is not an electronic device. It is the name of the weekly get together where the quize was taken and reviewed. cite: > Majerich, D. M., Stull, J., Varnum, S. J., & Ducette, J. P. (2011). Facilitation of formative assessments using clickers in a university physics course. Interdisciplinary Journal of E-Learning and Learning Objects, 7(2), 1-14. Retrieved from http://www.editlib.org/p/44726/article_44726.pdf pub-date: 2011-01-01 added-date: 2017-04-28 resource-type: pdf-document ---
{ "content_hash": "199df0302a3c0f8521c7bd67d0d5c8c8", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 230, "avg_line_length": 57.1, "alnum_prop": 0.7609457092819615, "repo_name": "lvollherbst/edtech-test", "id": "135fd439884cd5d7c07789038ce8746459cd06d9", "size": "1146", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "_leaf_nodes/2011-01-01-facilitation-of-formative-assessments-using-clickers-in-a-university-physics-course.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "75203" }, { "name": "HTML", "bytes": "94436" }, { "name": "JavaScript", "bytes": "60717" }, { "name": "Ruby", "bytes": "4992" } ], "symlink_target": "" }
package com.google.android.apps.paco; import org.joda.time.DateMidnight; import org.joda.time.DateTime; import org.joda.time.DateTimeConstants; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.joda.time.format.ISODateTimeFormat; public class TimeUtil { private static DateTimeFormatter timeFormatter = ISODateTimeFormat.time(); static final String DATETIME_FORMAT = "yyyy/MM/dd HH:mm:ssZ"; private static DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(DATETIME_FORMAT); private TimeUtil() { super(); // TODO Auto-generated constructor stub } public static String formatTime(long dateTimeMillis) { return new DateTime(dateTimeMillis).toString(timeFormatter); } public static String formatDateTime(long dateTimeMillis) { return new DateTime(dateTimeMillis).toString(dateTimeFormatter); } public static DateMidnight getMondayOfWeek(DateTime now) { DateMidnight mondayOfWeek = now.toDateMidnight(); int dow = mondayOfWeek.getDayOfWeek(); if (dow != DateTimeConstants.MONDAY) { mondayOfWeek = mondayOfWeek.minusDays(dow - 1); } return mondayOfWeek; } public static boolean isWeekend(int dayOfWeek) { return dayOfWeek == DateTimeConstants.SATURDAY || dayOfWeek == DateTimeConstants.SUNDAY; } public static boolean isWeekend(DateTime dateTime) { return isWeekend(dateTime.getDayOfWeek()); } public static DateTime skipWeekends(DateTime plusDays) { if (plusDays.getDayOfWeek() == DateTimeConstants.SATURDAY) { return plusDays.plusDays(2); } else if (plusDays.getDayOfWeek() == DateTimeConstants.SUNDAY) { return plusDays.plusDays(1); } return plusDays; } }
{ "content_hash": "cef8f002fd9780121db994f52221a14d", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 76, "avg_line_length": 30.789473684210527, "alnum_prop": 0.7435897435897436, "repo_name": "BobEvans/omgpaco", "id": "94a5df2562a1d72edd5d28a4d2714f3e04f218eb", "size": "2362", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Paco/src/com/google/android/apps/paco/TimeUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1019771" }, { "name": "JavaScript", "bytes": "135836" }, { "name": "Ruby", "bytes": "379" }, { "name": "Shell", "bytes": "1906" } ], "symlink_target": "" }
namespace Microsoft.Azure.Management.KeyVault { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// PrivateEndpointConnectionsOperations operations. /// </summary> internal partial class PrivateEndpointConnectionsOperations : IServiceOperations<KeyVaultManagementClient>, IPrivateEndpointConnectionsOperations { /// <summary> /// Initializes a new instance of the PrivateEndpointConnectionsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal PrivateEndpointConnectionsOperations(KeyVaultManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the KeyVaultManagementClient /// </summary> public KeyVaultManagementClient Client { get; private set; } /// <summary> /// Gets the specified private endpoint connection associated with the key /// vault. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group that contains the key vault. /// </param> /// <param name='vaultName'> /// The name of the key vault. /// </param> /// <param name='privateEndpointConnectionName'> /// Name of the private endpoint connection associated with the key vault. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<PrivateEndpointConnection>> GetWithHttpMessagesAsync(string resourceGroupName, string vaultName, string privateEndpointConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (vaultName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vaultName"); } if (vaultName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(vaultName, "^[a-zA-Z0-9-]{3,24}$")) { throw new ValidationException(ValidationRules.Pattern, "vaultName", "^[a-zA-Z0-9-]{3,24}$"); } } if (privateEndpointConnectionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "privateEndpointConnectionName"); } string apiVersion = "2019-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("privateEndpointConnectionName", privateEndpointConnectionName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/privateEndpointConnections/{privateEndpointConnectionName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{privateEndpointConnectionName}", System.Uri.EscapeDataString(privateEndpointConnectionName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PrivateEndpointConnection>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PrivateEndpointConnection>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates the specified private endpoint connection associated with the key /// vault. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group that contains the key vault. /// </param> /// <param name='vaultName'> /// The name of the key vault. /// </param> /// <param name='privateEndpointConnectionName'> /// Name of the private endpoint connection associated with the key vault. /// </param> /// <param name='properties'> /// The intended state of private endpoint connection. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<PrivateEndpointConnection,PrivateEndpointConnectionsPutHeaders>> PutWithHttpMessagesAsync(string resourceGroupName, string vaultName, string privateEndpointConnectionName, PrivateEndpointConnection properties, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (vaultName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vaultName"); } if (vaultName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(vaultName, "^[a-zA-Z0-9-]{3,24}$")) { throw new ValidationException(ValidationRules.Pattern, "vaultName", "^[a-zA-Z0-9-]{3,24}$"); } } if (privateEndpointConnectionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "privateEndpointConnectionName"); } if (properties == null) { throw new ValidationException(ValidationRules.CannotBeNull, "properties"); } string apiVersion = "2019-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("privateEndpointConnectionName", privateEndpointConnectionName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("properties", properties); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Put", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/privateEndpointConnections/{privateEndpointConnectionName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{privateEndpointConnectionName}", System.Uri.EscapeDataString(privateEndpointConnectionName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(properties != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(properties, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PrivateEndpointConnection,PrivateEndpointConnectionsPutHeaders>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PrivateEndpointConnection>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PrivateEndpointConnectionsPutHeaders>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified private endpoint connection associated with the key /// vault. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group that contains the key vault. /// </param> /// <param name='vaultName'> /// The name of the key vault. /// </param> /// <param name='privateEndpointConnectionName'> /// Name of the private endpoint connection associated with the key vault. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<PrivateEndpointConnection,PrivateEndpointConnectionsDeleteHeaders>> DeleteWithHttpMessagesAsync(string resourceGroupName, string vaultName, string privateEndpointConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<PrivateEndpointConnection,PrivateEndpointConnectionsDeleteHeaders> _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, vaultName, privateEndpointConnectionName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes the specified private endpoint connection associated with the key /// vault. /// </summary> /// <param name='resourceGroupName'> /// Name of the resource group that contains the key vault. /// </param> /// <param name='vaultName'> /// The name of the key vault. /// </param> /// <param name='privateEndpointConnectionName'> /// Name of the private endpoint connection associated with the key vault. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<PrivateEndpointConnection,PrivateEndpointConnectionsDeleteHeaders>> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string vaultName, string privateEndpointConnectionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (vaultName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vaultName"); } if (vaultName != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(vaultName, "^[a-zA-Z0-9-]{3,24}$")) { throw new ValidationException(ValidationRules.Pattern, "vaultName", "^[a-zA-Z0-9-]{3,24}$"); } } if (privateEndpointConnectionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "privateEndpointConnectionName"); } string apiVersion = "2019-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("privateEndpointConnectionName", privateEndpointConnectionName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.KeyVault/vaults/{vaultName}/privateEndpointConnections/{privateEndpointConnectionName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{privateEndpointConnectionName}", System.Uri.EscapeDataString(privateEndpointConnectionName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PrivateEndpointConnection,PrivateEndpointConnectionsDeleteHeaders>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PrivateEndpointConnection>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } try { _result.Headers = _httpResponse.GetHeadersAsJson().ToObject<PrivateEndpointConnectionsDeleteHeaders>(JsonSerializer.Create(Client.DeserializationSettings)); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the headers.", _httpResponse.GetHeadersAsJson().ToString(), ex); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
{ "content_hash": "e6ea418a6d52e675bb6ba9521e33bc77", "timestamp": "", "source": "github", "line_count": 743, "max_line_length": 379, "avg_line_length": 47.9650067294751, "alnum_prop": 0.5689152028733374, "repo_name": "yugangw-msft/azure-sdk-for-net", "id": "970a8e9528b0197d579fc32fdcc2a93fef36dc1a", "size": "35991", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "sdk/keyvault/Microsoft.Azure.Management.KeyVault/src/Generated/PrivateEndpointConnectionsOperations.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "118" }, { "name": "Batchfile", "bytes": "817" }, { "name": "C#", "bytes": "55680650" }, { "name": "CSS", "bytes": "685" }, { "name": "Cucumber", "bytes": "89597" }, { "name": "JavaScript", "bytes": "1719" }, { "name": "PowerShell", "bytes": "24329" }, { "name": "Shell", "bytes": "45" } ], "symlink_target": "" }
@(user: models.user.User)@layout.bootstrap("Admin") { @(_navBar(user,"home")) <div class="container"> <div class="row"> <div class="col-md-12"> <p>This is the admin tab</p> </div> </div> <div class="row"> <div class="col-md-12"> <li><a href="@routes.AdminController.contestForm">Create Contest</a></li> <li><a href="@routes.AdminController.inviteUsers">Invite Users</a></li> <li><a href="@routes.AdminController.editUsers">Edit User Roles</a></li> </div> </div> </div> }
{ "content_hash": "9465cb2f9a3a9e26d6d9060d09774768", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 81, "avg_line_length": 27.7, "alnum_prop": 0.5703971119133574, "repo_name": "rynmccrmck/thunderdome", "id": "04129861e147bdb0e788a1e9e5a4d5eda95299c9", "size": "554", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/views/admin.scala.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "330701" }, { "name": "HTML", "bytes": "467613" }, { "name": "JavaScript", "bytes": "8097" }, { "name": "Scala", "bytes": "90105" }, { "name": "XSLT", "bytes": "41986" } ], "symlink_target": "" }
package com.hazelcast.ringbuffer.impl; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.core.HazelcastInstanceAware; import com.hazelcast.core.IFunction; import com.hazelcast.instance.HazelcastInstanceImpl; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.Data; import com.hazelcast.nio.serialization.IdentifiedDataSerializable; import com.hazelcast.ringbuffer.ReadResultSet; import com.hazelcast.spi.serialization.SerializationService; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.IOException; import java.util.AbstractList; import static com.hazelcast.ringbuffer.impl.RingbufferDataSerializerHook.F_ID; import static com.hazelcast.ringbuffer.impl.RingbufferDataSerializerHook.READ_RESULT_SET; import static com.hazelcast.util.Preconditions.checkNotNegative; import static com.hazelcast.util.Preconditions.checkTrue; /** * A list for the {@link com.hazelcast.ringbuffer.impl.operations.ReadManyOperation}. * * The problem with a regular list is that if you store Data objects, then on the receiving side you get * a list with data objects. If you hand this list out to the caller, you have a problem because he sees * data objects instead of deserialized objects. * * @param <E> */ public class ReadResultSetImpl<E> extends AbstractList<E> implements IdentifiedDataSerializable, HazelcastInstanceAware, ReadResultSet<E> { private transient int minSize; private transient int maxSize; private transient IFunction<Object, Boolean> filter; private transient HazelcastInstance hz; private Data[] items; private int size; private int readCount; public ReadResultSetImpl() { } public ReadResultSetImpl(int minSize, int maxSize, HazelcastInstance hz, IFunction<Object, Boolean> filter) { this.minSize = minSize; this.maxSize = maxSize; this.items = new Data[maxSize]; this.hz = hz; this.filter = filter; } public boolean isMaxSizeReached() { return size == maxSize; } public boolean isMinSizeReached() { return size >= minSize; } @SuppressFBWarnings("EI_EXPOSE_REP") public Data[] getDataItems() { return items; } @Override public int readCount() { return readCount; } @Override public void setHazelcastInstance(HazelcastInstance hz) { this.hz = hz; } @Override public E get(int index) { checkNotNegative(index, "index should not be negative"); checkTrue(index < size, "index should not be equal or larger than size"); SerializationService serializationService = getSerializationService(); Data item = items[index]; return serializationService.toObject(item); } private SerializationService getSerializationService() { HazelcastInstanceImpl impl = (HazelcastInstanceImpl) hz; return impl.getSerializationService(); } public void addItem(Object item) { assert size < maxSize; readCount++; if (!acceptable(item)) { return; } items[size] = getSerializationService().toData(item); size++; } private boolean acceptable(Object item) { if (filter == null) { return true; } Object object = getSerializationService().toObject(item); return filter.apply(object); } @Override public boolean add(Object o) { throw new UnsupportedOperationException(); } @Override public int size() { return size; } @Override public int getFactoryId() { return F_ID; } @Override public int getId() { return READ_RESULT_SET; } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeInt(readCount); out.writeInt(size); for (int k = 0; k < size; k++) { out.writeData(items[k]); } } @Override public void readData(ObjectDataInput in) throws IOException { readCount = in.readInt(); size = in.readInt(); items = new Data[size]; for (int k = 0; k < size; k++) { items[k] = in.readData(); } } }
{ "content_hash": "74d403941433b52b718d724655cec385", "timestamp": "", "source": "github", "line_count": 156, "max_line_length": 113, "avg_line_length": 27.692307692307693, "alnum_prop": 0.6743055555555556, "repo_name": "emrahkocaman/hazelcast", "id": "432a12041e6740c8a037c211918ad522399458ea", "size": "4945", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hazelcast/src/main/java/com/hazelcast/ringbuffer/impl/ReadResultSetImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1449" }, { "name": "Java", "bytes": "30517986" }, { "name": "Shell", "bytes": "12217" } ], "symlink_target": "" }
using namespace arangodb; using namespace arangodb::rocksutils; RocksDBValue RocksDBValue::Database(VPackSlice data) { return RocksDBValue(RocksDBEntryType::Database, data); } RocksDBValue RocksDBValue::Collection(VPackSlice data) { return RocksDBValue(RocksDBEntryType::Collection, data); } RocksDBValue RocksDBValue::ReplicatedLog(VPackSlice data) { return RocksDBValue(RocksDBEntryType::ReplicatedLog, data); } RocksDBValue RocksDBValue::ReplicatedState(VPackSlice data) { return RocksDBValue(RocksDBEntryType::ReplicatedState, data); } RocksDBValue RocksDBValue::PrimaryIndexValue(LocalDocumentId const& docId, RevisionId rev) { return RocksDBValue(RocksDBEntryType::PrimaryIndexValue, docId, rev); } RocksDBValue RocksDBValue::EdgeIndexValue(std::string_view vertexId) { return RocksDBValue(RocksDBEntryType::EdgeIndexValue, vertexId); } RocksDBValue RocksDBValue::VPackIndexValue() { return RocksDBValue(RocksDBEntryType::VPackIndexValue); } RocksDBValue RocksDBValue::VPackIndexValue(VPackSlice data) { return RocksDBValue(RocksDBEntryType::VPackIndexValue, data); } RocksDBValue RocksDBValue::ZkdIndexValue() { return RocksDBValue(RocksDBEntryType::ZkdIndexValue); } RocksDBValue RocksDBValue::UniqueZkdIndexValue(LocalDocumentId const& docId) { return RocksDBValue(RocksDBEntryType::UniqueZkdIndexValue, docId, RevisionId::none()); } RocksDBValue RocksDBValue::UniqueVPackIndexValue(LocalDocumentId const& docId) { return RocksDBValue(RocksDBEntryType::UniqueVPackIndexValue, docId, RevisionId::none()); } RocksDBValue RocksDBValue::UniqueVPackIndexValue(LocalDocumentId const& docId, VPackSlice data) { return RocksDBValue(RocksDBEntryType::UniqueVPackIndexValue, docId, data); } RocksDBValue RocksDBValue::View(VPackSlice data) { return RocksDBValue(RocksDBEntryType::View, data); } RocksDBValue RocksDBValue::ReplicationApplierConfig(VPackSlice data) { return RocksDBValue(RocksDBEntryType::ReplicationApplierConfig, data); } RocksDBValue RocksDBValue::KeyGeneratorValue(VPackSlice data) { return RocksDBValue(RocksDBEntryType::KeyGeneratorValue, data); } RocksDBValue RocksDBValue::S2Value(S2Point const& p) { return RocksDBValue(p); } RocksDBValue RocksDBValue::Empty(RocksDBEntryType type) { return RocksDBValue(type); } RocksDBValue RocksDBValue::LogEntry( replication2::PersistingLogEntry const& entry) { return RocksDBValue(RocksDBEntryType::LogEntry, entry); } LocalDocumentId RocksDBValue::documentId(RocksDBValue const& value) { return documentId(value._buffer.data(), value._buffer.size()); } LocalDocumentId RocksDBValue::documentId(rocksdb::Slice const& slice) { return documentId(slice.data(), slice.size()); } LocalDocumentId RocksDBValue::documentId(std::string_view s) { return documentId(s.data(), s.size()); } bool RocksDBValue::revisionId(rocksdb::Slice const& slice, RevisionId& id) { if (slice.size() == sizeof(LocalDocumentId::BaseType) + sizeof(RevisionId)) { char const* data = slice.data() + sizeof(LocalDocumentId::BaseType); id = RevisionId{rocksutils::uint64FromPersistent(data)}; return true; } return false; } RevisionId RocksDBValue::revisionId(RocksDBValue const& value) { RevisionId id; if (revisionId(rocksdb::Slice(value.string()), id)) { return id; } THROW_ARANGO_EXCEPTION_MESSAGE( TRI_ERROR_INTERNAL, "Could not extract revisionId from rocksdb::Slice"); } RevisionId RocksDBValue::revisionId(rocksdb::Slice const& slice) { RevisionId id; if (revisionId(slice, id)) { return id; } THROW_ARANGO_EXCEPTION_MESSAGE( TRI_ERROR_INTERNAL, "Could not extract revisionId from rocksdb::Slice"); } std::string_view RocksDBValue::vertexId(rocksdb::Slice const& s) { return vertexId(s.data(), s.size()); } VPackSlice RocksDBValue::data(RocksDBValue const& value) { return data(value._buffer.data(), value._buffer.size()); } VPackSlice RocksDBValue::data(rocksdb::Slice const& slice) { return data(slice.data(), slice.size()); } VPackSlice RocksDBValue::data(std::string_view s) { return data(s.data(), s.size()); } VPackSlice RocksDBValue::indexStoredValues(rocksdb::Slice const& slice) { TRI_ASSERT( VPackSlice(reinterpret_cast<uint8_t const*>(slice.data())).isArray()); return data(slice.data(), slice.size()); } VPackSlice RocksDBValue::uniqueIndexStoredValues(rocksdb::Slice const& slice) { TRI_ASSERT(VPackSlice(reinterpret_cast<uint8_t const*>(slice.data() + sizeof(uint64_t))) .isArray()); return data(slice.data() + sizeof(uint64_t), slice.size() - sizeof(uint64_t)); } S2Point RocksDBValue::centroid(rocksdb::Slice const& s) { TRI_ASSERT(s.size() == sizeof(double) * 3); return S2Point( intToDouble(uint64FromPersistent(s.data())), intToDouble(uint64FromPersistent(s.data() + sizeof(uint64_t))), intToDouble(uint64FromPersistent(s.data() + sizeof(uint64_t) * 2))); } replication2::LogTerm RocksDBValue::logTerm(rocksdb::Slice const& slice) { TRI_ASSERT(slice.size() >= sizeof(uint64_t)); return replication2::LogTerm(uint64FromPersistent(slice.data())); } replication2::LogPayload RocksDBValue::logPayload(rocksdb::Slice const& slice) { TRI_ASSERT(slice.size() >= sizeof(uint64_t)); auto data = slice.ToStringView(); data.remove_prefix(sizeof(uint64_t)); return replication2::LogPayload::createFromSlice( VPackSlice(reinterpret_cast<uint8_t const*>(data.data()))); } RocksDBValue::RocksDBValue(RocksDBEntryType type) : _type(type), _buffer() {} RocksDBValue::RocksDBValue(RocksDBEntryType type, LocalDocumentId const& docId, RevisionId revision) : _type(type), _buffer() { switch (_type) { case RocksDBEntryType::UniqueVPackIndexValue: case RocksDBEntryType::UniqueZkdIndexValue: case RocksDBEntryType::PrimaryIndexValue: { if (!revision) { _buffer.reserve(sizeof(uint64_t)); uint64ToPersistent(_buffer, docId.id()); // LocalDocumentId } else { _buffer.reserve(sizeof(uint64_t) * 2); uint64ToPersistent(_buffer, docId.id()); // LocalDocumentId rocksutils::uint64ToPersistent(_buffer, revision.id()); // revision } break; } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER); } } RocksDBValue::RocksDBValue(RocksDBEntryType type, LocalDocumentId const& docId, VPackSlice data) : _type(type), _buffer() { switch (_type) { case RocksDBEntryType::UniqueVPackIndexValue: { size_t byteSize = static_cast<size_t>(data.byteSize()); _buffer.reserve(sizeof(uint64_t) + byteSize); uint64ToPersistent(_buffer, docId.id()); // LocalDocumentId _buffer.append(reinterpret_cast<char const*>(data.begin()), byteSize); break; } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER); } } RocksDBValue::RocksDBValue(RocksDBEntryType type, VPackSlice data) : _type(type), _buffer() { switch (_type) { case RocksDBEntryType::VPackIndexValue: TRI_ASSERT(data.isArray()); [[fallthrough]]; case RocksDBEntryType::Database: case RocksDBEntryType::Collection: case RocksDBEntryType::ReplicatedLog: case RocksDBEntryType::View: case RocksDBEntryType::KeyGeneratorValue: case RocksDBEntryType::ReplicationApplierConfig: { size_t byteSize = static_cast<size_t>(data.byteSize()); _buffer.reserve(byteSize); _buffer.append(reinterpret_cast<char const*>(data.begin()), byteSize); break; } case RocksDBEntryType::Document: TRI_ASSERT(false); // use for document => get free schellen break; default: THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER); } } RocksDBValue::RocksDBValue(RocksDBEntryType type, std::string_view data) : _type(type), _buffer() { switch (_type) { case RocksDBEntryType::EdgeIndexValue: { _buffer.reserve(static_cast<size_t>(data.size())); _buffer.append(data.data(), data.size()); break; } default: THROW_ARANGO_EXCEPTION(TRI_ERROR_BAD_PARAMETER); } } RocksDBValue::RocksDBValue(RocksDBEntryType type, replication2::PersistingLogEntry const& entry) { TRI_ASSERT(type == RocksDBEntryType::LogEntry); _type = type; VPackBuilder builder; entry.toVelocyPack(builder, replication2::PersistingLogEntry::omitLogIndex); _buffer.reserve(builder.size()); _buffer.append(reinterpret_cast<const char*>(builder.data()), builder.size()); } RocksDBValue::RocksDBValue(S2Point const& p) : _type(RocksDBEntryType::GeoIndexValue), _buffer() { _buffer.reserve(sizeof(uint64_t) * 3); uint64ToPersistent(_buffer, rocksutils::doubleToInt(p.x())); uint64ToPersistent(_buffer, rocksutils::doubleToInt(p.y())); uint64ToPersistent(_buffer, rocksutils::doubleToInt(p.z())); } LocalDocumentId RocksDBValue::documentId(char const* data, uint64_t size) { TRI_ASSERT(data != nullptr && size >= sizeof(LocalDocumentId::BaseType)); return LocalDocumentId(uint64FromPersistent(data)); } std::string_view RocksDBValue::vertexId(char const* data, size_t size) { TRI_ASSERT(data != nullptr); TRI_ASSERT(size >= sizeof(char)); return std::string_view(data, size); } VPackSlice RocksDBValue::data(char const* data, size_t size) { TRI_ASSERT(data != nullptr); TRI_ASSERT(size >= sizeof(char)); return VPackSlice(reinterpret_cast<uint8_t const*>(data)); }
{ "content_hash": "3e450b4e5d88b74af269931264c75fff", "timestamp": "", "source": "github", "line_count": 285, "max_line_length": 80, "avg_line_length": 33.70175438596491, "alnum_prop": 0.7096304008328995, "repo_name": "wiltonlazary/arangodb", "id": "ea240e6d1417a9a1f0bff3cfd40f9564ccc5c9c4", "size": "10918", "binary": false, "copies": "2", "ref": "refs/heads/devel", "path": "arangod/RocksDBEngine/RocksDBValue.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "61827" }, { "name": "C", "bytes": "309788" }, { "name": "C++", "bytes": "34723629" }, { "name": "CMake", "bytes": "383904" }, { "name": "CSS", "bytes": "210549" }, { "name": "EJS", "bytes": "231166" }, { "name": "HTML", "bytes": "23114" }, { "name": "JavaScript", "bytes": "33741286" }, { "name": "LLVM", "bytes": "14975" }, { "name": "NASL", "bytes": "269512" }, { "name": "NSIS", "bytes": "47138" }, { "name": "Pascal", "bytes": "75391" }, { "name": "Perl", "bytes": "9811" }, { "name": "PowerShell", "bytes": "7869" }, { "name": "Python", "bytes": "184352" }, { "name": "SCSS", "bytes": "255542" }, { "name": "Shell", "bytes": "134504" }, { "name": "TypeScript", "bytes": "179074" }, { "name": "Yacc", "bytes": "79620" } ], "symlink_target": "" }
<?php /** * The Footer widget areas. * * @package Reddle * @since Reddle 1.0 */ ?> <?php /* The footer widget area is triggered if any of the areas * have widgets. So let's check that first. * * If none of the sidebars have widgets, then let's bail early. */ if ( ! is_active_sidebar( 'sidebar-3' ) && ! is_active_sidebar( 'sidebar-4' ) && ! is_active_sidebar( 'sidebar-5' ) ) return; // If we get this far, we have widgets. Let do this. ?> <div id="supplementary" <?php reddle_footer_sidebar_class(); ?>> <?php if ( is_active_sidebar( 'sidebar-3' ) ) : ?> <div id="first" class="widget-area" role="complementary"> <?php dynamic_sidebar( 'sidebar-3' ); ?> </div><!-- #first .widget-area --> <?php endif; ?> <?php if ( is_active_sidebar( 'sidebar-4' ) ) : ?> <div id="second" class="widget-area" role="complementary"> <?php dynamic_sidebar( 'sidebar-4' ); ?> </div><!-- #second .widget-area --> <?php endif; ?> <?php if ( is_active_sidebar( 'sidebar-5' ) ) : ?> <div id="third" class="widget-area" role="complementary"> <?php dynamic_sidebar( 'sidebar-5' ); ?> </div><!-- #third .widget-area --> <?php endif; ?> </div><!-- #supplementary -->
{ "content_hash": "aceeb8bc01f91617f88ae21dc23858e3", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 64, "avg_line_length": 28.975609756097562, "alnum_prop": 0.601010101010101, "repo_name": "NewWorldOrderly/portfolio", "id": "f073ef364d837cf880f5c9f492b6f931fdc785fa", "size": "1188", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "old-site/wp-content/themes/reddle/sidebar-footer.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4763840" }, { "name": "JavaScript", "bytes": "2613430" }, { "name": "PHP", "bytes": "15794892" }, { "name": "Shell", "bytes": "406" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <parent> <groupId>org.jiemamy</groupId> <artifactId>jiemamy-master</artifactId> <version>1.7.3</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>functor</artifactId> <name>Core Functors</name> <version>0.1.1-SNAPSHOT</version> <issueManagement> <system>JIRA</system> <url>http://jira.jiemamy.org/browse/FUNC</url> </issueManagement> <ciManagement> <system>bamboo</system> <url>http://bamboo.jiemamy.org/browse/FUNC-DEF</url> <notifiers> <notifier> <sendOnSuccess>false</sendOnSuccess> <configuration> <recipients>[email protected]</recipients> </configuration> </notifier> </notifiers> </ciManagement> <inceptionYear>2009</inceptionYear> <developers> <developer> <id>ashigeru</id> <name>SUGURU Arakawa</name> <email>ashigeru at users.sourceforge.jp</email> <url>http://d.hatena.ne.jp/ashigeru/</url> <timezone>+9</timezone> </developer> </developers> <scm> <connection>scm:svn:http://svn.jiemamy.org/products/leto/functor/trunk</connection> <developerConnection>scm:svn:http://svn.jiemamy.org/products/leto/functor/trunk</developerConnection> <url>http://fisheye.jiemamy.org/browse/leto/functor/trunk</url> </scm> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit-dep</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-core</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.hamcrest</groupId> <artifactId>hamcrest-library</artifactId> <scope>test</scope> </dependency> </dependencies> <repositories> <repository> <id>jiemamy.org-release</id> <name>Jiemamy Repository</name> <url>http://maven.jiemamy.org/release</url> </repository> </repositories> </project>
{ "content_hash": "6ce191e9e94e806ed710f9d8f2693960", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 201, "avg_line_length": 32.911764705882355, "alnum_prop": 0.6577301161751564, "repo_name": "Jiemamy/functor", "id": "e7745f5344c8a0eec0c2053587d0924786c9f298", "size": "2238", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "76190" } ], "symlink_target": "" }
#pragma once // Pangolin video supports various cameras and file formats through // different 3rd party libraries. // // Video URI's take the following form: // scheme:[param1=value1,param2=value2,...]//device // // scheme = file | files | pango | shmem | dc1394 | uvc | v4l | openni2 | // openni | depthsense | pleora | teli | mjpeg | test | // thread | convert | debayer | split | join | shift | mirror | unpack // // file/files - read one or more streams from image file(s) / video // e.g. "files://~/data/dataset/img_*.jpg" // e.g. "files://~/data/dataset/img_[left,right]_*.pgm" // e.g. "files:///home/user/sequence/foo%03d.jpeg" // // e.g. "file:[fmt=GRAY8,size=640x480]///home/user/raw_image.bin" // e.g. "file:[realtime=1]///home/user/video/movie.pango" // e.g. "file:[stream=1]///home/user/video/movie.avi" // // dc1394 - capture video through a firewire camera // e.g. "dc1394:[fmt=RGB24,size=640x480,fps=30,iso=400,dma=10]//0" // e.g. "dc1394:[fmt=FORMAT7_1,size=640x480,pos=2+2,iso=400,dma=10]//0" // e.g. "dc1394:[fmt=FORMAT7_3,deinterlace=1]//0" // // v4l - capture video from a Video4Linux (USB) camera (normally YUVY422 format) // method=mmap|read|userptr // e.g. "v4l:///dev/video0" // e.g. "v4l[method=mmap]:///dev/video0" // // openni2 - capture video / depth from OpenNI2 SDK (Kinect / Xtrion etc) // imgN=grey|rgb|ir|ir8|ir24|depth|reg_depth // e.g. "openni2://' // e.g. "openni2:[img1=rgb,img2=depth,coloursync=true]//" // e.g. "openni2:[img1=depth,close=closerange,holefilter=true]//" // e.g. "openni2:[size=320x240,fps=60,img1=ir]//" // // openni - capture video / depth from OpenNI 1.0 SDK (Kinect / Xtrion etc) // Sensor modes containing '8' will truncate to 8-bits. // Sensor modes containing '+' explicitly enable IR illuminator // imgN=rgb|ir|ir8|ir+|ir8+|depth|reg_depth // autoexposure=true|false // e.g. "openni://' // e.g. "openni:[img1=rgb,img2=depth]//" // e.g. "openni:[size=320x240,fps=60,img1=ir]//" // // depthsense - capture video / depth from DepthSense SDK. // DepthSenseViewer can be used to alter capture settings. // imgN=depth|rgb // sizeN=QVGA|320x240|... // fpsN=25|30|60|... // e.g. "depthsense://" // e.g. "depthsense:[img1=depth,img2=rgb]//" // // pleora - USB 3 vision cameras accepts any option in the same format reported by eBUSPlayer // e.g. for lightwise cameras: "pleora:[size=512x256,pos=712x512,sn=00000274,ExposureTime=10000,PixelFormat=Mono12p,AcquisitionMode=SingleFrame,TriggerSource=Line0,TriggerMode=On]//" // e.g. for toshiba cameras: "pleora:[size=512x256,pos=712x512,sn=0300056,PixelSize=Bpp12,ExposureTime=10000,ImageFormatSelector=Format1,BinningHorizontal=2,BinningVertical=2]//" // e.g. toshiba alternated "pleora:[UserSetSelector=UserSet1,ExposureTime=10000,PixelSize=Bpp12,Width=1400,OffsetX=0,Height=1800,OffsetY=124,LineSelector=Line1,LineSource=ExposureActive,LineSelector=Line2,LineSource=Off,LineModeAll=6,LineInverterAll=6,UserSetSave=Execute, // UserSetSelector=UserSet2,PixelSize=Bpp12,Width=1400,OffsetX=1048,Height=1800,OffsetY=124,ExposureTime=10000,LineSelector=Line1,LineSource=Off,LineSelector=Line2,LineSource=ExposureActive,LineModeAll=6,LineInverterAll=6,UserSetSave=Execute, // SequentialShutterIndex=1,SequentialShutterEntry=1,SequentialShutterIndex=2,SequentialShutterEntry=2,SequentialShutterTerminateAt=2,SequentialShutterEnable=On,,AcquisitionFrameRateControl=Manual,AcquisitionFrameRate=70]//" // // thread - thread that continuously pulls from the child streams so that data in, unpacking, debayering etc can be decoupled from the main application thread // e.g. thread://pleora:// // e.g. thread://unpack://pleora:[PixelFormat=Mono12p]// // // convert - use FFMPEG to convert between video pixel formats // e.g. "convert:[fmt=RGB24]//v4l:///dev/video0" // e.g. "convert:[fmt=GRAY8]//v4l:///dev/video0" // // mjpeg - capture from (possibly networked) motion jpeg stream using FFMPEG // e.g. "mjpeg://http://127.0.0.1/?action=stream" // // debayer - debayer an input video stream // e.g. "debayer:[tile="BGGR",method="downsample"]//v4l:///dev/video0 // // split - split an input video into a one or more streams based on Region of Interest / memory specification // roiN=X+Y+WxH // memN=Offset:WxH:PitchBytes:Format // e.g. "split:[roi1=0+0+640x480,roi2=640+0+640x480]//files:///home/user/sequence/foo%03d.jpeg" // e.g. "split:[mem1=307200:640x480:1280:GRAY8,roi2=640+0+640x480]//files:///home/user/sequence/foo%03d.jpeg" // e.g. "split:[stream1=2,stream2=1]//pango://video.pango" // // join - join streams // e.g. "join:[sync_tolerance_us=100, sync_continuously=true]//{pleora:[sn=00000274]//}{pleora:[sn=00000275]//}" // // test - output test video sequence // e.g. "test://" // e.g. "test:[size=640x480,fmt=RGB24]//" #include <pangolin/utils/uri.h> #include <pangolin/video/video_exception.h> #include <pangolin/video/video_interface.h> #include <pangolin/video/video_output_interface.h> namespace pangolin { //! Open Video Interface from string specification (as described in this files header) PANGOLIN_EXPORT std::unique_ptr<VideoInterface> OpenVideo(const std::string& uri); //! Open Video Interface from Uri specification PANGOLIN_EXPORT std::unique_ptr<VideoInterface> OpenVideo(const Uri& uri); //! Open VideoOutput Interface from string specification (as described in this files header) PANGOLIN_EXPORT std::unique_ptr<VideoOutputInterface> OpenVideoOutput(const std::string& str_uri); //! Open VideoOutput Interface from Uri specification PANGOLIN_EXPORT std::unique_ptr<VideoOutputInterface> OpenVideoOutput(const Uri& uri); //! Create vector of matching interfaces either through direct cast or filter interface. template<typename T> std::vector<T*> FindMatchingVideoInterfaces( VideoInterface& video ) { std::vector<T*> matches; T* vid = dynamic_cast<T*>(&video); if(vid) { matches.push_back(vid); } VideoFilterInterface* vidf = dynamic_cast<VideoFilterInterface*>(&video); if(vidf) { std::vector<T*> fmatches = vidf->FindMatchingStreams<T>(); matches.insert(matches.begin(), fmatches.begin(), fmatches.end()); } return matches; } template<typename T> T* FindFirstMatchingVideoInterface( VideoInterface& video ) { T* vid = dynamic_cast<T*>(&video); if(vid) { return vid; } VideoFilterInterface* vidf = dynamic_cast<VideoFilterInterface*>(&video); if(vidf) { std::vector<T*> fmatches = vidf->FindMatchingStreams<T>(); if(fmatches.size()) { return fmatches[0]; } } return 0; } inline picojson::value GetVideoFrameProperties(VideoInterface* video) { VideoPropertiesInterface* pi = dynamic_cast<VideoPropertiesInterface*>(video); VideoFilterInterface* fi = dynamic_cast<VideoFilterInterface*>(video); if(pi) { return pi->FrameProperties(); }else if(fi){ if(fi->InputStreams().size() == 1) { return GetVideoFrameProperties(fi->InputStreams()[0]); }else if(fi->InputStreams().size() > 0){ picojson::value streams; for(size_t i=0; i< fi->InputStreams().size(); ++i) { const picojson::value dev_props = GetVideoFrameProperties(fi->InputStreams()[i]); if(dev_props.contains("streams")) { const picojson::value& dev_streams = dev_props["streams"]; for(size_t i=0; i < dev_streams.size(); ++i) { streams.push_back(dev_streams[i]); } }else{ streams.push_back(dev_props); } } if(streams.size() > 1) { picojson::value json = streams[0]; json["streams"] = streams; return json; }else{ return streams[0]; } } } return picojson::value(); } inline picojson::value GetVideoDeviceProperties(VideoInterface* video) { VideoPropertiesInterface* pi = dynamic_cast<VideoPropertiesInterface*>(video); VideoFilterInterface* fi = dynamic_cast<VideoFilterInterface*>(video); if(pi) { return pi->DeviceProperties(); }else if(fi){ if(fi->InputStreams().size() == 1) { return GetVideoDeviceProperties(fi->InputStreams()[0]); }else if(fi->InputStreams().size() > 0){ picojson::value streams; for(size_t i=0; i< fi->InputStreams().size(); ++i) { const picojson::value dev_props = GetVideoDeviceProperties(fi->InputStreams()[i]); if(dev_props.contains("streams")) { const picojson::value& dev_streams = dev_props["streams"]; for(size_t i=0; i < dev_streams.size(); ++i) { streams.push_back(dev_streams[i]); } }else{ streams.push_back(dev_props); } } if(streams.size() > 1) { picojson::value json = streams[0]; json["streams"] = streams; return json; }else{ return streams[0]; } } } return picojson::value(); } }
{ "content_hash": "29f95ddd906396da6b92c00b135e4373", "timestamp": "", "source": "github", "line_count": 232, "max_line_length": 276, "avg_line_length": 40.706896551724135, "alnum_prop": 0.6368064379500212, "repo_name": "randi120/Pangolin", "id": "bf66f751f72ad5c43ad873bcb74244ef5744221a", "size": "10665", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "include/pangolin/video/video.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "141701" }, { "name": "C++", "bytes": "1536190" }, { "name": "CMake", "bytes": "74584" }, { "name": "Objective-C", "bytes": "5433" }, { "name": "Objective-C++", "bytes": "25196" } ], "symlink_target": "" }
<?php /** * @task allocate Allocator * @task resource Managing Resources * @task lease Managing Leases */ final class DrydockAllocatorWorker extends DrydockWorker { protected function doWork() { $lease_phid = $this->getTaskDataValue('leasePHID'); $lease = $this->loadLease($lease_phid); $this->allocateAndAcquireLease($lease); } /* -( Allocator )---------------------------------------------------------- */ /** * Find or build a resource which can satisfy a given lease request, then * acquire the lease. * * @param DrydockLease Requested lease. * @return void * @task allocator */ private function allocateAndAcquireLease(DrydockLease $lease) { $blueprints = $this->loadBlueprintsForAllocatingLease($lease); // If we get nothing back, that means no blueprint is defined which can // ever build the requested resource. This is a permanent failure, since // we don't expect to succeed no matter how many times we try. if (!$blueprints) { $lease ->setStatus(DrydockLeaseStatus::STATUS_BROKEN) ->save(); throw new PhabricatorWorkerPermanentFailureException( pht( 'No active Drydock blueprint exists which can ever allocate a '. 'resource for lease "%s".', $lease->getPHID())); } // First, try to find a suitable open resource which we can acquire a new // lease on. $resources = $this->loadResourcesForAllocatingLease($blueprints, $lease); // If no resources exist yet, see if we can build one. if (!$resources) { $usable_blueprints = $this->removeOverallocatedBlueprints( $blueprints, $lease); // If we get nothing back here, some blueprint claims it can eventually // satisfy the lease, just not right now. This is a temporary failure, // and we expect allocation to succeed eventually. if (!$blueprints) { // TODO: More formal temporary failure here. We should retry this // "soon" but not "immediately". throw new Exception( pht('No blueprints have space to allocate a resource right now.')); } $usable_blueprints = $this->rankBlueprints($blueprints, $lease); $exceptions = array(); foreach ($usable_blueprints as $blueprint) { try { $resources[] = $this->allocateResource($blueprint, $lease); // Bail after allocating one resource, we don't need any more than // this. break; } catch (Exception $ex) { $exceptions[] = $ex; } } if (!$resources) { // TODO: We should distinguish between temporary and permament failures // here. If any blueprint failed temporarily, retry "soon". If none // of these failures were temporary, maybe this should be a permanent // failure? throw new PhutilAggregateException( pht( 'All blueprints failed to allocate a suitable new resource when '. 'trying to allocate lease "%s".', $lease->getPHID()), $exceptions); } // NOTE: We have not acquired the lease yet, so it is possible that the // resource we just built will be snatched up by some other lease before // we can. This is not problematic: we'll retry a little later and should // suceed eventually. } $resources = $this->rankResources($resources, $lease); $exceptions = array(); $allocated = false; foreach ($resources as $resource) { try { $this->acquireLease($resource, $lease); $allocated = true; break; } catch (Exception $ex) { $exceptions[] = $ex; } } if (!$allocated) { // TODO: We should distinguish between temporary and permanent failures // here. If any failures were temporary (specifically, failed to acquire // locks) throw new PhutilAggregateException( pht( 'Unable to acquire lease "%s" on any resouce.', $lease->getPHID()), $exceptions); } } /** * Get all the @{class:DrydockBlueprintImplementation}s which can possibly * build a resource to satisfy a lease. * * This method returns blueprints which might, at some time, be able to * build a resource which can satisfy the lease. They may not be able to * build that resource right now. * * @param DrydockLease Requested lease. * @return list<DrydockBlueprintImplementation> List of qualifying blueprint * implementations. * @task allocator */ private function loadBlueprintImplementationsForAllocatingLease( DrydockLease $lease) { $impls = DrydockBlueprintImplementation::getAllBlueprintImplementations(); $keep = array(); foreach ($impls as $key => $impl) { // Don't use disabled blueprint types. if (!$impl->isEnabled()) { continue; } // Don't use blueprint types which can't allocate the correct kind of // resource. if ($impl->getType() != $lease->getResourceType()) { continue; } if (!$impl->canAnyBlueprintEverAllocateResourceForLease($lease)) { continue; } $keep[$key] = $impl; } return $keep; } /** * Get all the concrete @{class:DrydockBlueprint}s which can possibly * build a resource to satisfy a lease. * * @param DrydockLease Requested lease. * @return list<DrydockBlueprint> List of qualifying blueprints. * @task allocator */ private function loadBlueprintsForAllocatingLease( DrydockLease $lease) { $viewer = $this->getViewer(); $impls = $this->loadBlueprintImplementationsForAllocatingLease($lease); if (!$impls) { return array(); } // TODO: When blueprints can be disabled, this query should ignore disabled // blueprints. $blueprints = id(new DrydockBlueprintQuery()) ->setViewer($viewer) ->withBlueprintClasses(array_keys($impls)) ->execute(); $keep = array(); foreach ($blueprints as $key => $blueprint) { if (!$blueprint->canEverAllocateResourceForLease($lease)) { continue; } $keep[$key] = $blueprint; } return $keep; } /** * Load a list of all resources which a given lease can possibly be * allocated against. * * @param list<DrydockBlueprint> Blueprints which may produce suitable * resources. * @param DrydockLease Requested lease. * @return list<DrydockResource> Resources which may be able to allocate * the lease. * @task allocator */ private function loadResourcesForAllocatingLease( array $blueprints, DrydockLease $lease) { assert_instances_of($blueprints, 'DrydockBlueprint'); $viewer = $this->getViewer(); $resources = id(new DrydockResourceQuery()) ->setViewer($viewer) ->withBlueprintPHIDs(mpull($blueprints, 'getPHID')) ->withTypes(array($lease->getResourceType())) ->withStatuses( array( DrydockResourceStatus::STATUS_PENDING, DrydockResourceStatus::STATUS_OPEN, )) ->execute(); $keep = array(); foreach ($resources as $key => $resource) { $blueprint = $resource->getBlueprint(); if (!$blueprint->canAcquireLeaseOnResource($resource, $lease)) { continue; } $keep[$key] = $resource; } return $keep; } /** * Remove blueprints which are too heavily allocated to build a resource for * a lease from a list of blueprints. * * @param list<DrydockBlueprint> List of blueprints. * @return list<DrydockBlueprint> List with blueprints that can not allocate * a resource for the lease right now removed. * @task allocator */ private function removeOverallocatedBlueprints( array $blueprints, DrydockLease $lease) { assert_instances_of($blueprints, 'DrydockBlueprint'); $keep = array(); foreach ($blueprints as $key => $blueprint) { if (!$blueprint->canAllocateResourceForLease($lease)) { continue; } $keep[$key] = $blueprint; } return $keep; } /** * Rank blueprints by suitability for building a new resource for a * particular lease. * * @param list<DrydockBlueprint> List of blueprints. * @param DrydockLease Requested lease. * @return list<DrydockBlueprint> Ranked list of blueprints. * @task allocator */ private function rankBlueprints(array $blueprints, DrydockLease $lease) { assert_instances_of($blueprints, 'DrydockBlueprint'); // TODO: Implement improvements to this ranking algorithm if they become // available. shuffle($blueprints); return $blueprints; } /** * Rank resources by suitability for allocating a particular lease. * * @param list<DrydockResource> List of resources. * @param DrydockLease Requested lease. * @return list<DrydockResource> Ranked list of resources. * @task allocator */ private function rankResources(array $resources, DrydockLease $lease) { assert_instances_of($resources, 'DrydockResource'); // TODO: Implement improvements to this ranking algorithm if they become // available. shuffle($resources); return $resources; } /* -( Managing Resources )------------------------------------------------- */ /** * Perform an actual resource allocation with a particular blueprint. * * @param DrydockBlueprint The blueprint to allocate a resource from. * @param DrydockLease Requested lease. * @return DrydockResource Allocated resource. * @task resource */ private function allocateResource( DrydockBlueprint $blueprint, DrydockLease $lease) { $resource = $blueprint->allocateResource($lease); $this->validateAllocatedResource($blueprint, $resource, $lease); // If this resource was allocated as a pending resource, queue a task to // activate it. if ($resource->getStatus() == DrydockResourceStatus::STATUS_PENDING) { PhabricatorWorker::scheduleTask( 'DrydockResourceWorker', array( 'resourcePHID' => $resource->getPHID(), ), array( 'objectPHID' => $resource->getPHID(), )); } return $resource; } /** * Check that the resource a blueprint allocated is roughly the sort of * object we expect. * * @param DrydockBlueprint Blueprint which built the resource. * @param wild Thing which the blueprint claims is a valid resource. * @param DrydockLease Lease the resource was allocated for. * @return void * @task resource */ private function validateAllocatedResource( DrydockBlueprint $blueprint, $resource, DrydockLease $lease) { if (!($resource instanceof DrydockResource)) { throw new Exception( pht( 'Blueprint "%s" (of type "%s") is not properly implemented: %s must '. 'return an object of type %s or throw, but returned something else.', $blueprint->getBlueprintName(), $blueprint->getClassName(), 'allocateResource()', 'DrydockResource')); } if (!$resource->isAllocatedResource()) { throw new Exception( pht( 'Blueprint "%s" (of type "%s") is not properly implemented: %s '. 'must actually allocate the resource it returns.', $blueprint->getBlueprintName(), $blueprint->getClassName(), 'allocateResource()')); } $resource_type = $resource->getType(); $lease_type = $lease->getResourceType(); if ($resource_type !== $lease_type) { // TODO: Destroy the resource here? throw new Exception( pht( 'Blueprint "%s" (of type "%s") is not properly implemented: it '. 'built a resource of type "%s" to satisfy a lease requesting a '. 'resource of type "%s".', $blueprint->getBlueprintName(), $blueprint->getClassName(), $resource_type, $lease_type)); } } /* -( Managing Leases )---------------------------------------------------- */ /** * Perform an actual lease acquisition on a particular resource. * * @param DrydockResource Resource to acquire a lease on. * @param DrydockLease Lease to acquire. * @return void * @task lease */ private function acquireLease( DrydockResource $resource, DrydockLease $lease) { $blueprint = $resource->getBlueprint(); $blueprint->acquireLease($resource, $lease); $this->validateAcquiredLease($blueprint, $resource, $lease); // If this lease has been acquired but not activated, queue a task to // activate it. if ($lease->getStatus() == DrydockLeaseStatus::STATUS_ACQUIRED) { PhabricatorWorker::scheduleTask( 'DrydockLeaseWorker', array( 'leasePHID' => $lease->getPHID(), ), array( 'objectPHID' => $lease->getPHID(), )); } } /** * Make sure that a lease was really acquired properly. * * @param DrydockBlueprint Blueprint which created the resource. * @param DrydockResource Resource which was acquired. * @param DrydockLease The lease which was supposedly acquired. * @return void * @task lease */ private function validateAcquiredLease( DrydockBlueprint $blueprint, DrydockResource $resource, DrydockLease $lease) { if (!$lease->isAcquiredLease()) { throw new Exception( pht( 'Blueprint "%s" (of type "%s") is not properly implemented: it '. 'returned from "%s" without acquiring a lease.', $blueprint->getBlueprintName(), $blueprint->getClassName(), 'acquireLease()')); } $lease_id = $lease->getResourceID(); $resource_id = $resource->getID(); if ($lease_id !== $resource_id) { // TODO: Destroy the lease? throw new Exception( pht( 'Blueprint "%s" (of type "%s") is not properly implemented: it '. 'returned from "%s" with a lease acquired on the wrong resource.', $blueprint->getBlueprintName(), $blueprint->getClassName(), 'acquireLease()')); } } }
{ "content_hash": "6e7d3253c6377eda24c1c6bb6279eacf", "timestamp": "", "source": "github", "line_count": 481, "max_line_length": 80, "avg_line_length": 29.532224532224532, "alnum_prop": 0.6238648363252376, "repo_name": "NigelGreenway/phabricator", "id": "428866243412612c19976355db5bef5653139a95", "size": "14205", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/applications/drydock/worker/DrydockAllocatorWorker.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "160255" }, { "name": "CSS", "bytes": "310784" }, { "name": "Groff", "bytes": "30134" }, { "name": "JavaScript", "bytes": "810300" }, { "name": "Makefile", "bytes": "9933" }, { "name": "PHP", "bytes": "12889459" }, { "name": "Python", "bytes": "7385" }, { "name": "Shell", "bytes": "15980" } ], "symlink_target": "" }
<?php /** * Z-BlogPHP Clinic. */ require 'clinic.class.php'; $clinic = new Clinic();
{ "content_hash": "16675d5ecec34044e1e4adf8fa00f88e", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 27, "avg_line_length": 14.5, "alnum_prop": 0.6091954022988506, "repo_name": "birdol/zblogphp", "id": "64b518b0c30d7454c170f688b9b54912799de04d", "size": "87", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "zb_users/plugin/clinic/clinic.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "563125" }, { "name": "HTML", "bytes": "237608" }, { "name": "Hack", "bytes": "105985" }, { "name": "JavaScript", "bytes": "1035195" }, { "name": "PHP", "bytes": "2265358" }, { "name": "TSQL", "bytes": "16325" } ], "symlink_target": "" }
namespace Azure.ResourceManager.Relay.Models { /// <summary> WCF relay type. </summary> public enum RelayType { /// <summary> NetTcp. </summary> NetTcp, /// <summary> Http. </summary> Http } }
{ "content_hash": "61e7e0dbb73da30827f7a18c65234508", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 44, "avg_line_length": 21.90909090909091, "alnum_prop": 0.5518672199170125, "repo_name": "Azure/azure-sdk-for-net", "id": "7031faf79fefe6e41178b6fe01c88f8734fccaf4", "size": "379", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/relay/Azure.ResourceManager.Relay/src/Generated/Models/RelayType.cs", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package client import ( "errors" "golang.org/x/net/context" "github.com/keybase/cli" "github.com/keybase/client/go/libcmdline" "github.com/keybase/client/go/libkb" keybase1 "github.com/keybase/client/go/protocol/keybase1" ) // CmdSimpleFSCopy is the 'fs cp' command. type CmdSimpleFSCopy struct { libkb.Contextified src []keybase1.Path dest keybase1.Path recurse bool interactive bool force bool opCanceler *OpCanceler } var _ Canceler = (*CmdSimpleFSCopy)(nil) // NewCmdSimpleFSCopy creates a new cli.Command. func NewCmdSimpleFSCopy(cl *libcmdline.CommandLine, g *libkb.GlobalContext) cli.Command { return cli.Command{ Name: "cp", ArgumentHelp: "<source> [source] <dest>", Usage: "copy one or more directory elements to dest", Action: func(c *cli.Context) { cl.ChooseCommand(&CmdSimpleFSCopy{ Contextified: libkb.NewContextified(g), opCanceler: NewOpCanceler(g), }, "cp", c) cl.SetNoStandalone() }, Flags: []cli.Flag{ cli.BoolFlag{ Name: "r, recursive", Usage: "Recurse into subdirectories", }, cli.BoolFlag{ Name: "i, interactive", Usage: "Prompt before overwrite", }, cli.BoolFlag{ Name: "f, force", Usage: "force overwrite", }, cli.IntFlag{ Name: "rev", Usage: "a revision number for the KBFS folder of the source paths", }, cli.StringFlag{ Name: "time", Usage: "a time for the KBFS folder of the source paths (eg \"2018-07-27 22:05\")", }, cli.StringFlag{ Name: "reltime, relative-time", Usage: "a relative time for the KBFS folder of the source paths (eg \"5m\")", }, }, } } // Run runs the command in client/server mode. func (c *CmdSimpleFSCopy) Run() error { cli, err := GetSimpleFSClient(c.G()) if err != nil { return err } ctx := context.TODO() c.G().Log.Debug("SimpleFSCopy (recursive: %v) to: %s", c.recurse, c.dest) destPaths, err := doSimpleFSGlob(ctx, c.G(), cli, c.src) if err != nil { return err } // Eat the error because it's ok here if the dest doesn't exist isDestDir, destPathString, _ := checkPathIsDir(ctx, cli, c.dest) for _, src := range destPaths { var dest keybase1.Path dest, err = makeDestPath(ctx, c.G(), cli, src, c.dest, isDestDir, destPathString) c.G().Log.Debug("SimpleFSCopy %s -> %s, %v", src, dest, isDestDir) if err == ErrTargetFileExists { if c.interactive { err = doOverwritePrompt(c.G(), dest.String()) } else if c.force { err = nil } } if err != nil { c.G().Log.Debug("SimpleFSCopy can't get paths together") return err } // Don't spawn new jobs if we've been cancelled. // TODO: This is still a race condition, if we get cancelled immediately after. if c.opCanceler.IsCancelled() { break } opid, err2 := cli.SimpleFSMakeOpid(ctx) if err2 != nil { return err2 } c.opCanceler.AddOp(opid) if c.recurse { err = cli.SimpleFSCopyRecursive(ctx, keybase1.SimpleFSCopyRecursiveArg{ OpID: opid, Src: src, Dest: dest, }) } else { err = cli.SimpleFSCopy(ctx, keybase1.SimpleFSCopyArg{ OpID: opid, Src: src, Dest: dest, }) } if err != nil { break } err = cli.SimpleFSWait(ctx, opid) if err != nil { break } } return err } // ParseArgv gets the required arguments for this command. func (c *CmdSimpleFSCopy) ParseArgv(ctx *cli.Context) error { var err error c.recurse = ctx.Bool("recursive") c.interactive = ctx.Bool("interactive") c.force = ctx.Bool("force") if c.force && c.interactive { return errors.New("force and interactive are incompatible") } c.src, c.dest, err = parseSrcDestArgs(c.G(), ctx, "cp") return err } // GetUsage says what this command needs to operate. func (c *CmdSimpleFSCopy) GetUsage() libkb.Usage { return libkb.Usage{ Config: true, KbKeyring: true, API: true, } } func (c *CmdSimpleFSCopy) Cancel() error { return c.opCanceler.Cancel() }
{ "content_hash": "86903ded6d3c199f69e69eacf63c6b8c", "timestamp": "", "source": "github", "line_count": 171, "max_line_length": 89, "avg_line_length": 23.18713450292398, "alnum_prop": 0.6506935687263556, "repo_name": "keybase/client", "id": "afa2900f246bc0c8dbc10bb8d1c2457dc2b8db59", "size": "4087", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "go/client/cmd_simplefs_copy.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "17403" }, { "name": "C", "bytes": "183175" }, { "name": "C++", "bytes": "26935" }, { "name": "CMake", "bytes": "2524" }, { "name": "CSS", "bytes": "46433" }, { "name": "CoffeeScript", "bytes": "28635" }, { "name": "Dockerfile", "bytes": "19841" }, { "name": "Go", "bytes": "32360664" }, { "name": "HTML", "bytes": "7113636" }, { "name": "Java", "bytes": "144690" }, { "name": "JavaScript", "bytes": "113705" }, { "name": "Makefile", "bytes": "8579" }, { "name": "Objective-C", "bytes": "1419995" }, { "name": "Objective-C++", "bytes": "34802" }, { "name": "Perl", "bytes": "2673" }, { "name": "Python", "bytes": "25189" }, { "name": "Roff", "bytes": "108890" }, { "name": "Ruby", "bytes": "38112" }, { "name": "Shell", "bytes": "186628" }, { "name": "Starlark", "bytes": "1928" }, { "name": "Swift", "bytes": "217" }, { "name": "TypeScript", "bytes": "2493" }, { "name": "XSLT", "bytes": "914" } ], "symlink_target": "" }
<?php namespace Sabre\VObject\Property\ICalendar; use Sabre\VObject\DateTimeParser; use Sabre\VObject\Property; use Sabre\Xml; class Period extends Property { /** * In case this is a multi-value property. This string will be used as a * delimiter. * * @var string|null */ public $delimiter = ','; /** * Sets a raw value coming from a mimedir (iCalendar/vCard) file. * * This has been 'unfolded', so only 1 line will be passed. Unescaping is * not yet done, but parameters are not included. * * @param string $val */ public function setRawMimeDirValue($val) { $this->setValue(explode($this->delimiter, $val)); } /** * Returns a raw mime-dir representation of the value. * * @return string */ public function getRawMimeDirValue() { return implode($this->delimiter, $this->getParts()); } /** * Returns the type of value. * * This corresponds to the VALUE= parameter. Every property also has a * 'default' valueType. * * @return string */ public function getValueType() { return 'PERIOD'; } /** * Sets the json value, as it would appear in a jCard or jCal object. * * The value must always be an array. * * @param array $value */ public function setJsonValue(array $value) { $value = array_map( function ($item) { return strtr(implode('/', $item), [':' => '', '-' => '']); }, $value ); parent::setJsonValue($value); } /** * Returns the value, in the format it should be encoded for json. * * This method must always return an array. * * @return array */ public function getJsonValue() { $return = []; foreach ($this->getParts() as $item) { list($start, $end) = explode('/', $item, 2); $start = DateTimeParser::parseDateTime($start); // This is a duration value. if ('P' === $end[0]) { $return[] = [ $start->format('Y-m-d\\TH:i:s'), $end, ]; } else { $end = DateTimeParser::parseDateTime($end); $return[] = [ $start->format('Y-m-d\\TH:i:s'), $end->format('Y-m-d\\TH:i:s'), ]; } } return $return; } /** * This method serializes only the value of a property. This is used to * create xCard or xCal documents. * * @param Xml\Writer $writer XML writer */ protected function xmlSerializeValue(Xml\Writer $writer) { $writer->startElement(strtolower($this->getValueType())); $value = $this->getJsonValue(); $writer->writeElement('start', $value[0][0]); if ('P' === $value[0][1][0]) { $writer->writeElement('duration', $value[0][1]); } else { $writer->writeElement('end', $value[0][1]); } $writer->endElement(); } }
{ "content_hash": "785927badc6e018df5dbf0627f3e28cf", "timestamp": "", "source": "github", "line_count": 127, "max_line_length": 77, "avg_line_length": 24.929133858267715, "alnum_prop": 0.5104232469993683, "repo_name": "linagora/sabre-vobject", "id": "17bfa5c5c6f5117282117cbacd460c5eabe52ea2", "size": "3476", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "lib/Property/ICalendar/Period.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "PHP", "bytes": "1068596" } ], "symlink_target": "" }
<!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_03) on Tue Nov 06 09:34:23 CST 2012 --> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Class org.eclipse.jetty.util.Atomics (Jetty :: Aggregate :: All core Jetty 8.1.8.v20121106 API)</title> <meta name="date" content="2012-11-06"> <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="Uses of Class org.eclipse.jetty.util.Atomics (Jetty :: Aggregate :: All core Jetty 8.1.8.v20121106 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><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/eclipse/jetty/util/Atomics.html" title="class in org.eclipse.jetty.util">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-all.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?org/eclipse/jetty/util//class-useAtomics.html" target="_top">Frames</a></li> <li><a href="Atomics.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"> <h2 title="Uses of Class org.eclipse.jetty.util.Atomics" class="title">Uses of Class<br>org.eclipse.jetty.util.Atomics</h2> </div> <div class="classUseContainer">No usage of org.eclipse.jetty.util.Atomics</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><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/eclipse/jetty/util/Atomics.html" title="class in org.eclipse.jetty.util">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-all.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?org/eclipse/jetty/util//class-useAtomics.html" target="_top">Frames</a></li> <li><a href="Atomics.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; 1995-2012 <a href="http://www.mortbay.com">Mort Bay Consulting</a>. All Rights Reserved.</small></p> </body> </html>
{ "content_hash": "3a356a4944ef40e8d0114512a7b2d858", "timestamp": "", "source": "github", "line_count": 117, "max_line_length": 145, "avg_line_length": 37.504273504273506, "alnum_prop": 0.6121239744758432, "repo_name": "oberlej/WebServeur-Ensimag", "id": "f9898bc0bc2533110c92d01f7774dd6cf219d3d2", "size": "4388", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "javadoc/org/eclipse/jetty/util/class-use/Atomics.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2245" }, { "name": "HTML", "bytes": "26002" }, { "name": "Java", "bytes": "53281" }, { "name": "JavaScript", "bytes": "31677" }, { "name": "Shell", "bytes": "33033" } ], "symlink_target": "" }
import * as L from 'leaflet'; declare module 'leaflet' { interface MapOptions { fullscreenControl?: true | {pseudoFullscreen: boolean}; } }
{ "content_hash": "c83e56166aaaa96cf5150957b9031463", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 63, "avg_line_length": 22.428571428571427, "alnum_prop": 0.6560509554140127, "repo_name": "nycdotnet/DefinitelyTyped", "id": "bf354e9155091a9c6c3703a6b92fc1178a0134ac", "size": "399", "binary": false, "copies": "14", "ref": "refs/heads/master", "path": "types/leaflet-fullscreen/index.d.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1193" }, { "name": "TypeScript", "bytes": "20263400" } ], "symlink_target": "" }
from __future__ import absolute_import from mock import patch from datetime import datetime from django.core.urlresolvers import reverse from sentry.models import ( Activity, File, Release, ReleaseCommit, ReleaseFile, ReleaseProject, Repository ) from sentry.testutils import APITestCase class ReleaseDetailsTest(APITestCase): def test_simple(self): user = self.create_user(is_staff=False, is_superuser=False) org = self.organization org.flags.allow_joinleave = False org.save() team1 = self.create_team(organization=org) team2 = self.create_team(organization=org) project = self.create_project(team=team1, organization=org) project2 = self.create_project(team=team2, organization=org) release = Release.objects.create( organization_id=org.id, version='abcabcabc', ) release2 = Release.objects.create( organization_id=org.id, version='12345678', ) release.add_project(project) release2.add_project(project2) self.create_member(teams=[team1], user=user, organization=org) self.login_as(user=user) ReleaseProject.objects.filter( project=project, release=release ).update(new_groups=5) url = reverse('sentry-api-0-organization-release-details', kwargs={ 'organization_slug': org.slug, 'version': release.version, }) response = self.client.get(url) assert response.status_code == 200, response.content assert response.data['version'] == release.version assert response.data['newGroups'] == 5 # no access url = reverse('sentry-api-0-organization-release-details', kwargs={ 'organization_slug': org.slug, 'version': release2.version, }) response = self.client.get(url) assert response.status_code == 403 def test_multiple_projects(self): user = self.create_user(is_staff=False, is_superuser=False) org = self.organization org.flags.allow_joinleave = False org.save() team1 = self.create_team(organization=org) team2 = self.create_team(organization=org) project = self.create_project(team=team1, organization=org) project2 = self.create_project(team=team2, organization=org) release = Release.objects.create( organization_id=org.id, version='abcabcabc', ) release.add_project(project) release.add_project(project2) self.create_member(teams=[team1, team2], user=user, organization=org) self.login_as(user=user) url = reverse('sentry-api-0-organization-release-details', kwargs={ 'organization_slug': org.slug, 'version': release.version, }) response = self.client.get(url) assert response.status_code == 200, response.content class UpdateReleaseDetailsTest(APITestCase): @patch('sentry.tasks.commits.fetch_commits') def test_simple(self, mock_fetch_commits): user = self.create_user(is_staff=False, is_superuser=False) org = self.organization org.flags.allow_joinleave = False org.save() repo = Repository.objects.create( organization_id=org.id, name='example/example', provider='dummy', ) repo2 = Repository.objects.create( organization_id=org.id, name='example/example2', provider='dummy', ) team1 = self.create_team(organization=org) team2 = self.create_team(organization=org) project = self.create_project(team=team1, organization=org) project2 = self.create_project(team=team2, organization=org) base_release = Release.objects.create( organization_id=org.id, version='000000000', ) base_release.add_project(project) release = Release.objects.create( organization_id=org.id, version='abcabcabc', ) release2 = Release.objects.create( organization_id=org.id, version='12345678', ) release.add_project(project) release2.add_project(project2) self.create_member(teams=[team1], user=user, organization=org) self.login_as(user=user) url = reverse('sentry-api-0-organization-release-details', kwargs={ 'organization_slug': org.slug, 'version': base_release.version, }) self.client.put(url, { 'ref': 'master', 'headCommits': [ {'currentId': '0' * 40, 'repository': repo.name}, {'currentId': '0' * 40, 'repository': repo2.name}, ], }) url = reverse('sentry-api-0-organization-release-details', kwargs={ 'organization_slug': org.slug, 'version': release.version, }) response = self.client.put(url, { 'ref': 'master', 'refs': [ {'commit': 'a' * 40, 'repository': repo.name}, {'commit': 'b' * 40, 'repository': repo2.name}, ], }) mock_fetch_commits.apply_async.assert_called_with( kwargs={ 'release_id': release.id, 'user_id': user.id, 'refs': [ {'commit': 'a' * 40, 'repository': repo.name}, {'commit': 'b' * 40, 'repository': repo2.name}, ], 'prev_release_id': base_release.id, } ) assert response.status_code == 200, response.content assert response.data['version'] == release.version release = Release.objects.get(id=release.id) assert release.ref == 'master' # no access url = reverse('sentry-api-0-organization-release-details', kwargs={ 'organization_slug': org.slug, 'version': release2.version, }) response = self.client.put(url, {'ref': 'master'}) assert response.status_code == 403 @patch('sentry.tasks.commits.fetch_commits') def test_deprecated_head_commits(self, mock_fetch_commits): user = self.create_user(is_staff=False, is_superuser=False) org = self.organization org.flags.allow_joinleave = False org.save() repo = Repository.objects.create( organization_id=org.id, name='example/example', provider='dummy', ) repo2 = Repository.objects.create( organization_id=org.id, name='example/example2', provider='dummy', ) team1 = self.create_team(organization=org) team2 = self.create_team(organization=org) project = self.create_project(team=team1, organization=org) project2 = self.create_project(team=team2, organization=org) base_release = Release.objects.create( organization_id=org.id, version='000000000', ) base_release.add_project(project) release = Release.objects.create( organization_id=org.id, version='abcabcabc', ) release2 = Release.objects.create( organization_id=org.id, version='12345678', ) release.add_project(project) release2.add_project(project2) self.create_member(teams=[team1], user=user, organization=org) self.login_as(user=user) url = reverse('sentry-api-0-organization-release-details', kwargs={ 'organization_slug': org.slug, 'version': base_release.version, }) self.client.put(url, { 'ref': 'master', 'headCommits': [ {'currentId': '0' * 40, 'repository': repo.name}, {'currentId': '0' * 40, 'repository': repo2.name}, ], }) url = reverse('sentry-api-0-organization-release-details', kwargs={ 'organization_slug': org.slug, 'version': release.version, }) response = self.client.put(url, { 'ref': 'master', 'headCommits': [ {'currentId': 'a' * 40, 'repository': repo.name}, {'currentId': 'b' * 40, 'repository': repo2.name}, ], }) mock_fetch_commits.apply_async.assert_called_with( kwargs={ 'release_id': release.id, 'user_id': user.id, 'refs': [ {'commit': 'a' * 40, 'previousCommit': None, 'repository': repo.name}, {'commit': 'b' * 40, 'previousCommit': None, 'repository': repo2.name}, ], 'prev_release_id': base_release.id, } ) assert response.status_code == 200, response.content assert response.data['version'] == release.version release = Release.objects.get(id=release.id) assert release.ref == 'master' # no access url = reverse('sentry-api-0-organization-release-details', kwargs={ 'organization_slug': org.slug, 'version': release2.version, }) response = self.client.put(url, {'ref': 'master'}) assert response.status_code == 403 def test_commits(self): user = self.create_user(is_staff=False, is_superuser=False) org = self.organization org.flags.allow_joinleave = False org.save() team = self.create_team(organization=org) project = self.create_project(team=team, organization=org) release = Release.objects.create( organization_id=org.id, version='abcabcabc', ) release.add_project(project) self.create_member(teams=[team], user=user, organization=org) self.login_as(user=user) url = reverse('sentry-api-0-organization-release-details', kwargs={ 'organization_slug': org.slug, 'version': release.version, }) response = self.client.put(url, data={ 'commits': [ {'id': 'a' * 40}, {'id': 'b' * 40}, ], }) assert response.status_code == 200, (response.status_code, response.content) rc_list = list(ReleaseCommit.objects.filter( release=release, ).select_related('commit', 'commit__author').order_by('order')) assert len(rc_list) == 2 for rc in rc_list: assert rc.organization_id == org.id def test_activity_generation(self): user = self.create_user(is_staff=False, is_superuser=False) org = self.organization org.flags.allow_joinleave = False org.save() team = self.create_team(organization=org) project = self.create_project(team=team, organization=org) release = Release.objects.create( organization_id=org.id, version='abcabcabc', ) release.add_project(project) self.create_member(teams=[team], user=user, organization=org) self.login_as(user=user) url = reverse('sentry-api-0-organization-release-details', kwargs={ 'organization_slug': org.slug, 'version': release.version, }) response = self.client.put(url, data={ 'dateReleased': datetime.utcnow().isoformat() + 'Z', }) assert response.status_code == 200, (response.status_code, response.content) release = Release.objects.get(id=release.id) assert release.date_released activity = Activity.objects.filter( type=Activity.RELEASE, project=project, ident=release.version, ) assert activity.exists() class ReleaseDeleteTest(APITestCase): def test_simple(self): user = self.create_user(is_staff=False, is_superuser=False) org = self.organization org.flags.allow_joinleave = False org.save() team = self.create_team(organization=org) project = self.create_project(team=team, organization=org) release = Release.objects.create( organization_id=org.id, version='abcabcabc', ) release.add_project(project) self.create_member(teams=[team], user=user, organization=org) self.login_as(user=user) release_file = ReleaseFile.objects.create( organization_id=project.organization_id, release=release, file=File.objects.create( name='application.js', type='release.file', ), name='http://example.com/application.js' ) url = reverse('sentry-api-0-organization-release-details', kwargs={ 'organization_slug': org.slug, 'version': release.version, }) response = self.client.delete(url) assert response.status_code == 204, response.content assert not Release.objects.filter(id=release.id).exists() assert not ReleaseFile.objects.filter(id=release_file.id).exists() def test_existing_group(self): user = self.create_user(is_staff=False, is_superuser=False) org = self.organization org.flags.allow_joinleave = False org.save() team = self.create_team(organization=org) project = self.create_project(team=team, organization=org) release = Release.objects.create( organization_id=org.id, version='abcabcabc', ) release.add_project(project) self.create_group(first_release=release) self.create_member(teams=[team], user=user, organization=org) self.login_as(user=user) url = reverse('sentry-api-0-organization-release-details', kwargs={ 'organization_slug': org.slug, 'version': release.version, }) response = self.client.delete(url) assert response.status_code == 400, response.content assert Release.objects.filter(id=release.id).exists() def test_bad_repo_name(self): user = self.create_user(is_staff=False, is_superuser=False) org = self.create_organization() org.flags.allow_joinleave = False org.save() team = self.create_team(organization=org) project = self.create_project( name='foo', organization=org, team=team ) release = Release.objects.create( organization_id=org.id, version='abcabcabc', ) release.add_project(project) self.create_member(teams=[team], user=user, organization=org) self.login_as(user=user) url = reverse('sentry-api-0-organization-release-details', kwargs={ 'organization_slug': org.slug, 'version': release.version, }) response = self.client.put(url, data={ 'version': '1.2.1', 'projects': [project.slug], 'refs': [{ 'repository': 'not_a_repo', 'commit': 'a' * 40, }] }) assert response.status_code == 400 assert response.data == { 'refs': [u'Invalid repository names: not_a_repo'] }
{ "content_hash": "dd860b7442069527bcf03f955b101167", "timestamp": "", "source": "github", "line_count": 481, "max_line_length": 91, "avg_line_length": 32.22037422037422, "alnum_prop": 0.5696864111498258, "repo_name": "JackDanger/sentry", "id": "cf580b1f27f91799891f950deb0128abe7fc5438", "size": "15498", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/sentry/api/endpoints/test_organization_release_details.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "583430" }, { "name": "HTML", "bytes": "319622" }, { "name": "JavaScript", "bytes": "624672" }, { "name": "Makefile", "bytes": "2660" }, { "name": "Python", "bytes": "6279717" } ], "symlink_target": "" }
/** * AUTOMATICALLY GENERATED CODE - DO NOT MODIFY */ package datatypes // no documentation yet type Auxiliary_Marketing_Event struct { Entity // no documentation yet CreateDate *Time `json:"createDate,omitempty" xmlrpc:"createDate,omitempty"` // no documentation yet EnabledFlag *int `json:"enabledFlag,omitempty" xmlrpc:"enabledFlag,omitempty"` // no documentation yet EndDate *Time `json:"endDate,omitempty" xmlrpc:"endDate,omitempty"` // no documentation yet Location *string `json:"location,omitempty" xmlrpc:"location,omitempty"` // no documentation yet ModifyDate *Time `json:"modifyDate,omitempty" xmlrpc:"modifyDate,omitempty"` // no documentation yet StartDate *Time `json:"startDate,omitempty" xmlrpc:"startDate,omitempty"` // no documentation yet Title *string `json:"title,omitempty" xmlrpc:"title,omitempty"` // no documentation yet Url *string `json:"url,omitempty" xmlrpc:"url,omitempty"` } // no documentation yet type Auxiliary_Network_Status struct { Entity } // A SoftLayer_Auxiliary_Notification_Emergency data object represents a notification event being broadcast to the SoftLayer customer base. It is used to provide information regarding outages or current known issues. type Auxiliary_Notification_Emergency struct { Entity // The date this event was created. CreateDate *Time `json:"createDate,omitempty" xmlrpc:"createDate,omitempty"` // The device (if any) effected by this event. Device *string `json:"device,omitempty" xmlrpc:"device,omitempty"` // The duration of this event. Duration *string `json:"duration,omitempty" xmlrpc:"duration,omitempty"` // The device (if any) effected by this event. Id *int `json:"id,omitempty" xmlrpc:"id,omitempty"` // The location effected by this event. Location *string `json:"location,omitempty" xmlrpc:"location,omitempty"` // A message describing this event. Message *string `json:"message,omitempty" xmlrpc:"message,omitempty"` // The last date this event was modified. ModifyDate *Time `json:"modifyDate,omitempty" xmlrpc:"modifyDate,omitempty"` // The service(s) (if any) effected by this event. ServicesAffected *string `json:"servicesAffected,omitempty" xmlrpc:"servicesAffected,omitempty"` // The signature of the SoftLayer employee department associated with this notification. Signature *Auxiliary_Notification_Emergency_Signature `json:"signature,omitempty" xmlrpc:"signature,omitempty"` // The date this event will start. StartDate *Time `json:"startDate,omitempty" xmlrpc:"startDate,omitempty"` // The status of this notification. Status *Auxiliary_Notification_Emergency_Status `json:"status,omitempty" xmlrpc:"status,omitempty"` // Current status record for this event. StatusId *int `json:"statusId,omitempty" xmlrpc:"statusId,omitempty"` } // Every SoftLayer_Auxiliary_Notification_Emergency has a signatureId that references a SoftLayer_Auxiliary_Notification_Emergency_Signature data type. The signature is the user or group responsible for the current event. type Auxiliary_Notification_Emergency_Signature struct { Entity // The name or signature for the current Emergency Notification. Name *string `json:"name,omitempty" xmlrpc:"name,omitempty"` } // Every SoftLayer_Auxiliary_Notification_Emergency has a statusId that references a SoftLayer_Auxiliary_Notification_Emergency_Status data type. The status is used to determine the current state of the event. type Auxiliary_Notification_Emergency_Status struct { Entity // A name describing the status of the current Emergency Notification. Name *string `json:"name,omitempty" xmlrpc:"name,omitempty"` } // The SoftLayer_Auxiliary_Shipping_Courier data type contains general information relating the different (major) couriers that SoftLayer may use for shipping. type Auxiliary_Shipping_Courier struct { Entity // The unique id of the shipping courier. Id *int `json:"id,omitempty" xmlrpc:"id,omitempty"` // The unique keyname of the shipping courier. KeyName *string `json:"keyName,omitempty" xmlrpc:"keyName,omitempty"` // The name of the shipping courier. Name *string `json:"name,omitempty" xmlrpc:"name,omitempty"` // The url to shipping courier's website. Url *string `json:"url,omitempty" xmlrpc:"url,omitempty"` } // no documentation yet type Auxiliary_Shipping_Courier_Type struct { Entity // no documentation yet Courier []Auxiliary_Shipping_Courier `json:"courier,omitempty" xmlrpc:"courier,omitempty"` // A count of CourierCount *uint `json:"courierCount,omitempty" xmlrpc:"courierCount,omitempty"` // no documentation yet Description *string `json:"description,omitempty" xmlrpc:"description,omitempty"` // no documentation yet Id *int `json:"id,omitempty" xmlrpc:"id,omitempty"` // no documentation yet KeyName *string `json:"keyName,omitempty" xmlrpc:"keyName,omitempty"` // no documentation yet Name *string `json:"name,omitempty" xmlrpc:"name,omitempty"` }
{ "content_hash": "66320329dccd8fea90b223d3ae71d8ea", "timestamp": "", "source": "github", "line_count": 138, "max_line_length": 223, "avg_line_length": 35.7463768115942, "alnum_prop": 0.768903304277316, "repo_name": "softlayer/softlayer-go", "id": "7a9d8f69266ddec52969756be40b8d18ad7e40d7", "size": "5525", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "datatypes/auxiliary.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "4663581" }, { "name": "Makefile", "bytes": "2110" } ], "symlink_target": "" }
module Tfsql module Parser # labels: first, rest(element) class PrefixListNode < Treetop::Runtime::SyntaxNode include Enumerable def each all.each {|e| yield e} end def all @all ||= [first] + tail end def [](position) all[position] end def tail rest.elements.map{|e| e.element} end def text_values all.map { |e| e.text_value } end def size all.size end end # labels: first, rest(element), last(element)? class ListNode < PrefixListNode def tail elements = rest.elements.map{|e| e.element} elements << last.element unless last.empty? end end class FunctionNode < PrefixListNode def name function_name.text_value end alias :arguments :all end class ComparisonNode < Treetop::Runtime::SyntaxNode def comparisons respond_to?(:left) ? [left, right] : [disjunction] end def operator comparison_operator.text_value end end class NamedFieldNode < Treetop::Runtime::SyntaxNode def table ns.text_value end def field Integer member.field.text_value rescue ArgumentError member.field.text_value end end class ColumnNode < Treetop::Runtime::SyntaxNode def table nil end def field num.text_value.to_i end end class JoinNode < Treetop::Runtime::SyntaxNode def type join_type.text_value end def on join_on.empty? ? nil : [join_on.left, join_on.right] end end class SourceNode < Treetop::Runtime::SyntaxNode def path source_path.string.text_value end def delimiter source_delimiter.empty? ? '\t' : source_delimiter.nonempty_string.string.text_value end def alias source_alias.empty? ? nil : source_alias.name.text_value end def schema source_schema.empty? ? nil : source_schema end end class SchemaColumnNode < Treetop::Runtime::SyntaxNode def name Integer column_name.text_value rescue ArgumentError column_name.text_value end def type column_type.empty? ? 'string' : column_type.type.text_value end end end end
{ "content_hash": "36327c0095f8c61c6585584680794e95", "timestamp": "", "source": "github", "line_count": 125, "max_line_length": 91, "avg_line_length": 19.16, "alnum_prop": 0.5820459290187892, "repo_name": "newtonapple/tfsql", "id": "37320882b573ec9501f0df246febabd3728bd015", "size": "2395", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/tfsql/parser/syntax_nodes.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "12706" } ], "symlink_target": "" }
package groovy.xml; import groovy.lang.Closure; import groovy.lang.GroovyRuntimeException; import groovy.lang.Writable; import groovy.util.Node; import groovy.xml.slurpersupport.GPathResult; import org.apache.groovy.io.StringBuilderWriter; import org.codehaus.groovy.runtime.InvokerHelper; import org.codehaus.groovy.runtime.StringGroovyMethods; import org.w3c.dom.Element; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.SchemaFactory; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.StringReader; import java.io.Writer; import java.net.URL; import java.nio.charset.StandardCharsets; /** * Used for pretty printing XML content and other XML related utilities. */ public class XmlUtil { /** * Return a pretty String version of the Element. * * @param element the Element to serialize * @return the pretty String representation of the Element */ public static String serialize(Element element) { return serialize(element, false); } /** * Return a pretty String version of the Element. * * @param element the Element to serialize * @param allowDocTypeDeclaration whether to allow doctype processing * @return the pretty String representation of the Element */ public static String serialize(Element element, boolean allowDocTypeDeclaration) { Writer sw = new StringBuilderWriter(); serialize(new DOMSource(element), sw, allowDocTypeDeclaration); return sw.toString(); } /** * Write a pretty version of the Element to the OutputStream. * * @param element the Element to serialize * @param os the OutputStream to write to */ public static void serialize(Element element, OutputStream os) { serialize(element, os, false); } /** * Write a pretty version of the Element to the OutputStream. * * @param element the Element to serialize * @param os the OutputStream to write to * @param allowDocTypeDeclaration whether to allow doctype processing */ public static void serialize(Element element, OutputStream os, boolean allowDocTypeDeclaration) { Source source = new DOMSource(element); serialize(source, os, allowDocTypeDeclaration); } /** * Write a pretty version of the Element to the Writer. * * @param element the Element to serialize * @param w the Writer to write to */ public static void serialize(Element element, Writer w) { serialize(element, w, false); } /** * Write a pretty version of the Element to the Writer. * * @param element the Element to serialize * @param w the Writer to write to * @param allowDocTypeDeclaration whether to allow doctype processing */ public static void serialize(Element element, Writer w, boolean allowDocTypeDeclaration) { Source source = new DOMSource(element); serialize(source, w, allowDocTypeDeclaration); } /** * Return a pretty String version of the Node. * * @param node the Node to serialize * @return the pretty String representation of the Node */ public static String serialize(Node node) { return serialize(asString(node)); } /** * Write a pretty version of the Node to the OutputStream. * * @param node the Node to serialize * @param os the OutputStream to write to */ public static void serialize(Node node, OutputStream os) { serialize(asString(node), os); } /** * Write a pretty version of the Node to the Writer. * * @param node the Node to serialize * @param w the Writer to write to */ public static void serialize(Node node, Writer w) { serialize(asString(node), w); } /** * Return a pretty version of the GPathResult. * * @param node a GPathResult to serialize to a String * @return the pretty String representation of the GPathResult */ public static String serialize(GPathResult node) { return serialize(asString(node)); } /** * Write a pretty version of the GPathResult to the OutputStream. * * @param node a GPathResult to serialize * @param os the OutputStream to write to */ public static void serialize(GPathResult node, OutputStream os) { serialize(asString(node), os); } /** * Write a pretty version of the GPathResult to the Writer. * * @param node a GPathResult to serialize * @param w the Writer to write to */ public static void serialize(GPathResult node, Writer w) { serialize(asString(node), w); } /** * Return a pretty String version of the XML content produced by the Writable. * * @param writable the Writable to serialize * @return the pretty String representation of the content from the Writable */ public static String serialize(Writable writable) { return serialize(asString(writable)); } /** * Write a pretty version of the XML content produced by the Writable to the OutputStream. * * @param writable the Writable to serialize * @param os the OutputStream to write to */ public static void serialize(Writable writable, OutputStream os) { serialize(asString(writable), os); } /** * Write a pretty version of the XML content produced by the Writable to the Writer. * * @param writable the Writable to serialize * @param w the Writer to write to */ public static void serialize(Writable writable, Writer w) { serialize(asString(writable), w); } /** * Return a pretty version of the XML content contained in the given String. * * @param xmlString the String to serialize * @return the pretty String representation of the original content */ public static String serialize(String xmlString) { return serialize(xmlString, false); } /** * Return a pretty version of the XML content contained in the given String. * * @param xmlString the String to serialize * @param allowDocTypeDeclaration whether to allow doctype processing * @return the pretty String representation of the original content */ public static String serialize(String xmlString, boolean allowDocTypeDeclaration) { Writer sw = new StringBuilderWriter(); serialize(asStreamSource(xmlString), sw, allowDocTypeDeclaration); return sw.toString(); } /** * Write a pretty version of the given XML string to the OutputStream. * * @param xmlString the String to serialize * @param os the OutputStream to write to */ public static void serialize(String xmlString, OutputStream os) { serialize(xmlString, os, false); } /** * Write a pretty version of the given XML string to the OutputStream. * * @param xmlString the String to serialize * @param allowDocTypeDeclaration whether to allow doctype processing * @param os the OutputStream to write to */ public static void serialize(String xmlString, OutputStream os, boolean allowDocTypeDeclaration) { serialize(asStreamSource(xmlString), os, allowDocTypeDeclaration); } /** * Write a pretty version of the given XML string to the Writer. * * @param xmlString the String to serialize * @param w the Writer to write to */ public static void serialize(String xmlString, Writer w) { serialize(xmlString, w, false); } /** * Write a pretty version of the given XML string to the Writer. * * @param xmlString the String to serialize * @param allowDocTypeDeclaration whether to allow doctype processing * @param w the Writer to write to */ public static void serialize(String xmlString, Writer w, boolean allowDocTypeDeclaration) { serialize(asStreamSource(xmlString), w, allowDocTypeDeclaration); } /** * Factory method to create a SAXParser configured to validate according to a particular schema language and * optionally providing the schema sources to validate with. * The created SAXParser will be namespace-aware and not validate against DTDs. * * @param schemaLanguage the schema language used, e.g. XML Schema or RelaxNG (as per the String representation in javax.xml.XMLConstants) * @param schemas the schemas to validate against * @return the created SAXParser * @throws SAXException * @throws ParserConfigurationException * @see #newSAXParser(String, boolean, boolean, Source...) * @since 1.8.7 */ public static SAXParser newSAXParser(String schemaLanguage, Source... schemas) throws SAXException, ParserConfigurationException { return newSAXParser(schemaLanguage, true, false, schemas); } /** * Factory method to create a SAXParser configured to validate according to a particular schema language and * optionally providing the schema sources to validate with. * * @param schemaLanguage the schema language used, e.g. XML Schema or RelaxNG (as per the String representation in javax.xml.XMLConstants) * @param namespaceAware will the parser be namespace aware * @param validating will the parser also validate against DTDs * @param schemas the schemas to validate against * @return the created SAXParser * @throws SAXException * @throws ParserConfigurationException * @since 1.8.7 */ public static SAXParser newSAXParser(String schemaLanguage, boolean namespaceAware, boolean validating, Source... schemas) throws SAXException, ParserConfigurationException { return newSAXParser(schemaLanguage, namespaceAware, validating, false, schemas); } /** * Factory method to create a SAXParser configured to validate according to a particular schema language and * optionally providing the schema sources to validate with. * * @param schemaLanguage the schema language used, e.g. XML Schema or RelaxNG (as per the String representation in javax.xml.XMLConstants) * @param namespaceAware will the parser be namespace aware * @param validating will the parser also validate against DTDs * @param allowDoctypeDecl whether to allow doctype declarations (potentially insecure) * @param schemas the schemas to validate against * @return the created SAXParser * @throws SAXException * @throws ParserConfigurationException * @since 3.0.11 */ public static SAXParser newSAXParser(String schemaLanguage, boolean namespaceAware, boolean validating, boolean allowDoctypeDecl, Source... schemas) throws SAXException, ParserConfigurationException { SAXParserFactory factory = newFactoryInstance(namespaceAware, validating, allowDoctypeDecl); if (schemas.length != 0) { SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage); factory.setSchema(schemaFactory.newSchema(schemas)); } SAXParser saxParser = factory.newSAXParser(); if (schemas.length == 0) { saxParser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", schemaLanguage); } return saxParser; } private static SAXParserFactory newFactoryInstance(boolean namespaceAware, boolean validating, boolean allowDoctypeDecl) { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setValidating(validating); factory.setNamespaceAware(namespaceAware); setFeatureQuietly(factory, XMLConstants.FEATURE_SECURE_PROCESSING, true); setFeatureQuietly(factory, "http://apache.org/xml/features/disallow-doctype-decl", !allowDoctypeDecl); return factory; } /** * Factory method to create a SAXParser configured to validate according to a particular schema language and * a File containing the schema to validate against. * The created SAXParser will be namespace-aware and not validate against DTDs. * * @param schemaLanguage the schema language used, e.g. XML Schema or RelaxNG (as per the String representation in javax.xml.XMLConstants) * @param schema a file containing the schema to validate against * @return the created SAXParser * @throws SAXException * @throws ParserConfigurationException * @see #newSAXParser(String, boolean, boolean, File) * @since 1.8.7 */ public static SAXParser newSAXParser(String schemaLanguage, File schema) throws SAXException, ParserConfigurationException { return newSAXParser(schemaLanguage, true, false, schema); } /** * Factory method to create a SAXParser configured to validate according to a particular schema language and * a File containing the schema to validate against. * * @param schemaLanguage the schema language used, e.g. XML Schema or RelaxNG (as per the String representation in javax.xml.XMLConstants) * @param namespaceAware will the parser be namespace aware * @param validating will the parser also validate against DTDs * @param schema a file containing the schema to validate against * @return the created SAXParser * @throws SAXException * @throws ParserConfigurationException * @since 1.8.7 */ public static SAXParser newSAXParser(String schemaLanguage, boolean namespaceAware, boolean validating, File schema) throws SAXException, ParserConfigurationException { SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage); return newSAXParser(namespaceAware, validating, schemaFactory.newSchema(schema)); } /** * Factory method to create a SAXParser configured to validate according to a particular schema language and * a URL pointing to the schema to validate against. * The created SAXParser will be namespace-aware and not validate against DTDs. * * @param schemaLanguage the schema language used, e.g. XML Schema or RelaxNG (as per the String representation in javax.xml.XMLConstants) * @param schema a URL pointing to the schema to validate against * @return the created SAXParser * @throws SAXException * @throws ParserConfigurationException * @see #newSAXParser(String, boolean, boolean, URL) * @since 1.8.7 */ public static SAXParser newSAXParser(String schemaLanguage, URL schema) throws SAXException, ParserConfigurationException { return newSAXParser(schemaLanguage, true, false, schema); } /** * Factory method to create a SAXParser configured to validate according to a particular schema language and * a URL pointing to the schema to validate against. * * @param schemaLanguage the schema language used, e.g. XML Schema or RelaxNG (as per the String representation in javax.xml.XMLConstants) * @param namespaceAware will the parser be namespace aware * @param validating will the parser also validate against DTDs * @param schema a URL pointing to the schema to validate against * @return the created SAXParser * @throws SAXException * @throws ParserConfigurationException * @since 1.8.7 */ public static SAXParser newSAXParser(String schemaLanguage, boolean namespaceAware, boolean validating, URL schema) throws SAXException, ParserConfigurationException { SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage); return newSAXParser(namespaceAware, validating, schemaFactory.newSchema(schema)); } /** * Escape the following characters {@code " ' & < >} with their XML entities, e.g. * {@code "bread" & "butter"} becomes {@code &quot;bread&quot; &amp; &quot;butter&quot}. * Notes:<ul> * <li>Supports only the five basic XML entities (gt, lt, quot, amp, apos)</li> * <li>Does not escape control characters</li> * <li>Does not support DTDs or external entities</li> * <li>Does not treat surrogate pairs specially</li> * <li>Does not perform Unicode validation on its input</li> * </ul> * * @param orig the original String * @return A new string in which all characters that require escaping * have been replaced with the corresponding XML entities. * @see #escapeControlCharacters(String) */ public static String escapeXml(String orig) { return StringGroovyMethods.collectReplacements(orig, new Closure<String>(null) { public String doCall(Character arg) { switch (arg) { case '&': return "&amp;"; case '<': return "&lt;"; case '>': return "&gt;"; case '"': return "&quot;"; case '\'': return "&apos;"; } return null; } }); } /** * Escape control characters (below 0x20) with their XML entities, e.g. * carriage return ({@code Ctrl-M or \r}) becomes {@code &#13;} * Notes:<ul> * <li>Does not escape non-ascii characters above 0x7e</li> * <li>Does not treat surrogate pairs specially</li> * <li>Does not perform Unicode validation on its input</li> * </ul> * * @param orig the original String * @return A new string in which all characters that require escaping * have been replaced with the corresponding XML entities. * @see #escapeXml(String) */ public static String escapeControlCharacters(String orig) { return StringGroovyMethods.collectReplacements(orig, new Closure<String>(null) { public String doCall(Character arg) { if (arg < 31) { return "&#" + (int) arg + ";"; } return null; } }); } private static SAXParser newSAXParser(boolean namespaceAware, boolean validating, Schema schema1) throws ParserConfigurationException, SAXException { SAXParserFactory factory = newFactoryInstance(namespaceAware, validating, false); factory.setSchema(schema1); return factory.newSAXParser(); } private static String asString(Node node) { Writer sw = new StringBuilderWriter(); PrintWriter pw = new PrintWriter(sw); XmlNodePrinter nodePrinter = new XmlNodePrinter(pw); nodePrinter.setPreserveWhitespace(true); nodePrinter.print(node); return sw.toString(); } private static String asString(GPathResult node) { // little bit of hackery to avoid Groovy dependency in this file try { Object builder = Class.forName("groovy.xml.StreamingMarkupBuilder").getDeclaredConstructor().newInstance(); InvokerHelper.setProperty(builder, "encoding", "UTF-8"); Writable w = (Writable) InvokerHelper.invokeMethod(builder, "bindNode", node); return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + w.toString(); } catch (Exception e) { return "Couldn't convert node to string because: " + e.getMessage(); } } // TODO: replace with stream-based version private static String asString(Writable writable) { if (writable instanceof GPathResult) { return asString((GPathResult) writable); //GROOVY-4285 } Writer sw = new StringBuilderWriter(); try { writable.writeTo(sw); } catch (IOException e) { // ignore } return sw.toString(); } private static StreamSource asStreamSource(String xmlString) { return new StreamSource(new StringReader(xmlString)); } private static void serialize(Source source, OutputStream os, boolean allowDocTypeDeclaration) { serialize(source, new StreamResult(new OutputStreamWriter(os, StandardCharsets.UTF_8)), allowDocTypeDeclaration); } private static void serialize(Source source, Writer w, boolean allowDocTypeDeclaration) { serialize(source, new StreamResult(w), allowDocTypeDeclaration); } private static void serialize(Source source, StreamResult target, boolean allowDocTypeDeclaration) { TransformerFactory factory = TransformerFactory.newInstance(); setFeatureQuietly(factory, "http://apache.org/xml/features/disallow-doctype-decl", !allowDocTypeDeclaration); setIndent(factory, 2); try { Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml"); transformer.transform(source, target); } catch (TransformerException e) { throw new GroovyRuntimeException(e.getMessage()); } } private static void setIndent(TransformerFactory factory, int indent) { // TODO: support older parser attribute values as well try { factory.setAttribute("indent-number", indent); } catch (IllegalArgumentException e) { // ignore for factories that don't support this } } public static void setFeatureQuietly(TransformerFactory factory, String feature, boolean value) { try { factory.setFeature(feature, value); } catch (TransformerConfigurationException ignored) { // feature is not supported, ignore } } public static void setFeatureQuietly(DocumentBuilderFactory factory, String feature, boolean value) { try { factory.setFeature(feature, value); } catch (ParserConfigurationException ignored) { // feature is not supported, ignore } } public static void setFeatureQuietly(SAXParserFactory factory, String feature, boolean value) { try { factory.setFeature(feature, value); } catch (ParserConfigurationException | SAXNotSupportedException | SAXNotRecognizedException ignored) { // feature is not supported, ignore } } }
{ "content_hash": "d416252e449ae61918404174036def47", "timestamp": "", "source": "github", "line_count": 575, "max_line_length": 204, "avg_line_length": 40.93565217391304, "alnum_prop": 0.6719772283116663, "repo_name": "apache/groovy", "id": "91cac1ab31e0f7cc6f1eb2c89b0ae7dffd2de236", "size": "24359", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "subprojects/groovy-xml/src/main/java/groovy/xml/XmlUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "60109" }, { "name": "Batchfile", "bytes": "23519" }, { "name": "CSS", "bytes": "79976" }, { "name": "Groovy", "bytes": "11180205" }, { "name": "HTML", "bytes": "81796" }, { "name": "Java", "bytes": "13487387" }, { "name": "JavaScript", "bytes": "1191" }, { "name": "Shell", "bytes": "58187" }, { "name": "Smarty", "bytes": "7825" } ], "symlink_target": "" }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <artifactId>karaf-runner</artifactId> <groupId>com.vaadin</groupId> <version>8.4-SNAPSHOT</version> <modelVersion>4.0.0</modelVersion> <build> <plugins> <plugin> <groupId>org.apache.karaf.tooling</groupId> <artifactId>karaf-maven-plugin</artifactId> <version>4.0.8</version> <configuration> <deployProjectArtifact>false</deployProjectArtifact> <startSsh>true</startSsh> </configuration> </plugin> </plugins> </build> </project>
{ "content_hash": "8f6702b8b1d891144a82e9f0c0518b89", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 108, "avg_line_length": 39.76190476190476, "alnum_prop": 0.5736526946107784, "repo_name": "mstahv/framework", "id": "54d137d56788cc16bc1751563a5a6b733e17d68a", "size": "835", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/servlet-containers/karaf/karaf-run/karaf-run-pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "751129" }, { "name": "HTML", "bytes": "101758" }, { "name": "Java", "bytes": "24443471" }, { "name": "JavaScript", "bytes": "131503" }, { "name": "Python", "bytes": "33975" }, { "name": "Shell", "bytes": "14720" }, { "name": "Smarty", "bytes": "175" } ], "symlink_target": "" }
source "$(dirname "${BASH_SOURCE}")/lib/init.sh" os::build::setup_env os::util::ensure::built_binary_exists 'client-gen' 'vendor/k8s.io/kubernetes/staging/src/k8s.io/kube-gen/cmd/client-gen' # list of package to generate client set for packages=( github.com/openshift/origin/pkg/authorization/apis/authorization github.com/openshift/origin/pkg/build/apis/build github.com/openshift/origin/pkg/deploy/apis/apps github.com/openshift/origin/pkg/image/apis/image github.com/openshift/origin/pkg/oauth/apis/oauth github.com/openshift/origin/pkg/project/apis/project github.com/openshift/origin/pkg/quota/apis/quota github.com/openshift/origin/pkg/route/apis/route github.com/openshift/origin/pkg/sdn/apis/network github.com/openshift/origin/pkg/security/apis/security github.com/openshift/origin/pkg/template/apis/template github.com/openshift/origin/pkg/user/apis/user ) function generate_clientset_for() { local package="$1";shift local name="$1";shift echo "-- Generating ${name} client set for ${package} ..." grouppkg=$(realpath --canonicalize-missing --relative-to=$(pwd) ${package}/..) client-gen --clientset-path="${grouppkg}/generated" \ --input-base="${package}" \ --output-base="../../.." \ --clientset-name="${name}" \ --go-header-file=hack/boilerplate.txt \ "$@" } verify="${VERIFY:-}" # remove the old client sets if we're not verifying if [[ -z "${verify}" ]]; then for pkg in "${packages[@]}"; do grouppkg=$(realpath --canonicalize-missing --relative-to=$(pwd) ${pkg}/../..) # delete all generated go files excluding files named *_expansion.go go list -f '{{.Dir}}' "${grouppkg}/generated/clientset" "${grouppkg}/generated/internalclientset" \ | xargs -n1 -I{} find {} -type f -not -name "*_expansion.go" -delete done fi for pkg in "${packages[@]}"; do shortGroup=$(basename "${pkg}") containingPackage=$(dirname "${pkg}") generate_clientset_for "${containingPackage}" "internalclientset" --group=${shortGroup} --input=${shortGroup} ${verify} "$@" generate_clientset_for "${containingPackage}" "clientset" --group=${shortGroup} --version=v1 --input=${shortGroup}/v1 ${verify} "$@" done
{ "content_hash": "d32d0f78408c3430d3ef045d20f22e98", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 134, "avg_line_length": 44, "alnum_prop": 0.6556603773584906, "repo_name": "jupierce/origin", "id": "f734bafdc5b2198c7149d7193eb7892e199777ca", "size": "2344", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "hack/update-generated-clientsets.sh", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "1842" }, { "name": "DIGITAL Command Language", "bytes": "117" }, { "name": "Go", "bytes": "19232091" }, { "name": "Groovy", "bytes": "5288" }, { "name": "HTML", "bytes": "74732" }, { "name": "Makefile", "bytes": "22539" }, { "name": "Protocol Buffer", "bytes": "658936" }, { "name": "Python", "bytes": "33408" }, { "name": "Roff", "bytes": "2049" }, { "name": "Ruby", "bytes": "484" }, { "name": "Shell", "bytes": "2190702" }, { "name": "Smarty", "bytes": "626" } ], "symlink_target": "" }
package com.shunwang.api.request.recharge; import com.shunwang.api.mapping.SWApiDocs; import com.shunwang.api.mapping.SWApiField; import com.shunwang.api.response.recharge.SWDisburseProcessResponse; import java.util.LinkedHashMap; import java.util.Map; /** * @author min.da * @since 2015-12-09 */ @SWApiDocs(code = "10", name = "消费充值完成接口", service = "/interface/disburseProcess.htm", methods = 2) public class SWDisburseProcessRequest extends AbstractSWRequest<SWDisburseProcessResponse> { private static final long serialVersionUID = 1582449395278491215L; @SWApiField(max = 50, desc = "订单号", orderby = 99) private String disburseNo; @SWApiField(max = 32, desc = "充值账号", orderby = 97) private String memberName; @SWApiField(desc = "充值金额: [{\"modeKey\":\"XXX\",\"fee\":\"XXX\"}]", orderby = 95) private String fee; @SWApiField(max = 1, desc = "终端类型,1:pc,2:手机", orderby = 93) private String terminalType; @SWApiField(max = 1, desc = "终端操作系统类型,1:ios,2:安卓", orderby = 91) private String osType; @SWApiField(max = 128, desc = "客户端IP", orderby = 89) private String clientIp; public SWDisburseProcessRequest(String secretKey) { super(secretKey); } @Override public Map<String, String> buildRequestParams() { Map<String, String> params = super.buildRequestParams(); params.put("disburseNo", disburseNo); params.put("memberName", memberName); params.put("fee", fee); params.put("terminalType", terminalType); params.put("osType", osType); params.put("clientIp", clientIp); return params; } @Override public Map<String, String> buildSignatureParams() { Map<String, String> signParams = new LinkedHashMap<String, String>(); signParams.put("disburseNo", disburseNo); signParams.put("fee", fee); signParams.put("memberName", memberName); signParams.put("terminalType", terminalType); signParams.put("osType", osType); signParams.put("companyMemberName", getCompanyMemberName()); signParams.put("time", getTime()); return signParams; } @Override public Class<SWDisburseProcessResponse> getResponseClass() { return SWDisburseProcessResponse.class; } public String getDisburseNo() { return disburseNo; } public void setDisburseNo(String disburseNo) { this.disburseNo = disburseNo; } public String getMemberName() { return memberName; } public void setMemberName(String memberName) { this.memberName = memberName; } public String getFee() { return fee; } public void setFee(String fee) { this.fee = fee; } public String getTerminalType() { return terminalType; } public void setTerminalType(String terminalType) { this.terminalType = terminalType; } public String getOsType() { return osType; } public void setOsType(String osType) { this.osType = osType; } public String getClientIp() { return clientIp; } public void setClientIp(String clientIp) { this.clientIp = clientIp; } }
{ "content_hash": "d7c70dee9e9bf9a0f3b8891c99f643be", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 99, "avg_line_length": 28.557522123893804, "alnum_prop": 0.6513789897737837, "repo_name": "waitttttttttttttttttttttttting/apitools", "id": "a1a6cba40e378552208262cf72bb872d89a72b65", "size": "3319", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "apitools-web/src/main/config/apidemos/recharge/disburseProcess-UTF-8/src/main/java/com/shunwang/api/request/recharge/SWDisburseProcessRequest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "29946" }, { "name": "HTML", "bytes": "11573" }, { "name": "Java", "bytes": "4785482" }, { "name": "JavaScript", "bytes": "2083148" } ], "symlink_target": "" }
using FluentMigrator; namespace bulky.Tests { [Migration(1)] public class Baseline : AutoReversingMigration { public override void Up() { Create.Table("User") .WithColumn("Id").AsInt32().PrimaryKey().Identity() .WithColumn("Email").AsAnsiString(); Create.Table("UserRole") .WithColumn("UserId").AsInt32().PrimaryKey() .WithColumn("RoleId").AsInt32().PrimaryKey(); } } }
{ "content_hash": "90866660703d1c83f18775e86b4bc202", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 67, "avg_line_length": 26.263157894736842, "alnum_prop": 0.5470941883767535, "repo_name": "teves-castro/bulky", "id": "3d65a7cf953edf9754debb035a69121649ad566a", "size": "499", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Bulky.Tests/Baseline.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "52599" }, { "name": "Shell", "bytes": "130" } ], "symlink_target": "" }
============== Editing Fields ============== Updating review requests is very much like :ref:`creating review requests <creating-review-requests>`. Once you have a review request out there, you can upload a new diff, add new file attachments, or modify the fields. Any changes you make will be seen by you only until you :ref:`publish the changes <publishing-review-requests>`. .. image:: review-request-fields.png Changing Fields =============== Most fields on a review request can be changed, with the exception of :guilabel:`Submitter`, :guilabel:`Commit` and :guilabel:`Repository`. To change a field, either click on the field (in the case of :guilabel:`Description` and :guilabel:`Testing Done`) or click on the pencil icon. A text box will appear allowing you to modify the value. To save a field, press the :kbd:`Enter` key or click :guilabel:`OK`. To revert your changes, press the :kbd:`Escape` key or click :guilabel:`Cancel'. Summary ------- The :guilabel:`Summary` field is a short, one-line description of the change. It's what people will see in their dashboard and in e-mail subject headers. You should aim to keep this short and as descriptive as possible. Description ----------- The :guilabel:`Description` field describes the change that will be reviewed. This is intended to provide enough information for reviewers to know what the change is about before they go to review it. This field supports rich text using the :term:`Markdown` language. See :ref:`using-markdown` for more information. Testing Done ------------ The :guilabel:`Testing Done` field describes how this change has been tested. This should cover any and all testing scenarios that have been done, in order to help reviewers feel more confident about the stability and design of the change. This field supports rich text using the :term:`Markdown` language. See :ref:`using-markdown` for more information. Branch ------ The :guilabel:`Branch` field describes which branch your change applies to. This is a very free-form field and can contain any text. Some examples may be: * ``trunk`` * ``master`` * ``my-feature`` * ``release-2.0`` * ``hotfix-branch -> release-2.0 -> main`` In the latter case, this could be used to show the series of branches that the change would be merged down to, starting at the branch where the change originated. Bugs ---- The :guilabel:`Bugs` field is a comma-separated list of bug IDs that the change addresses. If the repository is configured with a bug tracker, the bug IDs will link to the reports on the bug tracker. Depends On ---------- The :guilabel:`Depends On` field is a comma-separated list of review request IDs which are used to indicate dependencies between changes. The IDs will link to the other review requests, allowing reviewers to take that information into account when reading the changes. Groups ------ The :guilabel:`Groups` field is a comma-separated list of all review groups that should review the change. When entering a group, Review Board will attempt to auto-complete the group. It will match against either the group's ID, or the group's name. While auto-completing, a drop-down of possible groups will be displayed, showing both the ID and name. Review Board doesn't enforce that the groups must review the change before it can be submitted. This is a policy that is left up to each organization. People ------ The :guilabel:`People` field is a comma-separated list of all the people that should review the change. When entering a person, Review Board will attempt to auto-complete the person's information. It will match against either the person's username, or the person's first or last name. While auto-completing, a drop-down of possible people will be displayed, showing both the username and full name. Review Board doesn't enforce that the people listed must review the change before it can be submitted. This is a policy that is left up to each organization.
{ "content_hash": "2dd55027b9e6379867bd264a6764e220", "timestamp": "", "source": "github", "line_count": 124, "max_line_length": 80, "avg_line_length": 31.943548387096776, "alnum_prop": 0.7535975763696037, "repo_name": "1tush/reviewboard", "id": "0af8d76ffa83cdc2ccb75d6be68e4970ff365b4b", "size": "3961", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/manual/users/review-requests/fields.rst", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "685" }, { "name": "C#", "bytes": "340" }, { "name": "CSS", "bytes": "157867" }, { "name": "Java", "bytes": "340" }, { "name": "JavaScript", "bytes": "1256833" }, { "name": "Objective-C", "bytes": "288" }, { "name": "PHP", "bytes": "278" }, { "name": "Perl", "bytes": "103" }, { "name": "Python", "bytes": "3124372" }, { "name": "Ruby", "bytes": "172" }, { "name": "Shell", "bytes": "963" } ], "symlink_target": "" }
<?php namespace Helpers; /* * Session Class - prefix sessions with useful methods * * @author David Carr - [email protected] * @version 2.2 * @date June 27, 2014 * @date updated May 18 2015 */ class Session { /** * Determine if session has started * @var boolean */ private static $sessionStarted = false; /** * if session has not started, start sessions */ public static function init() { if (self::$sessionStarted == false) { session_start(); self::$sessionStarted = true; } } /** * Add value to a session * @param string $key name the data to save * @param string $value the data to save */ public static function set($key, $value = false) { /** * Check whether session is set in array or not * If array then set all session key-values in foreach loop */ if (is_array($key) && $value === false) { foreach ($key as $name => $value) { $_SESSION[SESSION_PREFIX.$name] = $value; } } else { $_SESSION[SESSION_PREFIX.$key] = $value; } } /** * extract item from session then delete from the session, finally return the item * @param string $key item to extract * @return string return item */ public static function pull($key) { $value = $_SESSION[SESSION_PREFIX.$key]; unset($_SESSION[SESSION_PREFIX.$key]); return $value; } /** * get item from session * * @param string $key item to look for in session * @param boolean $secondkey if used then use as a second key * @return string returns the key */ public static function get($key, $secondkey = false) { if ($secondkey == true) { if (isset($_SESSION[SESSION_PREFIX.$key][$secondkey])) { return $_SESSION[SESSION_PREFIX.$key][$secondkey]; } } else { if (isset($_SESSION[SESSION_PREFIX.$key])) { return $_SESSION[SESSION_PREFIX.$key]; } } return false; } /** * @return string with the session id. */ public static function id() { return session_id(); } /** * regenerate session_id * @return string session_id */ public static function regenerate() { session_regenerate_id(true); return session_id(); } /** * return the session array * @return array of session indexes */ public static function display() { return $_SESSION; } /** * empties and destroys the session */ public static function destroy($key = '') { if (self::$sessionStarted == true) { if (empty($key)) { session_unset(); session_destroy(); } else { unset($_SESSION[SESSION_PREFIX.$key]); } } } /** * display message * @return string return the message inside div */ public static function message($sessionName = 'success') { $msg = Session::pull($sessionName); if (!empty($msg)) { return "<div class='alert alert-success alert-dismissable'> <button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button> <h4><i class='fa fa-check'></i> ".$msg."</h4> </div>"; } } }
{ "content_hash": "22e69ddc91c0b45a279613d18474a6d9", "timestamp": "", "source": "github", "line_count": 141, "max_line_length": 106, "avg_line_length": 25.390070921985817, "alnum_prop": 0.5201117318435754, "repo_name": "umihnea/e-learning.inkdrop", "id": "752da18363c0dbe79e1a1590927f40abeddc402c", "size": "3581", "binary": false, "copies": "19", "ref": "refs/heads/master", "path": "app/Helpers/Session.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "541" }, { "name": "CSS", "bytes": "27233" }, { "name": "HTML", "bytes": "213" }, { "name": "JavaScript", "bytes": "54210" }, { "name": "PHP", "bytes": "375739" } ], "symlink_target": "" }
package com.sun.corba.se.spi.oa; /** This exception is thrown when an operation on an ObjectAdapter * fails because the ObjectAdapter was destroyed during the operation. */ public class OADestroyed extends Exception { }
{ "content_hash": "5b96f51e6811d37fa0f3dc3e16944102", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 70, "avg_line_length": 28, "alnum_prop": 0.7767857142857143, "repo_name": "wangsongpeng/jdk-src", "id": "f83d384ba78a486be8de8d38ee243755fd2aea74", "size": "439", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main/java/com/sun/corba/se/spi/oa/OADestroyed.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "193794" }, { "name": "C++", "bytes": "6565" }, { "name": "Java", "bytes": "85385971" } ], "symlink_target": "" }
package com.bwsw.cloudstack.pulse.validators /** * Created by Ivan Kudryavtsev on 28.07.17. */ abstract class Validator { protected def onError(params: Map[String, String]): String def validate(params: Map[String, String]): Either[String, String] } class PrimitiveValidator(field: String) extends Validator { def fieldName = field override protected def onError(params: Map[String, String]): String = "" override def validate(params: Map[String, String]): Either[String, String] = Left("") }
{ "content_hash": "44c1ec2ccdff6ab244d5e1af865a9c35", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 87, "avg_line_length": 28.38888888888889, "alnum_prop": 0.7279843444227005, "repo_name": "bwsw/cs-pulse-server", "id": "ad7a420a4f5a16f349b1418b0d369fcc66260fcb", "size": "511", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala-2.12/com/bwsw/cloudstack/pulse/validators/PrimitiveValidator.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "1190" }, { "name": "Scala", "bytes": "50277" }, { "name": "Shell", "bytes": "260" } ], "symlink_target": "" }
import {bootstrap} from 'angular2/platform/browser'; import {provide} from 'angular2/core'; import {HTTP_PROVIDERS} from 'angular2/http'; import {ROUTER_PROVIDERS, LocationStrategy, HashLocationStrategy} from 'angular2/router'; import {SeedApp} from './app/seed-app'; bootstrap(SeedApp, [ HTTP_PROVIDERS, ROUTER_PROVIDERS, provide(LocationStrategy, {useClass: HashLocationStrategy}) ]) .catch(err => console.error(err));
{ "content_hash": "8d2b3915f85b046b0bba3fadb582ec91", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 89, "avg_line_length": 30.714285714285715, "alnum_prop": 0.7581395348837209, "repo_name": "deostroll/ang2routing", "id": "afa4a3315034c408019dfd56634183440f828f7a", "size": "430", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/app.ts", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1236" }, { "name": "JavaScript", "bytes": "1717" }, { "name": "TypeScript", "bytes": "5402" } ], "symlink_target": "" }
var seleniumConfig = process.env.SELENIUM_OVERRIDES_CONFIG || '../selenium-overrides.js'; var SELENIUM_OVERRIDES = require(seleniumConfig)['selenium-overrides']; // Work around a potential npm race condition: // https://github.com/npm/npm/issues/6624 function requireSelenium(done, attempt) { attempt = attempt || 0; var selenium; try { selenium = require('selenium-standalone'); } catch (error) { if (attempt > 3) { throw error; } setTimeout( requireSelenium.bind(null, done, attempt + 1), Math.pow(2, attempt) // Exponential backoff to play it safe. ); } // All is well. done(selenium); } var config = SELENIUM_OVERRIDES || {}; config.logger = console.log.bind(console); if (!process.env.NOSELENIUM) { requireSelenium(function(selenium) { selenium.install(config, function(error) { if (error) { console.log('Failed to download selenium and/or chromedriver:', error); console.log( 'selenium-standalone will attempt to re-download next time it is run.'); // We explicitly do not fail the install process if this happens; the // user can still recover, unless their permissions are completely // screwey. } }); }); } else { console.log('skipping install of selenium because of NOSELENIUM flag'); }
{ "content_hash": "b1f06d51137e40a77d3c3d41a5c1adae", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 84, "avg_line_length": 29.8, "alnum_prop": 0.6577181208053692, "repo_name": "Polymer/tools", "id": "ef825ee863e69900bdcbc72c17bf6a5436a4f1b2", "size": "1876", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/wct-local/scripts/postinstall.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "7605" }, { "name": "HTML", "bytes": "3110999" }, { "name": "JavaScript", "bytes": "903683" }, { "name": "Shell", "bytes": "6045" }, { "name": "TypeScript", "bytes": "3330477" } ], "symlink_target": "" }
from PyQt4.QtCore import * from PyQt4.QtGui import * from qrtextedit import ScanQRTextEdit import re from decimal import Decimal from electrum import bitcoin import util RE_ADDRESS = '[1-9A-HJ-NP-Za-km-z]{26,}' RE_ALIAS = '(.*?)\s*\<([1-9A-HJ-NP-Za-km-z]{26,})\>' frozen_style = "QWidget { background-color:none; border:none;}" normal_style = "QPlainTextEdit { }" class PayToEdit(ScanQRTextEdit): def __init__(self, win): ScanQRTextEdit.__init__(self) self.win = win self.amount_edit = win.amount_e self.document().contentsChanged.connect(self.update_size) self.heightMin = 0 self.heightMax = 150 self.c = None self.textChanged.connect(self.check_text) self.outputs = [] self.errors = [] self.is_pr = False self.is_alias = False self.scan_f = win.pay_to_URI self.update_size() self.payto_address = None self.previous_payto = '' def setFrozen(self, b): self.setReadOnly(b) self.setStyleSheet(frozen_style if b else normal_style) for button in self.buttons: button.setHidden(b) def setGreen(self): self.setStyleSheet(util.GREEN_BG) def setExpired(self): self.setStyleSheet(util.RED_BG) def parse_address_and_amount(self, line): x, y = line.split(',') out_type, out = self.parse_output(x) amount = self.parse_amount(y) return out_type, out, amount def parse_output(self, x): try: address = self.parse_address(x) return bitcoin.TYPE_ADDRESS, address except: script = self.parse_script(x) return bitcoin.TYPE_SCRIPT, script def parse_script(self, x): from electrum.transaction import opcodes, push_script script = '' for word in x.split(): if word[0:3] == 'OP_': assert word in opcodes.lookup script += chr(opcodes.lookup[word]) else: script += push_script(word).decode('hex') return script def parse_amount(self, x): if x.strip() == '!': return '!' p = pow(10, self.amount_edit.decimal_point()) return int(p * Decimal(x.strip())) def parse_address(self, line): r = line.strip() m = re.match('^'+RE_ALIAS+'$', r) address = str(m.group(2) if m else r) assert bitcoin.is_address(address) return address def check_text(self): self.errors = [] if self.is_pr: return # filter out empty lines lines = filter(lambda x: x, self.lines()) outputs = [] total = 0 self.payto_address = None if len(lines) == 1: data = lines[0] if data.startswith("bitcoin:"): self.scan_f(data) return try: self.payto_address = self.parse_output(data) except: pass if self.payto_address: self.win.lock_amount(False) return is_max = False for i, line in enumerate(lines): try: _type, to_address, amount = self.parse_address_and_amount(line) except: self.errors.append((i, line.strip())) continue outputs.append((_type, to_address, amount)) if amount == '!': is_max = True else: total += amount self.win.is_max = is_max self.outputs = outputs self.payto_address = None if self.win.is_max: self.win.do_update_fee() else: self.amount_edit.setAmount(total if outputs else None) self.win.lock_amount(total or len(lines)>1) def get_errors(self): return self.errors def get_recipient(self): return self.payto_address def get_outputs(self, is_max): if self.payto_address: if is_max: amount = '!' else: amount = self.amount_edit.get_amount() _type, addr = self.payto_address self.outputs = [(_type, addr, amount)] return self.outputs[:] def lines(self): return unicode(self.toPlainText()).split('\n') def is_multiline(self): return len(self.lines()) > 1 def paytomany(self): self.setText("\n\n\n") self.update_size() def update_size(self): docHeight = self.document().size().height() h = docHeight*17 + 11 if self.heightMin <= h <= self.heightMax: self.setMinimumHeight(h) self.setMaximumHeight(h) self.verticalScrollBar().hide() def setCompleter(self, completer): self.c = completer self.c.setWidget(self) self.c.setCompletionMode(QCompleter.PopupCompletion) self.c.activated.connect(self.insertCompletion) def insertCompletion(self, completion): if self.c.widget() != self: return tc = self.textCursor() extra = completion.length() - self.c.completionPrefix().length() tc.movePosition(QTextCursor.Left) tc.movePosition(QTextCursor.EndOfWord) tc.insertText(completion.right(extra)) self.setTextCursor(tc) def textUnderCursor(self): tc = self.textCursor() tc.select(QTextCursor.WordUnderCursor) return tc.selectedText() def keyPressEvent(self, e): if self.isReadOnly(): return if self.c.popup().isVisible(): if e.key() in [Qt.Key_Enter, Qt.Key_Return]: e.ignore() return if e.key() in [Qt.Key_Tab]: e.ignore() return if e.key() in [Qt.Key_Down, Qt.Key_Up] and not self.is_multiline(): e.ignore() return QPlainTextEdit.keyPressEvent(self, e) ctrlOrShift = e.modifiers() and (Qt.ControlModifier or Qt.ShiftModifier) if self.c is None or (ctrlOrShift and e.text().isEmpty()): return eow = QString("~!@#$%^&*()_+{}|:\"<>?,./;'[]\\-=") hasModifier = (e.modifiers() != Qt.NoModifier) and not ctrlOrShift; completionPrefix = self.textUnderCursor() if hasModifier or e.text().isEmpty() or completionPrefix.length() < 1 or eow.contains(e.text().right(1)): self.c.popup().hide() return if completionPrefix != self.c.completionPrefix(): self.c.setCompletionPrefix(completionPrefix); self.c.popup().setCurrentIndex(self.c.completionModel().index(0, 0)) cr = self.cursorRect() cr.setWidth(self.c.popup().sizeHintForColumn(0) + self.c.popup().verticalScrollBar().sizeHint().width()) self.c.complete(cr) def qr_input(self): data = super(PayToEdit,self).qr_input() if data.startswith("bitcoin:"): self.scan_f(data) # TODO: update fee def resolve(self): self.is_alias = False if self.hasFocus(): return if self.is_multiline(): # only supports single line entries atm return if self.is_pr: return key = str(self.toPlainText()) if key == self.previous_payto: return self.previous_payto = key if not (('.' in key) and (not '<' in key) and (not ' ' in key)): return try: data = self.win.contacts.resolve(key) except: return if not data: return self.is_alias = True address = data.get('address') name = data.get('name') new_url = key + ' <' + address + '>' self.setText(new_url) self.previous_payto = new_url #if self.win.config.get('openalias_autoadd') == 'checked': self.win.contacts[key] = ('openalias', name) self.win.contact_list.on_update() self.setFrozen(True) if data.get('type') == 'openalias': self.validated = data.get('validated') if self.validated: self.setGreen() else: self.setExpired() else: self.validated = None
{ "content_hash": "bbffec352899ac05322054676d39fe7a", "timestamp": "", "source": "github", "line_count": 281, "max_line_length": 113, "avg_line_length": 29.661921708185055, "alnum_prop": 0.5454109178164367, "repo_name": "fireduck64/electrum", "id": "d71753162f23e61f07605703fa1e265f5069e731", "size": "9500", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "gui/qt/paytoedit.py", "mode": "33188", "license": "mit", "language": [ { "name": "GLSL", "bytes": "289" }, { "name": "HTML", "bytes": "3867" }, { "name": "Makefile", "bytes": "836" }, { "name": "NSIS", "bytes": "7125" }, { "name": "PHP", "bytes": "404" }, { "name": "Protocol Buffer", "bytes": "2354" }, { "name": "Python", "bytes": "1241321" }, { "name": "Shell", "bytes": "7035" } ], "symlink_target": "" }
Manually vendored from iamcal/emoji-data (Because git submodules cause more problems then they are worth for a single file.) Most recent vendoring from revision: iamcal/emoji-data@6cb685cd1e
{ "content_hash": "bc8cd1ea0b3f4ee8718e3dcc65bddfd9", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 69, "avg_line_length": 27.571428571428573, "alnum_prop": 0.8186528497409327, "repo_name": "mroth/emoji-data-js", "id": "413eea33cf3dc5ecf7676fc383cf237487c0a3f4", "size": "193", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "vendor/emoji-data/README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CoffeeScript", "bytes": "24042" } ], "symlink_target": "" }
<?php namespace Proxies\__CG__\GSB\MainBundle\Entity; /** * DO NOT EDIT THIS FILE - IT WAS CREATED BY DOCTRINE'S PROXY GENERATOR */ class DetailDemande extends \GSB\MainBundle\Entity\DetailDemande implements \Doctrine\ORM\Proxy\Proxy { /** * @var \Closure the callback responsible for loading properties in the proxy object. This callback is called with * three parameters, being respectively the proxy object to be initialized, the method that triggered the * initialization process and an array of ordered parameters that were passed to that method. * * @see \Doctrine\Common\Persistence\Proxy::__setInitializer */ public $__initializer__; /** * @var \Closure the callback responsible of loading properties that need to be copied in the cloned object * * @see \Doctrine\Common\Persistence\Proxy::__setCloner */ public $__cloner__; /** * @var boolean flag indicating if this object was already initialized * * @see \Doctrine\Common\Persistence\Proxy::__isInitialized */ public $__isInitialized__ = false; /** * @var array properties to be lazy loaded, with keys being the property * names and values being their default values * * @see \Doctrine\Common\Persistence\Proxy::__getLazyProperties */ public static $lazyPropertiesDefaults = array(); /** * @param \Closure $initializer * @param \Closure $cloner */ public function __construct($initializer = null, $cloner = null) { $this->__initializer__ = $initializer; $this->__cloner__ = $cloner; } /** * * @return array */ public function __sleep() { if ($this->__isInitialized__) { return array('__isInitialized__', '' . "\0" . 'GSB\\MainBundle\\Entity\\DetailDemande' . "\0" . 'id', '' . "\0" . 'GSB\\MainBundle\\Entity\\DetailDemande' . "\0" . 'idDemande', '' . "\0" . 'GSB\\MainBundle\\Entity\\DetailDemande' . "\0" . 'idDept', '' . "\0" . 'GSB\\MainBundle\\Entity\\DetailDemande' . "\0" . 'numOrdre'); } return array('__isInitialized__', '' . "\0" . 'GSB\\MainBundle\\Entity\\DetailDemande' . "\0" . 'id', '' . "\0" . 'GSB\\MainBundle\\Entity\\DetailDemande' . "\0" . 'idDemande', '' . "\0" . 'GSB\\MainBundle\\Entity\\DetailDemande' . "\0" . 'idDept', '' . "\0" . 'GSB\\MainBundle\\Entity\\DetailDemande' . "\0" . 'numOrdre'); } /** * */ public function __wakeup() { if ( ! $this->__isInitialized__) { $this->__initializer__ = function (DetailDemande $proxy) { $proxy->__setInitializer(null); $proxy->__setCloner(null); $existingProperties = get_object_vars($proxy); foreach ($proxy->__getLazyProperties() as $property => $defaultValue) { if ( ! array_key_exists($property, $existingProperties)) { $proxy->$property = $defaultValue; } } }; } } /** * */ public function __clone() { $this->__cloner__ && $this->__cloner__->__invoke($this, '__clone', array()); } /** * Forces initialization of the proxy */ public function __load() { $this->__initializer__ && $this->__initializer__->__invoke($this, '__load', array()); } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __isInitialized() { return $this->__isInitialized__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setInitialized($initialized) { $this->__isInitialized__ = $initialized; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setInitializer(\Closure $initializer = null) { $this->__initializer__ = $initializer; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __getInitializer() { return $this->__initializer__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic */ public function __setCloner(\Closure $cloner = null) { $this->__cloner__ = $cloner; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific cloning logic */ public function __getCloner() { return $this->__cloner__; } /** * {@inheritDoc} * @internal generated method: use only when explicitly handling proxy specific loading logic * @static */ public function __getLazyProperties() { return self::$lazyPropertiesDefaults; } /** * {@inheritDoc} */ public function getIdDemande() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getIdDemande', array()); return parent::getIdDemande(); } /** * {@inheritDoc} */ public function getId() { if ($this->__isInitialized__ === false) { return (int) parent::getId(); } $this->__initializer__ && $this->__initializer__->__invoke($this, 'getId', array()); return parent::getId(); } /** * {@inheritDoc} */ public function setId($id) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setId', array($id)); return parent::setId($id); } /** * {@inheritDoc} */ public function setIdDept($idDept) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setIdDept', array($idDept)); return parent::setIdDept($idDept); } /** * {@inheritDoc} */ public function getIdDept() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getIdDept', array()); return parent::getIdDept(); } /** * {@inheritDoc} */ public function setNumOrdre($numOrdre) { $this->__initializer__ && $this->__initializer__->__invoke($this, 'setNumOrdre', array($numOrdre)); return parent::setNumOrdre($numOrdre); } /** * {@inheritDoc} */ public function getNumOrdre() { $this->__initializer__ && $this->__initializer__->__invoke($this, 'getNumOrdre', array()); return parent::getNumOrdre(); } }
{ "content_hash": "0b7f1dba18d8c1030f58c62c97d0dc9f", "timestamp": "", "source": "github", "line_count": 257, "max_line_length": 335, "avg_line_length": 26.470817120622566, "alnum_prop": 0.5571071586064972, "repo_name": "Taskim/PPE3", "id": "023951dace77dbfbba4d09a5bbe5bbe89a377ddb", "size": "6803", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/cache/dev/doctrine/orm/Proxies/__CG__GSBMainBundleEntityDetailDemande.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "3073" }, { "name": "Batchfile", "bytes": "385" }, { "name": "CSS", "bytes": "17929" }, { "name": "HTML", "bytes": "24702" }, { "name": "JavaScript", "bytes": "1452" }, { "name": "PHP", "bytes": "101920" }, { "name": "Shell", "bytes": "617" } ], "symlink_target": "" }
import os from flask import Flask, request from freeipa_api_client import IPAPassword import requests app = Flask(__name__) FREEIPA_API_SERVER_URL = os.environ['FREEIPA_API_SERVER_URL'] @app.route('%s/' % os.environ.get('FREEIPA_CHANGE_PASSWORD_URL_PREFIX'), methods=['GET', 'POST']) def hello_world(): if request.method == 'POST': error_message = None if not request.form.get('username'): error_message = "Please, enter username." elif not request.form.get('current_password'): error_message = "Please, enter current password." elif not request.form.get('new_password1'): error_message = "Please, enter new password." elif request.form.get('new_password1') != request.form.get('new_password2'): error_message = "Passwords don't match." else: ipa_password_api = IPAPassword(requests, FREEIPA_API_SERVER_URL) password_change_status, password_change_response = ipa_password_api.changePassword( request.form['username'], request.form['current_password'], request.form['new_password1'] ) if not password_change_status: error_message = password_change_response.headers.get('x-ipa-pwchange-policy-error') if not error_message: error_message = password_change_response.headers.get('x-ipa-pwchange-result') if not error_message: error_message = "Unexpected error: <pre>%r</pre><br><pre>%r</pre>" % ( password_change_response.headers, password_change_response.content, ) return ( ('<div>%s</div>' % (error_message if error_message else 'Password is changed successfuly!')) + '<a href="">Back</a>' ) return ( '<form method="POST">' '<label style="display: block">Username: <input type="text" name="username"></label>' '<label style="display: block">Current Password: <input type="password" name="current_password"></label>' '<label style="display: block">New Password: <input type="password" name="new_password1"></label>' '<label style="display: block">New Password (once again): <input type="password" name="new_password2"></label>' '<input type="submit" value="Change Password">' '</form>' )
{ "content_hash": "39823aeb82c701d0b9bfcef6be3b8a1d", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 123, "avg_line_length": 44.464285714285715, "alnum_prop": 0.5839357429718876, "repo_name": "frol/freeipa-change-password-service", "id": "f11e09946b95b5e39d4fa1d2e1e90e2315df31b1", "size": "2490", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "freeipa_change_password_service.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "2490" } ], "symlink_target": "" }
layout: inner position: right title: 'Head Up Display Designer' date: 2014-11-15 12:00:00 categories: development design tags: C# Windows-Presentation-Framework featured_image: 'img/posts/2014-11-15-hud-designer.jpg' project_link: 'https://github.com/cephalic/hud-designer' button_icon: 'github' button_text: 'Visit Project' lead_text: 'A Head Up Display designer for the NADS MiniSim' ---
{ "content_hash": "22baa67f1c90bc23e376aff9b08c5a77", "timestamp": "", "source": "github", "line_count": 12, "max_line_length": 60, "avg_line_length": 32.416666666666664, "alnum_prop": 0.7712082262210797, "repo_name": "cephalic/cephalic.github.io", "id": "2081eac267880a225905e0184c367291a0aa0b3c", "size": "393", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2015-04-15-hud-designer.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8594" }, { "name": "HTML", "bytes": "10839" }, { "name": "JavaScript", "bytes": "59" } ], "symlink_target": "" }
{% extends 'profiles/base.html' %} {% block body %} <div class="container-fluid"> <div class="well"> {% if request.user.nonmusician %} <div align="Center"> <form method="POST"> {% csrf_token %} {{ update_area_form }} <input type="submit" value="Change"> </form> </div> {% endif %} </div> <!-- div well --> </div> <!-- div container-fluid --> {% endblock %}
{ "content_hash": "876714be7f8cc61d87bb79c2855559a4", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 44, "avg_line_length": 18.363636363636363, "alnum_prop": 0.5371287128712872, "repo_name": "lancekrogers/music-network", "id": "735e2ddb68f1dac3cd2f1ede2a4fa6c963e62e1f", "size": "404", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "cleff/profiles/templates/updates/update-area-nonmusician.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "50628" }, { "name": "HTML", "bytes": "48099" }, { "name": "JavaScript", "bytes": "668599" }, { "name": "Python", "bytes": "141988" } ], "symlink_target": "" }
/* Data */ (function(window){ var FWDData = function(props, playListElement){ var self = this; var prototype = FWDData.prototype; this.navigatorImage_img; this.mainPreloader_img = null; this.mainLightboxCloseButtonN_img = null; this.mainLightboxCloseButtonS_img = null; this.controllerBackgroundLeft_img = null; this.controllerBackgroundRight_img = null; this.controllerMoveDownN_img = null; this.controllerMoveDownS_img = null; this.controllerMoveDownD_img = null; this.controllerMoveUpN_img = null; this.controllerMoveUpS_img = null; this.controllerMoveUpD_img = null; this.controllerNextN_img = null; this.controllerNextS_img = null; this.controllerNextD_img = null; this.controllerPrevN_img = null; this.controllerPrevS_img = null; this.controllerPrevD_img = null; this.controllerHideMarkersN_img = null; this.controllerHideMarkersS_img = null; this.controllerShowMarkersN_img = null; this.controllerShowMarkersS_img = null; this.controllerInfoN_img = null; this.controllerInfoS_img = null; this.controllerHideN_img = null; this.controllerHideS_img = null; this.controllerShowN_img = null; this.controllerShowS_img = null; this.controllerFullScreenNormalN_img = null; this.controllerFullScreenNormalS_img = null; this.controllerFullScreenFullN_img = null; this.controllerFullScreenFullS_img = null; this.zoomInN_img = null; this.zoomInS_img = null; this.zoomOutN_img = null; this.zoomOutS_img = null; this.scrollBarHandlerN_img = null; this.scrollBarHandlerS_img = null; this.scrollBarLeft_img = null; this.scrollBarRight_img = null; this.toolTipLeft_img = null; this.toolTipPointer_img = null; this.infoWindowCloseNormal_img = null; this.infoWindowCloseSelected_img = null; this.originalImage_img = null; this.navigatorImage_img = null; this.props_obj = props; this.rootElement_el = null; this.skinPaths_ar = []; this.images_ar = []; this.markersList_ar = []; this.toolTipWindows_ar = []; this.buttons_ar = null; this.buttonsLabels_ar = null; this.contextMenuLabels_ar = null; this.skinPath_str = undefined; this.backgroundColor_str = null; this.handMovePath_str = null; this.handGrabPath_str = null; this.controllerBackgroundMiddlePath_str = null; this.scrollBarMiddlePath_str = null; this.controllerPosition_str = null; this.preloaderFontColor_str = null; this.preloaderBackgroundColor_str = null; this.preloaderText_str = null; this.buttonToolTipLeft_str = null; this.buttonToolTipMiddle_str = null; this.buttonToolTipRight_str = null; this.buttonToolTipBottomPointer_str = null; this.buttonToolTipTopPointer_str = null; this.buttonToolTipFontColor_str = null; this.contextMenuBackgroundColor_str = null; this.contextMenuBorderColor_str = null; this.contextMenuSpacerColor_str = null; this.contextMenuItemNormalColor_str = null; this.contextMenuItemSelectedColor_str = null; this.contextMenuItemSelectedColor_str = null; this.contextMenuItemDisabledColor_str = null; this.navigatorPosition_str = null; this.navigatorHandlerColor_str = null; this.navigatorBorderColor_str = null; this.infoText_str = null; this.infoWindowBackgroundColor_str = null; this.infoWindowScrollBarColor_str = null; this.originalImagePath_str = null; this.navigatorImagePath_str = null; this.dragRotationSpeed; this.panSpeed; this.zoomSpeed; this.controllerHeight; this.imageWidth; this.imageHeight; this.largeImageWidth; this.largeImageHeight; this.spaceBetweenButtons; this.startSpaceBetweenButtons; this.scrollBarOffsetX; this.doubleClickZoomFactor; this.zoomFactor; this.startZoomFactor; this.controllerOffsetY; this.hideControllerDelay; this.controllerBackgroundOpacity; this.controllerMaxWidth; this.countLoadedSkinImages = 0; this.countLoadedImages = 0; this.scrollBarHandlerToolTipOffsetY; this.zoomInAndOutToolTipOffsetY; this.buttonsToolTipOffsetY; this.hideControllerOffsetY; this.scrollBarPosition; this.startSpaceForScrollBarButtons; this.totalGraphics; this.navigatorWidth; this.navigatorHeight; this.navigatorOffsetX; this.navigatorOffsetY; this.infoWindowBackgroundOpacity; this.markerToolTipOffsetY; this.toolTipWindowMaxWidth; this.lightBoxBackgroundOpacity; this.parseDelayId_to; this.loadImageId_to; this.addKeyboardSupport_bl; this.showContextMenu_bl; this.showNavigator_bl; this.inversePanDirection_bl; this.useEntireScreenFor3dObject_bl; this.hideController_bl; this.showScriptDeveloper_bl; this.showMarkers_bl; this.hasNavigatorError_bl = false; this.showMarkersInfo_bl = false; this.addDoubleClickSupport_bl = false; this.isMobile_bl = FWDUtils.isMobile; this.hasPointerEvent_bl = FWDUtils.hasPointerEvent; //###################################// /*init*/ //###################################// self.init = function(){ self.parseDelayId_to = setTimeout(self.parseProperties, 100); }; //#############################################// // parse properties. //#############################################// self.parseProperties = function(){ var markersElement_el; var childKids_ar; var playListChildren_ar; var markersChildren_ar; var errorMessage_str; var mediaKid; var test; var obj; var obj2; var child; var hasError_bl; var attributeMissing; var positionError; var hasElementWithAttribute; var hasMarker_bl; var hasContent_bl = false; //set the root element of the zoomer list. self.rootElement_el = playListElement; if(!self.rootElement_el){ errorMessage_str = "Make sure that the a div with the id - <font color='#FFFFFF'>" + self.props_obj.playListAndSkinId + "</font> exists, self represents the data playlist."; self.dispatchEvent(FWDData.LOAD_ERROR, {text:errorMessage_str}); return; } self.originalImagePath_str = self.props_obj.imagePath; if(!self.originalImagePath_str){ errorMessage_str = "The <font color='#FFFFFF'>imagePath</font> property which represents the path for the iamge to zoom is not defined in the constructor function!"; self.dispatchEvent(FWDData.LOAD_ERROR, {text:errorMessage_str}); return; } self.rootElement_el.style.display = "none"; markersElement_el = FWDUtils.getChildFromNodeListFromAttribute(self.rootElement_el, "data-markers"); self.showNavigator_bl = self.props_obj.showNavigator; self.showNavigator_bl = self.showNavigator_bl == "yes" ? true : false; if(self.props_obj.showNavigatorOnMobile && self.props_obj.showNavigatorOnMobile == "no" && self.isMobile_bl && self.showNavigator_bl) self.showNavigator_bl = false; self.showMarkersInfo_bl = self.props_obj.showMarkersInfo == "yes" ? true : false; if(self.isMobile_bl) self.showMarkersInfo_bl = false; self.addDoubleClickSupport_bl = self.props_obj.addDoubleClickSupport; self.addDoubleClickSupport_bl = self.addDoubleClickSupport_bl == "yes" ? true : false; if(FWDUtils.isIEAndLessThen9) self.addDoubleClickSupport_bl = false; //set main properties. self.backgroundColor_str = self.props_obj.backgroundColor || "transparent"; self.preloaderFontColor_str = self.props_obj.preloaderFontColor || "#000000"; self.preloaderBackgroundColor_str = self.props_obj.preloaderBackgroundColor || "transparent"; self.preloaderText_str = self.props_obj.preloaderText || "Loading:"; self.controllerPosition_str = self.props_obj.controllerPosition || "bottom"; if(self.controllerPosition_str != "top" && self.controllerPosition_str != "bottom") self.controllerPosition_str = "top"; if(!self.props_obj.buttons){ errorMessage_str = "The <font color='#FFFFFF'>buttons</font> is not defined in the contructor, this is necessary to setup the main buttons."; self.dispatchEvent(FWDData.LOAD_ERROR, {text:errorMessage_str}); return; } self.buttons_ar = FWDUtils.splitAndTrim(self.props_obj.buttons, true, true); if(self.isMobile_bl && !self.hasPointerEvent_bl){ self.buttonsLabels_ar = null; self.contextMenuLabels_ar = null; }else{ if(self.props_obj.buttonsToolTips) self.buttonsLabels_ar = FWDUtils.splitAndTrim(self.props_obj.buttonsToolTips, false); if(self.props_obj.contextMenuLabels) self.contextMenuLabels_ar = FWDUtils.splitAndTrim(self.props_obj.contextMenuLabels, false); } self.showScriptDeveloper_bl = self.props_obj.showScriptDeveloper; self.showScriptDeveloper_bl = self.showScriptDeveloper_bl == "no" ? false : true; self.dragRotationSpeed = self.props_obj.dragRotationSpeed || .5; if(isNaN(self.dragRotationSpeed)) self.dragRotationSpeed = .5; if(self.dragRotationSpeed < 0){ self.dragRotationSpeed = 0; }else if(self.dragRotationSpeed > 1){ self.dragRotationSpeed = 1; } self.panSpeed = self.props_obj.panSpeed || 1; if(isNaN(self.panSpeed)) self.panSpeed = 1; if(self.panSpeed < 1){ self.panSpeed = 1; }else if(self.panSpeed > 100){ self.panSpeed = 100; } self.zoomSpeed = self.props_obj.zoomSpeed || .1; if(isNaN(self.zoomSpeed)) self.zoomSpeed = .1; if(self.zoomSpeed < .1){ self.zoomSpeed = .1; }else if(self.zoomSpeed > 1){ self.zoomSpeed = 1; } self.imageWidth = self.props_obj.imageWidth; if(!self.imageWidth){ self.showPropertyError("imageWidth"); return }else{ self.imageWidth = parseInt(self.imageWidth); } self.imageHeight = self.props_obj.imageHeight; if(!self.imageHeight){ self.showPropertyError("imageHeight"); return }else{ self.imageHeight = parseInt(self.imageHeight); } self.zoomFactor = self.props_obj.zoomFactor; if(self.zoomFactor == undefined){ self.showPropertyError("zoomFactor"); return; } if(self.zoomFactor < 1){ self.zoomFactor = 1; }else if(self.zoomFactor > 5){ self.zoomFactor = 5; } self.doubleClickZoomFactor = self.props_obj.doubleClickZoomFactor; if(isNaN(self.doubleClickZoomFactor)) self.doubleClickZoomFactor = self.zoomFactor; if(self.doubleClickZoomFactor > self.zoomFactor) self.doubleClickZoomFactor = self.zoomFactor; self.startZoomFactor = self.props_obj.startZoomFactor; if(self.startZoomFactor == undefined){ self.startZoomFactor = "default"; return; } if(!isNaN(self.startZoomFactor)){ if(self.startZoomFactor < .1){ self.startZoomFactor = .1; }else if(self.startZoomFactor > self.zoomFactor){ self.startZoomFactor = self.zoomFactor; } } self.navigatorOffsetX = self.props_obj.navigatorOffsetX || 0; if(isNaN(self.navigatorOffsetX)) self.navigatorOffsetX = 0; self.navigatorOffsetY = self.props_obj.navigatorOffsetY || 0; if(isNaN(self.navigatorOffsetY)) self.navigatorOffsetY = 0; self.controllerBackgroundOpacity = self.props_obj.controllerBackgroundOpacity; if(!self.controllerBackgroundOpacity) self.controllerBackgroundOpacity = 1; if(isNaN(self.controllerBackgroundOpacity)) self.controllerBackgroundOpacity = 1; if(self.controllerBackgroundOpacity < 0){ self.controllerBackgroundOpacity = 0; }else if(self.controllerBackgroundOpacity > 1){ self.controllerBackgroundOpacity = 1; } self.controllerMaxWidth = self.props_obj.controllerMaxWidth; if(!self.controllerMaxWidth) self.controllerMaxWidth = 900; if(isNaN(self.controllerMaxWidth)) self.controllerMaxWidth = 900; if(self.controllerMaxWidth < 200) self.controllerMaxWidth = 200; self.hideControllerDelay = self.props_obj.hideControllerDelay; if(self.hideControllerDelay){ self.hideController_bl = true; if(isNaN(self.hideControllerDelay)){ self.hideControllerDelay = 4000; }else if(self.hideControllerDelay < 0){ self.hideControllerDelay = 4000; }else{ self.hideControllerDelay *= 1000; } } self.spaceBetweenButtons = self.props_obj.spaceBetweenButtons || 0; self.scrollBarPosition = self.props_obj.scrollBarPosition || 0; self.startSpaceForScrollBarButtons = self.props_obj.startSpaceForScrollBarButtons || 0; self.startSpaceBetweenButtons = self.props_obj.startSpaceBetweenButtons || 0; self.startSpaceForScrollBar = self.props_obj.startSpaceForScrollBar || 0; self.scrollBarOffsetX = self.props_obj.scrollBarOffsetX || 0; self.controllerOffsetY = self.props_obj.controllerOffsetY || 0; self.scrollBarHandlerToolTipOffsetY = self.props_obj.scrollBarHandlerToolTipOffsetY || 0; self.zoomInAndOutToolTipOffsetY = self.props_obj.zoomInAndOutToolTipOffsetY || 0; self.buttonsToolTipOffsetY = self.props_obj.buttonsToolTipOffsetY || 0; self.hideControllerOffsetY = self.props_obj.hideControllerOffsetY || 0; self.infoWindowBackgroundOpacity = self.props_obj.infoWindowBackgroundOpacity || 1; self.markerToolTipOffsetY = self.props_obj.markerToolTipOffsetY || 1; self.toolTipWindowMaxWidth = self.props_obj.toolTipWindowMaxWidth || 300; self.buttonToolTipFontColor_str = self.props_obj.buttonToolTipFontColor || "#000000"; self.contextMenuBackgroundColor_str = self.props_obj.contextMenuBackgroundColor || "#000000"; self.contextMenuBorderColor_str = self.props_obj.contextMenuBorderColor || "#FF0000"; self.contextMenuSpacerColor_str = self.props_obj.contextMenuSpacerColor || "#FF0000"; self.contextMenuItemNormalColor_str = self.props_obj.contextMenuItemNormalColor || "#FF0000"; self.contextMenuItemSelectedColor_str = self.props_obj.contextMenuItemSelectedColor || "#FF0000"; self.contextMenuItemDisabledColor_str = self.props_obj.contextMenuItemDisabledColor || "#FF0000"; self.infoWindowBackgroundColor_str = self.props_obj.infoWindowBackgroundColor || "#FF0000"; self.infoWindowScrollBarColor_str = self.props_obj.infoWindowScrollBarColor || "#FF0000"; self.navigatorImagePath_str = self.props_obj.navigatorImagePath; if(self.showNavigator_bl && !self.navigatorImagePath_str) { errorMessage_str = "The <font color='#FFFFFF'>navigatorImagePath</font> is not defined in the contructor, this is necessary to setup the navigator."; self.dispatchEvent(FWDData.LOAD_ERROR, {text:errorMessage_str}); return; } self.navigatorPosition_str = self.props_obj.navigatorPosition || "topleft"; self.navigatorPosition_str = String(self.navigatorPosition_str).toLowerCase(); test = self.navigatorPosition_str == "topleft" || self.navigatorPosition_str == "topright" || self.navigatorPosition_str == "bottomleft" || self.navigatorPosition_str == "bottomright"; if(!test) self.navigatorPosition_str = "topleft"; self.navigatorHandlerColor_str = self.props_obj.navigatorHandlerColor || "#FF0000"; self.navigatorBorderColor_str = self.props_obj.navigatorBorderColor || "#FF0000"; self.showContextMenu_bl = self.props_obj.showContextMenu; self.showContextMenu_bl = self.showContextMenu_bl == "no" ? false : true; self.inversePanDirection_bl = self.props_obj.inversePanDirection; self.inversePanDirection_bl = self.inversePanDirection_bl == "yes" ? true : false; self.addKeyboardSupport_bl = self.props_obj.addKeyboardSupport == "no" ? false : true; if(self.isMobile_bl) self.addKeyboardSupport_bl = false; self.useEntireScreenFor3dObject_bl = self.props_obj.useEntireScreen; self.useEntireScreenFor3dObject_bl = self.useEntireScreenFor3dObject_bl == "yes" ? true : false; self.infoText_str = FWDUtils.getChildFromNodeListFromAttribute(self.rootElement_el, "data-info"); if(self.infoText_str){ self.infoText_str = self.infoText_str.innerHTML; }else{ self.infoText_str = "not defined make sure that an ul element with the attribute data-info is defined!"; } //markers. if(markersElement_el) self.showMarkers_bl = true; if(self.showMarkers_bl){ markersChildren_ar = FWDUtils.getChildren(markersElement_el); for(var i=0; i<markersChildren_ar.length; i++){ obj = {}; child = markersChildren_ar[i]; hasError_bl = false; attributeMissing = ""; //check for markers attributes. hasElementWithAttribute = FWDUtils.hasAttribute(child, "data-marker-type", i); if(!hasElementWithAttribute){ self.showMarkerError("data-marker-type", i); return; } hasElementWithAttribute = FWDUtils.hasAttribute(child, "data-marker-normal-state-path", i); if(!hasElementWithAttribute){ self.showMarkerError("data-marker-normal-state-path", i); return; } hasElementWithAttribute = FWDUtils.hasAttribute(child, "data-marker-selected-state-path", i); if(!hasElementWithAttribute){ self.showMarkerError("data-marker-selected-state-path"); return; } hasElementWithAttribute = FWDUtils.hasAttribute(child, "data-marker-left"); if(!hasElementWithAttribute){ self.showMarkerError("data-marker-left", i); return; } hasElementWithAttribute = FWDUtils.hasAttribute(child, "data-marker-top"); if(!hasElementWithAttribute){ self.showMarkerError("data-marker-top", i); return; } hasElementWithAttribute = FWDUtils.hasAttribute(child, "data-marker-width"); if(!hasElementWithAttribute){ self.showMarkerError("data-marker-width", i); return; } hasElementWithAttribute = FWDUtils.hasAttribute(child, "data-marker-height"); if(!hasElementWithAttribute){ self.showMarkerError("data-marker-height", i); return; } hasElementWithAttribute = FWDUtils.hasAttribute(child, "data-show-after-zoom-factor"); if(!hasElementWithAttribute){ self.showMarkerError("data-show-after-zoom-factor", i); return; } obj.type = FWDUtils.getAttributeValue(child, "data-marker-type"); test = obj.type == "link" || obj.type == "tooltip" || obj.type == "infowindow"; if(!test){ self.showMarkerTypeError(obj.type, i); return; } if(FWDUtils.hasAttribute(child, "data-show-content")){ if(FWDUtils.trim(FWDUtils.getAttributeValue(child, "data-show-content")) == "no") { hasContent_bl = false; }else{ hasContent_bl = true; } }else{ hasContent_bl = true; } obj.normalStatePath_str = FWDUtils.trim(FWDUtils.getAttributeValue(child, "data-marker-normal-state-path")); obj.selectedStatePath_str = FWDUtils.trim(FWDUtils.getAttributeValue(child, "data-marker-selected-state-path")); obj.toolTipLabel = FWDUtils.getAttributeValue(child, "data-tool-tip-label") || undefined; obj.markerX = parseInt(FWDUtils.getAttributeValue(child, "data-marker-left")); if(isNaN(obj.markerX)) obj.markerX = 0; obj.markerY = parseInt(FWDUtils.getAttributeValue(child, "data-marker-top")); if(isNaN(obj.markerY)) obj.markerY = 0; obj.markerWidth = parseInt(FWDUtils.getAttributeValue(child, "data-marker-width")); if(isNaN(obj.markerWidth)) obj.markerWidth = 5; obj.markerHeight = parseInt(FWDUtils.getAttributeValue(child, "data-marker-height")); if(isNaN(obj.markerHeight)) obj.markerHeight = 5; obj.showAfterScale = parseFloat(FWDUtils.getAttributeValue(child, "data-show-after-zoom-factor")); if(isNaN(obj.showAfterScale)) obj.showAfterScale = 0; if(obj.type == "link"){ obj.link = FWDUtils.getAttributeValue(child, "data-marker-url") || "http://www.link-is-not-defined.com"; obj.target = FWDUtils.getAttributeValue(child, "data-marker-target") || "_blank"; }else{ obj.innerHTML = child.innerHTML; } test = FWDUtils.getAttributeValue(child, "data-reg-point"); test = test === "center" || test === "centertop" || test === "centerbottom"; if(!test){ test = "center"; }else{ test = FWDUtils.trim(FWDUtils.getAttributeValue(child, "data-reg-point")).toLowerCase(); } obj.regPoint = test; obj.maxWidth = parseInt(FWDUtils.getAttributeValue(child, "data-marker-window-width")); if(isNaN(obj.maxWidth)) obj.maxWidth = 200; obj.hasContent_bl = hasContent_bl; var obj2 = {}; if(obj.type == "tooltip"){ obj2.innerHTML = child.innerHTML; obj2.maxWidth = obj.maxWidth; obj2.hasContent_bl = hasContent_bl; self.toolTipWindows_ar.push(obj2); }; self.markersList_ar.push(obj); } } self.skinPath_str = self.props_obj.skinPath; if(!self.skinPath_str){ errorMessage_str = "The <font color='#FFFFFF'>skinPath</font> property is not defined in the constructor function!"; self.dispatchEvent(FWDData.LOAD_ERROR, {text:errorMessage_str}); return; } if((self.skinPath_str.lastIndexOf("/") + 1) != self.skinPath_str.length){ self.skinPath_str += "/"; } //setup skin paths self.handMovePath_str = self.skinPath_str + "move.cur"; self.handGrabPath_str = self.skinPath_str + "handgrab.cur"; var preloaderPath_str = self.skinPath_str + "preloader.png"; var mainLightBoxCloseButtonNPath_str = self.skinPath_str + "lightbox-close-icon.png"; var mainLightBoxCloseButtonSPath_str = self.skinPath_str + "lightbox-close-icon-rollover.png"; var controllerBackgroundLeftPath_str = self.skinPath_str + "bg-bar-left.png"; var controllerBackgroundRight_str = self.skinPath_str + "bg-bar-right.png"; var controllerDownButtonN_str = self.skinPath_str + "down-icon.png"; var controllerDownButtonS_str = self.skinPath_str + "down-icon-rollover.png"; var controllerDownButtonD_str = self.skinPath_str + "down-icon-disabled.png"; var controllerUpButtonN_str = self.skinPath_str + "up-icon.png"; var controllerUpButtonS_str = self.skinPath_str + "up-icon-rollover.png"; var controllerUpButtonD_str = self.skinPath_str + "up-icon-disabled.png"; var controllerNextN_str = self.skinPath_str + "right-icon.png"; var controllerNextS_str = self.skinPath_str + "right-icon-rollover.png"; var controllerNextD_str = self.skinPath_str + "right-icon-disabled.png"; var controllerPrevN_str = self.skinPath_str + "left-icon.png"; var controllerPrevS_str = self.skinPath_str + "left-icon-rollover.png"; var controllerPrevD_str = self.skinPath_str + "left-icon-disabled.png"; var hideMarkersN_str = self.skinPath_str + "hide-markers-icon.png"; var hideMarkersS_str = self.skinPath_str + "hide-markers-icon-rollover.png"; var showMarkersN_str = self.skinPath_str + "show-markers-icon.png"; var showMarkersS_str = self.skinPath_str + "show-markers-icon-rollover.png"; var controllerInfoN_str = self.skinPath_str + "info-icon.png"; var controllerInfoS_str = self.skinPath_str + "info-icon-rollover.png"; var controllerHideN_str = self.skinPath_str + "hide-controller-icon.png"; var controllerHideS_str = self.skinPath_str + "hide-controller-icon-rollover.png"; var controllerShowN_str = self.skinPath_str + "show-controller-icon.png"; var controllerShowS_str = self.skinPath_str + "show-controller-icon-rollover.png"; var controllerFullScreemNormalN_str = self.skinPath_str + "fullscr-normal-icon.png"; var controllerFullScreenNormalS_str = self.skinPath_str + "fullscr-normal-icon-rollover.png"; var controllerFullScreemFullN_str = self.skinPath_str + "fullscr-full-icon.png"; var controllerFullScreenFullS_str = self.skinPath_str + "fullscr-full-icon-rollover.png"; var zoomInN_str = self.skinPath_str + "zoomin.png"; var zoomInS_str = self.skinPath_str + "zoomin-rollover.png"; var zoomOutN_str = self.skinPath_str + "zoomout.png"; var zoomOutS_str = self.skinPath_str + "zoomout-rollover.png"; var scrollBarHandlerN_str = self.skinPath_str + "handler.png"; var scrollBarHandlerS_str = self.skinPath_str + "handler-rollover.png"; var scrollBarLeft_str = self.skinPath_str + "scrool-left.png"; var scrollBarRight_str = self.skinPath_str + "scrool-right.png"; self.scrollBarMiddlePath_str = self.skinPath_str + "scrool-middle.png"; self.controllerBackgroundMiddlePath_str = self.skinPath_str + "bg-bar-middle.png"; self.buttonToolTipLeft_str = self.skinPath_str + "button-tool-tip-left.png"; self.buttonToolTipMiddle_str = self.skinPath_str + "button-tool-tip-middle.png"; self.buttonToolTipRight_str = self.skinPath_str + "button-tool-tip-right.png"; self.buttonToolTipBottomPointer_str = self.skinPath_str + "button-tool-tip-down-pointer.png"; self.buttonToolTipTopPointer_str = self.skinPath_str + "button-tool-tip-top-pointer.png"; var infoWindowCloseNormal_str = self.skinPath_str + "close-icon.png"; var infoWindowCloseSelected_str = self.skinPath_str + "close-icon-rollover.png"; //set skin graphics paths. self.skinPaths_ar.push(preloaderPath_str); self.skinPaths_ar.push(mainLightBoxCloseButtonNPath_str); self.skinPaths_ar.push(mainLightBoxCloseButtonSPath_str); self.skinPaths_ar.push(controllerBackgroundLeftPath_str); self.skinPaths_ar.push(controllerBackgroundRight_str); self.skinPaths_ar.push(controllerDownButtonN_str); self.skinPaths_ar.push(controllerDownButtonS_str); self.skinPaths_ar.push(controllerDownButtonD_str); self.skinPaths_ar.push(controllerUpButtonN_str); self.skinPaths_ar.push(controllerUpButtonS_str); self.skinPaths_ar.push(controllerUpButtonD_str); self.skinPaths_ar.push(controllerNextN_str); self.skinPaths_ar.push(controllerNextS_str); self.skinPaths_ar.push(controllerNextD_str); self.skinPaths_ar.push(controllerPrevN_str); self.skinPaths_ar.push(controllerPrevS_str); self.skinPaths_ar.push(controllerPrevD_str); self.skinPaths_ar.push(hideMarkersN_str); self.skinPaths_ar.push(hideMarkersS_str); self.skinPaths_ar.push(showMarkersN_str); self.skinPaths_ar.push(showMarkersS_str); self.skinPaths_ar.push(controllerInfoN_str); self.skinPaths_ar.push(controllerInfoS_str); self.skinPaths_ar.push(controllerHideN_str); self.skinPaths_ar.push(controllerHideS_str); self.skinPaths_ar.push(controllerShowN_str); self.skinPaths_ar.push(controllerShowS_str); self.skinPaths_ar.push(controllerFullScreemNormalN_str); self.skinPaths_ar.push(controllerFullScreenNormalS_str); self.skinPaths_ar.push(controllerFullScreemFullN_str); self.skinPaths_ar.push(controllerFullScreenFullS_str); self.skinPaths_ar.push(zoomInN_str); self.skinPaths_ar.push(zoomInS_str); self.skinPaths_ar.push(zoomOutN_str); self.skinPaths_ar.push(zoomOutS_str); self.skinPaths_ar.push(scrollBarHandlerN_str); self.skinPaths_ar.push(scrollBarHandlerS_str); self.skinPaths_ar.push(scrollBarLeft_str); self.skinPaths_ar.push(scrollBarRight_str); self.skinPaths_ar.push(self.buttonToolTipTopPointer_str); self.skinPaths_ar.push(self.buttonToolTipLeft_str); self.skinPaths_ar.push(infoWindowCloseNormal_str); self.skinPaths_ar.push(infoWindowCloseSelected_str); self.skinPaths_ar.push(self.buttonToolTipMiddle_str); self.skinPaths_ar.push(self.buttonToolTipRight_str); self.skinPaths_ar.push(self.controllerBackgroundMiddlePath_str); self.totalGraphics = self.skinPaths_ar.length; self.loadSkin(); }; //####################################// /* load buttons graphics */ //###################################// self.loadSkin = function(){ if(self.image_img){ self.image_img.onload = null; self.image_img.onerror = null; } var imagePath = self.skinPaths_ar[self.countLoadedSkinImages]; self.image_img = new Image(); self.image_img.onload = self.onSkinLoadHandler; self.image_img.onerror = self.onKinLoadErrorHandler; self.image_img.src = imagePath; }; self.onSkinLoadHandler = function(e){ if(self.countLoadedSkinImages == 0){ self.mainPreloader_img = self.image_img; self.dispatchEvent(FWDData.PRELOADER_LOAD_DONE); self.dispatchEvent(FWDData.SKIN_PROGRESS); }else if(self.countLoadedSkinImages == 1){ self.mainLightboxCloseButtonN_img = self.image_img; }else if(self.countLoadedSkinImages == 2){ self.mainLightboxCloseButtonS_img = self.image_img; self.dispatchEvent(FWDData.LIGHBOX_CLOSE_BUTTON_LOADED); }else if(self.countLoadedSkinImages == 3){ self.controllerBackgroundLeft_img = self.image_img; self.controllerHeight = self.controllerBackgroundLeft_img.height; }else if(self.countLoadedSkinImages == 4){ self.controllerBackgroundRight_img = self.image_img; }else if(self.countLoadedSkinImages == 5){ self.controllerMoveDownN_img = self.image_img; }else if(self.countLoadedSkinImages == 6){ self.controllerMoveDownS_img = self.image_img; }else if(self.countLoadedSkinImages == 7){ self.controllerMoveDownD_img = self.image_img; }else if(self.countLoadedSkinImages == 8){ self.controllerMoveUpN_img = self.image_img; }else if(self.countLoadedSkinImages == 9){ self.controllerMoveUpS_img = self.image_img; }else if(self.countLoadedSkinImages == 10){ self.controllerMoveUpD_img = self.image_img; }else if(self.countLoadedSkinImages == 11){ self.controllerNextN_img = self.image_img; }else if(self.countLoadedSkinImages == 12){ self.controllerNextS_img = self.image_img; }else if(self.countLoadedSkinImages == 13){ self.controllerNextD_img = self.image_img; }else if(self.countLoadedSkinImages == 14){ self.controllerPrevN_img = self.image_img; }else if(self.countLoadedSkinImages == 15){ self.controllerPrevS_img = self.image_img; }else if(self.countLoadedSkinImages == 16){ self.controllerPrevD_img = self.image_img; }else if(self.countLoadedSkinImages == 17){ self.controllerHideMarkersN_img = self.image_img; }else if(self.countLoadedSkinImages == 18){ self.controllerHideMarkersS_img = self.image_img; }else if(self.countLoadedSkinImages == 19){ self.controllerShowMarkersN_img = self.image_img; }else if(self.countLoadedSkinImages == 20){ self.controllerShowMarkersS_img = self.image_img; }else if(self.countLoadedSkinImages == 21){ self.controllerInfoN_img = self.image_img; }else if(self.countLoadedSkinImages == 22){ self.controllerInfoS_img = self.image_img; }else if(self.countLoadedSkinImages == 23){ self.controllerHideN_img = self.image_img; }else if(self.countLoadedSkinImages == 24){ self.controllerHideS_img = self.image_img; }else if(self.countLoadedSkinImages == 25){ self.controllerShowN_img = self.image_img; }else if(self.countLoadedSkinImages == 26){ self.controllerShowS_img = self.image_img; }else if(self.countLoadedSkinImages == 27){ self.controllerFullScreenNormalN_img = self.image_img; }else if(self.countLoadedSkinImages == 28){ self.controllerFullScreenNormalS_img = self.image_img; }else if(self.countLoadedSkinImages == 29){ self.controllerFullScreenFullN_img = self.image_img; }else if(self.countLoadedSkinImages == 30){ self.controllerFullScreenFullS_img = self.image_img; }else if(self.countLoadedSkinImages == 31){ self.zoomInN_img = self.image_img; }else if(self.countLoadedSkinImages == 32){ self.zoomInS_img = self.image_img; }else if(self.countLoadedSkinImages == 33){ self.zoomOutN_img = self.image_img; }else if(self.countLoadedSkinImages == 34){ self.zoomOutS_img = self.image_img; }else if(self.countLoadedSkinImages == 35){ self.scrollBarHandlerN_img = self.image_img; }else if(self.countLoadedSkinImages == 36){ self.scrollBarHandlerS_img = self.image_img; }else if(self.countLoadedSkinImages == 37){ self.scrollBarLeft_img = self.image_img; }else if(self.countLoadedSkinImages == 38){ self.scrollBarRight_img = self.image_img; }else if(self.countLoadedSkinImages == 39){ self.toolTipPointer_img = self.image_img; }else if(self.countLoadedSkinImages == 40){ self.toolTipLeft_img = self.image_img; }else if(self.countLoadedSkinImages == 41){ self.infoWindowCloseNormal_img = self.image_img; }else if(self.countLoadedSkinImages == 42){ self.infoWindowCloseSelected_img = self.image_img; } self.countLoadedSkinImages++; if(self.countLoadedSkinImages < self.totalGraphics){ self.loadImageId_to = setTimeout(self.loadSkin, 16); }else{ self.dispatchEvent(FWDData.SKIN_PROGRESS, {percent:self.countLoadedSkinImages/self.totalGraphics}); self.dispatchEvent(FWDData.LOAD_DONE); if(self.showNavigator_bl){ self.loadNavigatorImage(); }else{ self.loadMainImage(); } } }; self.onKinLoadErrorHandler = function(e){ var message = "The skin graphics with the label <font color='#FFFFFF'>" + self.skinPaths_ar[self.countLoadedSkinImages] + "</font> can't be loaded, make sure that the image exists and the path is correct!"; console.log(e); var err = {text:message}; self.dispatchEvent(FWDData.LOAD_ERROR, err); }; self.stopToLoad = function(){ clearTimeout(self.loadImageId_to); if(self.image_img){ self.image_img.onload = null; self.image_img.onerror = null; } if(self.navigatorImage_img){ self.navigatorImage_img.onload = null; self.navigatorImage_img.onerror = null; } }; //####################################// /* load navigator images */ //###################################// self.loadNavigatorImage = function(){ if(self.image_img){ self.image_img.onload = null; self.image_img.onerror = null; } var imagePath = self.navigatorImagePath_str; self.image_img = new Image(); self.image_img.onload = self.onNavigatorImageLoadHandler; self.image_img.onerror = self.onNavigatorImageLoadErrorHandler; self.image_img.src = imagePath; }; self.onNavigatorImageLoadHandler = function(){ self.navigatorWidth = self.image_img.width; self.navigatorHeight = self.image_img.height; self.navigatorImage_img = self.image_img; self.loadMainImage(); self.dispatchEvent(FWDData.IMAGES_PROGRESS); }; //####################################// /* load small images */ //###################################// self.loadMainImage = function(){ if(self.hasNavigatorError_bl) return; if(self.image_img){ self.image_img.onload = null; self.image_img.onerror = null; } self.image_img = new Image(); self.image_img.onload = self.onImageLoadHandler; self.image_img.onerror = self.onImageLoadErrorHandler; self.image_img.src = self.originalImagePath_str; }; self.onImageLoadHandler = function(e){ self.originalImage_img = self.image_img; self.dispatchEvent(FWDData.IMAGES_LOAD_COMPLETE); }; self.onLastNavigatorImageLoadHandler = function(e){ if(self == null) return; self.dispatchEvent(FWDData.IMAGES_LOAD_COMPLETE); }; self.onNavigatorImageLoadErrorHandler = function(e){ var message = "The navigator image with the label <font color='#FFFFFF'>" + self.navigatorImagePath_str + "</font> can't be loaded, make sure that the image exists and the path is correct!"; self.hasNavigatorError_bl = true; var err = {text:message}; self.dispatchEvent(FWDData.LOAD_ERROR, err); console.log(e); }; self.onImageLoadErrorHandler = function(e){ var message = "The image with the label <font color='#FFFFFF'>" + self.originalImagePath_str + "</font> can't be loaded, make sure that the image exists and the path is correct!"; console.log(e); var err = {text:message}; self.dispatchEvent(FWDData.LOAD_ERROR, err); }; //####################################// /* check if element with and attribute exists or throw error */ //####################################// self.checkForAttribute = function(e, attr, position){ var test = FWDUtils.getChildFromNodeListFromAttribute(e, attr); test = test ? FWDUtils.trim(FWDUtils.getAttributeValue(test, attr)) : undefined; if(!test){ if(position != undefined){ self.dispatchEvent(FWDData.LOAD_ERROR, {text:"Element with attribute <font color='#FFFFFF'>" + attr + "</font> is not defined at positon <font color='#FFFFFF'>" + (position + 1) + "</font>"}); }else{ self.dispatchEvent(FWDData.LOAD_ERROR, {text:"Element with attribute <font color='#FFFFFF'>" + attr + "</font> is not defined."}); } return; } return test; }; //####################################// /* show error if a required property is not defined */ //####################################// self.showPropertyError = function(error){ self.dispatchEvent(FWDData.LOAD_ERROR, {text:"The property called <font color='#FFFFFF'>" + error + "</font> is not defined."}); }; self.showMarkerError = function(error, position){ self.dispatchEvent(FWDData.LOAD_ERROR, {text:"The marker at position <font color='#FFFFFF'>" + (position + 1) + "</font> dose not have defined an attribute <font color='#FFFFFF'>" + error + "</font>."}); }; self.showMarkerTypeError = function(error, position){ self.dispatchEvent(FWDData.LOAD_ERROR, {text:"Marker type is incorrect <font color='#FFFFFF'>" + error + "</font> at position <font color='#FFFFFF'>" + position + "</font>. Accepted types are <font color='#FFFFFF'>link, tooltip, infowindow</font>."}); }; //####################################// /*destroy */ //####################################// self.destroy = function(){ var img_img; clearTimeout(self.parseDelayId_to); clearTimeout(self.loadImageId_to); if(self.image_img){ self.image_img.onload = null; self.image_img.onerror = null; self.image_img.src = null; } if(self.navigatorImage_img){ self.navigatorImage_img.onload = null; self.navigatorImage_img.onerror = null; self.navigatorImage_img.src = null; } if(self.mainPreloader_img) self.mainPreloader_img.src = null; if(self.mainLightboxCloseButtonN_img) self.mainLightboxCloseButtonN_img.src = null; if(self.mainLightboxCloseButtonS_img) self.mainLightboxCloseButtonS_img.src = null; if(self.controllerBackgroundLeft_img) self.controllerBackgroundLeft_img.src = null; if(self.controllerBackgroundRight_img) self.controllerBackgroundRight_img.src = null; if(self.controllerMoveDownN_img) self.controllerMoveDownN_img.src = null; if(self.controllerMoveDownS_img) self.controllerMoveDownS_img.src = null; if(self.controllerMoveDownD_img) self.controllerMoveDownD_img.src = null; if(self.controllerMoveUpN_img) self.controllerMoveUpN_img.src = null; if(self.controllerMoveUpS_img) self.controllerMoveUpS_img.src = null; if(self.controllerMoveUpD_img) self.controllerMoveUpD_img.src = null; if(self.controllerNextN_img) self.controllerNextN_img.src = null; if(self.controllerNextS_img) self.controllerNextS_img.src = null; if(self.controllerNextD_img) self.controllerNextD_img.src = null; if(self.controllerPrevN_img) self.controllerPrevN_img.src = null; if(self.controllerPrevS_img) self.controllerPrevS_img.src = null; if(self.controllerPrevD_img) self.controllerPrevD_img.src = null; if(self.controllerHideMarkersN_img) self.controllerHideMarkersN_img.src = null; if(self.controllerHideMarkersS_img) self.controllerHideMarkersS_img.src = null; if(self.controllerShowMarkersN_img) self.controllerShowMarkersN_img.src = null; if(self.controllerShowMarkersS_img) self.controllerShowMarkersS_img.src = null; if(self.controllerInfoN_img) self.controllerInfoN_img.src = null; if(self.controllerHideN_img) self.controllerHideN_img.src = null; if(self.controllerHideS_img) self.controllerHideS_img.src = null; if(self.controllerShowN_img) self.controllerShowN_img.src = null; if(self.controllerShowS_img) self.controllerShowS_img.src = null; if(self.controllerFullScreenNormalN_img) self.controllerFullScreenNormalN_img.src = null; if(self.controllerFullScreenNormalS_img) self.controllerFullScreenNormalS_img.src = null; if(self.controllerFullScreenFullN_img) self.controllerFullScreenFullN_img.src = null; if(self.controllerFullScreenFullS_img) self.controllerFullScreenFullS_img.src = null; if(self.zoomInN_img) self.zoomInN_img.src = null; if(self.zoomInS_img) self.zoomInS_img.src = null; if(self.zoomOutN_img) self.zoomOutN_img.src = null; if(self.zoomOutS_img) self.zoomOutS_img.src = null; if(self.scrollBarHandlerN_img) self.scrollBarHandlerN_img.src = null; if(self.scrollBarHandlerN_img) self.scrollBarHandlerN_img.src = null; if(self.scrollBarHandlerS_img) self.scrollBarHandlerS_img.src = null; if(self.scrollBarLeft_img) self.scrollBarLeft_img.src = null; if(self.scrollBarLeft_img) self.scrollBarLeft_img.src = null; if(self.scrollBarRight_img) self.scrollBarRight_img.src = null; if(self.toolTipLeft_img) self.toolTipLeft_img.src = null; if(self.toolTipPointer_img) self.toolTipPointer_img.src = null; if(self.infoWindowCloseNormal_img) self.infoWindowCloseNormal_img.src = null; if(self.infoWindowCloseSelected_img) self.infoWindowCloseSelected_img.src = null; self.mainPreloader_img = null; self.mainLightboxCloseButtonN_img = null; self.mainLightboxCloseButtonS_img = null; self.controllerBackgroundLeft_img = null; self.controllerBackgroundRight_img = null; self.controllerMoveDownN_img = null; self.controllerMoveDownS_img = null; self.controllerMoveUpN_img = null; self.controllerMoveUpS_img = null; self.controllerNextN_img = null; self.controllerNextS_img = null; self.controllerPrevN_img = null; self.controllerPrevS_img = null; self.controllerHideMarkersN_img = null; self.controllerHideMarkersS_img = null; self.controllerShowMarkersN_img = null; self.controllerShowMarkersS_img = null; self.controllerInfoN_img = null; self.controllerInfoS_img = null; self.controllerHideN_img = null; self.controllerHideS_img = null; self.controllerShowN_img = null; self.controllerShowS_img = null; self.controllerFullScreenNormalN_img = null; self.controllerFullScreenNormalS_img = null; self.controllerFullScreenFullN_img = null; self.controllerFullScreenFullS_img = null; self.zoomInN_img = null; self.zoomInS_img = null; self.zoomOutN_img = null; self.zoomOutS_img = null; self.scrollBarHandlerN_img = null; self.scrollBarHandlerS_img = null; self.scrollBarLeft_img = null; self.scrollBarRight_img = null; self.toolTipLeft_img = null; self.toolTipPointer_img = null; self.infoWindowCloseNormal_img = null; self.infoWindowCloseSelected_img = null; this.props_obj = null; this.rootElement_el = null; this.skinPaths_ar = null; this.markersList_ar = null; this.toolTipWindows_ar = null; this.buttons_ar = null; this.buttonsLabels_ar = null; this.contextMenuLabels_ar = null; this.backgroundColor_str = null; this.handMovePath_str = null; this.handGrabPath_str = null; this.controllerBackgroundMiddlePath_str = null; this.scrollBarMiddlePath_str = null; this.controllerPosition_str = null; this.preloaderFontColor_str = null; this.preloaderBackgroundColor_str = null; this.preloaderText_str = null; this.buttonToolTipLeft_str = null; this.buttonToolTipMiddle_str = null; this.buttonToolTipRight_str = null; this.buttonToolTipBottomPointer_str = null; this.buttonToolTipTopPointer_str = null; this.buttonToolTipFontColor_str = null; this.contextMenuBackgroundColor_str = null; this.contextMenuBorderColor_str = null; this.contextMenuSpacerColor_str = null; this.contextMenuItemNormalColor_str = null; this.contextMenuItemSelectedColor_str = null; this.contextMenuItemSelectedColor_str = null; this.contextMenuItemDisabledColor_str = null; this.navigatorPosition_str = null; this.navigatorHandlerColor_str = null; this.navigatorBorderColor_str = null; this.infoText_str = null; this.infoWindowBackgroundColor_str = null; this.infoWindowScrollBarColor_str = null; prototype.destroy(); self = null; prototype = null; FWDData.prototype = null; }; self.init(); }; /* set prototype */ FWDData.setPrototype = function(){ FWDData.prototype = new FWDEventDispatcher(); }; FWDData.prototype = null; FWDData.PRELOADER_LOAD_DONE = "onPreloaderLoadDone"; FWDData.LOAD_DONE = "onLoadDone"; FWDData.LOAD_ERROR = "onLoadError"; FWDData.LIGHBOX_CLOSE_BUTTON_LOADED = "onLightBoxCloseButtonLoadDone"; FWDData.IMAGE_LOADED = "onImageLoaded"; FWDData.FIRST_IMAGE_LOAD_COMPLETE = "onFirstImageLoadComplete"; FWDData.IMAGES_LOAD_COMPLETE = "onImagesLoadComplete"; FWDData.SKIN_PROGRESS = "onSkinProgress"; FWDData.IMAGES_PROGRESS = "onImagesPogress"; FWDData.hasTouch_bl = false; window.FWDData = FWDData; }(window));
{ "content_hash": "6b79b334a82db7a3a21d2f6671e477d7", "timestamp": "", "source": "github", "line_count": 1069, "max_line_length": 254, "avg_line_length": 41.864359214218894, "alnum_prop": 0.71199696109758, "repo_name": "ModelAnnotation/model", "id": "390e53900c96b2db7dea9a4de0828591c8c89839", "size": "44753", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "zoom/js/FWDData.js", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "427" }, { "name": "CSS", "bytes": "265252" }, { "name": "HTML", "bytes": "4983899" }, { "name": "JavaScript", "bytes": "2176095" }, { "name": "PHP", "bytes": "8186785" }, { "name": "Smarty", "bytes": "181993" } ], "symlink_target": "" }
package core.issue; import com.alorma.github.sdk.bean.info.RepoInfo; import core.BodyRequest; public class EditIssueCommentBodyRequest { private RepoInfo repoInfo; private String commentId; private BodyRequest body; public EditIssueCommentBodyRequest(RepoInfo repoInfo, String commentId, String body) { this.repoInfo = repoInfo; this.commentId = commentId; this.body = new BodyRequest(body); } public RepoInfo getRepoInfo() { return repoInfo; } public String getCommentId() { return commentId; } public BodyRequest getBody() { return body; } }
{ "content_hash": "3460a5322a6c02a72ea744386811acea", "timestamp": "", "source": "github", "line_count": 28, "max_line_length": 88, "avg_line_length": 21.285714285714285, "alnum_prop": 0.7315436241610739, "repo_name": "epiphany27/Gitskarios", "id": "87f5d14689525680221f6b507b2011260720a79b", "size": "596", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "app/src/main/java/core/issue/EditIssueCommentBodyRequest.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "6351" }, { "name": "HTML", "bytes": "4856" }, { "name": "Java", "bytes": "1010530" }, { "name": "JavaScript", "bytes": "336585" } ], "symlink_target": "" }
title: Match Ending String Patterns localeTitle: Padrões de Sequência de Correspondência Final --- ## Padrões de Sequência de Correspondência Final Este é um esboço. [Ajude nossa comunidade a expandi-lo](https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/javascript-algorithms-and-data-structures/regular-expressions/match-ending-string-patterns/index.md) . [Este guia de estilo rápido ajudará a garantir que sua solicitação de recebimento seja aceita](https://github.com/freecodecamp/guides/blob/master/README.md) .
{ "content_hash": "f5279801181c7b513eb35f466d78f46e", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 234, "avg_line_length": 67.875, "alnum_prop": 0.8158379373848987, "repo_name": "HKuz/FreeCodeCamp", "id": "3452d8c09ced79918b05e212d1c2d7c18dcdec00", "size": "559", "binary": false, "copies": "4", "ref": "refs/heads/fix/JupyterNotebook", "path": "guide/portuguese/certifications/javascript-algorithms-and-data-structures/regular-expressions/match-ending-string-patterns/index.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "193850" }, { "name": "HTML", "bytes": "100244" }, { "name": "JavaScript", "bytes": "522369" } ], "symlink_target": "" }
<?php /** * Template to display search results * * @package WordPress * @subpackage Minimatica * @since Minimatica 1.0 */ get_header(); ?> <div class="title-container"> <h1 class="page-title"><?php _e( 'Search Results for', 'minimatica' ); ?>: &quot;<?php echo get_search_query(); ?>&quot;</h1> </div><!-- .title-container --> <div id="container"> <?php get_template_part( 'loop', 'search' ); ?> <?php get_sidebar(); ?> <div class="clear"></div> </div><!-- #container --> <?php get_footer(); ?>
{ "content_hash": "8e315e8c7123a28e1323346d7a0db561", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 126, "avg_line_length": 26.57894736842105, "alnum_prop": 0.6059405940594059, "repo_name": "SOSWEB-CH/protocall", "id": "7151a3a4cddf882a749b5493c12562ee48d61b68", "size": "505", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "wp-content/themes/protocall/search.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "78872" }, { "name": "ActionScript", "bytes": "23806" }, { "name": "Assembly", "bytes": "99902" }, { "name": "CSS", "bytes": "910799" }, { "name": "ColdFusion", "bytes": "141230" }, { "name": "JavaScript", "bytes": "2948203" }, { "name": "Lasso", "bytes": "21346" }, { "name": "PHP", "bytes": "23086341" }, { "name": "Perl", "bytes": "37190" }, { "name": "Python", "bytes": "42260" }, { "name": "XSLT", "bytes": "5859" } ], "symlink_target": "" }
require "time" class Time class << self unless respond_to?(:w3cdtf) # This method converts a W3CDTF string date/time format to Time object. # # The W3CDTF format is defined here: http://www.w3.org/TR/NOTE-datetime # # Time.w3cdtf('2003-02-15T13:50:05-05:00') # # => 2003-02-15 10:50:05 -0800 # Time.w3cdtf('2003-02-15T13:50:05-05:00').class # # => Time def w3cdtf(date) if /\A\s* (-?\d+)-(\d\d)-(\d\d) (?:T (\d\d):(\d\d)(?::(\d\d))? (\.\d+)? (Z|[+-]\d\d:\d\d)?)? \s*\z/ix =~ date and (($5 and $8) or (!$5 and !$8)) datetime = [$1.to_i, $2.to_i, $3.to_i, $4.to_i, $5.to_i, $6.to_i] usec = 0 usec = $7.to_f * 1000000 if $7 zone = $8 if zone off = zone_offset(zone, datetime[0]) datetime = apply_offset(*(datetime + [off])) datetime << usec time = Time.utc(*datetime) force_zone!(time, zone, off) time else datetime << usec Time.local(*datetime) end else raise ArgumentError.new("invalid date: #{date.inspect}") end end end end unless method_defined?(:w3cdtf) # This method converts a Time object to a String. The String contains the # time in W3CDTF date/time format. # # The W3CDTF format is defined here: http://www.w3.org/TR/NOTE-datetime # # Time.now.w3cdtf # # => "2013-08-26T14:12:10.817124-07:00" def w3cdtf if usec.zero? fraction_digits = 0 else fraction_digits = Math.log10(usec.to_s.sub(/0*$/, '').to_i).floor + 1 end xmlschema(fraction_digits) end end end require "English" require "rss/utils" require "rss/converter" require "rss/xml-stylesheet" module RSS # The current version of RSS VERSION = "0.2.7" # The URI of the RSS 1.0 specification URI = "http://purl.org/rss/1.0/" DEBUG = false # :nodoc: # The basic error all other RSS errors stem from. Rescue this error if you # want to handle any given RSS error and you don't care about the details. class Error < StandardError; end # RSS, being an XML-based format, has namespace support. If two namespaces are # declared with the same name, an OverlappedPrefixError will be raised. class OverlappedPrefixError < Error attr_reader :prefix def initialize(prefix) @prefix = prefix end end # The InvalidRSSError error is the base class for a variety of errors # related to a poorly-formed RSS feed. Rescue this error if you only # care that a file could be invalid, but don't care how it is invalid. class InvalidRSSError < Error; end # Since RSS is based on XML, it must have opening and closing tags that # match. If they don't, a MissingTagError will be raised. class MissingTagError < InvalidRSSError attr_reader :tag, :parent def initialize(tag, parent) @tag, @parent = tag, parent super("tag <#{tag}> is missing in tag <#{parent}>") end end # Some tags must only exist a specific number of times in a given RSS feed. # If a feed has too many occurrences of one of these tags, a TooMuchTagError # will be raised. class TooMuchTagError < InvalidRSSError attr_reader :tag, :parent def initialize(tag, parent) @tag, @parent = tag, parent super("tag <#{tag}> is too much in tag <#{parent}>") end end # Certain attributes are required on specific tags in an RSS feed. If a feed # is missing one of these attributes, a MissingAttributeError is raised. class MissingAttributeError < InvalidRSSError attr_reader :tag, :attribute def initialize(tag, attribute) @tag, @attribute = tag, attribute super("attribute <#{attribute}> is missing in tag <#{tag}>") end end # RSS does not allow for free-form tag names, so if an RSS feed contains a # tag that we don't know about, an UnknownTagError is raised. class UnknownTagError < InvalidRSSError attr_reader :tag, :uri def initialize(tag, uri) @tag, @uri = tag, uri super("tag <#{tag}> is unknown in namespace specified by uri <#{uri}>") end end # Raised when an unexpected tag is encountered. class NotExpectedTagError < InvalidRSSError attr_reader :tag, :uri, :parent def initialize(tag, uri, parent) @tag, @uri, @parent = tag, uri, parent super("tag <{#{uri}}#{tag}> is not expected in tag <#{parent}>") end end # For backward compatibility :X NotExceptedTagError = NotExpectedTagError # :nodoc: # Attributes are in key-value form, and if there's no value provided for an # attribute, a NotAvailableValueError will be raised. class NotAvailableValueError < InvalidRSSError attr_reader :tag, :value, :attribute def initialize(tag, value, attribute=nil) @tag, @value, @attribute = tag, value, attribute message = "value <#{value}> of " message << "attribute <#{attribute}> of " if attribute message << "tag <#{tag}> is not available." super(message) end end # Raised when an unknown conversion error occurs. class UnknownConversionMethodError < Error attr_reader :to, :from def initialize(to, from) @to = to @from = from super("can't convert to #{to} from #{from}.") end end # for backward compatibility UnknownConvertMethod = UnknownConversionMethodError # :nodoc: # Raised when a conversion failure occurs. class ConversionError < Error attr_reader :string, :to, :from def initialize(string, to, from) @string = string @to = to @from = from super("can't convert #{@string} to #{to} from #{from}.") end end # Raised when a required variable is not set. class NotSetError < Error attr_reader :name, :variables def initialize(name, variables) @name = name @variables = variables super("required variables of #{@name} are not set: #{@variables.join(', ')}") end end # Raised when a RSS::Maker attempts to use an unknown maker. class UnsupportedMakerVersionError < Error attr_reader :version def initialize(version) @version = version super("Maker doesn't support version: #{@version}") end end module BaseModel include Utils def install_have_child_element(tag_name, uri, occurs, name=nil, type=nil) name ||= tag_name add_need_initialize_variable(name) install_model(tag_name, uri, occurs, name) writer_type, reader_type = type def_corresponded_attr_writer name, writer_type def_corresponded_attr_reader name, reader_type install_element(name) do |n, elem_name| <<-EOC if @#{n} "\#{@#{n}.to_s(need_convert, indent)}" else '' end EOC end end alias_method(:install_have_attribute_element, :install_have_child_element) def install_have_children_element(tag_name, uri, occurs, name=nil, plural_name=nil) name ||= tag_name plural_name ||= "#{name}s" add_have_children_element(name, plural_name) add_plural_form(name, plural_name) install_model(tag_name, uri, occurs, plural_name, true) def_children_accessor(name, plural_name) install_element(name, "s") do |n, elem_name| <<-EOC rv = [] @#{n}.each do |x| value = "\#{x.to_s(need_convert, indent)}" rv << value if /\\A\\s*\\z/ !~ value end rv.join("\n") EOC end end def install_text_element(tag_name, uri, occurs, name=nil, type=nil, disp_name=nil) name ||= tag_name disp_name ||= name self::ELEMENTS << name unless self::ELEMENTS.include?(name) add_need_initialize_variable(name) install_model(tag_name, uri, occurs, name) def_corresponded_attr_writer(name, type, disp_name) def_corresponded_attr_reader(name, type || :convert) install_element(name) do |n, elem_name| <<-EOC if respond_to?(:#{n}_content) content = #{n}_content else content = @#{n} end if content rv = "\#{indent}<#{elem_name}>" value = html_escape(content) if need_convert rv << convert(value) else rv << value end rv << "</#{elem_name}>" rv else '' end EOC end end def install_date_element(tag_name, uri, occurs, name=nil, type=nil, disp_name=nil) name ||= tag_name type ||= :w3cdtf disp_name ||= name self::ELEMENTS << name add_need_initialize_variable(name) install_model(tag_name, uri, occurs, name) # accessor convert_attr_reader name date_writer(name, type, disp_name) install_element(name) do |n, elem_name| <<-EOC if @#{n} rv = "\#{indent}<#{elem_name}>" value = html_escape(@#{n}.#{type}) if need_convert rv << convert(value) else rv << value end rv << "</#{elem_name}>" rv else '' end EOC end end private def install_element(name, postfix="") elem_name = name.sub('_', ':') method_name = "#{name}_element#{postfix}" add_to_element_method(method_name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{method_name}(need_convert=true, indent='') #{yield(name, elem_name)} end private :#{method_name} EOC end def inherit_convert_attr_reader(*attrs) attrs.each do |attr| attr = attr.id2name if attr.kind_of?(Integer) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{attr}_without_inherit convert(@#{attr}) end def #{attr} if @#{attr} #{attr}_without_inherit elsif @parent @parent.#{attr} else nil end end EOC end end def uri_convert_attr_reader(*attrs) attrs.each do |attr| attr = attr.id2name if attr.kind_of?(Integer) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{attr}_without_base convert(@#{attr}) end def #{attr} value = #{attr}_without_base return nil if value.nil? if /\\A[a-z][a-z0-9+.\\-]*:/i =~ value value else "\#{base}\#{value}" end end EOC end end def convert_attr_reader(*attrs) attrs.each do |attr| attr = attr.id2name if attr.kind_of?(Integer) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{attr} convert(@#{attr}) end EOC end end def yes_clean_other_attr_reader(*attrs) attrs.each do |attr| attr = attr.id2name if attr.kind_of?(Integer) module_eval(<<-EOC, __FILE__, __LINE__ + 1) attr_reader(:#{attr}) def #{attr}? YesCleanOther.parse(@#{attr}) end EOC end end def yes_other_attr_reader(*attrs) attrs.each do |attr| attr = attr.id2name if attr.kind_of?(Integer) module_eval(<<-EOC, __FILE__, __LINE__ + 1) attr_reader(:#{attr}) def #{attr}? Utils::YesOther.parse(@#{attr}) end EOC end end def csv_attr_reader(*attrs) separator = nil if attrs.last.is_a?(Hash) options = attrs.pop separator = options[:separator] end separator ||= ", " attrs.each do |attr| attr = attr.id2name if attr.kind_of?(Integer) module_eval(<<-EOC, __FILE__, __LINE__ + 1) attr_reader(:#{attr}) def #{attr}_content if @#{attr}.nil? @#{attr} else @#{attr}.join(#{separator.dump}) end end EOC end end def date_writer(name, type, disp_name=name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{name}=(new_value) if new_value.nil? @#{name} = new_value elsif new_value.kind_of?(Time) @#{name} = new_value.dup else if @do_validate begin @#{name} = Time.__send__('#{type}', new_value) rescue ArgumentError raise NotAvailableValueError.new('#{disp_name}', new_value) end else @#{name} = nil if /\\A\\s*\\z/ !~ new_value.to_s begin unless Date._parse(new_value, false).empty? @#{name} = Time.parse(new_value) end rescue ArgumentError end end end end # Is it need? if @#{name} class << @#{name} undef_method(:to_s) alias_method(:to_s, :#{type}) end end end EOC end def integer_writer(name, disp_name=name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{name}=(new_value) if new_value.nil? @#{name} = new_value else if @do_validate begin @#{name} = Integer(new_value) rescue ArgumentError raise NotAvailableValueError.new('#{disp_name}', new_value) end else @#{name} = new_value.to_i end end end EOC end def positive_integer_writer(name, disp_name=name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{name}=(new_value) if new_value.nil? @#{name} = new_value else if @do_validate begin tmp = Integer(new_value) raise ArgumentError if tmp <= 0 @#{name} = tmp rescue ArgumentError raise NotAvailableValueError.new('#{disp_name}', new_value) end else @#{name} = new_value.to_i end end end EOC end def boolean_writer(name, disp_name=name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{name}=(new_value) if new_value.nil? @#{name} = new_value else if @do_validate and ![true, false, "true", "false"].include?(new_value) raise NotAvailableValueError.new('#{disp_name}', new_value) end if [true, false].include?(new_value) @#{name} = new_value else @#{name} = new_value == "true" end end end EOC end def text_type_writer(name, disp_name=name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{name}=(new_value) if @do_validate and !["text", "html", "xhtml", nil].include?(new_value) raise NotAvailableValueError.new('#{disp_name}', new_value) end @#{name} = new_value end EOC end def content_writer(name, disp_name=name) klass_name = "self.class::#{Utils.to_class_name(name)}" module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{name}=(new_value) if new_value.is_a?(#{klass_name}) @#{name} = new_value else @#{name} = #{klass_name}.new @#{name}.content = new_value end end EOC end def yes_clean_other_writer(name, disp_name=name) module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name}=(value) value = (value ? "yes" : "no") if [true, false].include?(value) @#{name} = value end EOC end def yes_other_writer(name, disp_name=name) module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name}=(new_value) if [true, false].include?(new_value) new_value = new_value ? "yes" : "no" end @#{name} = new_value end EOC end def csv_writer(name, disp_name=name) module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name}=(new_value) @#{name} = Utils::CSV.parse(new_value) end EOC end def csv_integer_writer(name, disp_name=name) module_eval(<<-EOC, __FILE__, __LINE__ + 1) def #{name}=(new_value) @#{name} = Utils::CSV.parse(new_value) {|v| Integer(v)} end EOC end def def_children_accessor(accessor_name, plural_name) module_eval(<<-EOC, *get_file_and_line_from_caller(2)) def #{plural_name} @#{accessor_name} end def #{accessor_name}(*args) if args.empty? @#{accessor_name}.first else @#{accessor_name}[*args] end end def #{accessor_name}=(*args) receiver = self.class.name warn("Warning:\#{caller.first.sub(/:in `.*'\z/, '')}: " \ "Don't use `\#{receiver}\##{accessor_name} = XXX'/" \ "`\#{receiver}\#set_#{accessor_name}(XXX)'. " \ "Those APIs are not sense of Ruby. " \ "Use `\#{receiver}\##{plural_name} << XXX' instead of them.") if args.size == 1 @#{accessor_name}.push(args[0]) else @#{accessor_name}.__send__("[]=", *args) end end alias_method(:set_#{accessor_name}, :#{accessor_name}=) EOC end end module SetupMaker def setup_maker(maker) target = maker_target(maker) unless target.nil? setup_maker_attributes(target) setup_maker_element(target) setup_maker_elements(target) end end private def maker_target(maker) nil end def setup_maker_attributes(target) end def setup_maker_element(target) self.class.need_initialize_variables.each do |var| value = __send__(var) next if value.nil? if value.respond_to?("setup_maker") and !not_need_to_call_setup_maker_variables.include?(var) value.setup_maker(target) else setter = "#{var}=" if target.respond_to?(setter) target.__send__(setter, value) end end end end def not_need_to_call_setup_maker_variables [] end def setup_maker_elements(parent) self.class.have_children_elements.each do |name, plural_name| if parent.respond_to?(plural_name) target = parent.__send__(plural_name) __send__(plural_name).each do |elem| elem.setup_maker(target) end end end end end class Element extend BaseModel include Utils extend Utils::InheritedReader include SetupMaker INDENT = " " MUST_CALL_VALIDATORS = {} MODELS = [] GET_ATTRIBUTES = [] HAVE_CHILDREN_ELEMENTS = [] TO_ELEMENT_METHODS = [] NEED_INITIALIZE_VARIABLES = [] PLURAL_FORMS = {} class << self def must_call_validators inherited_hash_reader("MUST_CALL_VALIDATORS") end def models inherited_array_reader("MODELS") end def get_attributes inherited_array_reader("GET_ATTRIBUTES") end def have_children_elements inherited_array_reader("HAVE_CHILDREN_ELEMENTS") end def to_element_methods inherited_array_reader("TO_ELEMENT_METHODS") end def need_initialize_variables inherited_array_reader("NEED_INITIALIZE_VARIABLES") end def plural_forms inherited_hash_reader("PLURAL_FORMS") end def inherited_base ::RSS::Element end def inherited(klass) klass.const_set(:MUST_CALL_VALIDATORS, {}) klass.const_set(:MODELS, []) klass.const_set(:GET_ATTRIBUTES, []) klass.const_set(:HAVE_CHILDREN_ELEMENTS, []) klass.const_set(:TO_ELEMENT_METHODS, []) klass.const_set(:NEED_INITIALIZE_VARIABLES, []) klass.const_set(:PLURAL_FORMS, {}) tag_name = klass.name.split(/::/).last tag_name[0, 1] = tag_name[0, 1].downcase klass.instance_variable_set(:@tag_name, tag_name) klass.instance_variable_set(:@have_content, false) end def install_must_call_validator(prefix, uri) self::MUST_CALL_VALIDATORS[uri] = prefix end def install_model(tag, uri, occurs=nil, getter=nil, plural=false) getter ||= tag if m = self::MODELS.find {|t, u, o, g, p| t == tag and u == uri} m[2] = occurs else self::MODELS << [tag, uri, occurs, getter, plural] end end def install_get_attribute(name, uri, required=true, type=nil, disp_name=nil, element_name=nil) disp_name ||= name element_name ||= name writer_type, reader_type = type def_corresponded_attr_writer name, writer_type, disp_name def_corresponded_attr_reader name, reader_type if type == :boolean and /^is/ =~ name alias_method "#{$POSTMATCH}?", name end self::GET_ATTRIBUTES << [name, uri, required, element_name] add_need_initialize_variable(disp_name) end def def_corresponded_attr_writer(name, type=nil, disp_name=nil) disp_name ||= name case type when :integer integer_writer name, disp_name when :positive_integer positive_integer_writer name, disp_name when :boolean boolean_writer name, disp_name when :w3cdtf, :rfc822, :rfc2822 date_writer name, type, disp_name when :text_type text_type_writer name, disp_name when :content content_writer name, disp_name when :yes_clean_other yes_clean_other_writer name, disp_name when :yes_other yes_other_writer name, disp_name when :csv csv_writer name when :csv_integer csv_integer_writer name else attr_writer name end end def def_corresponded_attr_reader(name, type=nil) case type when :inherit inherit_convert_attr_reader name when :uri uri_convert_attr_reader name when :yes_clean_other yes_clean_other_attr_reader name when :yes_other yes_other_attr_reader name when :csv csv_attr_reader name when :csv_integer csv_attr_reader name, :separator => "," else convert_attr_reader name end end def content_setup(type=nil, disp_name=nil) writer_type, reader_type = type def_corresponded_attr_writer :content, writer_type, disp_name def_corresponded_attr_reader :content, reader_type @have_content = true end def have_content? @have_content end def add_have_children_element(variable_name, plural_name) self::HAVE_CHILDREN_ELEMENTS << [variable_name, plural_name] end def add_to_element_method(method_name) self::TO_ELEMENT_METHODS << method_name end def add_need_initialize_variable(variable_name) self::NEED_INITIALIZE_VARIABLES << variable_name end def add_plural_form(singular, plural) self::PLURAL_FORMS[singular] = plural end def required_prefix nil end def required_uri "" end def need_parent? false end def install_ns(prefix, uri) if self::NSPOOL.has_key?(prefix) raise OverlappedPrefixError.new(prefix) end self::NSPOOL[prefix] = uri end def tag_name @tag_name end end attr_accessor :parent, :do_validate def initialize(do_validate=true, attrs=nil) @parent = nil @converter = nil if attrs.nil? and (do_validate.is_a?(Hash) or do_validate.is_a?(Array)) do_validate, attrs = true, do_validate end @do_validate = do_validate initialize_variables(attrs || {}) end def tag_name self.class.tag_name end def full_name tag_name end def converter=(converter) @converter = converter targets = children.dup self.class.have_children_elements.each do |variable_name, plural_name| targets.concat(__send__(plural_name)) end targets.each do |target| target.converter = converter unless target.nil? end end def convert(value) if @converter @converter.convert(value) else value end end def valid?(ignore_unknown_element=true) validate(ignore_unknown_element) true rescue RSS::Error false end def validate(ignore_unknown_element=true) do_validate = @do_validate @do_validate = true validate_attribute __validate(ignore_unknown_element) ensure @do_validate = do_validate end def validate_for_stream(tags, ignore_unknown_element=true) validate_attribute __validate(ignore_unknown_element, tags, false) end def to_s(need_convert=true, indent='') if self.class.have_content? return "" if !empty_content? and !content_is_set? rv = tag(indent) do |next_indent| if empty_content? "" else xmled_content end end else rv = tag(indent) do |next_indent| self.class.to_element_methods.collect do |method_name| __send__(method_name, false, next_indent) end end end rv = convert(rv) if need_convert rv end def have_xml_content? false end def need_base64_encode? false end def set_next_element(tag_name, next_element) klass = next_element.class prefix = "" prefix << "#{klass.required_prefix}_" if klass.required_prefix key = "#{prefix}#{tag_name.gsub(/-/, '_')}" if self.class.plural_forms.has_key?(key) ary = __send__("#{self.class.plural_forms[key]}") ary << next_element else __send__("#{key}=", next_element) end end protected def have_required_elements? self.class::MODELS.all? do |tag, uri, occurs, getter| if occurs.nil? or occurs == "+" child = __send__(getter) if child.is_a?(Array) children = child children.any? {|c| c.have_required_elements?} else !child.to_s.empty? end else true end end end private def initialize_variables(attrs) normalized_attrs = {} attrs.each do |key, value| normalized_attrs[key.to_s] = value end self.class.need_initialize_variables.each do |variable_name| value = normalized_attrs[variable_name.to_s] if value __send__("#{variable_name}=", value) else instance_variable_set("@#{variable_name}", nil) end end initialize_have_children_elements @content = normalized_attrs["content"] if self.class.have_content? end def initialize_have_children_elements self.class.have_children_elements.each do |variable_name, plural_name| instance_variable_set("@#{variable_name}", []) end end def tag(indent, additional_attrs={}, &block) next_indent = indent + INDENT attrs = collect_attrs return "" if attrs.nil? return "" unless have_required_elements? attrs.update(additional_attrs) start_tag = make_start_tag(indent, next_indent, attrs.dup) if block content = block.call(next_indent) else content = [] end if content.is_a?(String) content = [content] start_tag << ">" end_tag = "</#{full_name}>" else content = content.reject{|x| x.empty?} if content.empty? return "" if attrs.empty? end_tag = "/>" else start_tag << ">\n" end_tag = "\n#{indent}</#{full_name}>" end end start_tag + content.join("\n") + end_tag end def make_start_tag(indent, next_indent, attrs) start_tag = ["#{indent}<#{full_name}"] unless attrs.empty? start_tag << attrs.collect do |key, value| %Q[#{h key}="#{h value}"] end.join("\n#{next_indent}") end start_tag.join(" ") end def collect_attrs attrs = {} _attrs.each do |name, required, alias_name| value = __send__(alias_name || name) return nil if required and value.nil? next if value.nil? return nil if attrs.has_key?(name) attrs[name] = value end attrs end def tag_name_with_prefix(prefix) "#{prefix}:#{tag_name}" end # For backward compatibility def calc_indent '' end def children rv = [] self.class.models.each do |name, uri, occurs, getter| value = __send__(getter) next if value.nil? value = [value] unless value.is_a?(Array) value.each do |v| rv << v if v.is_a?(Element) end end rv end def _tags rv = [] self.class.models.each do |name, uri, occurs, getter, plural| value = __send__(getter) next if value.nil? if plural and value.is_a?(Array) rv.concat([[uri, name]] * value.size) else rv << [uri, name] end end rv end def _attrs self.class.get_attributes.collect do |name, uri, required, element_name| [element_name, required, name] end end def __validate(ignore_unknown_element, tags=_tags, recursive=true) if recursive children.compact.each do |child| child.validate end end must_call_validators = self.class.must_call_validators tags = tag_filter(tags.dup) p tags if DEBUG must_call_validators.each do |uri, prefix| _validate(ignore_unknown_element, tags[uri], uri) meth = "#{prefix}_validate" if !prefix.empty? and respond_to?(meth, true) __send__(meth, ignore_unknown_element, tags[uri], uri) end end end def validate_attribute _attrs.each do |a_name, required, alias_name| value = instance_variable_get("@#{alias_name || a_name}") if required and value.nil? raise MissingAttributeError.new(tag_name, a_name) end __send__("#{alias_name || a_name}=", value) end end def _validate(ignore_unknown_element, tags, uri, models=self.class.models) count = 1 do_redo = false not_shift = false tag = nil models = models.find_all {|model| model[1] == uri} element_names = models.collect {|model| model[0]} if tags tags_size = tags.size tags = tags.sort_by {|x| element_names.index(x) || tags_size} end models.each_with_index do |model, i| name, _, occurs, = model if DEBUG p "before" p tags p model end if not_shift not_shift = false elsif tags tag = tags.shift end if DEBUG p "mid" p count end case occurs when '?' if count > 2 raise TooMuchTagError.new(name, tag_name) else if name == tag do_redo = true else not_shift = true end end when '*' if name == tag do_redo = true else not_shift = true end when '+' if name == tag do_redo = true else if count > 1 not_shift = true else raise MissingTagError.new(name, tag_name) end end else if name == tag if models[i+1] and models[i+1][0] != name and tags and tags.first == name raise TooMuchTagError.new(name, tag_name) end else raise MissingTagError.new(name, tag_name) end end if DEBUG p "after" p not_shift p do_redo p tag end if do_redo do_redo = false count += 1 redo else count = 1 end end if !ignore_unknown_element and !tags.nil? and !tags.empty? raise NotExpectedTagError.new(tags.first, uri, tag_name) end end def tag_filter(tags) rv = {} tags.each do |tag| rv[tag[0]] = [] unless rv.has_key?(tag[0]) rv[tag[0]].push(tag[1]) end rv end def empty_content? false end def content_is_set? if have_xml_content? __send__(self.class.xml_getter) else content end end def xmled_content if have_xml_content? __send__(self.class.xml_getter).to_s else _content = content _content = [_content].pack("m").delete("\n") if need_base64_encode? h(_content) end end end module RootElementMixin include XMLStyleSheetMixin attr_reader :output_encoding attr_reader :feed_type, :feed_subtype, :feed_version attr_accessor :version, :encoding, :standalone def initialize(feed_version, version=nil, encoding=nil, standalone=nil) super() @feed_type = nil @feed_subtype = nil @feed_version = feed_version @version = version || '1.0' @encoding = encoding @standalone = standalone @output_encoding = nil end def feed_info [@feed_type, @feed_version, @feed_subtype] end def output_encoding=(enc) @output_encoding = enc self.converter = Converter.new(@output_encoding, @encoding) end def setup_maker(maker) maker.version = version maker.encoding = encoding maker.standalone = standalone xml_stylesheets.each do |xss| xss.setup_maker(maker) end super end def to_feed(type, &block) Maker.make(type) do |maker| setup_maker(maker) block.call(maker) if block end end def to_rss(type, &block) to_feed("rss#{type}", &block) end def to_atom(type, &block) to_feed("atom:#{type}", &block) end def to_xml(type=nil, &block) if type.nil? or same_feed_type?(type) to_s else to_feed(type, &block).to_s end end private def same_feed_type?(type) if /^(atom|rss)?(\d+\.\d+)?(?::(.+))?$/i =~ type feed_type = ($1 || @feed_type).downcase feed_version = $2 || @feed_version feed_subtype = $3 || @feed_subtype [feed_type, feed_version, feed_subtype] == feed_info else false end end def tag(indent, attrs={}, &block) rv = super(indent, ns_declarations.merge(attrs), &block) return rv if rv.empty? "#{xmldecl}#{xml_stylesheet_pi}#{rv}" end def xmldecl rv = %Q[<?xml version="#{@version}"] if @output_encoding or @encoding rv << %Q[ encoding="#{@output_encoding or @encoding}"] end rv << %Q[ standalone="yes"] if @standalone rv << "?>\n" rv end def ns_declarations decls = {} self.class::NSPOOL.collect do |prefix, uri| prefix = ":#{prefix}" unless prefix.empty? decls["xmlns#{prefix}"] = uri end decls end def maker_target(target) target end end end
{ "content_hash": "53ad98ef3cf693df2cdff18f4bd02234", "timestamp": "", "source": "github", "line_count": 1352, "max_line_length": 87, "avg_line_length": 26.63609467455621, "alnum_prop": 0.5481783849827835, "repo_name": "jmatbastos/rbenv", "id": "4f6732b4d25ef61784a0dd3e519051089d4df912", "size": "36012", "binary": false, "copies": "14", "ref": "refs/heads/master", "path": "versions/2.2.3/lib/ruby/2.2.0/rss/rss.rb", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "686796" }, { "name": "C++", "bytes": "20424" }, { "name": "CSS", "bytes": "75657" }, { "name": "CoffeeScript", "bytes": "17135" }, { "name": "Groff", "bytes": "34057" }, { "name": "HTML", "bytes": "69883" }, { "name": "Java", "bytes": "142859" }, { "name": "JavaScript", "bytes": "624417" }, { "name": "Makefile", "bytes": "44207" }, { "name": "Ragel in Ruby Host", "bytes": "60990" }, { "name": "Ruby", "bytes": "8435792" }, { "name": "Shell", "bytes": "90473" } ], "symlink_target": "" }
<!DOCTYPE html> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. --><html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no, width=device-width"> <meta name="generator" content="joDoc"> <title>Apache Cordova API Documentation</title> <link rel="stylesheet" type="text/css" href="index.css"> <link rel="stylesheet" type="text/css" href="mobile.css" media="only screen and (max-device-width: 1024px)"> <link rel="stylesheet" type="text/css" href="prettify/prettify.css"> </head> <body> <div id="header"> <h1><a href="index.html">Apache <strong>Cordova</strong> Documentation</a></h1> <small> <select><optgroup label="English" value="en"> <option value="edge">edge</option> <option value="2.9.0rc1">2.9.0rc1</option> <option value="2.9.0">2.9.0</option> <option value="2.8.0">2.8.0</option> <option value="2.7.0rc1">2.7.0rc1</option> <option value="2.7.0">2.7.0</option> <option selected value="2.6.0rc1">2.6.0rc1</option> <option value="2.6.0">2.6.0</option> <option value="2.5.0rc1">2.5.0rc1</option> <option value="2.5.0">2.5.0</option> <option value="2.4.0rc1">2.4.0rc1</option> <option value="2.4.0">2.4.0</option> <option value="2.3.0rc2">2.3.0rc2</option> <option value="2.3.0rc1">2.3.0rc1</option> <option value="2.3.0">2.3.0</option> <option value="2.2.0rc2">2.2.0rc2</option> <option value="2.2.0rc1">2.2.0rc1</option> <option value="2.2.0">2.2.0</option> <option value="2.1.0rc2">2.1.0rc2</option> <option value="2.1.0rc1">2.1.0rc1</option> <option value="2.1.0">2.1.0</option> <option value="2.0.0rc1">2.0.0rc1</option> <option value="2.0.0">2.0.0</option> <option value="1.9.0rc1">1.9.0rc1</option> <option value="1.9.0">1.9.0</option> <option value="1.8.1">1.8.1</option> <option value="1.8.0rc1">1.8.0rc1</option> <option value="1.8.0">1.8.0</option> <option value="1.7.0rc1">1.7.0rc1</option> <option value="1.7.0">1.7.0</option> <option value="1.6.1">1.6.1</option> <option value="1.6.0rc1">1.6.0rc1</option> <option value="1.6.0">1.6.0</option> <option value="1.5.0rc1">1.5.0rc1</option> <option value="1.5.0">1.5.0</option> </optgroup> <optgroup label="Japanese" value="jp"> <option value="2.2.0">2.2.0</option> <option value="2.1.0">2.1.0</option> <option value="2.0.0">2.0.0</option> <option value="1.9.0">1.9.0</option> <option value="1.8.1">1.8.1</option> <option value="1.7.0">1.7.0</option> </optgroup> <optgroup label="Korean" value="kr"><option value="2.0.0">2.0.0</option></optgroup></select></small> </div> <div id="subheader"> <h1>Camera</h1> <small><select><option value="Camera">Camera</option> <option value="Camera_methods">      - Methods</option> <option value="Camera_permissions">      - Permissions</option> <option value="camera.getPicture">camera.getPicture</option> <option value="camera.getPicture_description">      - Description</option> <option value="camera.getPicture_supported_platforms">      - Supported Platforms</option> <option value="camera.getPicture_ios_quirks">      - iOS Quirks</option> <option value="camera.getPicture_windows_phone_7_quirks">      - Windows Phone 7 Quirks</option> <option value="camera.getPicture_tizen_quirks">      - Tizen Quirks</option> <option value="camera.getPicture_quick_example">      - Quick Example</option> <option value="camera.getPicture_full_example">      - Full Example</option> <option value="cameraSuccess">cameraSuccess</option> <option value="cameraSuccess_parameters">      - Parameters</option> <option value="cameraSuccess_example">      - Example</option> <option value="cameraError">cameraError</option> <option value="cameraError_parameters">      - Parameters</option> <option value="cameraOptions">cameraOptions</option> <option value="cameraOptions_options">      - Options</option> <option value="cameraOptions_android_quirks">      - Android Quirks</option> <option value="cameraOptions_blackberry_quirks">      - BlackBerry Quirks</option> <option value="cameraOptions_webos_quirks">      - webOS Quirks</option> <option value="cameraOptions_ios_quirks">      - iOS Quirks</option> <option value="cameraOptions_windows_phone_7_and_8_quirks">      - Windows Phone 7 and 8 Quirks</option> <option value="cameraOptions_bada_1_2_quirks">      - Bada 1.2 Quirks</option> <option value="cameraOptions_tizen_quirks">      - Tizen Quirks</option> <option value="CameraPopoverOptions">CameraPopoverOptions</option> <option value="CameraPopoverOptions_camerapopoveroptions">      - CameraPopoverOptions</option> <option value="CameraPopoverOptions_quick_example">      - Quick Example</option> <option value="CameraPopoverHandle">CameraPopoverHandle</option> <option value="CameraPopoverHandle_methods">      - Methods</option> <option value="CameraPopoverHandle_supported_platforms">      - Supported Platforms</option> <option value="CameraPopoverHandle_setposition">      - setPosition</option> <option value="CameraPopoverHandle_quick_example">      - Quick Example</option> <option value="CameraPopoverHandle_full_example">      - Full Example</option></select></small> </div> <div id="sidebar"> <div class="vertical_divider"></div> <h1>API Reference</h1> <ul> <li><a href="cordova_accelerometer_accelerometer.md.html#Accelerometer">Accelerometer</a></li> <li><a href="cordova_camera_camera.md.html#Camera">Camera</a></li> <li><a href="cordova_media_capture_capture.md.html#Capture">Capture</a></li> <li><a href="cordova_compass_compass.md.html#Compass">Compass</a></li> <li><a href="cordova_connection_connection.md.html#Connection">Connection</a></li> <li><a href="cordova_contacts_contacts.md.html#Contacts">Contacts</a></li> <li><a href="cordova_device_device.md.html#Device">Device</a></li> <li><a href="cordova_events_events.md.html#Events">Events</a></li> <li><a href="cordova_file_file.md.html#File">File</a></li> <li><a href="cordova_geolocation_geolocation.md.html#Geolocation">Geolocation</a></li> <li><a href="cordova_globalization_globalization.md.html#Globalization">Globalization</a></li> <li><a href="cordova_inappbrowser_inappbrowser.md.html#InAppBrowser">InAppBrowser</a></li> <li><a href="cordova_media_media.md.html#Media">Media</a></li> <li><a href="cordova_notification_notification.md.html#Notification">Notification</a></li> <li><a href="cordova_splashscreen_splashscreen.md.html#Splashscreen">Splashscreen</a></li> <li><a href="cordova_storage_storage.md.html#Storage">Storage</a></li> </ul> <h1>Guides</h1> <ul> <li><a href="guide_getting-started_index.md.html#Getting%20Started%20Guides">Getting Started Guides</a></li> <li><a href="guide_command-line_index.md.html#Command-Line%20Usage">Command-Line Usage</a></li> <li><a href="guide_upgrading_index.md.html#Upgrading%20Guides">Upgrading Guides</a></li> <li><a href="guide_project-settings_index.md.html#Project%20Settings">Project Settings</a></li> <li><a href="guide_plugin-development_index.md.html#Plugin%20Development%20Guide">Plugin Development Guide</a></li> <li><a href="guide_whitelist_index.md.html#Domain%20Whitelist%20Guide">Domain Whitelist Guide</a></li> <li><a href="guide_cordova-webview_index.md.html#Embedding%20WebView">Embedding WebView</a></li> <li><a href="_index.html">Keyword Index</a></li> </ul> </div> <div id="scrollable"> <div id="content"> <h1><a name="Camera">Camera</a></h1> <blockquote> <p>The <code>camera</code> object provides access to the device's default camera application.</p> </blockquote> <h2> <a name="Camera_methods">Methods</a> </h2> <ul> <li><a href="cordova_camera_camera.md.html#camera.getPicture">camera.getPicture</a></li> <li><a href="cordova_camera_camera.cleanup.md.html#camera.cleanup">camera.cleanup</a></li> </ul> <h2> <a name="Camera_permissions">Permissions</a> </h2> <h3>Android</h3> <h4>app/res/xml/config.xml</h4> <pre class="prettyprint"><code>&lt;plugin name="<a href="cordova_camera_camera.md.html#Camera">Camera</a>" value="org.apache.cordova.CameraLauncher" /&gt; </code></pre> <h4>app/AndroidManifest</h4> <pre class="prettyprint"><code>&lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&gt; </code></pre> <h3>Bada</h3> <h4>manifest.xml</h4> <pre class="prettyprint"><code>&lt;Privilege&gt; &lt;Name&gt;CAMERA&lt;/Name&gt; &lt;/Privilege&gt; &lt;Privilege&gt; &lt;Name&gt;RECORDING&lt;/Name&gt; &lt;/Privilege&gt; </code></pre> <h3>BlackBerry WebWorks</h3> <h4>www/plugins.xml</h4> <pre class="prettyprint"><code>&lt;plugin name="<a href="cordova_camera_camera.md.html#Camera">Camera</a>" value="org.apache.cordova.camera.<a href="cordova_camera_camera.md.html#Camera">Camera</a>" /&gt; </code></pre> <h4>www/config.xml</h4> <pre class="prettyprint"><code>&lt;feature id="blackberry.media.camera" /&gt; &lt;rim:permissions&gt; &lt;rim:permit&gt;use_camera&lt;/rim:permit&gt; &lt;/rim:permissions&gt; </code></pre> <h3>iOS</h3> <h4>config.xml</h4> <pre class="prettyprint"><code>&lt;plugin name="<a href="cordova_camera_camera.md.html#Camera">Camera</a>" value="CDVCamera" /&gt; </code></pre> <h3>webOS</h3> <pre class="prettyprint"><code>No permissions are required. </code></pre> <h3>Windows Phone</h3> <h4>Properties/WPAppManifest.xml</h4> <pre class="prettyprint"><code>&lt;Capabilities&gt; &lt;Capability Name="ID_CAP_ISV_CAMERA" /&gt; &lt;Capability Name="ID_HW_FRONTCAMERA" /&gt; &lt;/Capabilities&gt; </code></pre> <p>Reference: <a class="external" href="http://msdn.microsoft.com/en-us/library/ff769509%28v=vs.92%29.aspx">Application Manifest for Windows Phone</a></p> <h3>Tizen</h3> <h4>config.xml</h4> <pre class="prettyprint"><code>&lt;feature name="http://tizen.org/api/application" required="true"/&gt; &lt;feature name="http://tizen.org/api/application.launch" required="true"/&gt; </code></pre> <p>Reference: <a class="external" href="https://developer.tizen.org/help/topic/org.tizen.help.gs/Creating%20a%20Project.html?path=0_1_1_3#8814682_CreatingaProject-EditingconfigxmlFeatures">Application Manifest for Tizen Web Application</a></p> <hr> <h1><a name="camera.getPicture">camera.getPicture</a></h1> <p>Takes a photo using the camera or retrieves a photo from the device's album. The image is passed to the success callback as a base64 encoded <code>String</code> or as the URI of an image file. The method itself returns a <a href="cordova_camera_camera.md.html#CameraPopoverHandle">CameraPopoverHandle</a> object, which can be used to reposition the file selection popover.</p> <pre class="prettyprint"><code>navigator.<a href="cordova_camera_camera.md.html#camera.getPicture">camera.getPicture</a>( <a href="cordova_camera_camera.md.html#cameraSuccess">cameraSuccess</a>, <a href="cordova_camera_camera.md.html#cameraError">cameraError</a>, [ <a href="cordova_camera_camera.md.html#cameraOptions">cameraOptions</a> ] ); </code></pre> <h2> <a name="camera.getPicture_description">Description</a> </h2> <p>Function <code><a href="cordova_camera_camera.md.html#camera.getPicture">camera.getPicture</a></code> opens the device's default camera application so that the user can take a picture (if <code><a href="cordova_camera_camera.md.html#Camera">Camera</a>.sourceType = <a href="cordova_camera_camera.md.html#Camera">Camera</a>.PictureSourceType.CAMERA</code>, which is the default). Once the photo is taken, the camera application closes and your application is restored.</p> <p>If <code><a href="cordova_camera_camera.md.html#Camera">Camera</a>.sourceType = <a href="cordova_camera_camera.md.html#Camera">Camera</a>.PictureSourceType.PHOTOLIBRARY</code> or <code><a href="cordova_camera_camera.md.html#Camera">Camera</a>.PictureSourceType.SAVEDPHOTOALBUM</code>, then a photo chooser dialog is shown, from which a photo from the album can be selected. A <code><a href="cordova_camera_camera.md.html#CameraPopoverHandle">CameraPopoverHandle</a></code> object, which can be used to reposition the photo chooser dialog (eg. when the device orientation changes) is returned by <code><a href="cordova_camera_camera.md.html#camera.getPicture">camera.getPicture</a></code>.</p> <p>The return value will be sent to the <code><a href="cordova_camera_camera.md.html#cameraSuccess">cameraSuccess</a></code> function, in one of the following formats, depending on the <code><a href="cordova_camera_camera.md.html#cameraOptions">cameraOptions</a></code> you specify:</p> <ul> <li>A <code>String</code> containing the Base64 encoded photo image.</li> <li>A <code>String</code> representing the image file location on local storage (default).</li> </ul> <p>You can do whatever you want with the encoded image or URI, for example:</p> <ul> <li>Render the image in an <code>&lt;img&gt;</code> tag <em>(see example below)</em> </li> <li>Save the data locally (<code>LocalStorage</code>, <a class="external" href="http://brianleroux.github.com/lawnchair/">Lawnchair</a>, etc)</li> <li>Post the data to a remote server</li> </ul> <p><strong>Note:</strong> The image quality of pictures taken using the camera on newer devices is quite good, and images from the Photo Album will not be downscaled to a lower quality, even if a quality parameter is specified. <strong><em>Encoding such images using Base64 has caused memory issues on many newer devices. Therefore, using FILE_URI as the '<a href="cordova_camera_camera.md.html#Camera">Camera</a>.destinationType' is highly recommended.</em></strong></p> <h2> <a name="camera.getPicture_supported_platforms">Supported Platforms</a> </h2> <ul> <li>Android</li> <li>Blackberry WebWorks (OS 5.0 and higher)</li> <li>iOS</li> <li>Windows Phone 7 and 8</li> <li>Bada 1.2</li> <li>webOS</li> <li>Tizen</li> <li>Windows 8</li> </ul> <h2> <a name="camera.getPicture_ios_quirks">iOS Quirks</a> </h2> <p>Including a JavaScript alert() in either of the callback functions can cause problems. Wrap the alert in a setTimeout() to allow the iOS image picker or popover to fully <a href="cordova_inappbrowser_inappbrowser.md.html#close">close</a> before the alert is displayed: </p> <pre class="prettyprint"><code>setTimeout(function() { // do your thing here! }, 0); </code></pre> <h2> <a name="camera.getPicture_windows_phone_7_quirks">Windows Phone 7 Quirks</a> </h2> <p>Invoking the native camera application while your device is connected via Zune will not work, and the error callback will be triggered.</p> <h2> <a name="camera.getPicture_tizen_quirks">Tizen Quirks</a> </h2> <p>Only 'destinationType: <a href="cordova_camera_camera.md.html#Camera">Camera</a>.DestinationType.FILE_URI' and 'sourceType: <a href="cordova_camera_camera.md.html#Camera">Camera</a>.PictureSourceType.PHOTOLIBRARY' are supported.</p> <h2> <a name="camera.getPicture_quick_example">Quick Example</a> </h2> <p>Take photo and retrieve Base64-encoded image:</p> <pre class="prettyprint"><code>navigator.<a href="cordova_camera_camera.md.html#camera.getPicture">camera.getPicture</a>(onSuccess, onFail, { quality: 50, destinationType: <a href="cordova_camera_camera.md.html#Camera">Camera</a>.DestinationType.DATA_URL }); function onSuccess(imageData) { var image = document.getElementById('myImage'); image.src = "data:image/jpeg;base64," + imageData; } function onFail(message) { alert('Failed because: ' + message); } </code></pre> <p>Take photo and retrieve image file location: </p> <pre class="prettyprint"><code>navigator.<a href="cordova_camera_camera.md.html#camera.getPicture">camera.getPicture</a>(onSuccess, onFail, { quality: 50, destinationType: <a href="cordova_camera_camera.md.html#Camera">Camera</a>.DestinationType.FILE_URI }); function onSuccess(imageURI) { var image = document.getElementById('myImage'); image.src = imageURI; } function onFail(message) { alert('Failed because: ' + message); } </code></pre> <h2> <a name="camera.getPicture_full_example">Full Example</a> </h2> <pre class="prettyprint"><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;<a href="cordova_media_capture_capture.md.html#Capture">Capture</a> Photo&lt;/title&gt; &lt;script type="text/javascript" charset="utf-8" src="cordova-2.5.0.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" charset="utf-8"&gt; var pictureSource; // picture source var destinationType; // sets the format of returned value // Wait for Cordova to connect with the device // document.<a href="cordova_inappbrowser_inappbrowser.md.html#addEventListener">addEventListener</a>("<a href="cordova_events_events.md.html#deviceready">deviceready</a>",onDeviceReady,false); // Cordova is ready to be used! // function onDeviceReady() { pictureSource=navigator.camera.PictureSourceType; destinationType=navigator.camera.DestinationType; } // Called when a photo is successfully retrieved // function onPhotoDataSuccess(imageData) { // Uncomment to view the base64 encoded image data // console.log(imageData); // Get image handle // var smallImage = document.getElementById('smallImage'); // Unhide image elements // smallImage.style.display = 'block'; // Show the captured photo // The inline CSS rules are used to resize the image // smallImage.src = "data:image/jpeg;base64," + imageData; } // Called when a photo is successfully retrieved // function onPhotoURISuccess(imageURI) { // Uncomment to view the image file URI // console.log(imageURI); // Get image handle // var largeImage = document.getElementById('largeImage'); // Unhide image elements // largeImage.style.display = 'block'; // Show the captured photo // The inline CSS rules are used to resize the image // largeImage.src = imageURI; } // A button will call this function // function capturePhoto() { // Take picture using device camera and retrieve image as base64-encoded string navigator.<a href="cordova_camera_camera.md.html#camera.getPicture">camera.getPicture</a>(onPhotoDataSuccess, onFail, { quality: 50, destinationType: destinationType.DATA_URL }); } // A button will call this function // function capturePhotoEdit() { // Take picture using device camera, allow edit, and retrieve image as base64-encoded string navigator.<a href="cordova_camera_camera.md.html#camera.getPicture">camera.getPicture</a>(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true, destinationType: destinationType.DATA_URL }); } // A button will call this function // function getPhoto(source) { // Retrieve image file location from specified source navigator.<a href="cordova_camera_camera.md.html#camera.getPicture">camera.getPicture</a>(onPhotoURISuccess, onFail, { quality: 50, destinationType: destinationType.FILE_URI, sourceType: source }); } // Called if something bad happens. // function onFail(message) { alert('Failed because: ' + message); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;button onclick="capturePhoto();"&gt;<a href="cordova_media_capture_capture.md.html#Capture">Capture</a> Photo&lt;/button&gt; &lt;br&gt; &lt;button onclick="capturePhotoEdit();"&gt;<a href="cordova_media_capture_capture.md.html#Capture">Capture</a> Editable Photo&lt;/button&gt; &lt;br&gt; &lt;button onclick="getPhoto(pictureSource.PHOTOLIBRARY);"&gt;From Photo Library&lt;/button&gt;&lt;br&gt; &lt;button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);"&gt;From Photo Album&lt;/button&gt;&lt;br&gt; &lt;img style="display:none;width:60px;height:60px;" id="smallImage" src="" /&gt; &lt;img style="display:none;" id="largeImage" src="" /&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <hr> <h1><a name="cameraSuccess">cameraSuccess</a></h1> <p>onSuccess callback function that provides the image data.</p> <pre class="prettyprint"><code>function(imageData) { // Do something with the image } </code></pre> <h2> <a name="cameraSuccess_parameters">Parameters</a> </h2> <ul> <li> <strong>imageData:</strong> Base64 encoding of the image data, OR the image file URI, depending on <code><a href="cordova_camera_camera.md.html#cameraOptions">cameraOptions</a></code> used. (<code>String</code>)</li> </ul> <h2> <a name="cameraSuccess_example">Example</a> </h2> <pre class="prettyprint"><code>// Show image // function cameraCallback(imageData) { var image = document.getElementById('myImage'); image.src = "data:image/jpeg;base64," + imageData; } </code></pre> <hr> <h1><a name="cameraError">cameraError</a></h1> <p>onError callback function that provides an error message.</p> <pre class="prettyprint"><code>function(message) { // Show a helpful message } </code></pre> <h2> <a name="cameraError_parameters">Parameters</a> </h2> <ul> <li> <strong>message:</strong> The message is provided by the device's native code. (<code>String</code>)</li> </ul> <hr> <h1><a name="cameraOptions">cameraOptions</a></h1> <p>Optional parameters to customize the camera settings.</p> <pre class="prettyprint"><code>{ quality : 75, destinationType : <a href="cordova_camera_camera.md.html#Camera">Camera</a>.DestinationType.DATA_URL, sourceType : <a href="cordova_camera_camera.md.html#Camera">Camera</a>.PictureSourceType.CAMERA, allowEdit : true, encodingType: <a href="cordova_camera_camera.md.html#Camera">Camera</a>.EncodingType.JPEG, targetWidth: 100, targetHeight: 100, popoverOptions: <a href="cordova_camera_camera.md.html#CameraPopoverOptions">CameraPopoverOptions</a>, saveToPhotoAlbum: false }; </code></pre> <h2> <a name="cameraOptions_options">Options</a> </h2> <ul> <li><p><strong>quality:</strong> Quality of saved image. Range is [0, 100]. (<code>Number</code>)</p></li> <li> <p><strong>destinationType:</strong> Choose the format of the return value. Defined in navigator.camera.DestinationType (<code>Number</code>)</p> <pre class="prettyprint"><code><a href="cordova_camera_camera.md.html#Camera">Camera</a>.DestinationType = { DATA_URL : 0, // Return image as base64 encoded string FILE_URI : 1, // Return image file URI NATIVE_URI : 2 // Return image native URI (eg. assets-library:// on iOS or content:// on Android) }; </code></pre> </li> <li> <p><strong>sourceType:</strong> Set the source of the picture. Defined in nagivator.camera.PictureSourceType (<code>Number</code>)</p> <pre class="prettyprint"><code><a href="cordova_camera_camera.md.html#Camera">Camera</a>.PictureSourceType = { PHOTOLIBRARY : 0, CAMERA : 1, SAVEDPHOTOALBUM : 2 }; </code></pre> </li> <li><p><strong>allowEdit:</strong> Allow simple editing of image before selection. (<code>Boolean</code>)</p></li> <li> <p><strong>encodingType:</strong> Choose the encoding of the returned image file. Defined in navigator.camera.EncodingType (<code>Number</code>)</p> <pre class="prettyprint"><code><a href="cordova_camera_camera.md.html#Camera">Camera</a>.EncodingType = { JPEG : 0, // Return JPEG encoded image PNG : 1 // Return PNG encoded image }; </code></pre> </li> <li><p><strong>targetWidth:</strong> Width in pixels to scale image. Must be used with targetHeight. Aspect ratio is maintained. (<code>Number</code>)</p></li> <li><p><strong>targetHeight:</strong> Height in pixels to scale image. Must be used with targetWidth. Aspect ratio is maintained. (<code>Number</code>)</p></li> <li> <p><strong>mediaType:</strong> Set the type of media to select from. Only works when PictureSourceType is PHOTOLIBRARY or SAVEDPHOTOALBUM. Defined in nagivator.camera.MediaType (<code>Number</code>)</p> <pre class="prettyprint"><code><a href="cordova_camera_camera.md.html#Camera">Camera</a>.MediaType = { PICTURE: 0, // allow selection of still pictures only. DEFAULT. Will return format specified via DestinationType VIDEO: 1, // allow selection of video only, WILL ALWAYS RETURN FILE_URI ALLMEDIA : 2 // allow selection from all media types </code></pre> <p>};</p> </li> <li><p><strong>correctOrientation:</strong> Rotate the image to correct for the orientation of the device during capture. (<code>Boolean</code>)</p></li> <li> <strong>saveToPhotoAlbum:</strong> Save the image to the photo album on the device after capture. (<code>Boolean</code>)</li> <li> <strong>popoverOptions:</strong> iOS only options to specify popover location in iPad. Defined in <a href="cordova_camera_camera.md.html#CameraPopoverOptions">CameraPopoverOptions</a>.</li> <li> <p><strong>cameraDirection:</strong> Choose the camera to use (front- or back-facing). Defined in navigator.camera.Direction (<code>Number</code>)</p> <pre class="prettyprint"><code><a href="cordova_camera_camera.md.html#Camera">Camera</a>.Direction = { BACK : 0, // Use the back-facing camera FRONT : 1 // Use the front-facing camera }; </code></pre> </li> </ul> <h2> <a name="cameraOptions_android_quirks">Android Quirks</a> </h2> <ul> <li>Ignores the <code>allowEdit</code> parameter.</li> <li> <a href="cordova_camera_camera.md.html#Camera">Camera</a>.PictureSourceType.PHOTOLIBRARY and <a href="cordova_camera_camera.md.html#Camera">Camera</a>.PictureSourceType.SAVEDPHOTOALBUM both display the same photo album.</li> </ul> <h2> <a name="cameraOptions_blackberry_quirks">BlackBerry Quirks</a> </h2> <ul> <li>Ignores the <code>quality</code> parameter.</li> <li>Ignores the <code>sourceType</code> parameter.</li> <li>Ignores the <code>allowEdit</code> parameter.</li> <li>Application must have key injection permissions to <a href="cordova_inappbrowser_inappbrowser.md.html#close">close</a> native <a href="cordova_camera_camera.md.html#Camera">Camera</a> application after photo is taken.</li> <li>Using Large image sizes may result in inability to encode image on later model devices with high resolution cameras (e.g. Torch 9800).</li> <li> <a href="cordova_camera_camera.md.html#Camera">Camera</a>.MediaType is not supported.</li> <li>Ignores the <code>correctOrientation</code> parameter.</li> <li>Ignores the <code>cameraDirection</code> parameter.</li> </ul> <h2> <a name="cameraOptions_webos_quirks">webOS Quirks</a> </h2> <ul> <li>Ignores the <code>quality</code> parameter.</li> <li>Ignores the <code>sourceType</code> parameter.</li> <li>Ignores the <code>allowEdit</code> parameter.</li> <li> <a href="cordova_camera_camera.md.html#Camera">Camera</a>.MediaType is not supported.</li> <li>Ignores the <code>correctOrientation</code> parameter.</li> <li>Ignores the <code>saveToPhotoAlbum</code> parameter.</li> <li>Ignores the <code>cameraDirection</code> parameter.</li> </ul> <h2> <a name="cameraOptions_ios_quirks">iOS Quirks</a> </h2> <ul> <li>Set <code>quality</code> below 50 to avoid memory error on some devices.</li> <li>When <code>destinationType.FILE_URI</code> is used, photos are saved in the application's temporary directory. </li> </ul> <h2> <a name="cameraOptions_windows_phone_7_and_8_quirks">Windows Phone 7 and 8 Quirks</a> </h2> <ul> <li>Ignores the <code>allowEdit</code> parameter.</li> <li>Ignores the <code>correctOrientation</code> parameter.</li> <li>Ignores the <code>cameraDirection</code> parameter.</li> </ul> <h2> <a name="cameraOptions_bada_1_2_quirks">Bada 1.2 Quirks</a> </h2> <ul> <li>options not supported</li> <li>always returns a FILE URI</li> </ul> <h2> <a name="cameraOptions_tizen_quirks">Tizen Quirks</a> </h2> <ul> <li>options not supported</li> <li>always returns a FILE URI</li> </ul> <hr> <h1><a name="CameraPopoverOptions">CameraPopoverOptions</a></h1> <p>Parameters only used by iOS to specify the anchor element location and arrow direction of popover used on iPad when selecting images from the library or album.</p> <pre class="prettyprint"><code>{ x : 0, y : 32, width : 320, height : 480, arrowDir : <a href="cordova_camera_camera.md.html#Camera">Camera</a>.PopoverArrowDirection.ARROW_ANY }; </code></pre> <h2> <a name="CameraPopoverOptions_camerapopoveroptions">CameraPopoverOptions</a> </h2> <ul> <li><p><strong>x:</strong> x pixel coordinate of element on the screen to anchor popover onto. (<code>Number</code>)</p></li> <li><p><strong>y:</strong> y pixel coordinate of element on the screen to anchor popover onto. (<code>Number</code>)</p></li> <li><p><strong>width:</strong> width, in pixels, of the element on the screen to anchor popover onto. (<code>Number</code>)</p></li> <li><p><strong>height:</strong> height, in pixels, of the element on the screen to anchor popover onto. (<code>Number</code>)</p></li> <li> <p><strong>arrowDir:</strong> Direction the arrow on the popover should point. Defined in <a href="cordova_camera_camera.md.html#Camera">Camera</a>.PopoverArrowDirection (<code>Number</code>)</p> <pre class="prettyprint"><code> <a href="cordova_camera_camera.md.html#Camera">Camera</a>.PopoverArrowDirection = { ARROW_UP : 1, // matches iOS UIPopoverArrowDirection constants ARROW_DOWN : 2, ARROW_LEFT : 4, ARROW_RIGHT : 8, ARROW_ANY : 15 }; </code></pre> </li> </ul> <p>Note that the size of the popover may change to adjust to the direction of the arrow and orientation of the screen. Make sure to account for orientation changes when specifying the anchor element location. </p> <h2> <a name="CameraPopoverOptions_quick_example">Quick Example</a> </h2> <pre class="prettyprint"><code> var popover = new <a href="cordova_camera_camera.md.html#CameraPopoverOptions">CameraPopoverOptions</a>(300,300,100,100,<a href="cordova_camera_camera.md.html#Camera">Camera</a>.PopoverArrowDirection.ARROW_ANY); var options = { quality: 50, destinationType: <a href="cordova_camera_camera.md.html#Camera">Camera</a>.DestinationType.DATA_URL,sourceType: <a href="cordova_camera_camera.md.html#Camera">Camera</a>.PictureSource.SAVEDPHOTOALBUM, popoverOptions : popover }; navigator.<a href="cordova_camera_camera.md.html#camera.getPicture">camera.getPicture</a>(onSuccess, onFail, options); function onSuccess(imageData) { var image = document.getElementById('myImage'); image.src = "data:image/jpeg;base64," + imageData; } function onFail(message) { alert('Failed because: ' + message); } </code></pre> <hr> <h1><a name="CameraPopoverHandle">CameraPopoverHandle</a></h1> <p>A handle to the popover dialog created by <code><a href="cordova_camera_camera.md.html#camera.getPicture">camera.getPicture</a></code>.</p> <h2> <a name="CameraPopoverHandle_methods">Methods</a> </h2> <ul> <li> <strong>setPosition:</strong> Set the position of the popover.</li> </ul> <h2> <a name="CameraPopoverHandle_supported_platforms">Supported Platforms</a> </h2> <ul> <li>iOS</li> </ul> <h2> <a name="CameraPopoverHandle_setposition">setPosition</a> </h2> <p>Set the position of the popover.</p> <p><strong>Parameters:</strong> - cameraPopoverOptions - the <a href="cordova_camera_camera.md.html#CameraPopoverOptions">CameraPopoverOptions</a> specifying the new position</p> <h2> <a name="CameraPopoverHandle_quick_example">Quick Example</a> </h2> <pre class="prettyprint"><code> var cameraPopoverOptions = new <a href="cordova_camera_camera.md.html#CameraPopoverOptions">CameraPopoverOptions</a>(300, 300, 100, 100, <a href="cordova_camera_camera.md.html#Camera">Camera</a>.PopoverArrowDirection.ARROW_ANY); cameraPopoverHandle.setPosition(cameraPopoverOptions); </code></pre> <h2> <a name="CameraPopoverHandle_full_example">Full Example</a> </h2> <pre class="prettyprint"><code> function onSuccess(imageData) { // Do stuff with the image! } function onFail(message) { alert('Failed to get the picture: ' + message); } var cameraPopoverHandle = navigator.<a href="cordova_camera_camera.md.html#camera.getPicture">camera.getPicture</a>(onSuccess, onFail, { destinationType: <a href="cordova_camera_camera.md.html#Camera">Camera</a>.DestinationType.FILE_URI, sourceType: <a href="cordova_camera_camera.md.html#Camera">Camera</a>.PictureSourceType.PHOTOLIBRARY }); // Reposition the popover if the orientation changes. window.onorientationchange = function() { var cameraPopoverOptions = new <a href="cordova_camera_camera.md.html#CameraPopoverOptions">CameraPopoverOptions</a>(0, 0, 100, 100, 0); cameraPopoverHandle.setPosition(cameraPopoverOptions); } </code></pre> </div> </div> <!-- Functionality and Syntax Highlighting --> <script type="text/javascript" src="index.js"></script><script type="text/javascript" src="prettify/prettify.js"></script> </body> </html>
{ "content_hash": "1bcbf8b7aefa14024a5de8e90877787c", "timestamp": "", "source": "github", "line_count": 784, "max_line_length": 696, "avg_line_length": 42.91581632653061, "alnum_prop": 0.7083159959579147, "repo_name": "csantanapr/cordova-blog", "id": "296c349c7c74b7ffaaba7ab73f74e13afb41b1a8", "size": "33808", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/docs/en/2.6.0rc1/cordova_camera_camera.md.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "513242" }, { "name": "JavaScript", "bytes": "919394" }, { "name": "Ruby", "bytes": "41871" }, { "name": "Shell", "bytes": "52" } ], "symlink_target": "" }
'use strict'; var extScope; angular.module('flowableModeler') .controller('DecisionTableEditorController', ['$rootScope', '$scope', '$q', '$translate', '$http', '$timeout', '$location', '$modal', '$route', '$routeParams', 'DecisionTableService', 'UtilityService', 'uiGridConstants', 'hotRegisterer', function ($rootScope, $scope, $q, $translate, $http, $timeout, $location, $modal, $route, $routeParams, DecisionTableService, UtilityService, uiGridConstants, hotRegisterer) { extScope = $scope; $rootScope.decisionTableChanges = false; var hotDecisionTableEditorInstance; var hitPolicies = ['FIRST', 'ANY', 'UNIQUE', 'PRIORITY', 'RULE ORDER', 'OUTPUT ORDER', 'COLLECT']; var stringOperators = ['==', '!=', 'IS IN', 'IS NOT IN']; var numberOperators = ['==', '!=', '<', '>', '>=', '<=', 'IS IN', 'IS NOT IN']; var booleanOperators = ['==', '!=']; var dateOperators = ['==', '!=', '<', '>', '>=', '<=', 'IS IN', 'IS NOT IN']; var collectionOperators = ['ANY OF', 'NONE OF', 'ALL OF', 'NOT ALL OF', '==', '!=']; var allOperators = ['==', '!=', '<', '>', '>=', '<=', 'ANY OF', 'NONE OF', 'ALL OF', 'NOT ALL OF', 'IS IN', 'IS NOT IN']; var collectOperators = { 'SUM': '+', 'MIN': '<', 'MAX': '>', 'COUNT': '#' }; var columnIdCounter = 0; var hitPolicyHeaderElement; var dateFormat = 'YYYY-MM-DD'; // Model init $scope.status = {loading: true}; $scope.model = { rulesData: [], columnDefs: [], columnVariableIdMap: {}, startOutputExpression: 0, selectedRow: undefined, availableInputVariableTypes: ['string', 'number', 'boolean', 'date', 'collection'], availableOutputVariableTypes: ['string', 'number', 'boolean', 'date'] }; // Hot Model init $scope.model.hotSettings = { contextMenu: { items: { "insert_row_above": { name: 'Insert rule above', callback: function (key, options) { if (hotDecisionTableEditorInstance.getSelected()) { $scope.addRule(hotDecisionTableEditorInstance.getSelected()[0]); } } }, "insert_row_below": { name: 'Add rule below', callback: function (key, options) { if (hotDecisionTableEditorInstance.getSelected()) { $scope.addRule(hotDecisionTableEditorInstance.getSelected()[0] + 1); } } }, "clear_row": { name: 'Clear rule', callback: function (key, options) { if (hotDecisionTableEditorInstance.getSelected()) { $scope.clearRule(hotDecisionTableEditorInstance.getSelected()[0]); } } }, "remove_row": { name: 'Remove this rule', disabled: function () { // if only 1 rule disable if (hotDecisionTableEditorInstance.getSelected()) { return $scope.model.rulesData.length < 2; } else { return false; } } }, "hsep1": "---------", "move_rule_up": { name: 'Move rule up', disabled: function () { if (hotDecisionTableEditorInstance.getSelected()) { return hotDecisionTableEditorInstance.getSelected()[0] === 0; } }, callback: function (key, options) { $scope.moveRuleUpwards(); } }, "move_rule_down": { name: 'Move rule down', disabled: function () { if (hotDecisionTableEditorInstance.getSelected()) { return hotDecisionTableEditorInstance.getSelected()[0] + 1 === $scope.model.rulesData.length; } }, callback: function (key, options) { $scope.moveRuleDownwards(); } }, "hsep2": "---------", "add_input": { name: 'Add input', callback: function (key, options) { if (hotDecisionTableEditorInstance.getSelected()) { $scope.openInputExpressionEditor(hotDecisionTableEditorInstance.getSelected()[1], true); } } }, "add_output": { name: 'Add output', callback: function (key, options) { if (hotDecisionTableEditorInstance.getSelected()) { if (hotDecisionTableEditorInstance.getSelected()[1] < $scope.model.startOutputExpression) { $scope.openOutputExpressionEditor($scope.currentDecisionTable.outputExpressions.length, true); } else { $scope.openOutputExpressionEditor((hotDecisionTableEditorInstance.getSelected()[1] - $scope.model.startOutputExpression), true); } } } }, "hsep3": "---------", "undo": { name: 'Undo' }, "redo": { name: 'Redo' } } }, manualColumnResize: false, stretchH: 'all', outsideClickDeselects: false, viewportColumnRenderingOffset: $scope.model.columnDefs.length + 10 }; $scope.hitPolicies = []; hitPolicies.forEach(function (id) { $scope.hitPolicies.push({ id: id, label: 'DECISION-TABLE.HIT-POLICIES.' + id }); }); $scope.collectOperators = []; Object.keys(collectOperators).forEach(function (key) { $scope.collectOperators.push({ id: key, label: 'DECISION-TABLE.COLLECT-OPERATORS.' + key }); }); $scope.addRule = function (rowNumber) { if (rowNumber !== undefined) { $scope.model.rulesData.splice(rowNumber, 0, createDefaultRow()); } else { $scope.model.rulesData.push(createDefaultRow()); } if (hotDecisionTableEditorInstance) { hotDecisionTableEditorInstance.render(); } }; $scope.removeRule = function () { $scope.model.rulesData.splice($scope.model.selectedRow, 1); }; $scope.clearRule = function (rowNumber) { if (rowNumber === undefined) { return; } $scope.model.rulesData[rowNumber] = createDefaultRow(); if (hotDecisionTableEditorInstance) { hotDecisionTableEditorInstance.render(); } }; $scope.moveRuleUpwards = function () { $scope.model.rulesData.splice($scope.model.selectedRow - 1, 0, $scope.model.rulesData.splice($scope.model.selectedRow, 1)[0]); if (hotDecisionTableEditorInstance) { hotDecisionTableEditorInstance.render(); } }; $scope.moveRuleDownwards = function () { $scope.model.rulesData.splice($scope.model.selectedRow + 1, 0, $scope.model.rulesData.splice($scope.model.selectedRow, 1)[0]); if (hotDecisionTableEditorInstance) { hotDecisionTableEditorInstance.render(); } }; $scope.doAfterGetColHeader = function (col, TH) { if ($scope.model.columnDefs[col] && $scope.model.columnDefs[col].expressionType === 'input-operator') { TH.className += "input-operator-header"; } else if ($scope.model.columnDefs[col] && $scope.model.columnDefs[col].expressionType === 'input-expression') { TH.className += "input-expression-header"; if ($scope.model.startOutputExpression - 1 === col) { TH.className += " last"; } } else if ($scope.model.columnDefs[col] && $scope.model.columnDefs[col].expressionType === 'output') { TH.className += "output-header"; if ($scope.model.startOutputExpression === col) { TH.className += " first"; } } }; $scope.doAfterModifyColWidth = function (width, col) { if ($scope.model.columnDefs[col] && $scope.model.columnDefs[col].width) { var settingsWidth = $scope.model.columnDefs[col].width; if (settingsWidth > width) { return settingsWidth; } } return width; }; $scope.doAfterOnCellMouseDown = function (event, coords, TD) { // clicked hit policy indicator if (coords.row === 0 && coords.col === 0 && TD.className === '') { $scope.openHitPolicyEditor(); } else { if (coords && coords.row !== undefined) { $timeout(function () { $scope.model.selectedRow = coords.row; }); } } }; $scope.doAfterScroll = function () { if (hotDecisionTableEditorInstance) { hotDecisionTableEditorInstance.render(); } }; $scope.doAfterRender = function (isForced) { if (hitPolicyHeaderElement) { var element = document.querySelector("thead > tr > th:first-of-type"); if (element) { var firstChild = element.firstChild; element.className = 'hit-policy-container'; element.replaceChild(hitPolicyHeaderElement[0], firstChild); } } if (hotDecisionTableEditorInstance === undefined) { $timeout(function () { hotDecisionTableEditorInstance = hotRegisterer.getInstance('decision-table-editor'); hotDecisionTableEditorInstance.validateCells(); }); } else { hotDecisionTableEditorInstance.validateCells(); } }; $scope.dumpData = function () { console.log($scope.currentDecisionTable); console.log($scope.model.rulesData); console.log($scope.model.columnDefs); }; $scope.doAfterValidate = function (isValid, value, row, prop, source) { if (isCorrespondingCollectionOperator(row, prop)) { return true; } else if (isCustomExpression(value) || isDashValue(value)) { disableCorrespondingOperatorCell(row, prop); return true; } else { enableCorrespondingOperatorCell(row, prop); } }; // dummy validator for text fields in order to trigger the post validation hook var textValidator = function(value, callback) { callback(true); }; var isCustomExpression = function (val) { return !!(val != null && (String(val).startsWith('${') || String(val).startsWith('#{'))); }; var isDashValue = function (val) { return !!(val != null && "-" === val); }; var isCorrespondingCollectionOperator = function (row, prop) { var operatorCol = getCorrespondingOperatorCell(row, prop); var operatorCellMeta = hotDecisionTableEditorInstance.getCellMeta(row, operatorCol); var isCollectionOperator = false; if (isOperatorCell(operatorCellMeta)) { var operatorValue = hotDecisionTableEditorInstance.getDataAtCell(row, operatorCol); if (operatorValue === "ANY OF" || operatorValue === "NONE OF" || operatorValue === "ALL OF" || operatorValue === "NOT ALL OF" || operatorValue === "IS IN" || operatorValue === "IS NOT IN") { isCollectionOperator = true; } } return isCollectionOperator; }; var disableCorrespondingOperatorCell = function (row, prop) { var operatorCol = getCorrespondingOperatorCell(row, prop); var operatorCellMeta = hotDecisionTableEditorInstance.getCellMeta(row, operatorCol); if (!isOperatorCell(operatorCellMeta)) { return; } if (operatorCellMeta.className != null && operatorCellMeta.className.indexOf('custom-expression-operator') !== -1) { return; } var currentEditor = hotDecisionTableEditorInstance.getCellEditor(row, operatorCol); hotDecisionTableEditorInstance.setCellMeta(row, operatorCol, 'className', operatorCellMeta.className + ' custom-expression-operator'); hotDecisionTableEditorInstance.setCellMeta(row, operatorCol, 'originalEditor', currentEditor); hotDecisionTableEditorInstance.setCellMeta(row, operatorCol, 'editor', false); hotDecisionTableEditorInstance.setDataAtCell(row, operatorCol, null); }; var enableCorrespondingOperatorCell = function (row, prop) { var operatorCol = getCorrespondingOperatorCell(row, prop); var operatorCellMeta = hotDecisionTableEditorInstance.getCellMeta(row, operatorCol); if (!isOperatorCell(operatorCellMeta)) { return; } if (operatorCellMeta == null || operatorCellMeta.className == null || operatorCellMeta.className.indexOf('custom-expression-operator') == -1) { return; } operatorCellMeta.className = operatorCellMeta.className.replace('custom-expression-operator', ''); hotDecisionTableEditorInstance.setCellMeta(row, operatorCol, 'className', operatorCellMeta.className); hotDecisionTableEditorInstance.setCellMeta(row, operatorCol, 'editor', operatorCellMeta.originalEditor); hotDecisionTableEditorInstance.setDataAtCell(row, operatorCol, '=='); }; var getCorrespondingOperatorCell = function (row, prop) { var currentCol = hotDecisionTableEditorInstance.propToCol(prop); if (currentCol < 1) { return; } var operatorCol = currentCol - 1; return operatorCol; }; var isOperatorCell = function (cellMeta) { return !(cellMeta == null || cellMeta.prop == null || typeof cellMeta.prop !== 'string'|| cellMeta.prop.endsWith("_operator") === false); }; var createNewInputExpression = function (inputExpression) { var newInputExpression; if (inputExpression) { newInputExpression = { id: _generateColumnId(), label: inputExpression.label, variableId: inputExpression.variableId, type: inputExpression.type, newVariable: inputExpression.newVariable, entries: inputExpression.entries }; } else { newInputExpression = { id: _generateColumnId(), label: null, variableId: null, type: null, newVariable: null, entries: null }; } return newInputExpression; }; var createNewOutputExpression = function (outputExpression) { var newOutputExpression; if (outputExpression) { newOutputExpression = { id: _generateColumnId(), label: outputExpression.label, variableId: outputExpression.variableId, type: outputExpression.type, newVariable: outputExpression.newVariable, entries: outputExpression.entries }; } else { newOutputExpression = { id: _generateColumnId(), label: null, variableId: null, type: null, newVariable: null, entries: null }; } return newOutputExpression; }; $scope.addNewInputExpression = function (inputExpression, insertPos) { var newInputExpression = createNewInputExpression(inputExpression); // insert expression at position or just add if (insertPos !== undefined && insertPos !== -1) { $scope.currentDecisionTable.inputExpressions.splice(insertPos, 0, newInputExpression); } else { $scope.currentDecisionTable.inputExpressions.push(newInputExpression); } // update data model with initial values $scope.model.rulesData.forEach(function (rowData) { rowData[newInputExpression.id + '_expression'] = '-'; }); // update column definitions off the source model $scope.evaluateDecisionHeaders($scope.currentDecisionTable); }; $scope.addNewOutputExpression = function (outputExpression, insertPos) { var newOutputExpression = createNewOutputExpression(outputExpression); // insert expression at position or just add if (insertPos !== undefined && insertPos !== -1) { $scope.currentDecisionTable.outputExpressions.splice(insertPos, 0, newOutputExpression); } else { $scope.currentDecisionTable.outputExpressions.push(newOutputExpression); } // update column definitions off the source model $scope.evaluateDecisionHeaders($scope.currentDecisionTable); }; $scope.removeInputExpression = function (expressionPos) { var removedElements = $scope.currentDecisionTable.inputExpressions.splice(expressionPos, 1); removePropertyFromGrid(removedElements[0].id, 'input'); $scope.evaluateDecisionHeaders($scope.currentDecisionTable); }; var removePropertyFromGrid = function (key, type) { if ($scope.model.rulesData) { $scope.model.rulesData.forEach(function (rowData) { if (type === 'input') { delete rowData[key + '_operator']; delete rowData[key + '_expression']; } else if (type === 'output') { delete rowData[key]; } }); } }; $scope.removeOutputExpression = function (expressionPos) { var removedElements = $scope.currentDecisionTable.outputExpressions.splice(expressionPos, 1); removePropertyFromGrid(removedElements[0].id, 'output'); $scope.evaluateDecisionHeaders($scope.currentDecisionTable); }; $scope.openInputExpressionEditor = function (expressionPos, newExpression) { var editTemplate = 'views/popup/decision-table-edit-input-expression.html'; $scope.model.newExpression = !!newExpression; if (!$scope.model.newExpression) { $scope.model.selectedExpression = $scope.currentDecisionTable.inputExpressions[expressionPos]; } else { if (expressionPos >= $scope.model.startOutputExpression) { $scope.model.selectedColumn = $scope.model.startOutputExpression - 1; } else { $scope.model.selectedColumn = Math.floor(expressionPos / 2); } } _internalCreateModal({ template: editTemplate, scope: $scope }, $modal, $scope); }; $scope.openOutputExpressionEditor = function (expressionPos, newExpression) { var editTemplate = 'views/popup/decision-table-edit-output-expression.html'; $scope.model.newExpression = !!newExpression; $scope.model.hitPolicy = $scope.currentDecisionTable.hitIndicator; $scope.model.selectedColumn = expressionPos; if (!$scope.model.newExpression) { $scope.model.selectedExpression = $scope.currentDecisionTable.outputExpressions[expressionPos]; } _internalCreateModal({ template: editTemplate, scope: $scope }, $modal, $scope); }; $scope.openHitPolicyEditor = function () { var editTemplate = 'views/popup/decision-table-edit-hit-policy.html'; $scope.model.hitPolicy = $scope.currentDecisionTable.hitIndicator; $scope.model.collectOperator = $scope.currentDecisionTable.collectOperator; _internalCreateModal({ template: editTemplate, scope: $scope }, $modal, $scope); }; var _loadDecisionTableDefinition = function (modelId) { DecisionTableService.fetchDecisionTableDetails(modelId).then(function (decisionTable) { $rootScope.currentDecisionTable = decisionTable.decisionTableDefinition; $rootScope.currentDecisionTable.id = decisionTable.id; $rootScope.currentDecisionTable.key = decisionTable.decisionTableDefinition.key; $rootScope.currentDecisionTable.name = decisionTable.name; $rootScope.currentDecisionTable.description = decisionTable.description; $scope.model.lastUpdatedBy = decisionTable.lastUpdatedBy; $scope.model.createdBy = decisionTable.createdBy; // decision table model to used in save dialog $rootScope.currentDecisionTableModel = { id: decisionTable.id, name: decisionTable.name, key: decisionTable.key, description: decisionTable.description }; if (!$rootScope.currentDecisionTable.hitIndicator) { $rootScope.currentDecisionTable.hitIndicator = hitPolicies[0]; } var hitPolicyHeaderString = '<div class="hit-policy-header"><a onclick="triggerHitPolicyEditor()">' + $rootScope.currentDecisionTable.hitIndicator.substring(0, 1); if ($rootScope.currentDecisionTable.collectOperator) { hitPolicyHeaderString += collectOperators[$rootScope.currentDecisionTable.collectOperator]; } hitPolicyHeaderString += '</a></div>'; hitPolicyHeaderElement = angular.element(hitPolicyHeaderString); evaluateDecisionTableGrid($rootScope.currentDecisionTable); $timeout(function () { // Flip switch in timeout to start watching all decision-related models // after next digest cycle, to prevent first false-positive $scope.status.loading = false; $rootScope.decisionTableChanges = false; }); }); }; var composeInputOperatorColumnDefinition = function (inputExpression) { var expressionPosition = $scope.currentDecisionTable.inputExpressions.indexOf(inputExpression); var columnDefinition = { data: inputExpression.id + '_operator', expressionType: 'input-operator', expression: inputExpression, width: '70', className: 'input-operator-cell', type: 'dropdown', source: getOperatorsForColumnType(inputExpression.type) }; if ($scope.currentDecisionTable.inputExpressions.length !== 1) { columnDefinition.title = '<div class="header-remove-expression">' + '<a onclick="triggerRemoveExpression(\'input\',' + expressionPosition + ',true)"><span class="glyphicon glyphicon-minus-sign"></span></a>' + '</div>'; } return columnDefinition; }; var getOperatorsForColumnType = function (type) { switch (type) { case 'number': return numberOperators; case 'date': return dateOperators; case 'boolean': return booleanOperators; case 'string': return stringOperators; case 'collection': return collectionOperators; default: return allOperators; } }; var composeInputExpressionColumnDefinition = function (inputExpression) { var expressionPosition = $scope.currentDecisionTable.inputExpressions.indexOf(inputExpression); var type; switch (inputExpression.type) { case 'date': type = 'date'; break; case 'number': type = 'numeric'; break; case 'boolean': type = 'dropdown'; break; default: type = 'text'; } var columnDefinition = { data: inputExpression.id + '_expression', type: type, title: '<div class="input-header">' + '<a onclick="triggerExpressionEditor(\'input\',' + expressionPosition + ',false)"><span class="header-label">' + (inputExpression.label ? inputExpression.label : "New Input") + '</span></a>' + '<br><span class="header-variable">' + (inputExpression.variableId ? inputExpression.variableId : "none") + '</span>' + '<br/><span class="header-variable-type">' + (inputExpression.type ? inputExpression.type : "") + '</brspan>' + '</div>' + '<div class="header-add-new-expression">' + '<a onclick="triggerExpressionEditor(\'input\',' + expressionPosition + ',true)"><span class="glyphicon glyphicon-plus-sign"></span></a>' + '</div>', expressionType: 'input-expression', expression: inputExpression, className: 'htCenter', width: '200' }; if (inputExpression.entries && inputExpression.entries.length > 0) { var entriesOptionValues = inputExpression.entries.slice(0, inputExpression.entries.length); entriesOptionValues.push('-'); columnDefinition.type = 'dropdown'; columnDefinition.strict = true; columnDefinition.source = entriesOptionValues; columnDefinition.title = '<div class="input-header">' + '<a onclick="triggerExpressionEditor(\'input\',' + expressionPosition + ',false)"><span class="header-label">' + (inputExpression.label ? inputExpression.label : "New Input") + '</span></a>' + '<br><span class="header-variable">' + (inputExpression.variableId ? inputExpression.variableId : "none") + '</span>' + '<br/><span class="header-variable-type">' + (inputExpression.type ? inputExpression.type : "") + '</span>' + '<br><span class="header-entries">[' + inputExpression.entries.join() + ']</span>' + '</div>' + '<div class="header-add-new-expression">' + '<a onclick="triggerExpressionEditor(\'input\',' + expressionPosition + ',true)"><span class="glyphicon glyphicon-plus-sign"></span></a>' + '</div>'; } else if (type === 'text') { columnDefinition.validator = textValidator; } if (type === 'date') { columnDefinition.dateFormat = dateFormat; columnDefinition.validator = function (value, callback) { if (value === '-') { callback(true); } else { Handsontable.DateValidator.call(this, value, callback); } } } else if (type === 'dropdown') { columnDefinition.source = ['true', 'false', '-']; } if (type !== 'text') { columnDefinition.allowEmpty = false; } return columnDefinition; }; var composeOutputColumnDefinition = function (outputExpression) { var expressionPosition = $scope.currentDecisionTable.outputExpressions.indexOf(outputExpression); var type; switch (outputExpression.type) { case 'date': type = 'date'; break; case 'number': type = 'numeric'; break; case 'boolean': type = 'dropdown'; break; default: type = 'text'; } var title = ''; var columnDefinition = { data: outputExpression.id, type: type, expressionType: 'output', expression: outputExpression, className: 'htCenter', width: '270' }; if ($scope.currentDecisionTable.outputExpressions.length !== 1) { title = '<div class="header-remove-expression">' + '<a onclick="triggerRemoveExpression(\'output\',' + expressionPosition + ',true)"><span class="glyphicon glyphicon-minus-sign"></span></a>' + '</div>'; } if (outputExpression.entries && outputExpression.entries.length > 0) { var entriesOptionValues = outputExpression.entries.slice(0, outputExpression.entries.length); columnDefinition.type = 'dropdown'; columnDefinition.source = entriesOptionValues; columnDefinition.strict = true; title += '<div class="output-header">' + '<a onclick="triggerExpressionEditor(\'output\',' + expressionPosition + ',false)"><span class="header-label">' + (outputExpression.label ? outputExpression.label : "New Output") + '</span></a>' + '<br><span class="header-variable">' + (outputExpression.variableId ? outputExpression.variableId : "none") + '</span>' + '<br/><span class="header-variable-type">' + (outputExpression.type ? outputExpression.type : "") + '</span>' + '<br><span class="header-entries">[' + outputExpression.entries.join() + ']</span>' + '</div>' + '<div class="header-add-new-expression">' + '<a onclick="triggerExpressionEditor(\'output\',' + expressionPosition + ',true)"><span class="glyphicon glyphicon-plus-sign"></span></a>' + '</div>'; } else { title += '<div class="output-header">' + '<a onclick="triggerExpressionEditor(\'output\',' + expressionPosition + ',false)"><span class="header-label">' + (outputExpression.label ? outputExpression.label : "New Output") + '</span></a>' + '<br><span class="header-variable">' + (outputExpression.variableId ? outputExpression.variableId : "none") + '</span>' + '<br/><span class="header-variable-type">' + (outputExpression.type ? outputExpression.type : "") + '</span>' + '</div>' + '<div class="header-add-new-expression">' + '<a onclick="triggerExpressionEditor(\'output\',' + expressionPosition + ',true)"><span class="glyphicon glyphicon-plus-sign"></span></a>' + '</div>'; } if (type === 'date') { columnDefinition.dateFormat = dateFormat; } else if (type === 'dropdown') { columnDefinition.source = ['true', 'false', '-']; } columnDefinition.title = title; return columnDefinition; }; $scope.evaluateDecisionHeaders = function (decisionTable) { var element = document.querySelector("thead > tr > th:first-of-type > div > a"); if (element) { if (decisionTable.collectOperator) { element.innerHTML = decisionTable.hitIndicator.substring(0, 1) + collectOperators[decisionTable.collectOperator]; } else { element.innerHTML = decisionTable.hitIndicator.substring(0, 1); } } var columnDefinitions = []; var inputExpressionCounter = 0; if (decisionTable.inputExpressions && decisionTable.inputExpressions.length > 0) { decisionTable.inputExpressions.forEach(function (inputExpression) { var inputOperatorColumnDefinition = composeInputOperatorColumnDefinition(inputExpression); columnDefinitions.push(inputOperatorColumnDefinition); setGridValues(inputOperatorColumnDefinition.data, inputOperatorColumnDefinition.expressionType); var inputExpressionColumnDefinition = composeInputExpressionColumnDefinition(inputExpression); columnDefinitions.push(inputExpressionColumnDefinition); setGridValues(inputExpressionColumnDefinition.data, inputExpressionColumnDefinition.expressionType); inputExpressionCounter += 2; }); } else { // create default input expression decisionTable.inputExpressions = []; var inputExpression = createNewInputExpression(); decisionTable.inputExpressions.push(inputExpression); columnDefinitions.push(composeInputOperatorColumnDefinition(inputExpression)); columnDefinitions.push(composeInputExpressionColumnDefinition(inputExpression)); inputExpressionCounter += 2; } columnDefinitions[inputExpressionCounter - 1].className += ' last'; $scope.model.startOutputExpression = inputExpressionCounter; if (decisionTable.outputExpressions && decisionTable.outputExpressions.length > 0) { decisionTable.outputExpressions.forEach(function (outputExpression) { columnDefinitions.push(composeOutputColumnDefinition(outputExpression)); }); } else { // create default output expression decisionTable.outputExpressions = []; var outputExpression = createNewOutputExpression(); decisionTable.outputExpressions.push(outputExpression); columnDefinitions.push(composeOutputColumnDefinition(outputExpression)); } columnDefinitions[inputExpressionCounter].className += ' first'; // timeout needed for trigger hot update when removing column defs $scope.model.columnDefs = columnDefinitions; $timeout(function () { if (hotDecisionTableEditorInstance) { hotDecisionTableEditorInstance.render(); } }); }; var setGridValues = function (key, type) { if ($scope.model.rulesData) { $scope.model.rulesData.forEach(function (rowData) { if (type === 'input-operator') { if (!(key in rowData) || rowData[key] === '') { rowData[key] = '=='; } } }); } }; var createDefaultRow = function () { var defaultRow = {}; $scope.model.columnDefs.forEach(function (columnDefinition) { if (columnDefinition.expressionType === 'input-operator') { defaultRow[columnDefinition.data] = '=='; } else if (columnDefinition.expressionType === 'input-expression') { defaultRow[columnDefinition.data] = '-'; } else if (columnDefinition.expressionType === 'output') { defaultRow[columnDefinition.data] = ''; } }); return defaultRow; }; var evaluateDecisionGrid = function (decisionTable) { var tmpRuleGrid = []; // rows if (decisionTable.rules && decisionTable.rules.length > 0) { decisionTable.rules.forEach(function (rule) { // rule data var tmpRowValues = {}; for (var i = 0; i < Object.keys(rule).length; i++) { var id = Object.keys(rule)[i]; $scope.model.columnDefs.forEach(function (columnDef) { // set counter to max value var expressionId = 0; try { expressionId = parseInt(columnDef.expression.id); } catch (e) { } if (expressionId > columnIdCounter) { columnIdCounter = expressionId; } }); // collection operators backwards compatibility // var cellValue = regressionTransformation(id, rule[id]); tmpRowValues[id] = rule[id]; } tmpRuleGrid.push(tmpRowValues); }); } else { // initialize default values tmpRuleGrid.push(createDefaultRow()); } // $rootScope.currentDecisionTableRules = tmpRuleGrid; $scope.model.rulesData = tmpRuleGrid; }; var evaluateDecisionTableGrid = function (decisionTable) { $scope.evaluateDecisionHeaders(decisionTable); evaluateDecisionGrid(decisionTable); }; // fetch table from service and populate model _loadDecisionTableDefinition($routeParams.modelId); var _generateColumnId = function () { columnIdCounter++; return "" + columnIdCounter; }; }]); angular.module('flowableModeler') .controller('DecisionTableInputConditionEditorCtlr', ['$rootScope', '$scope', 'hotRegisterer', '$timeout', function ($rootScope, $scope, hotRegisterer, $timeout) { var getEntriesValues = function (entriesArrayOfArrays) { var newEntriesArray = []; // remove last value entriesArrayOfArrays.pop(); entriesArrayOfArrays.forEach(function (entriesArray) { newEntriesArray.push(entriesArray[0]); }); return newEntriesArray; }; var createEntriesValues = function (entriesArray) { var localCopy = entriesArray.slice(0); var entriesArrayOfArrays = []; while (localCopy.length) { entriesArrayOfArrays.push(localCopy.splice(0, 1)); } return entriesArrayOfArrays; }; var deleteRowRenderer = function (instance, td, row) { td.innerHTML = ''; td.className = 'remove_container'; if ((row + 1) != $scope.popup.selectedExpressionInputValues.length) { var div = document.createElement('div'); div.onclick = function () { return instance.alter("remove_row", row); }; div.className = 'btn'; div.appendChild(document.createTextNode('x')); td.appendChild(div); } return td; }; // condition input options if ($scope.model.newExpression === false) { $scope.popup = { selectedExpressionLabel: $scope.model.selectedExpression.label ? $scope.model.selectedExpression.label : '', selectedExpressionVariableId: $scope.model.selectedExpression.variableId, selectedExpressionVariableType: $scope.model.selectedExpression.type ? $scope.model.selectedExpression.type : $scope.model.availableInputVariableTypes[0], selectedExpressionInputValues: $scope.model.selectedExpression.entries && $scope.model.selectedExpression.entries.length > 0 ? createEntriesValues($scope.model.selectedExpression.entries) : [['']], columnDefs: [ { width: '300' }, { width: '40', readOnly: true, renderer: deleteRowRenderer } ], hotSettings: { stretchH: 'none' } }; } else { $scope.popup = { selectedExpressionLabel: '', selectedExpressionVariableId: '', selectedExpressionVariableType: $scope.model.availableInputVariableTypes[0], selectedExpressionInputValues: [['']], columnDefs: [ { width: '300' }, { renderer: deleteRowRenderer, readOnly: true, width: '40' } ], hotSettings: { stretchH: 'none' } }; } $scope.save = function () { if ($scope.model.newExpression) { var newInputExpression = { variableId: $scope.popup.selectedExpressionVariableId, type: $scope.popup.selectedExpressionVariableType, label: $scope.popup.selectedExpressionLabel, entries: $scope.popup.selectedExpressionVariableType !== 'collection' ? getEntriesValues($scope.popup.selectedExpressionInputValues) : [] }; $scope.addNewInputExpression(newInputExpression, $scope.model.selectedColumn + 1); } else { $scope.model.selectedExpression.variableId = $scope.popup.selectedExpressionVariableId; $scope.model.selectedExpression.type = $scope.popup.selectedExpressionVariableType; $scope.model.selectedExpression.label = $scope.popup.selectedExpressionLabel; $scope.model.selectedExpression.entries = $scope.popup.selectedExpressionVariableType !== 'collection' ? getEntriesValues($scope.popup.selectedExpressionInputValues) : []; $scope.evaluateDecisionHeaders($scope.currentDecisionTable); } $scope.close(); }; $scope.setExpressionVariableType = function (variableType) { $scope.popup.selectedExpressionVariable = null; $scope.popup.selectedExpressionVariableType = variableType; }; $scope.setNewVariable = function (value) { $scope.popup.selectedExpressionNewVariable = value; if (value) { $scope.setExpressionVariableType('variable'); } }; $scope.close = function () { $scope.$hide(); }; // Cancel button handler $scope.cancel = function () { $scope.close(); }; }]); angular.module('flowableModeler') .controller('DecisionTableConclusionEditorCtrl', ['$rootScope', '$scope', '$q', '$translate', 'hotRegisterer', function ($rootScope, $scope, $q, $translate, hotRegisterer) { var hotInstance; var getEntriesValues = function (entriesArrayOfArrays) { var newEntriesArray = []; // remove last value entriesArrayOfArrays.pop(); entriesArrayOfArrays.forEach(function (entriesArray) { newEntriesArray.push(entriesArray[0]); }); return newEntriesArray; }; var createEntriesValues = function (entriesArray) { var localCopy = entriesArray.slice(0); var entriesArrayOfArrays = []; while (localCopy.length) { entriesArrayOfArrays.push(localCopy.splice(0, 1)); } return entriesArrayOfArrays; }; var deleteRowRenderer = function (instance, td, row) { td.innerHTML = ''; td.className = 'remove_container'; if ((row + 1) != $scope.popup.selectedExpressionOutputValues.length) { var div = document.createElement('div'); div.onclick = function () { return instance.alter("remove_row", row); }; div.className = 'btn'; div.appendChild(document.createTextNode('x')); td.appendChild(div); } return td; }; $scope.doAfterRender = function () { hotInstance = hotRegisterer.getInstance('decision-table-allowed-values'); }; if ($scope.model.newExpression === false) { $scope.popup = { selectedExpressionLabel: $scope.model.selectedExpression.label ? $scope.model.selectedExpression.label : '', selectedExpressionNewVariableId: $scope.model.selectedExpression.variableId, selectedExpressionNewVariableType: $scope.model.selectedExpression.type ? $scope.model.selectedExpression.type : $scope.model.availableOutputVariableTypes[0], selectedExpressionOutputValues: $scope.model.selectedExpression.entries && $scope.model.selectedExpression.entries.length > 0 ? createEntriesValues($scope.model.selectedExpression.entries) : [['']], currentHitPolicy: $scope.model.hitPolicy, columnDefs: [ { width: '250' }, { width: '40', readOnly: true, renderer: deleteRowRenderer } ], hotSettings: { currentColClassName: 'currentCol', stretchH: 'none' } }; } else { $scope.popup = { selectedExpressionLabel: '', selectedExpressionNewVariableId: '', selectedExpressionNewVariableType: $scope.model.availableOutputVariableTypes[0], selectedExpressionOutputValues: [['']], currentHitPolicy: $scope.model.hitPolicy, columnDefs: [ { width: '250' }, { width: '40', readOnly: true, renderer: deleteRowRenderer } ], hotSettings: { stretchH: 'none' } }; } // Cancel button handler $scope.cancel = function () { $scope.close(); }; // Saving the edited input $scope.save = function () { if ($scope.model.newExpression) { var newOutputExpression = { variableId: $scope.popup.selectedExpressionNewVariableId, type: $scope.popup.selectedExpressionNewVariableType, label: $scope.popup.selectedExpressionLabel, entries: getEntriesValues(hotInstance.getData()) }; $scope.addNewOutputExpression(newOutputExpression, $scope.model.selectedColumn + 1); } else { $scope.model.selectedExpression.variableId = $scope.popup.selectedExpressionNewVariableId; $scope.model.selectedExpression.type = $scope.popup.selectedExpressionNewVariableType; $scope.model.selectedExpression.label = $scope.popup.selectedExpressionLabel; $scope.model.selectedExpression.entries = getEntriesValues(hotInstance.getData()); $scope.evaluateDecisionHeaders($scope.currentDecisionTable); } $scope.close(); }; $scope.close = function () { $scope.$hide(); }; $scope.dumpData = function () { console.log(hotInstance.getData()); } }]); angular.module('flowableModeler') .controller('DecisionTableHitPolicyEditorCtrl', ['$rootScope', '$scope', '$q', '$translate', function ($rootScope, $scope, $q, $translate) { $scope.popup = { currentHitPolicy: $scope.model.hitPolicy, currentCollectOperator: $scope.model.collectOperator, availableHitPolicies: $scope.hitPolicies, availableCollectOperators: $scope.collectOperators }; // Cancel button handler $scope.cancel = function () { $scope.close(); }; // Saving the edited input $scope.save = function () { $scope.currentDecisionTable.hitIndicator = $scope.popup.currentHitPolicy; if ($scope.popup.currentHitPolicy === 'COLLECT') { $scope.currentDecisionTable.collectOperator = $scope.popup.currentCollectOperator; } else { $scope.currentDecisionTable.collectOperator = undefined; } $scope.evaluateDecisionHeaders($scope.currentDecisionTable); $scope.close(); }; $scope.close = function () { $scope.$hide(); }; }]);
{ "content_hash": "f5db13b6e493ec904745c94754b21cc1", "timestamp": "", "source": "github", "line_count": 1191, "max_line_length": 220, "avg_line_length": 45.74643157010915, "alnum_prop": 0.49684310990382496, "repo_name": "flowable/flowable-engine", "id": "6024b2e5014ffbbf6ecb861baafa0abf1b6a12ff", "size": "55093", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "modules/flowable-ui/flowable-ui-modeler-frontend/src/main/resources/static/modeler/scripts/controllers/decision-table-editor.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "166" }, { "name": "CSS", "bytes": "673786" }, { "name": "Dockerfile", "bytes": "477" }, { "name": "Groovy", "bytes": "482" }, { "name": "HTML", "bytes": "1201811" }, { "name": "Handlebars", "bytes": "6004" }, { "name": "Java", "bytes": "46660725" }, { "name": "JavaScript", "bytes": "12668702" }, { "name": "Mustache", "bytes": "2383" }, { "name": "PLSQL", "bytes": "268970" }, { "name": "SQLPL", "bytes": "238673" }, { "name": "Shell", "bytes": "12773" }, { "name": "TSQL", "bytes": "19452" } ], "symlink_target": "" }
// Copyright 2019 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.lib.sandbox; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.devtools.build.lib.actions.ActionInput; import com.google.devtools.build.lib.actions.Spawn; import com.google.devtools.build.lib.exec.local.LocalEnvProvider; import com.google.devtools.build.lib.exec.local.WindowsLocalEnvProvider; import com.google.devtools.build.lib.runtime.CommandEnvironment; import com.google.devtools.build.lib.sandbox.SandboxHelpers.SandboxInputs; import com.google.devtools.build.lib.vfs.Path; import com.google.devtools.build.lib.vfs.PathFragment; import java.io.IOException; import java.time.Duration; /** Spawn runner that uses BuildXL Sandbox APIs to execute a local subprocess. */ final class WindowsSandboxedSpawnRunner extends AbstractSandboxSpawnRunner { private final Path execRoot; private final PathFragment windowsSandbox; private final LocalEnvProvider localEnvProvider; private final Duration timeoutKillDelay; /** * Creates a sandboxed spawn runner that uses the {@code windows-sandbox} tool. * * @param cmdEnv the command environment to use * @param timeoutKillDelay an additional grace period before killing timing out commands * @param windowsSandboxPath path to windows-sandbox binary */ WindowsSandboxedSpawnRunner( CommandEnvironment cmdEnv, Duration timeoutKillDelay, PathFragment windowsSandboxPath) { super(cmdEnv); this.execRoot = cmdEnv.getExecRoot(); this.windowsSandbox = windowsSandboxPath; this.timeoutKillDelay = timeoutKillDelay; this.localEnvProvider = new WindowsLocalEnvProvider(cmdEnv.getClientEnv()); } @Override protected SandboxedSpawn prepareSpawn(Spawn spawn, SpawnExecutionContext context) throws IOException { Path tmpDir = createActionTemp(execRoot); Path commandTmpDir = tmpDir.getRelative("work"); commandTmpDir.createDirectory(); ImmutableMap<String, String> environment = ImmutableMap.copyOf( localEnvProvider.rewriteLocalEnv( spawn.getEnvironment(), binTools, commandTmpDir.getPathString())); SandboxInputs readablePaths = SandboxHelpers.processInputFiles( spawn, context, execRoot, getSandboxOptions().symlinkedSandboxExpandsTreeArtifactsInRunfilesTree); ImmutableSet.Builder<Path> writablePaths = ImmutableSet.builder(); writablePaths.addAll(getWritableDirs(execRoot, environment)); for (ActionInput output : spawn.getOutputFiles()) { writablePaths.add(execRoot.getRelative(output.getExecPath())); } Duration timeout = context.getTimeout(); if (!readablePaths.getSymlinks().isEmpty()) { throw new IOException( "Windows sandbox does not support unresolved symlinks yet (" + Joiner.on(", ").join(readablePaths.getSymlinks().keySet()) + ")"); } WindowsSandboxUtil.CommandLineBuilder commandLineBuilder = WindowsSandboxUtil.commandLineBuilder(windowsSandbox, spawn.getArguments()) .setWritableFilesAndDirectories(writablePaths.build()) .setReadableFilesAndDirectories(readablePaths.getFiles()) .setInaccessiblePaths(getInaccessiblePaths()) .setUseDebugMode(getSandboxOptions().sandboxDebug) .setKillDelay(timeoutKillDelay); if (!timeout.isZero()) { commandLineBuilder.setTimeout(timeout); } return new WindowsSandboxedSpawn(execRoot, environment, commandLineBuilder.build()); } private static Path createActionTemp(Path execRoot) throws IOException { return execRoot.getRelative( java.nio.file.Files.createTempDirectory( java.nio.file.Paths.get(execRoot.getPathString()), "windows-sandbox.") .getFileName() .toString()); } @Override public String getName() { return "windows-sandbox"; } }
{ "content_hash": "2b1d1a4eb4481eb9f6ab0614b4d7773b", "timestamp": "", "source": "github", "line_count": 115, "max_line_length": 94, "avg_line_length": 40.02608695652174, "alnum_prop": 0.7379969585053227, "repo_name": "aehlig/bazel", "id": "10df1aaacdaa75a3e394bbe3f9a96cbd4df81d27", "size": "4603", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/google/devtools/build/lib/sandbox/WindowsSandboxedSpawnRunner.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "1588" }, { "name": "C", "bytes": "27067" }, { "name": "C++", "bytes": "1513394" }, { "name": "Dockerfile", "bytes": "839" }, { "name": "HTML", "bytes": "21053" }, { "name": "Java", "bytes": "35178923" }, { "name": "Makefile", "bytes": "248" }, { "name": "Objective-C", "bytes": "10369" }, { "name": "Objective-C++", "bytes": "1043" }, { "name": "PowerShell", "bytes": "15438" }, { "name": "Python", "bytes": "2519187" }, { "name": "Ruby", "bytes": "639" }, { "name": "Shell", "bytes": "1916092" }, { "name": "Smarty", "bytes": "18683" } ], "symlink_target": "" }
import capacity from '../yearCapacity' describe('Capacity reducer', () => { it('returns default state', () => { expect(capacity()).toMatchObject({ data: {}, loading: false, polling: false }) }) it('marks as loading on YEAR_CAPACITY_FETCH_STARTED', () => { expect(capacity({}, { type: 'YEAR_CAPACITY_FETCH_STARTED' })).toMatchObject({ loading: true }) }) it('marks as loading on YEAR_CAPACITY_FETCH_SUCCESS', () => { expect(capacity( {}, { type: 'YEAR_CAPACITY_FETCH_SUCCESS', data: [ { name: 'foo' } ] } )).toMatchObject({ loading: false, valid: true, data: [ { name: 'foo' } ] }) }) it('marks as loading on YEAR_CAPACITY_FETCH_ERROR', () => { expect(capacity({}, { type: 'YEAR_CAPACITY_FETCH_ERROR', error: 'error' })).toMatchObject({ loading: false, error: 'error' }) }) it('marks as loading on YEAR_CAPACITY_POLL_START', () => { expect(capacity({}, { type: 'YEAR_CAPACITY_POLL_START' })).toMatchObject({ polling: true }) }) it('marks as loading on YEAR_CAPACITY_POLL_STOP', () => { expect(capacity({}, { type: 'YEAR_CAPACITY_POLL_STOP' })).toMatchObject({ polling: false }) }) })
{ "content_hash": "cf9ddc0aa89180140bf998b3ede77c13", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 95, "avg_line_length": 26.367346938775512, "alnum_prop": 0.5456656346749226, "repo_name": "just-paja/improtresk-web", "id": "7a48a9d273daf30272cdeed109db9c62403a990d", "size": "1292", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/years/reducers/__tests__/yearCapacity.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10359" }, { "name": "JavaScript", "bytes": "820268" }, { "name": "Shell", "bytes": "596" } ], "symlink_target": "" }
package org.optaplanner.examples.cloudbalancing.app; import org.optaplanner.examples.cloudbalancing.domain.CloudBalance; import org.optaplanner.examples.cloudbalancing.persistence.CloudBalanceXmlSolutionFileIO; import org.optaplanner.examples.cloudbalancing.swingui.CloudBalancingPanel; import org.optaplanner.examples.common.app.CommonApp; import org.optaplanner.persistence.common.api.domain.solution.SolutionFileIO; /** * For an easy example, look at {@link CloudBalancingHelloWorld} instead. */ public class CloudBalancingApp extends CommonApp<CloudBalance> { public static final String SOLVER_CONFIG = "org/optaplanner/examples/cloudbalancing/solver/cloudBalancingSolverConfig.xml"; public static final String DATA_DIR_NAME = "cloudbalancing"; public static void main(String[] args) { prepareSwingEnvironment(); new CloudBalancingApp().init(); } public CloudBalancingApp() { super("Cloud balancing", "Assign processes to computers.\n\n" + "Each computer must have enough hardware to run all of its processes.\n" + "Each used computer inflicts a maintenance cost.", SOLVER_CONFIG, DATA_DIR_NAME, CloudBalancingPanel.LOGO_PATH); } @Override protected CloudBalancingPanel createSolutionPanel() { return new CloudBalancingPanel(); } @Override public SolutionFileIO<CloudBalance> createSolutionFileIO() { return new CloudBalanceXmlSolutionFileIO(); } }
{ "content_hash": "a488fb0d116af38364de3c4bdff2e29d", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 127, "avg_line_length": 35.22727272727273, "alnum_prop": 0.7174193548387097, "repo_name": "droolsjbpm/optaplanner", "id": "63ec16dfd086640d2974f59ff54454912439dab6", "size": "2170", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "optaplanner-examples/src/main/java/org/optaplanner/examples/cloudbalancing/app/CloudBalancingApp.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2602" }, { "name": "CSS", "bytes": "13781" }, { "name": "FreeMarker", "bytes": "114386" }, { "name": "HTML", "bytes": "678" }, { "name": "Java", "bytes": "6988206" }, { "name": "JavaScript", "bytes": "215434" }, { "name": "Shell", "bytes": "1548" } ], "symlink_target": "" }
from .model import * # noqa from .transformer_layer_xmod import * # noqa
{ "content_hash": "e5978217f7a75fc972f72a91a4fa6863", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 45, "avg_line_length": 37.5, "alnum_prop": 0.7066666666666667, "repo_name": "pytorch/fairseq", "id": "bbf7694920eb00bed27e17dac272611be1ab44f9", "size": "253", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "fairseq/models/xmod/__init__.py", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "21106" }, { "name": "Cuda", "bytes": "38166" }, { "name": "Cython", "bytes": "13294" }, { "name": "Lua", "bytes": "4210" }, { "name": "Python", "bytes": "3699357" }, { "name": "Shell", "bytes": "2182" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>geometric-algebra: 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 / geometric-algebra - 0.8.8</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> geometric-algebra <small> 0.8.8 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2022-04-22 10:41:02 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-04-22 10:41:02 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.3 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Laurent Théry&quot; homepage: &quot;https://github.com/thery/GeometricAlgebra&quot; bug-reports: &quot;https://github.com/thery/GeometricAlgebra&quot; dev-repo: &quot;git+https://github.com/thery/GeometricAlgebra.git&quot; authors : &quot;Laurent Théry&quot; license: &quot;LGPL&quot; build: [ [make &quot;-j%{jobs}%&quot;] ] install: [ [make &quot;install&quot;] ] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/GeometricAlgebra&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8~&quot; &amp; &lt; &quot;8.11&quot;} ] synopsis: &quot;Grassman Cayley and Clifford formalisations&quot; flags: light-uninstall url { src: &quot;https://github.com/thery/GeometricAlgebra/archive/v8.8.zip&quot; checksum: &quot;md5=12dfbc7869435e2777342fe0a0243283&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-geometric-algebra.0.8.8 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-geometric-algebra -&gt; coq &lt; 8.11 -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) 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-geometric-algebra.0.8.8</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>
{ "content_hash": "447709c01714b43655de6242026d629e", "timestamp": "", "source": "github", "line_count": 164, "max_line_length": 159, "avg_line_length": 39.823170731707314, "alnum_prop": 0.5336089419690706, "repo_name": "coq-bench/coq-bench.github.io", "id": "9ddc7e32fea199674ec3d3b103f64ac9ba7c2d61", "size": "6558", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "clean/Linux-x86_64-4.08.1-2.0.5/released/8.11.2/geometric-algebra/0.8.8.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package com.smart.smartchart.widget.hellocharts.view; import android.content.Context; import android.graphics.Canvas; import android.os.Build; import android.support.v4.view.ViewCompat; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import com.smart.smartchart.widget.hellocharts.animation.ChartAnimationListener; import com.smart.smartchart.widget.hellocharts.animation.ChartDataAnimator; import com.smart.smartchart.widget.hellocharts.animation.ChartDataAnimatorV14; import com.smart.smartchart.widget.hellocharts.animation.ChartDataAnimatorV8; import com.smart.smartchart.widget.hellocharts.animation.ChartViewportAnimator; import com.smart.smartchart.widget.hellocharts.animation.ChartViewportAnimatorV14; import com.smart.smartchart.widget.hellocharts.animation.ChartViewportAnimatorV8; import com.smart.smartchart.widget.hellocharts.computator.ChartComputator; import com.smart.smartchart.widget.hellocharts.gesture.ChartTouchHandler; import com.smart.smartchart.widget.hellocharts.gesture.ContainerScrollType; import com.smart.smartchart.widget.hellocharts.gesture.ZoomType; import com.smart.smartchart.widget.hellocharts.listener.ViewportChangeListener; import com.smart.smartchart.widget.hellocharts.model.SelectedValue; import com.smart.smartchart.widget.hellocharts.model.Viewport; import com.smart.smartchart.widget.hellocharts.renderer.AxesRenderer; import com.smart.smartchart.widget.hellocharts.renderer.ChartRenderer; import com.smart.smartchart.widget.hellocharts.util.ChartUtils; /** * Abstract class for charts views. * * @author Leszek Wach */ public abstract class AbstractChartView extends View implements Chart { protected ChartComputator chartComputator; protected AxesRenderer axesRenderer; protected ChartTouchHandler touchHandler; protected ChartRenderer chartRenderer; protected ChartDataAnimator dataAnimator; protected ChartViewportAnimator viewportAnimator; protected boolean isInteractive = true; protected boolean isContainerScrollEnabled = false; protected ContainerScrollType containerScrollType; public AbstractChartView(Context context) { this(context, null, 0); } public AbstractChartView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public AbstractChartView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); chartComputator = new ChartComputator(); touchHandler = new ChartTouchHandler(context, this); axesRenderer = new AxesRenderer(context, this); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { this.dataAnimator = new ChartDataAnimatorV8(this); this.viewportAnimator = new ChartViewportAnimatorV8(this); } else { this.viewportAnimator = new ChartViewportAnimatorV14(this); this.dataAnimator = new ChartDataAnimatorV14(this); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override protected void onSizeChanged(int width, int height, int oldWidth, int oldHeight) { super.onSizeChanged(width, height, oldWidth, oldHeight); chartComputator.setContentRect(getWidth(), getHeight(), getPaddingLeft(), getPaddingTop(), getPaddingRight(), getPaddingBottom()); chartRenderer.onChartSizeChanged(); axesRenderer.onChartSizeChanged(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (isEnabled()) { axesRenderer.drawInBackground(canvas); int clipRestoreCount = canvas.save(); canvas.clipRect(chartComputator.getContentRectMinusAllMargins()); chartRenderer.draw(canvas); canvas.restoreToCount(clipRestoreCount); chartRenderer.drawUnclipped(canvas); axesRenderer.drawInForeground(canvas); } else { canvas.drawColor(ChartUtils.DEFAULT_COLOR); } } @Override public boolean onTouchEvent(MotionEvent event) { super.onTouchEvent(event); if (isInteractive) { boolean needInvalidate; if (isContainerScrollEnabled) { needInvalidate = touchHandler.handleTouchEvent(event, getParent(), containerScrollType); } else { needInvalidate = touchHandler.handleTouchEvent(event); } if (needInvalidate) { ViewCompat.postInvalidateOnAnimation(this); } return true; } else { return false; } } @Override public void computeScroll() { super.computeScroll(); if (isInteractive) { if (touchHandler.computeScroll()) { ViewCompat.postInvalidateOnAnimation(this); } } } @Override public void startDataAnimation() { dataAnimator.startAnimation(Long.MIN_VALUE); } @Override public void startDataAnimation(long duration) { dataAnimator.startAnimation(duration); } @Override public void cancelDataAnimation() { dataAnimator.cancelAnimation(); } @Override public void animationDataUpdate(float scale) { getChartData().update(scale); chartRenderer.onChartViewportChanged(); ViewCompat.postInvalidateOnAnimation(this); } @Override public void animationDataFinished() { getChartData().finish(); chartRenderer.onChartViewportChanged(); ViewCompat.postInvalidateOnAnimation(this); } @Override public void setDataAnimationListener(ChartAnimationListener animationListener) { dataAnimator.setChartAnimationListener(animationListener); } @Override public void setViewportAnimationListener(ChartAnimationListener animationListener) { viewportAnimator.setChartAnimationListener(animationListener); } @Override public void setViewportChangeListener(ViewportChangeListener viewportChangeListener) { chartComputator.setViewportChangeListener(viewportChangeListener); } @Override public ChartRenderer getChartRenderer() { return chartRenderer; } @Override public void setChartRenderer(ChartRenderer renderer) { chartRenderer = renderer; resetRendererAndTouchHandler(); ViewCompat.postInvalidateOnAnimation(this); } @Override public AxesRenderer getAxesRenderer() { return axesRenderer; } @Override public ChartComputator getChartComputator() { return chartComputator; } @Override public ChartTouchHandler getTouchHandler() { return touchHandler; } @Override public boolean isInteractive() { return isInteractive; } @Override public void setInteractive(boolean isInteractive) { this.isInteractive = isInteractive; } @Override public boolean isZoomEnabled() { return touchHandler.isZoomEnabled(); } @Override public void setZoomEnabled(boolean isZoomEnabled) { touchHandler.setZoomEnabled(isZoomEnabled); } @Override public boolean isScrollEnabled() { return touchHandler.isScrollEnabled(); } @Override public void setScrollEnabled(boolean isScrollEnabled) { touchHandler.setScrollEnabled(isScrollEnabled); } @Override public void moveTo(float x, float y) { Viewport scrollViewport = computeScrollViewport(x, y); setCurrentViewport(scrollViewport); } @Override public void moveToWithAnimation(float x, float y) { Viewport scrollViewport = computeScrollViewport(x, y); setCurrentViewportWithAnimation(scrollViewport); } private Viewport computeScrollViewport(float x, float y) { Viewport maxViewport = getMaximumViewport(); Viewport currentViewport = getCurrentViewport(); Viewport scrollViewport = new Viewport(currentViewport); if (maxViewport.contains(x, y)) { final float width = currentViewport.width(); final float height = currentViewport.height(); final float halfWidth = width / 2; final float halfHeight = height / 2; float left = x - halfWidth; float top = y + halfHeight; left = Math.max(maxViewport.left, Math.min(left, maxViewport.right - width)); top = Math.max(maxViewport.bottom + height, Math.min(top, maxViewport.top)); scrollViewport.set(left, top, left + width, top - height); } return scrollViewport; } @Override public boolean isValueTouchEnabled() { return touchHandler.isValueTouchEnabled(); } @Override public void setValueTouchEnabled(boolean isValueTouchEnabled) { touchHandler.setValueTouchEnabled(isValueTouchEnabled); } @Override public ZoomType getZoomType() { return touchHandler.getZoomType(); } @Override public void setZoomType(ZoomType zoomType) { touchHandler.setZoomType(zoomType); } @Override public float getMaxZoom() { return chartComputator.getMaxZoom(); } @Override public void setMaxZoom(float maxZoom) { chartComputator.setMaxZoom(maxZoom); ViewCompat.postInvalidateOnAnimation(this); } @Override public float getZoomLevel() { Viewport maxViewport = getMaximumViewport(); Viewport currentViewport = getCurrentViewport(); return Math.max(maxViewport.width() / currentViewport.width(), maxViewport.height() / currentViewport.height()); } @Override public void setZoomLevel(float x, float y, float zoomLevel) { Viewport zoomViewport = computeZoomViewport(x, y, zoomLevel); setCurrentViewport(zoomViewport); } @Override public void setZoomLevelWithAnimation(float x, float y, float zoomLevel) { Viewport zoomViewport = computeZoomViewport(x, y, zoomLevel); setCurrentViewportWithAnimation(zoomViewport); } private Viewport computeZoomViewport(float x, float y, float zoomLevel) { final Viewport maxViewport = getMaximumViewport(); Viewport zoomViewport = new Viewport(getMaximumViewport()); if (maxViewport.contains(x, y)) { if (zoomLevel < 1) { zoomLevel = 1; } else if (zoomLevel > getMaxZoom()) { zoomLevel = getMaxZoom(); } final float newWidth = zoomViewport.width() / zoomLevel; final float newHeight = zoomViewport.height() / zoomLevel; final float halfWidth = newWidth / 2; final float halfHeight = newHeight / 2; float left = x - halfWidth; float right = x + halfWidth; float top = y + halfHeight; float bottom = y - halfHeight; if (left < maxViewport.left) { left = maxViewport.left; right = left + newWidth; } else if (right > maxViewport.right) { right = maxViewport.right; left = right - newWidth; } if (top > maxViewport.top) { top = maxViewport.top; bottom = top - newHeight; } else if (bottom < maxViewport.bottom) { bottom = maxViewport.bottom; top = bottom + newHeight; } ZoomType zoomType = getZoomType(); if (ZoomType.HORIZONTAL_AND_VERTICAL == zoomType) { zoomViewport.set(left, top, right, bottom); } else if (ZoomType.HORIZONTAL == zoomType) { zoomViewport.left = left; zoomViewport.right = right; } else if (ZoomType.VERTICAL == zoomType) { zoomViewport.top = top; zoomViewport.bottom = bottom; } } return zoomViewport; } @Override public Viewport getMaximumViewport() { return chartRenderer.getMaximumViewport(); } @Override public void setMaximumViewport(Viewport maxViewport) { chartRenderer.setMaximumViewport(maxViewport); ViewCompat.postInvalidateOnAnimation(this); } @Override public void setCurrentViewportWithAnimation(Viewport targetViewport) { if (null != targetViewport) { viewportAnimator.cancelAnimation(); viewportAnimator.startAnimation(getCurrentViewport(), targetViewport); } ViewCompat.postInvalidateOnAnimation(this); } @Override public void setCurrentViewportWithAnimation(Viewport targetViewport, long duration) { if (null != targetViewport) { viewportAnimator.cancelAnimation(); viewportAnimator.startAnimation(getCurrentViewport(), targetViewport, duration); } ViewCompat.postInvalidateOnAnimation(this); } @Override public Viewport getCurrentViewport() { return getChartRenderer().getCurrentViewport(); } @Override public void setCurrentViewport(Viewport targetViewport) { if (null != targetViewport) { chartRenderer.setCurrentViewport(targetViewport); } ViewCompat.postInvalidateOnAnimation(this); } @Override public void resetViewports() { chartRenderer.setMaximumViewport(null); chartRenderer.setCurrentViewport(null); } @Override public boolean isViewportCalculationEnabled() { return chartRenderer.isViewportCalculationEnabled(); } @Override public void setViewportCalculationEnabled(boolean isEnabled) { chartRenderer.setViewportCalculationEnabled(isEnabled); } @Override public boolean isValueSelectionEnabled() { return touchHandler.isValueSelectionEnabled(); } @Override public void setValueSelectionEnabled(boolean isValueSelectionEnabled) { touchHandler.setValueSelectionEnabled(isValueSelectionEnabled); } @Override public void selectValue(SelectedValue selectedValue) { chartRenderer.selectValue(selectedValue); callTouchListener(); ViewCompat.postInvalidateOnAnimation(this); } @Override public SelectedValue getSelectedValue() { return chartRenderer.getSelectedValue(); } @Override public boolean isContainerScrollEnabled() { return isContainerScrollEnabled; } @Override public void setContainerScrollEnabled(boolean isContainerScrollEnabled, ContainerScrollType containerScrollType) { this.isContainerScrollEnabled = isContainerScrollEnabled; this.containerScrollType = containerScrollType; } protected void onChartDataChange() { chartComputator.resetContentRect(); chartRenderer.onChartDataChanged(); axesRenderer.onChartDataChanged(); ViewCompat.postInvalidateOnAnimation(this); } /** * You should call this method in derived classes, most likely from constructor if you changed chart/axis renderer, * touch handler or chart computator */ protected void resetRendererAndTouchHandler() { this.chartRenderer.resetRenderer(); this.axesRenderer.resetRenderer(); this.touchHandler.resetTouchHandler(); } /** * When embedded in a ViewPager, this will be called in order to know if we can scroll. * If this returns true, the ViewPager will ignore the drag so that we can scroll our content. * If this return false, the ViewPager will assume we won't be able to scroll and will consume the drag * * @param direction Amount of pixels being scrolled (x axis) * @return true if the chart can be scrolled (ie. zoomed and not against the edge of the chart) */ @Override public boolean canScrollHorizontally(int direction) { if (getZoomLevel() <= 1.0) { return false; } final Viewport currentViewport = getCurrentViewport(); final Viewport maximumViewport = getMaximumViewport(); if (direction < 0) { return currentViewport.left > maximumViewport.left; } else { return currentViewport.right < maximumViewport.right; } } }
{ "content_hash": "7d3937dd611f546f6436a43fcaa07050", "timestamp": "", "source": "github", "line_count": 508, "max_line_length": 120, "avg_line_length": 32.50196850393701, "alnum_prop": 0.6742171885409727, "repo_name": "huashengzzz/SmartChart", "id": "f66acef7ebf6156e9e1545b85cf6b2f8bf981d4b", "size": "16511", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/smart/smartchart/widget/hellocharts/view/AbstractChartView.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1066559" } ], "symlink_target": "" }
#ifndef _CONFIG_FAT_SL_H #define _CONFIG_FAT_SL_H #include "../version/ver_fat_sl.h" #if VER_FAT_SL_MAJOR != 5 || VER_FAT_SL_MINOR != 2 #error Incompatible FAT_SL version number! #endif #include "../api/api_mdriver.h" #ifdef __cplusplus extern "C" { #endif /************************************************************************** ** ** FAT SL user settings ** **************************************************************************/ #define F_SECTOR_SIZE 512u /* Disk sector size. */ #define F_FS_THREAD_AWARE 1 /* Set to one if the file system will be access from more than one task. */ #define RTOS_SUPPORT 0 #define F_MAXPATH 64 /* Maximum length a file name (including its full path) can be. */ #define F_MAX_LOCK_WAIT_TICKS 20 /* The maximum number of RTOS ticks to wait when attempting to obtain a lock on the file system when F_FS_THREAD_AWARE is set to 1. */ #ifdef __cplusplus } #endif #endif /* _CONFIG_FAT_SL_H */
{ "content_hash": "0c0e4b9ada40dce37cf77a6dfede66cd", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 172, "avg_line_length": 29.323529411764707, "alnum_prop": 0.5476429287863591, "repo_name": "tipstrying/stm32f10x_makefile_freertos", "id": "b414237173784b35ed1c2039b0789f148f475fc9", "size": "2779", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "fatfs/config/config_fat_sl.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "90358" }, { "name": "C", "bytes": "4194845" }, { "name": "C++", "bytes": "263270" }, { "name": "HTML", "bytes": "28905" }, { "name": "Makefile", "bytes": "8390" }, { "name": "Objective-C", "bytes": "23571" }, { "name": "Shell", "bytes": "101" } ], "symlink_target": "" }
# IMPORTANT: This file is generated by cucumber-rails - edit at your own peril. # It is recommended to regenerate this file in the future when you upgrade to a # newer version of cucumber-rails. Consider adding your own code to a new file # instead of editing this one. Cucumber will automatically load all features/**/*.rb # files. require 'cucumber/rails' # Capybara defaults to CSS3 selectors rather than XPath. # If you'd prefer to use XPath, just uncomment this line and adjust any # selectors in your step definitions to use the XPath syntax. # Capybara.default_selector = :xpath # By default, any exception happening in your Rails application will bubble up # to Cucumber so that your scenario will fail. This is a different from how # your application behaves in the production environment, where an error page will # be rendered instead. # # Sometimes we want to override this default behaviour and allow Rails to rescue # exceptions and display an error page (just like when the app is running in production). # Typical scenarios where you want to do this is when you test your error pages. # There are two ways to allow Rails to rescue exceptions: # # 1) Tag your scenario (or feature) with @allow-rescue # # 2) Set the value below to true. Beware that doing this globally is not # recommended as it will mask a lot of errors for you! # ActionController::Base.allow_rescue = false # Remove/comment out the lines below if your app doesn't have a database. # For some databases (like MongoDB and CouchDB) you may need to use :truncation instead. begin DatabaseCleaner.orm = 'mongoid' DatabaseCleaner.strategy = :truncation rescue NameError raise "You need to add database_cleaner to your Gemfile (in the :test group) if you wish to use it." end # You may also want to configure DatabaseCleaner to use different strategies for certain features and scenarios. # See the DatabaseCleaner documentation for details. Example: # # Before('@no-txn,@selenium,@culerity,@celerity,@javascript') do # # { :except => [:widgets] } may not do what you expect here # # as Cucumber::Rails::Database.javascript_strategy overrides # # this setting. # DatabaseCleaner.strategy = :truncation # end # # Before('~@no-txn', '~@selenium', '~@culerity', '~@celerity', '~@javascript') do # DatabaseCleaner.strategy = :transaction # end # # Possible values are :truncation and :transaction # The :transaction strategy is faster, but might give you threading problems. # See https://github.com/cucumber/cucumber-rails/blob/master/features/choose_javascript_database_strategy.feature Cucumber::Rails::Database.javascript_strategy = :truncation
{ "content_hash": "230c0d50e936063a8992b9e3e4976868", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 113, "avg_line_length": 45.186440677966104, "alnum_prop": 0.7569392348087022, "repo_name": "vkaldi/jserror", "id": "02963b6e6c4a9b7745f6c36628282f1fb3406de0", "size": "2666", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "features/support/env.rb", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "62963" }, { "name": "Ruby", "bytes": "49036" } ], "symlink_target": "" }
import React from 'react' const App = () => ( <h1>🎉 Hello Meetup React &amp; React Native 🎉</h1> ) export default App
{ "content_hash": "e97c05c4bc6b224b6a2671f2f56b3422", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 52, "avg_line_length": 17.428571428571427, "alnum_prop": 0.639344262295082, "repo_name": "etienne-dldc/react-layout-box", "id": "97937e3f59854e8077acbb4ca2aac00408ad5373", "size": "128", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/App.js", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "1137" }, { "name": "JavaScript", "bytes": "14203" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <meta name="lang:clipboard.copy" content="Copy to clipboard"> <meta name="lang:clipboard.copied" content="Copied to clipboard"> <meta name="lang:search.language" content="en"> <meta name="lang:search.pipeline.stopwords" content="True"> <meta name="lang:search.pipeline.trimmer" content="True"> <meta name="lang:search.result.none" content="No matching documents"> <meta name="lang:search.result.one" content="1 matching document"> <meta name="lang:search.result.other" content="# matching documents"> <meta name="lang:search.tokenizer" content="[\s\-]+"> <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin> <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet"> <style> body, input { font-family: "Roboto", "Helvetica Neue", Helvetica, Arial, sans-serif } code, kbd, pre { font-family: "Roboto Mono", "Courier New", Courier, monospace } </style> <link rel="stylesheet" href="../_static/stylesheets/application.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/> <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/> <link rel="stylesheet" href="../_static/fonts/material-icons.css"/> <meta name="theme-color" content="#3f51b5"> <script src="../_static/javascripts/modernizr.js"></script> <title>statsmodels.regression.linear_model.GLS.endog_names &#8212; statsmodels</title> <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png"> <link rel="manifest" href="../_static/icons/site.webmanifest"> <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191"> <meta name="msapplication-TileColor" content="#2b5797"> <meta name="msapplication-config" content="../_static/icons/browserconfig.xml"> <link rel="stylesheet" href="../_static/stylesheets/examples.css"> <link rel="stylesheet" href="../_static/stylesheets/deprecation.css"> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" href="../_static/material.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script src="../_static/jquery.js"></script> <script src="../_static/underscore.js"></script> <script src="../_static/doctools.js"></script> <script crossorigin="anonymous" integrity="sha256-Ae2Vz/4ePdIu6ZyI/5ZGsYnb+m0JlOmKPjt6XZ9JJkA=" src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js"></script> <script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["$", "$"], ["\\(", "\\)"]], "processEscapes": true, "ignoreClass": "document", "processClass": "math|output_area"}})</script> <link rel="shortcut icon" href="../_static/favicon.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.regression.linear_model.GLS.exog_names" href="statsmodels.regression.linear_model.GLS.exog_names.html" /> <link rel="prev" title="statsmodels.regression.linear_model.GLS.df_resid" href="statsmodels.regression.linear_model.GLS.df_resid.html" /> </head> <body dir=ltr data-md-color-primary=indigo data-md-color-accent=blue> <svg class="md-svg"> <defs data-children-count="0"> <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg> </defs> </svg> <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer"> <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search"> <label class="md-overlay" data-md-component="overlay" for="__drawer"></label> <a href="#generated/statsmodels.regression.linear_model.GLS.endog_names" tabindex="1" class="md-skip"> Skip to content </a> <header class="md-header" data-md-component="header"> <nav class="md-header-nav md-grid"> <div class="md-flex navheader"> <div class="md-flex__cell md-flex__cell--shrink"> <a href="../index.html" title="statsmodels" class="md-header-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" height="26" alt="statsmodels logo"> </a> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--menu md-header-nav__button" for="__drawer"></label> </div> <div class="md-flex__cell md-flex__cell--stretch"> <div class="md-flex__ellipsis md-header-nav__title" data-md-component="title"> <span class="md-header-nav__topic">statsmodels v0.12.2</span> <span class="md-header-nav__topic"> statsmodels.regression.linear_model.GLS.endog_names </span> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <label class="md-icon md-icon--search md-header-nav__button" for="__search"></label> <div class="md-search" data-md-component="search" role="dialog"> <label class="md-search__overlay" for="__search"></label> <div class="md-search__inner" role="search"> <form class="md-search__form" action="../search.html" method="GET" name="search"> <input type="text" class="md-search__input" name="q" placeholder="Search" autocapitalize="off" autocomplete="off" spellcheck="false" data-md-component="query" data-md-state="active"> <label class="md-icon md-search__icon" for="__search"></label> <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1"> &#xE5CD; </button> </form> <div class="md-search__output"> <div class="md-search__scrollwrap" data-md-scrollfix> <div class="md-search-result" data-md-component="result"> <div class="md-search-result__meta"> Type to start searching </div> <ol class="md-search-result__list"></ol> </div> </div> </div> </div> </div> </div> <div class="md-flex__cell md-flex__cell--shrink"> <div class="md-header-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> </div> <script src="../_static/javascripts/version_dropdown.js"></script> <script> var json_loc = "../_static/versions.json", target_loc = "../../", text = "Versions"; $( document ).ready( add_version_dropdown(json_loc, target_loc, text)); </script> </div> </nav> </header> <div class="md-container"> <nav class="md-tabs" data-md-component="tabs"> <div class="md-tabs__inner md-grid"> <ul class="md-tabs__list"> <li class="md-tabs__item"><a href="../user-guide.html" class="md-tabs__link">User Guide</a></li> <li class="md-tabs__item"><a href="../regression.html" class="md-tabs__link">Linear Regression</a></li> <li class="md-tabs__item"><a href="statsmodels.regression.linear_model.GLS.html" class="md-tabs__link">statsmodels.regression.linear_model.GLS</a></li> </ul> </div> </nav> <main class="md-main"> <div class="md-main__inner md-grid" data-md-component="container"> <div class="md-sidebar md-sidebar--primary" data-md-component="navigation"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--primary" data-md-level="0"> <label class="md-nav__title md-nav__title--site" for="__drawer"> <a href="../index.html" title="statsmodels" class="md-nav__button md-logo"> <img src="../_static/statsmodels-logo-v2-bw.svg" alt=" logo" width="48" height="48"> </a> <a href="../index.html" title="statsmodels">statsmodels v0.12.2</a> </label> <div class="md-nav__source"> <a href="https://github.com/statsmodels/statsmodels" title="Go to repository" class="md-source" data-md-source="github"> <div class="md-source__icon"> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28"> <use xlink:href="#__github" width="24" height="24"></use> </svg> </div> <div class="md-source__repository"> statsmodels </div> </a> </div> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../install.html" class="md-nav__link">Installing statsmodels</a> </li> <li class="md-nav__item"> <a href="../gettingstarted.html" class="md-nav__link">Getting started</a> </li> <li class="md-nav__item"> <a href="../user-guide.html" class="md-nav__link">User Guide</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../user-guide.html#background" class="md-nav__link">Background</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#regression-and-linear-models" class="md-nav__link">Regression and Linear Models</a> <ul class="md-nav__list"> <li class="md-nav__item"> <a href="../regression.html" class="md-nav__link">Linear Regression</a> </li> <li class="md-nav__item"> <a href="../glm.html" class="md-nav__link">Generalized Linear Models</a> </li> <li class="md-nav__item"> <a href="../gee.html" class="md-nav__link">Generalized Estimating Equations</a> </li> <li class="md-nav__item"> <a href="../gam.html" class="md-nav__link">Generalized Additive Models (GAM)</a> </li> <li class="md-nav__item"> <a href="../rlm.html" class="md-nav__link">Robust Linear Models</a> </li> <li class="md-nav__item"> <a href="../mixed_linear.html" class="md-nav__link">Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../discretemod.html" class="md-nav__link">Regression with Discrete Dependent Variable</a> </li> <li class="md-nav__item"> <a href="../mixed_glm.html" class="md-nav__link">Generalized Linear Mixed Effects Models</a> </li> <li class="md-nav__item"> <a href="../anova.html" class="md-nav__link">ANOVA</a> </li></ul> </li> <li class="md-nav__item"> <a href="../user-guide.html#time-series-analysis" class="md-nav__link">Time Series Analysis</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#other-models" class="md-nav__link">Other Models</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#statistics-and-tools" class="md-nav__link">Statistics and Tools</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#data-sets" class="md-nav__link">Data Sets</a> </li> <li class="md-nav__item"> <a href="../user-guide.html#sandbox" class="md-nav__link">Sandbox</a> </li></ul> </li> <li class="md-nav__item"> <a href="../examples/index.html" class="md-nav__link">Examples</a> </li> <li class="md-nav__item"> <a href="../api.html" class="md-nav__link">API Reference</a> </li> <li class="md-nav__item"> <a href="../about.html" class="md-nav__link">About statsmodels</a> </li> <li class="md-nav__item"> <a href="../dev/index.html" class="md-nav__link">Developer Page</a> </li> <li class="md-nav__item"> <a href="../release/index.html" class="md-nav__link">Release Notes</a> </li> </ul> </nav> </div> </div> </div> <div class="md-sidebar md-sidebar--secondary" data-md-component="toc"> <div class="md-sidebar__scrollwrap"> <div class="md-sidebar__inner"> <nav class="md-nav md-nav--secondary"> <ul class="md-nav__list" data-md-scrollfix=""> <li class="md-nav__item"><a class="md-nav__extra_link" href="../_sources/generated/statsmodels.regression.linear_model.GLS.endog_names.rst.txt">Show Source</a> </li> <li id="searchbox" class="md-nav__item"></li> </ul> </nav> </div> </div> </div> <div class="md-content"> <article class="md-content__inner md-typeset" role="main"> <h1 id="generated-statsmodels-regression-linear-model-gls-endog-names--page-root">statsmodels.regression.linear_model.GLS.endog_names<a class="headerlink" href="#generated-statsmodels-regression-linear-model-gls-endog-names--page-root" title="Permalink to this headline">¶</a></h1> <dl class="py method"> <dt id="statsmodels.regression.linear_model.GLS.endog_names"> <em class="property">property </em><code class="sig-prename descclassname">GLS.</code><code class="sig-name descname">endog_names</code><a class="headerlink" href="#statsmodels.regression.linear_model.GLS.endog_names" title="Permalink to this definition">¶</a></dt> <dd><p>Names of endogenous variables.</p> </dd></dl> </article> </div> </div> </main> </div> <footer class="md-footer"> <div class="md-footer-nav"> <nav class="md-footer-nav__inner md-grid"> <a href="statsmodels.regression.linear_model.GLS.df_resid.html" title="statsmodels.regression.linear_model.GLS.df_resid" class="md-flex md-footer-nav__link md-footer-nav__link--prev" rel="prev"> <div class="md-flex__cell md-flex__cell--shrink"> <i class="md-icon md-icon--arrow-back md-footer-nav__button"></i> </div> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"> <span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Previous </span> statsmodels.regression.linear_model.GLS.df_resid </span> </div> </a> <a href="statsmodels.regression.linear_model.GLS.exog_names.html" title="statsmodels.regression.linear_model.GLS.exog_names" class="md-flex md-footer-nav__link md-footer-nav__link--next" rel="next"> <div class="md-flex__cell md-flex__cell--stretch md-footer-nav__title"><span class="md-flex__ellipsis"> <span class="md-footer-nav__direction"> Next </span> statsmodels.regression.linear_model.GLS.exog_names </span> </div> <div class="md-flex__cell md-flex__cell--shrink"><i class="md-icon md-icon--arrow-forward md-footer-nav__button"></i> </div> </a> </nav> </div> <div class="md-footer-meta md-typeset"> <div class="md-footer-meta__inner md-grid"> <div class="md-footer-copyright"> <div class="md-footer-copyright__highlight"> &#169; Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. </div> Last updated on Feb 02, 2021. <br/> Created using <a href="http://www.sphinx-doc.org/">Sphinx</a> 3.4.3. and <a href="https://github.com/bashtage/sphinx-material/">Material for Sphinx</a> </div> </div> </div> </footer> <script src="../_static/javascripts/application.js"></script> <script>app.initialize({version: "1.0.4", url: {base: ".."}})</script> </body> </html>
{ "content_hash": "472d46bf2ed4a7efcb044bc739088b47", "timestamp": "", "source": "github", "line_count": 490, "max_line_length": 999, "avg_line_length": 36.94489795918367, "alnum_prop": 0.5912279732640999, "repo_name": "statsmodels/statsmodels.github.io", "id": "59ec5c4c379c04375cf4794ff01636d6c3c8e280", "size": "18107", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "v0.12.2/generated/statsmodels.regression.linear_model.GLS.endog_names.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
layout: post100 title: Class Metadata categories: XAP100NET parent: pono-xml-metadata-overview.html weight: 100 --- {% summary %}{% endsummary %} # Name {: .table .table-condensed .table-bordered} |Syntax | name | |Description| Contains the full qualified name of the specified class. Because this attribute is of the XML type `ID`, there can only be one `class-descriptor` per class. | Example: {%highlight xml%} <gigaspaces-mapping> <class name="Model.Person"> </class> </gigaspaces-mapping> {%endhighlight%} # Alias name {: .table .table-condensed .table-bordered} |Syntax | alias-name | |Argument | boolean| |Description| Gives the ability to map a C# class name (including namespace) to a space class name | Example: {%highlight xml%} <gigaspaces-mapping> <class name="Model.Person" alias-name="CommonPerson"> </class> </gigaspaces-mapping> {%endhighlight%} # Persistence {: .table .table-condensed .table-bordered} |Syntax | persist | |Argument | boolean| |Default | false| |Description| This field indicates the persistency mode of the object. When a space is defined as persistent, a `true` value for this attribute will persist objects of this type. | Example: {%highlight xml%} <gigaspaces-mapping> <class name="Model.Person" persist="true"> </class> </gigaspaces-mapping> {%endhighlight%} {%learn%}./space-persistency.html{%endlearn%} # Replication {: .table .table-condensed .table-bordered} |Syntax | replicate | |Argument | boolean| |Default | false| |Description| This field indicates the replication mode of the object. When a space is defined as replicated, a `true` value for this attribute will replicate objects of this type.| Example: {%highlight xml%} <gigaspaces-mapping> <class name="Model.Person" replicate="true"> </class> </gigaspaces-mapping> {%endhighlight%} {%learn%}{%currentadmurl%}/replication.html{%endlearn%} # FIFO Support {: .table .table-condensed .table-bordered} |Syntax | fifo | |Argument | [FifoSupport](http://www.gigaspaces.com/docs/dotnetdocs{%currentversion%}/html/T_GigaSpaces_Core_Metadata_FifoSupport.htm)| |Default | off| |Description| Enabling FIFO operations. | Example: {%highlight xml%} <gigaspaces-mapping> <class name="Model.Person" fifo="operation"> </class> </gigaspaces-mapping> {%endhighlight%} {%learn%}./fifo-support.html{%endlearn%} # Storage Type {: .table .table-condensed .table-bordered} |Syntax | storage-type | |Argument | [StorageType](http://www.gigaspaces.com/docs/dotnetdocs{%currentversion%}/html/T_GigaSpaces_Core_Metadata_StorageType.htm)| |Default | object | |Description| To determine a default storage type for each non primitive property for which a (field level) storage type was not defined.| Example: {%highlight xml%} <gigaspaces-mapping> <class name="Model.Person" storage-type="binary" /> </gigaspaces-mapping> {%endhighlight%} {%learn%}./poco-storage-type.html{%endlearn%} {%comment%} # Include Properties {: .table .table-condensed .table-bordered} |Syntax | include-properties | |Argument | [IncludeProperties](http://www.gigaspaces.com/docs/dotnetdocs{%currentversion%}/html/T_GigaSpaces_Core_Metadata_IncludeMembers.htm) | |Default | all| |Description| `implicit` takes into account all PONO fields -- even if a `get` method is not declared as a `SpaceProperty`, it is taken into account as a space field.`explicit` takes into account only the `get` methods which are declared in the mapping file. | Example: {%highlight xml%} <gigaspaces-mapping> <class name="Model.Person" include-properties="public" /> </gigaspaces-mapping> {%endhighlight%} {%endcomment%} # Inherit Index {: .table .table-condensed .table-bordered} |Syntax | inherit-indexes | |Argument | boolean | |Default | true| |Description| Whether to use the class indexes list only, or to also include the superclass' indexes. {% wbr %}If the class does not define indexes, superclass indexes are used. {% wbr %}Options:{% wbr %}- `false` -- class indexes only.{% wbr %}- `true` -- class indexes and superclass indexes.| Example: {%highlight xml%} <gigaspaces-mapping> <class name="Model.Person" inherit-indexes="false" /> </gigaspaces-mapping> {%endhighlight%} {%learn%}./indexing.html{%endlearn%} # Compound Index {: .table .table-condensed .table-bordered} |Syntax | compound-index paths | |Argument(s)| string | |Values | attribute name(s) | |Description| Indexes can be defined for multiple properties of a class | Example: {%highlight xml%} <gigaspaces-mapping> <class name="Data" > <compound-index paths="Data1, Data2"/> ... </class> </gigaspaces-mapping> {%endhighlight%} {%learn%}./indexing-compound.html{%endlearn%}
{ "content_hash": "aad1c2639929cfa847b29b38c5be9028", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 295, "avg_line_length": 25.69148936170213, "alnum_prop": 0.7024844720496894, "repo_name": "yohanakh/gigaspaces-wiki-jekyll", "id": "1f80fa3d27c280acd477a746c022179b6922d6b3", "size": "4834", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "xap100net/pono-xml-metadata-class.markdown", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "483" }, { "name": "C#", "bytes": "24326" }, { "name": "CSS", "bytes": "384026" }, { "name": "HTML", "bytes": "139381" }, { "name": "JavaScript", "bytes": "84963" }, { "name": "Ruby", "bytes": "59966" } ], "symlink_target": "" }
using MagicalLifeGUIWindows.GUI.Reusable; using MagicalLifeGUIWindows.Input; using System.Collections.Generic; namespace MagicalLifeGUIWindows.GUI { /// <summary> /// Handles transitioning between menus. /// </summary> public static class MenuHandler { private static int DisplayIndex = -1; /// <summary> /// The menus that we are currently handling. /// Containers[0] is the very first menu showed /// Containers[x] is the latest menu showed. /// </summary> private static List<GuiContainer> Containers = new List<GuiContainer>(); /// <summary> /// Displays the menu/popup. /// <paramref name="ignore"/>A container to not clear when popping up a new one, such as the in game escape menu.<paramref name="ignore"/> /// </summary> /// <param name="container"></param> public static void DisplayMenu(GuiContainer container) { BoundHandler.Popup(container); Containers.Add(container); DisplayIndex = Containers.Count - 1; } /// <summary> /// Displays the last shown menu. /// </summary> public static void Back() { if (DisplayIndex > 0 && Containers[DisplayIndex].Child == null) { DisplayIndex--; BoundHandler.Popup(Containers[DisplayIndex]); } else { NullChild(BoundHandler.GUIWindows[DisplayIndex]); } } private static void NullChild(GuiContainer container) { if (container.Child == null) { if (DisplayIndex > 0) { BoundHandler.GUIWindows.Remove(container); } } else { if (container.Child.Child == null) { container.Child = null; } else { NullChild(container.Child); } } } /// <summary> /// Clears all menu steps previously stored. /// <paramref name="ignore"/>A container to not clear, such as the in game GUI.<paramref name="ignore"/> /// </summary> public static void Clear() { BoundHandler.GUIWindows.RemoveAll(x => !x.IsHUD); Containers.Clear(); } } }
{ "content_hash": "b3c82a6ca13fd5f5d8515b823dfa3af3", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 154, "avg_line_length": 30.82716049382716, "alnum_prop": 0.5122146575891069, "repo_name": "SneakyTactician/EarthWithMagic", "id": "98c92714444e6586205f4957a145c63f99dff7c6", "size": "2499", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MonoGUI/MonoGUI/MenuHandler.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "199386" } ], "symlink_target": "" }
<?php namespace Oro\Bundle\UserBundle\Tests\Unit\Validator; use Doctrine\Common\Persistence\ManagerRegistry; use Doctrine\ORM\EntityManagerInterface; use Oro\Bundle\DataGridBundle\Tools\DatagridRouteHelper; use Oro\Bundle\FilterBundle\Form\Type\Filter\TextFilterType; use Oro\Bundle\FilterBundle\Grid\Extension\AbstractFilterExtension; use Oro\Bundle\UserBundle\Entity\Repository\UserRepository; use Oro\Bundle\UserBundle\Entity\User; use Oro\Bundle\UserBundle\Validator\Constraints\EmailCaseInsensitiveOptionConstraint; use Oro\Bundle\UserBundle\Validator\EmailCaseInsensitiveOptionValidator; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\Context\ExecutionContextInterface; use Symfony\Component\Validator\Exception\UnexpectedTypeException; use Symfony\Component\Validator\Violation\ConstraintViolationBuilderInterface; use Symfony\Contracts\Translation\TranslatorInterface; class EmailCaseInsensitiveOptionValidatorTest extends \PHPUnit\Framework\TestCase { /** @var UserRepository|\PHPUnit\Framework\MockObject\MockObject */ private $userRepository; /** @var TranslatorInterface|\PHPUnit\Framework\MockObject\MockObject */ private $translator; /** @var DatagridRouteHelper|\PHPUnit\Framework\MockObject\MockObject */ private $datagridRouteHelper; /** @var EmailCaseInsensitiveOptionValidator */ private $validator; /** @var EmailCaseInsensitiveOptionConstraint */ private $constraint; /** @var ConstraintViolationBuilderInterface|\PHPUnit\Framework\MockObject\MockObject */ private $violationBuilder; /** @var ExecutionContextInterface|\PHPUnit\Framework\MockObject\MockObject */ private $executionContext; protected function setUp() { $this->userRepository = $this->createMock(UserRepository::class); $doctrine = $this->createMock(ManagerRegistry::class); $em = $this->createMock(EntityManagerInterface::class); $doctrine->expects($this->any()) ->method('getManagerForClass') ->with(User::class) ->willReturn($em); $em->expects($this->any()) ->method('getRepository') ->with(User::class) ->willReturn($this->userRepository); $this->translator = $this->createMock(TranslatorInterface::class); $this->datagridRouteHelper = $this->createMock(DatagridRouteHelper::class); $this->validator = new EmailCaseInsensitiveOptionValidator( $doctrine, $this->translator, $this->datagridRouteHelper ); $this->constraint = new EmailCaseInsensitiveOptionConstraint(); $this->violationBuilder = $this->createMock(ConstraintViolationBuilderInterface::class); $this->violationBuilder->expects($this->any())->method('setInvalidValue')->willReturnSelf(); $this->violationBuilder->expects($this->any())->method('addViolation')->willReturnSelf(); $this->executionContext = $this->createMock(ExecutionContextInterface::class); } public function testValidateExceptions() { $this->expectException(UnexpectedTypeException::class); $this->expectExceptionMessage( sprintf('Expected argument of type "%s"', EmailCaseInsensitiveOptionConstraint::class) ); /** @var Constraint $constraint */ $constraint = $this->createMock(Constraint::class); $this->validator->initialize($this->executionContext); $this->validator->validate('', $constraint); } /** * @dataProvider validateValidDataProvider * * @param bool $value * @param bool $isCaseInsensitiveCollation * @param array $emails */ public function testValidateValid(bool $value, bool $isCaseInsensitiveCollation, array $emails) { $this->userRepository->expects($this->any()) ->method('isCaseInsensitiveCollation') ->willReturn($isCaseInsensitiveCollation); $this->userRepository->expects($this->any()) ->method('findLowercaseDuplicatedEmails') ->with(10) ->willReturn($emails); $this->executionContext->expects($this->never()) ->method('buildViolation'); $this->validator->initialize($this->executionContext); $this->validator->validate($value, $this->constraint); } /** * @return array */ public function validateValidDataProvider() { return [ [ 'value' => false, 'isCaseInsensitiveCollation' => false, 'emails' => [] ], [ 'value' => true, 'isCaseInsensitiveCollation' => false, 'emails' => [] ], [ 'value' => true, 'isCaseInsensitiveCollation' => true, 'emails' => [] ], ]; } public function testValidateInvalidCaseInsensitive() { $this->userRepository->expects($this->once()) ->method('isCaseInsensitiveCollation') ->willReturn(true); $this->userRepository->expects($this->never()) ->method('findLowercaseDuplicatedEmails'); $this->datagridRouteHelper->expects($this->never()) ->method('generate'); $this->translator->expects($this->never()) ->method('trans'); $this->executionContext->expects($this->once()) ->method('buildViolation') ->with($this->constraint->collationMessage) ->willReturn($this->violationBuilder); $this->validator->initialize($this->executionContext); $this->validator->validate(false, $this->constraint); } public function testValidateInvalidDuplicatedEmails() { $this->userRepository->expects($this->never()) ->method('isCaseInsensitiveCollation'); $this->userRepository->expects($this->once()) ->method('findLowercaseDuplicatedEmails') ->with(10) ->willReturn(['[email protected]']); $this->datagridRouteHelper->expects($this->once()) ->method('generate') ->with( 'oro_user_index', 'users-grid', [ AbstractFilterExtension::MINIFIED_FILTER_PARAM => [ 'email' => [ 'type' => TextFilterType::TYPE_IN, 'value' => implode(',', ['[email protected]']), ] ] ] ) ->willReturn('some/link/to/grid'); $this->translator->expects($this->once()) ->method('trans') ->with($this->constraint->duplicatedEmailsClickHere, [], 'validators') ->willReturnArgument(0); $this->executionContext->expects($this->once()) ->method('buildViolation') ->with($this->constraint->duplicatedEmailsMessage) ->willReturn($this->violationBuilder); $this->violationBuilder->expects($this->once()) ->method('setParameters') ->with( [ '%click_here%' => sprintf( '<a href="some/link/to/grid">%s</a>', $this->constraint->duplicatedEmailsClickHere ) ] ) ->willReturnSelf(); $this->validator->initialize($this->executionContext); $this->validator->validate(true, $this->constraint); } }
{ "content_hash": "9e37ab6084542407e4426d46435916e9", "timestamp": "", "source": "github", "line_count": 214, "max_line_length": 100, "avg_line_length": 35.63551401869159, "alnum_prop": 0.6072646210333071, "repo_name": "orocrm/platform", "id": "6a0ae4a8c574d4209c1dde3b121f69cd913bbc4f", "size": "7626", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Oro/Bundle/UserBundle/Tests/Unit/Validator/EmailCaseInsensitiveOptionValidatorTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "618485" }, { "name": "Gherkin", "bytes": "158217" }, { "name": "HTML", "bytes": "1648915" }, { "name": "JavaScript", "bytes": "3326127" }, { "name": "PHP", "bytes": "37828618" } ], "symlink_target": "" }
import java.util.ArrayList; public class Partie { private ArrayList<Carte> cards = new ArrayList<Carte>(); private ArrayList<Carte> cards_on_table = new ArrayList<Carte>(); private Joueur player1; private Joueur player2; public Partie (Joueur player1, Joueur player2){ this.player1 = player1; this.player2 = player2; cards_factory(); shuffling(); dealing(); } public void comment (String c){ System.out.println(c); } public void shuffling(){ int n = this.cards.size(); for (int i = 0; i < n; i++) { int r = i + (int) (Math.random() * (n-i)); Carte tmp = this.cards.get(i); // tampon this.cards.set(i,this.cards.get(r)) ; this.cards.set(r,tmp); } }; public void cards_factory(){ int values[] = {1,2,3,4,5,6,7,8,9,10,11,12,13}; String colors[] = {"coeur","carreau","trefle","pique"}; for (int i = 0; i<colors.length; i++){ for (int j = 0; j<values.length; j++){ Carte x = new Carte (values[j],colors[i]); this.cards.add(x); } } }; public void dealing(){ for (int i = 0; i < this.cards.size(); i++) { if (i % 2 == 0) this.player1.take_card(this.cards.get(i)); else this.player2.take_card(this.cards.get(i)); } }; public void playing(){ // on demmarre le jeu String winner = ""; boolean game_won = false; boolean game_too_long = false; boolean bataille = false; int round_number = 0;// numéro de tours int max_depth = 0; // depth max int memo_best_round = 0; // mémoire du meilleur tour while(game_won == false && game_too_long == false){ round_number++; comment("Tour n°"+Integer.toString(round_number)+""); // les joueurs tirent chacun une carte this.cards_on_table.add(this.player1.give_card()); comment(this.player1.name()+" joue "+this.cards_on_table.get(this.cards_on_table.size()-1).read()+""); this.cards_on_table.add(this.player2.give_card()); comment(this.player2.name()+" joue "+this.cards_on_table.get(this.cards_on_table.size()-1).read()+""); // on compare les cartes if(this.cards_on_table.get(this.cards_on_table.size()-1).greater_than(this.cards_on_table.get(this.cards_on_table.size()-2))){ winner = this.player2.name(); // this.player2 est le dernier à jouer et sa carte est superieure } else if (this.cards_on_table.get(this.cards_on_table.size()-1).lower_than(this.cards_on_table.get(this.cards_on_table.size()-2))){ winner = this.player1.name(); // this.player2 est le dernier à jouer et sa carte est inferieure } else { // Bataille ! bataille=true; int p = 0; while(bataille){ p++; if(p>max_depth) { // on garde au moins le premier des meilleurs tours en mémoire (meilleur tour = plus grande profondeur) max_depth=p; memo_best_round=round_number; } String depth =""; for (int i = 0;i<p;i++) { depth+="\t"; } comment(depth+"Bataille !"); if(this.player2.show_hand().size()>1 && this.player1.show_hand().size()>1){ this.cards_on_table.add(this.player1.give_card()); comment(depth+this.player1.name()+" cache une carte "+this.cards_on_table.get(this.cards_on_table.size()-1).read()+""); this.cards_on_table.add(this.player2.give_card()); comment(depth+this.player2.name()+" cache une carte "+this.cards_on_table.get(this.cards_on_table.size()-1).read()+""); this.cards_on_table.add(this.player1.give_card()); comment(depth+this.player1.name()+" joue "+this.cards_on_table.get(this.cards_on_table.size()-1).read()+""); this.cards_on_table.add(this.player2.give_card()); comment(depth+this.player2.name()+" joue "+this.cards_on_table.get(this.cards_on_table.size()-1).read()+""); // on compare les cartes if(this.cards_on_table.get(this.cards_on_table.size()-1).greater_than(this.cards_on_table.get(this.cards_on_table.size()-2))){ winner = this.player2.name(); // this.player2 est le dernier à jouer et sa carte est superieure bataille=false; } else if (this.cards_on_table.get(this.cards_on_table.size()-1).lower_than(this.cards_on_table.get(this.cards_on_table.size()-2))){ winner = this.player1.name(); // this.player2 est le dernier à jouer et sa carte est inferieure bataille=false; } else { bataille=true; } } else { // un des deux joueurs n'a plus assez de cartes pour jouer // alors il donne gentillement la carte qu'il lui reste if(this.player2.show_hand().size()==1){ this.cards_on_table.add(this.player2.give_card()); comment(depth+this.player2.name()+" n'a plus qu'une seule carte, un "+this.cards_on_table.get(this.cards_on_table.size()-1).read()); comment( " qu'il donne gentillement à "+this.player1.name()+"."); winner = this.player1.name(); } else if(this.player1.show_hand().size()==1){ this.cards_on_table.add(this.player1.give_card()); comment(depth+this.player1.name()+" n'a plus qu'une seule carte, un "+this.cards_on_table.get(this.cards_on_table.size()-1).read()); comment( " qu'il donne gentillement à"+this.player2.name()+"."); winner = this.player2.name(); } else if(this.player2.show_hand().size()==0){ this.cards_on_table.add(this.player2.give_card()); comment(depth+"Mais "+this.player2.name()+" n'a plus de carte ! Pas de carte, pas de bataille possible ! "); winner =this.player1.name(); } else if(this.player1.show_hand().size()==0){ this.cards_on_table.add(this.player1.give_card()); comment(depth+"Mais "+this.player1.name()+" n'a plus de carte ! Pas de carte, pas de bataille possible ! "); winner = this.player2.name(); } bataille = false; } } } comment( winner + " emporte ce pli."); if (winner.equals(this.player1.name())){ while (this.cards_on_table.size()!=0){ this.player1.take_card(this.cards_on_table.get(0)); this.cards_on_table.remove(0); } } else if (winner.equals(this.player2.name())){ while (this.cards_on_table.size()!=0){ this.player2.take_card(this.cards_on_table.get(0)); this.cards_on_table.remove(0); } } if (this.player2.show_hand().size() == 0) { comment("\nHolala ! "+this.player2.name()+" n'a plus de carte !"); comment(this.player1.name()+" est le gagnant !"); game_won = true; } else if (this.player1.show_hand().size() == 0){ comment("Holala ! "+this.player1.name()+" n'a plus de carte !"); comment(this.player2.name()+" est le gagnant !"); game_won = true; } else{ comment("("+this.player1.name()+" "+this.player1.show_hand().size()+" cartes, "+this.player2.name()+" "+this.player2.show_hand().size()+" cartes)\n"); } if(round_number >=50000 && game_won == false){ game_too_long = true; comment("La partie est trop longue, et il n'y a plus rien à boire !"); if (this.player1.show_hand().size()>this.player2.show_hand().size()){ comment(this.player2.name()+" concède la victoire à "+this.player1.name()+" "+this.player1.show_hand().size()+" à "+this.player2.show_hand().size()+" !"); }else if (this.player2.show_hand().size()>this.player1.show_hand().size()){ comment(this.player1.name()+" concède la victoire à "+this.player2.name()+" "+this.player2.show_hand().size()+" à "+this.player1.show_hand().size()+" !"); }else{ comment("Les deux compétiteurs se réjouissent de terminer sur un match nul "+this.player2.show_hand().size()+" à "+this.player1.show_hand().size()+" !"); } } } if(memo_best_round>0 && max_depth>1) comment("Le plus beau tour a été le n°"+memo_best_round+" avec "+max_depth+" batailles imbriquées."); }; };
{ "content_hash": "e39f9426e14fb02534a30ec9b97c5977", "timestamp": "", "source": "github", "line_count": 183, "max_line_length": 159, "avg_line_length": 42.442622950819676, "alnum_prop": 0.6196729754087807, "repo_name": "zegilooo/Java-01-Bataille", "id": "f47c9157675488aabb629800872edc6e30fb70e5", "size": "7791", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Partie.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "9774" } ], "symlink_target": "" }
var settings = { level : undefined } //end all of output var close = function(){ settings.level = Number.MAX_VALUE; } //dynamically change the log level, all of output var setLevel = function(level){ settings.level = level; } exports.settings = settings; exports.close = close; exports.setLevel = setLevel;
{ "content_hash": "af59ae79a7260148273b2ef52132cb5e", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 49, "avg_line_length": 16.526315789473685, "alnum_prop": 0.7197452229299363, "repo_name": "jungho-shin/rms", "id": "9eef1ecdfd3aa073f74182c966e5452fd5b7f91a", "size": "314", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "node_modules/tracer/lib/settings.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "3868087" }, { "name": "HTML", "bytes": "7480" }, { "name": "JavaScript", "bytes": "5075322" } ], "symlink_target": "" }
<ServerManagerConfiguration> <ProxyGroup name="representations"> <RepresentationProxy name="StreamingContourRepresentation" class="vtkStreamingContourRepresentation" processes="client|renderserver|dataserver"> <Documentation> This is the new representation type we are adding. </Documentation> <InputProperty command="SetInputConnection" name="Input"> <DataTypeDomain name="input_type"> <DataType value="vtkImageData" /> </DataTypeDomain> <InputArrayDomain attribute_type="any" name="input_array_any"> </InputArrayDomain> <Documentation>Set the input to the representation.</Documentation> </InputProperty> <DoubleVectorProperty command="SetPointSize" default_values="2.0" name="PointSize" number_of_elements="1"> <DoubleRangeDomain min="0" name="range" /> </DoubleVectorProperty> <DoubleVectorProperty command="SetContourValue" default_values="90" name="ContourValue" number_of_elements="1"> </DoubleVectorProperty> <StringVectorProperty command="SetInputArrayToProcess" element_types="0 0 0 0 2" name="ColorArrayName" number_of_elements="5"> <Documentation> Set the array to color with. One must specify the field association and the array name of the array. If the array is missing, scalar coloring will automatically be disabled. </Documentation> <RepresentedArrayListDomain name="array_list" input_domain_name="input_array_any"> <RequiredProperties> <Property function="Input" name="Input" /> </RequiredProperties> </RepresentedArrayListDomain> <FieldDataDomain name="field_list" disable_update_domain_entries="1" force_point_cell_data="1"> <RequiredProperties> <Property function="Input" name="Input" /> </RequiredProperties> </FieldDataDomain> </StringVectorProperty> <ProxyProperty command="SetLookupTable" name="LookupTable" skip_dependency="1"> <Documentation>Set the lookup-table to use to map data array to colors. Lookuptable is only used with MapScalars to ON.</Documentation> <ProxyGroupDomain name="groups"> <Group name="lookup_tables" /> </ProxyGroupDomain> </ProxyProperty> <DoubleVectorProperty command="SetOpacity" default_values="1.0" name="Opacity" number_of_elements="1"> <DoubleRangeDomain max="1" min="0" name="range" /> </DoubleVectorProperty> <!-- End of StreamingContourRepresentation --> </RepresentationProxy> <RepresentationProxy name="StreamingThresholdRepresentation" class="vtkStreamingThresholdRepresentation" processes="client|renderserver|dataserver"> <Documentation> This is the new representation type we are adding. </Documentation> <InputProperty command="SetInputConnection" name="Input"> <DataTypeDomain name="input_type"> <DataType value="vtkImageData" /> </DataTypeDomain> <InputArrayDomain attribute_type="any" name="input_array_any"> </InputArrayDomain> <Documentation>Set the input to the representation.</Documentation> </InputProperty> <DoubleVectorProperty command="SetContourValue" default_values="90" name="ContourValue" number_of_elements="1"> </DoubleVectorProperty> <DoubleVectorProperty command="SetPointSize" default_values="2.0" name="PointSize" number_of_elements="1"> <DoubleRangeDomain min="0" name="range" /> </DoubleVectorProperty> <StringVectorProperty command="SetInputArrayToProcess" element_types="0 0 0 0 2" name="ColorArrayName" number_of_elements="5"> <Documentation> Set the array to color with. One must specify the field association and the array name of the array. If the array is missing, scalar coloring will automatically be disabled. </Documentation> <RepresentedArrayListDomain name="array_list" input_domain_name="input_array_any"> <RequiredProperties> <Property function="Input" name="Input" /> </RequiredProperties> </RepresentedArrayListDomain> <FieldDataDomain name="field_list" disable_update_domain_entries="1" force_point_cell_data="1"> <RequiredProperties> <Property function="Input" name="Input" /> </RequiredProperties> </FieldDataDomain> </StringVectorProperty> <ProxyProperty command="SetLookupTable" name="LookupTable" skip_dependency="1"> <Documentation>Set the lookup-table to use to map data array to colors. Lookuptable is only used with MapScalars to ON.</Documentation> <ProxyGroupDomain name="groups"> <Group name="lookup_tables" /> </ProxyGroupDomain> </ProxyProperty> <DoubleVectorProperty command="SetOpacity" default_values="1.0" name="Opacity" number_of_elements="1"> <DoubleRangeDomain max="1" min="0" name="range" /> </DoubleVectorProperty> <!-- End of StreamingThresholdRepresentation --> </RepresentationProxy> <Extension name="UniformGridRepresentation"> <Documentation> Extends standard UniformGridRepresentation by adding StreamingContourRepresentation and StreamingThresholdRepresentation as new type of representation. </Documentation> <!-- this adds to what is already defined in PVRepresentationBase --> <RepresentationType subproxy="StreamingContourRepresentation" text="Streaming Contour" /> <SubProxy> <Proxy name="StreamingContourRepresentation" proxygroup="representations" proxyname="StreamingContourRepresentation"> </Proxy> <ShareProperties subproxy="SurfaceRepresentation"> <Exception name="Input" /> <Exception name="Visibility" /> </ShareProperties> <ExposedProperties> <Property name="ContourValue" /> </ExposedProperties> </SubProxy> <RepresentationType subproxy="StreamingThresholdRepresentation" text="Streaming Threshold" /> <SubProxy> <Proxy name="StreamingThresholdRepresentation" proxygroup="representations" proxyname="StreamingThresholdRepresentation"> </Proxy> <ShareProperties subproxy="SurfaceRepresentation"> <Exception name="Input" /> <Exception name="Visibility" /> </ShareProperties> <!-- <ExposedProperties> <Property name="ContourValue" /> </ExposedProperties> --> </SubProxy> </Extension> </ProxyGroup> </ServerManagerConfiguration>
{ "content_hash": "d2908a63c5f6f1aa3c644b583e071d5f", "timestamp": "", "source": "github", "line_count": 191, "max_line_length": 84, "avg_line_length": 40.78534031413613, "alnum_prop": 0.5817715019255456, "repo_name": "Hovden/tomviz", "id": "78928b4e5c38ad1c7b73d7612373d4338a70f301", "size": "7790", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "tomviz/dax/TomVizStreaming.xml", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C++", "bytes": "520732" }, { "name": "CMake", "bytes": "14109" }, { "name": "Python", "bytes": "20637" } ], "symlink_target": "" }
package de.fau.cs.osr.utils.visitor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; import de.fau.cs.osr.utils.StringTools; public abstract class VisitorStackController<T> { public static boolean DEBUG = false; private static final String VISIT_METHOD_NAME = "visit"; private static final Class<?> BATON_CLASS = Baton.class; private static final Map<String, Cache> CACHES = new HashMap<String, Cache>(); // ========================================================================= public static <S> Cache getOrRegisterCache( String name, List<? extends StackedVisitorInterface<S>> visitorStack) throws IncompatibleVisitorStackDefinition { return getOrRegisterCache(name, visitorStack, .6f, 256, 384); } public static synchronized <S> Cache getOrRegisterCache( String name, List<? extends StackedVisitorInterface<S>> visitorStack, float loadFactor, int lowerCapacity, int upperCapacity) throws IncompatibleVisitorStackDefinition { Cache cache = CACHES.get(name); if (cache == null) { cache = new Cache(visitorStack, loadFactor, lowerCapacity, upperCapacity); CACHES.put(name, cache); } else { cache.verifyDefinition(visitorStack); } return cache; } public static synchronized boolean dropCache(String name) { return (CACHES.remove(name) != null); } // ========================================================================= private final Cache cache; private StackedVisitorInterface<T>[] visitorStack; private StackedVisitorInterface<T>[] enabledVisitors; private Baton baton; // ========================================================================= protected VisitorStackController( String cacheName, List<? extends StackedVisitorInterface<T>> visitorStack) throws IncompatibleVisitorStackDefinition { this(getOrRegisterCache(cacheName, visitorStack), visitorStack); } protected VisitorStackController( Cache cache, List<? extends StackedVisitorInterface<T>> visitorStack) throws IncompatibleVisitorStackDefinition { for (StackedVisitorInterface<T> visitor : visitorStack) { if (visitor == null) throw new NullPointerException("Visitor stack contains <null>s"); } @SuppressWarnings({ "unchecked", "rawtypes" }) int tmp = new HashSet(visitorStack).size(); if (tmp != visitorStack.size()) throw new IllegalArgumentException("Visitor stack contains duplicates!"); cache.verifyDefinition(visitorStack); @SuppressWarnings({ "unchecked" }) StackedVisitorInterface<T>[] stackArray = new StackedVisitorInterface[visitorStack.size()]; this.cache = cache; this.visitorStack = visitorStack.toArray(stackArray); this.enabledVisitors = Arrays.copyOf(this.visitorStack, this.visitorStack.length); } // ========================================================================= public int indexOfVisitor(StackedVisitorInterface<T> visitor) { for (int i = 0; i < visitorStack.length; ++i) { if (visitorStack[i] == visitor) return i; } return -1; } public void setVisitor(int i, StackedVisitorInterface<T> visitor) { if (visitor == null) throw new NullPointerException(); if (cache.cacheDef.visitorStackDef[i] != visitor.getClass()) throw new IllegalArgumentException("Replacement visitor's class does not matched the replaced visitor's class"); visitorStack[i] = visitor; if (isVisitorEnabled(i)) enabledVisitors[i] = visitor; } public StackedVisitorInterface<T> getVisitor(int i) { return visitorStack[i]; } public StackedVisitorInterface<T> getEnabledVisitor(int i) { return enabledVisitors[i]; } public boolean isVisitorEnabled(int i) { return (getEnabledVisitor(i) != null); } public void disableVisitor(int i) { enabledVisitors[i] = null; } public void enableVisitor(int i) { enabledVisitors[i] = visitorStack[i]; } public void setVisitorEnabled(int i, boolean enable) { if (enable) enableVisitor(i); else disableVisitor(i); } // ========================================================================= /** * Start visitation at the given node. * * @param node * The node at which the visitation will start. * @return The result of the visitation. If the visit() method for the given * node doesn't return a value, <code>null</code> is returned. */ public Object go(T node) { T startNode = (T) before(node); this.baton = new Baton(); Object result = resolveAndVisit(startNode); return after(node, result); } protected T before(T node) { T transformed = node; for (int i = 0; i < visitorStack.length; ++i) { if (isVisitorEnabled(i)) { T result = getEnabledVisitor(i).before(transformed); if (result == null) { disableVisitor(i); } else { transformed = result; } } } return transformed; } protected Object after(T node, Object result) { for (int i = 0; i < visitorStack.length; ++i) { if (isVisitorEnabled(i)) result = getEnabledVisitor(i).after(node, result); } return result; } // ========================================================================= protected abstract Object visitNotFound(T node); protected Object handleVisitingException(T node, Throwable cause) { throw new VisitingException(node, cause); } // ========================================================================= protected Object resolveAndVisit(T node) { Class<?> nClass = node.getClass(); VisitChain key = new VisitChain(nClass); VisitChain visiChain = cache.get(key); try { if (visiChain == null) { visiChain = buildVisitChain(key); cache.put(visiChain); } if (visiChain.isEmpty()) { return visitNotFound(node); } else { return visiChain.invokeChain(baton, this, node); } } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof VisitingException) throw (VisitingException) cause; return handleVisitingException(node, cause); } catch (VisitingException e) { throw e; } catch (VisitNotFoundException e) { throw e; } catch (Exception e) { throw new VisitorException(node, e); } } private VisitChain buildVisitChain(VisitChain key) throws SecurityException, NoSuchMethodException { Class<?> nClass = key.getNodeClass(); List<Link> chain = new ArrayList<Link>(); for (int i = 0; i < visitorStack.length; ++i) { Class<?> vClass = visitorStack[i].getClass(); Method method = findVisit(vClass, nClass); if (method != null) chain.add(new Link(i, method)); } return new VisitChain(key, chain); } private static Method findVisit(final Class<?> vClass, final Class<?> nClass) throws NoSuchMethodException, SecurityException { Method method = null; List<Class<?>> candidates = new ArrayList<Class<?>>(); // Do a breadth first search in the hierarchy Queue<Class<?>> work = new ArrayDeque<Class<?>>(); work.add(nClass); while (!work.isEmpty()) { Class<?> workItem = work.remove(); try { method = vClass.getMethod(VISIT_METHOD_NAME, BATON_CLASS, workItem); candidates.add(workItem); } catch (NoSuchMethodException e) { // Consider non-interface classes first Class<?> superclass = workItem.getSuperclass(); if (superclass != null) work.add(superclass); for (Class<?> i : workItem.getInterfaces()) work.add(i); } } if (!candidates.isEmpty()) { Collections.sort(candidates, new Comparator<Class<?>>() { @Override public int compare(Class<?> arg0, Class<?> arg1) { if (arg0 == arg1) { return 0; } else if (arg0.isAssignableFrom(arg1)) { return +1; } else if (arg1.isAssignableFrom(arg0)) { return -1; } else { throw new MultipleVisitMethodsMatchException(vClass, nClass, arg0, arg1); } } }); method = vClass.getMethod(VISIT_METHOD_NAME, BATON_CLASS, candidates.get(0)); } return method; } // ========================================================================= protected static final class VisitChain implements Comparable<VisitChain> { private static long useCounter = 0; private long lastUse = -1; private final Class<?> nodeClass; private final Link[] chain; public VisitChain(Class<?> nClass) { this.nodeClass = nClass; this.chain = null; } public VisitChain(VisitChain chain, List<Link> links) { this.nodeClass = chain.nodeClass; this.chain = links.toArray(new Link[links.size()]); } public Class<?> getNodeClass() { return nodeClass; } public boolean isEmpty() { return (chain.length == 0); } @SuppressWarnings({ "rawtypes" }) public Object invokeChain( Baton baton, VisitorStackController controller, Object node) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException { touch(); // this method must only be called on non-empty chains if (isEmpty()) throw new AssertionError(); Object visitNext = node; // If there are no enabled visitors just return the node itself Object result = node; StackedVisitorInterface[] enabledVisitors = controller.enabledVisitors; int i = 0; chainIter: while (true) { StackedVisitorInterface visitor = enabledVisitors[chain[i].visitorIndex]; if (visitor != null) { if (DEBUG) System.err.println(chain[i].method + ": " + StringTools.crop(visitNext.toString(), 32)); result = chain[i].method.invoke(visitor, baton, visitNext); // We must always query the code to reset it, even if result == null int batonCode = baton.queryAndResetCode(); if (result == null) break chainIter; switch (batonCode) { case Baton.REDISPATCH: // Re-dispatch if instance of nodeClass if (nodeClass.isInstance(result)) result = redispatch(controller, result); // Leave chain break chainIter; case Baton.CONTINUE_SAME_TYPE_OR_REDISPATCH: if (node.getClass() != result.getClass()) { // Re-dispatch if instance of nodeClass if (nodeClass.isInstance(result)) result = redispatch(controller, result); // Leave chain break chainIter; } else { // Continue to next visitor break; } case Baton.CONTINUE_ASSIGNABLE_TYPE_OR_REDISPATCH: if (!node.getClass().isInstance(result)) { // Re-dispatch if instance of nodeClass if (nodeClass.isInstance(result)) result = redispatch(controller, result); // Leave chain break chainIter; } else { // Continue to next visitor break; } case Baton.CONTINUE_SAME_REF: if (visitNext != result) { // Leave chain break chainIter; } else { // Continue to next visitor break; } case Baton.CONTINUE_SAME_TYPE: if (node.getClass() != result.getClass()) { // Leave chain break chainIter; } else { // Continue to next visitor break; } case Baton.CONTINUE_ASSIGNABLE_TYPE: if (!node.getClass().isInstance(result)) { // Leave chain break chainIter; } else { // Continue to next visitor break; } case Baton.SKIP: // Leave chain break chainIter; default: throw new AssertionError(batonCode); } ++i; if (i >= chain.length) break chainIter; visitNext = result; } else { ++i; if (i >= chain.length) break; } } return result; } @SuppressWarnings({ "rawtypes", "unchecked" }) private Object redispatch( VisitorStackController controller, Object visitNext) { if (DEBUG) System.err.println(StringTools.crop(visitNext.toString(), 32)); return controller.resolveAndVisit(visitNext); } public void touch() { lastUse = ++useCounter; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + nodeClass.hashCode(); return result; } @Override public boolean equals(Object obj) { VisitChain other = (VisitChain) obj; if (nodeClass != other.nodeClass) return false; return true; } @Override public int compareTo(VisitChain o) { // Equality is not possible! return (lastUse < o.lastUse) ? -1 : +1; } } // ========================================================================= private static final class Link { private final int visitorIndex; private final Method method; public Link(int visitorIndex, Method method) { this.visitorIndex = visitorIndex; this.method = method; } } // ========================================================================= public static final class Cache { private int lowerCapacity; private int upperCapacity; private final CacheDefinition cacheDef; private final ConcurrentHashMap<VisitChain, VisitChain> cache; private Cache(List<? extends StackedVisitorInterface<?>> visitorStack, float loadFactor, int lowerCapacity, int upperCapacity) { this.lowerCapacity = lowerCapacity; this.upperCapacity = upperCapacity; this.cacheDef = new CacheDefinition(visitorStack); this.cache = new ConcurrentHashMap<VisitChain, VisitChain>(lowerCapacity, loadFactor); } private void verifyDefinition( List<? extends StackedVisitorInterface<?>> visitorStack) throws IncompatibleVisitorStackDefinition { if (!new CacheDefinition(visitorStack).equals(cacheDef)) throw new IncompatibleVisitorStackDefinition("Incompatible visitor stack"); } private VisitChain get(VisitChain key) { return cache.get(key); } private synchronized VisitChain put(VisitChain chain) { VisitChain cached = cache.putIfAbsent(chain, chain); if (cached != null) { return cached; } else { // Make sure the target is not swept from the cache ... chain.touch(); if (cache.size() > upperCapacity) sweepCache(); return chain; } } private synchronized void sweepCache() { if (cache.size() <= upperCapacity) return; VisitChain keys[] = new VisitChain[cache.size()]; Enumeration<VisitChain> keysEnum = cache.keys(); int i = 0; while (i < keys.length && keysEnum.hasMoreElements()) keys[i++] = keysEnum.nextElement(); int length = i; Arrays.sort(keys, 0, length); int to = length - lowerCapacity; for (int j = 0; j < to; ++j) cache.remove(keys[j]); } } // ========================================================================= private static final class CacheDefinition { private final int hash; private final Class<?>[] visitorStackDef; public CacheDefinition( List<? extends StackedVisitorInterface<?>> visitorStack) { @SuppressWarnings("rawtypes") Class[] visitorStackDef = new Class[visitorStack.size()]; int hash = 0; int i = 0; for (StackedVisitorInterface<?> visitor : visitorStack) { visitorStackDef[i] = visitor.getClass(); hash = hash * 13 + visitorStackDef[i].hashCode() * 17; ++i; } this.hash = hash; this.visitorStackDef = visitorStackDef; } @Override public int hashCode() { return hash; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CacheDefinition other = (CacheDefinition) obj; if (!Arrays.equals(visitorStackDef, other.visitorStackDef)) return false; return true; } } }
{ "content_hash": "982f5c2992060dbbaa2671707e71e539", "timestamp": "", "source": "github", "line_count": 702, "max_line_length": 126, "avg_line_length": 23.024216524216524, "alnum_prop": 0.6274206521066633, "repo_name": "sweble/osr-common", "id": "80dfc4d07c94fca7ea70bb6d7f0be8f4eb08448a", "size": "16829", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "utils-parent/utils/src/main/java/de/fau/cs/osr/utils/visitor/VisitorStackController.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "583217" }, { "name": "Python", "bytes": "1248" }, { "name": "Shell", "bytes": "11246" } ], "symlink_target": "" }
namespace mojo { namespace embedder { // A simple implementation of |PlatformSharedBuffer|. class MOJO_SYSTEM_IMPL_EXPORT SimplePlatformSharedBuffer final : public PlatformSharedBuffer { public: // Creates a shared buffer of size |num_bytes| bytes (initially zero-filled). // |num_bytes| must be nonzero. Returns null on failure. static SimplePlatformSharedBuffer* Create(size_t num_bytes); static SimplePlatformSharedBuffer* CreateFromPlatformHandle( size_t num_bytes, ScopedPlatformHandle platform_handle); // |PlatformSharedBuffer| implementation: size_t GetNumBytes() const override; scoped_ptr<PlatformSharedBufferMapping> Map(size_t offset, size_t length) override; bool IsValidMap(size_t offset, size_t length) override; scoped_ptr<PlatformSharedBufferMapping> MapNoCheck(size_t offset, size_t length) override; ScopedPlatformHandle DuplicatePlatformHandle() override; ScopedPlatformHandle PassPlatformHandle() override; private: explicit SimplePlatformSharedBuffer(size_t num_bytes); ~SimplePlatformSharedBuffer() override; // Implemented in simple_platform_shared_buffer_{posix,win}.cc: // This is called by |Create()| before this object is given to anyone. bool Init(); // This is like |Init()|, but for |CreateFromPlatformHandle()|. (Note: It // should verify that |platform_handle| is an appropriate handle for the // claimed |num_bytes_|.) bool InitFromPlatformHandle(ScopedPlatformHandle platform_handle); // The platform-dependent part of |Map()|; doesn't check arguments. scoped_ptr<PlatformSharedBufferMapping> MapImpl(size_t offset, size_t length); const size_t num_bytes_; // This is set in |Init()|/|InitFromPlatformHandle()| and never modified // (except by |PassPlatformHandle()|; see the comments above its declaration), // hence does not need to be protected by a lock. ScopedPlatformHandle handle_; MOJO_DISALLOW_COPY_AND_ASSIGN(SimplePlatformSharedBuffer); }; // An implementation of |PlatformSharedBufferMapping|, produced by // |SimplePlatformSharedBuffer|. class MOJO_SYSTEM_IMPL_EXPORT SimplePlatformSharedBufferMapping : public PlatformSharedBufferMapping { public: ~SimplePlatformSharedBufferMapping() override; void* GetBase() const override; size_t GetLength() const override; private: friend class SimplePlatformSharedBuffer; SimplePlatformSharedBufferMapping(void* base, size_t length, void* real_base, size_t real_length) : base_(base), length_(length), real_base_(real_base), real_length_(real_length) {} void Unmap(); void* const base_; const size_t length_; void* const real_base_; const size_t real_length_; MOJO_DISALLOW_COPY_AND_ASSIGN(SimplePlatformSharedBufferMapping); }; } // namespace embedder } // namespace mojo #endif // THIRD_PARTY_MOJO_SRC_MOJO_EDK_EMBEDDER_SIMPLE_PLATFORM_SHARED_BUFFER_H_
{ "content_hash": "ac191660e165fa2980fff53c6ccabab4", "timestamp": "", "source": "github", "line_count": 88, "max_line_length": 82, "avg_line_length": 35.29545454545455, "alnum_prop": 0.6999356084996781, "repo_name": "js0701/chromium-crosswalk", "id": "90b8dd1d87431a75ef7b6f692ea8a30cf00183fb", "size": "3642", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "third_party/mojo/src/mojo/edk/embedder/simple_platform_shared_buffer.h", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
<?php // No direct access defined('_HZEXEC_') or die(); /** * Display groups associated with a resource */ class plgResourcesGroups extends \Hubzero\Plugin\Plugin { /** * Affects constructor behavior. If true, language files will be loaded automatically. * * @var boolean */ protected $_autoloadLanguage = true; /** * Return the alias and name for this category of content * * @param object $resource Current resource * @return array */ public function &onResourcesSubAreas($resource) { $areas = array( 'groups' => Lang::txt('PLG_RESOURCES_GROUPS') ); return $areas; } /** * Return data on a resource sub view (this will be some form of HTML) * * @param object $resource Current resource * @param string $option Name of the component * @param integer $miniview View style * @return array */ public function onResourcesSub($resource, $option, $miniview=0) { $arr = array( 'area' => $this->_name, 'html' => '', 'metadata' => '' ); if (!$resource->get('group_owner') || substr($resource->get('group_owner'), 0, strlen('app-')) == 'app-') { return $arr; } $group = \Hubzero\User\Group::getInstance($resource->get('group_owner')); if (!$group || !$group->get('gidNumber')) { return $arr; } // Pass the view some info $view = $this->view('default', 'display') ->set('option', $option) ->set('resource', $resource) ->set('params', $this->params) ->set('group', $group); if ($miniview) { $view->setLayout('mini'); } // Return the output $arr['html'] = $view ->setErrors($this->getErrors()) ->loadTemplate(); return $arr; } }
{ "content_hash": "79ed081090eb4045b49344a39cec25e8", "timestamp": "", "source": "github", "line_count": 80, "max_line_length": 107, "avg_line_length": 21.0375, "alnum_prop": 0.6066547831253714, "repo_name": "anthonyfuentes/hubzero-cms", "id": "20a1c517f2d191495d2fb404124e76628e10c135", "size": "1831", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "core/plugins/resources/groups/groups.php", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "171251" }, { "name": "AngelScript", "bytes": "1638" }, { "name": "CSS", "bytes": "2719754" }, { "name": "HTML", "bytes": "1289374" }, { "name": "JavaScript", "bytes": "12613354" }, { "name": "PHP", "bytes": "24940952" }, { "name": "Shell", "bytes": "10678" }, { "name": "TSQL", "bytes": "572" } ], "symlink_target": "" }
package schemamanager import ( "encoding/json" "fmt" "time" log "github.com/golang/glog" "golang.org/x/net/context" querypb "github.com/youtube/vitess/go/vt/proto/query" ) const ( // SchemaChangeDirName is the key name in the ControllerFactory params. // It specifies the schema change directory. SchemaChangeDirName = "schema_change_dir" // SchemaChangeUser is the key name in the ControllerFactory params. // It specifies the user who submits this schema change. SchemaChangeUser = "schema_change_user" ) // ControllerFactory takes a set params and construct a Controller instance. type ControllerFactory func(params map[string]string) (Controller, error) var ( controllerFactories = make(map[string]ControllerFactory) ) // Controller is responsible for getting schema change for a // certain keyspace and also handling various events happened during schema // change. type Controller interface { Open(ctx context.Context) error Read(ctx context.Context) (sqls []string, err error) Close() Keyspace() string OnReadSuccess(ctx context.Context) error OnReadFail(ctx context.Context, err error) error OnValidationSuccess(ctx context.Context) error OnValidationFail(ctx context.Context, err error) error OnExecutorComplete(ctx context.Context, result *ExecuteResult) error } // Executor applies schema changes to underlying system type Executor interface { Open(ctx context.Context, keyspace string) error Validate(ctx context.Context, sqls []string) error Execute(ctx context.Context, sqls []string) *ExecuteResult Close() } // ExecuteResult contains information about schema management state type ExecuteResult struct { FailedShards []ShardWithError SuccessShards []ShardResult CurSQLIndex int Sqls []string ExecutorErr string TotalTimeSpent time.Duration } // ShardWithError contains information why a shard failed to execute given sql type ShardWithError struct { Shard string Err string } // ShardResult contains sql execute information on a particula shard type ShardResult struct { Shard string Result *querypb.QueryResult } // Run schema changes on Vitess through VtGate func Run(ctx context.Context, controller Controller, executor Executor) error { if err := controller.Open(ctx); err != nil { log.Errorf("failed to open data sourcer: %v", err) return err } defer controller.Close() sqls, err := controller.Read(ctx) if err != nil { log.Errorf("failed to read data from data sourcer: %v", err) controller.OnReadFail(ctx, err) return err } controller.OnReadSuccess(ctx) if len(sqls) == 0 { return nil } keyspace := controller.Keyspace() if err := executor.Open(ctx, keyspace); err != nil { log.Errorf("failed to open executor: %v", err) return err } defer executor.Close() if err := executor.Validate(ctx, sqls); err != nil { log.Errorf("validation fail: %v", err) controller.OnValidationFail(ctx, err) return err } if err := controller.OnValidationSuccess(ctx); err != nil { return err } result := executor.Execute(ctx, sqls) if err := controller.OnExecutorComplete(ctx, result); err != nil { return err } if result.ExecutorErr != "" || len(result.FailedShards) > 0 { out, _ := json.MarshalIndent(result, "", " ") return fmt.Errorf("Schema change failed, ExecuteResult: %v\n", string(out)) } return nil } // RegisterControllerFactory register a control factory. func RegisterControllerFactory(name string, factory ControllerFactory) { if _, ok := controllerFactories[name]; ok { panic(fmt.Sprintf("register a registered key: %s", name)) } controllerFactories[name] = factory } // GetControllerFactory gets a ControllerFactory. func GetControllerFactory(name string) (ControllerFactory, error) { factory, ok := controllerFactories[name] if !ok { return nil, fmt.Errorf("there is no data sourcer factory with name: %s", name) } return factory, nil }
{ "content_hash": "b1c8480ffed3780902723bb41e567d75", "timestamp": "", "source": "github", "line_count": 135, "max_line_length": 80, "avg_line_length": 28.85925925925926, "alnum_prop": 0.7440965092402464, "repo_name": "tjyang/vitess", "id": "9944ad641acc3073c1471658114fd989ade6300a", "size": "4053", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "go/vt/schemamanager/schemamanager.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "9588" }, { "name": "CSS", "bytes": "202224" }, { "name": "Go", "bytes": "4771381" }, { "name": "HTML", "bytes": "46202" }, { "name": "Java", "bytes": "165580" }, { "name": "JavaScript", "bytes": "48518" }, { "name": "Liquid", "bytes": "8009" }, { "name": "Makefile", "bytes": "5071" }, { "name": "PHP", "bytes": "726238" }, { "name": "Protocol Buffer", "bytes": "75481" }, { "name": "Python", "bytes": "657888" }, { "name": "Ruby", "bytes": "466" }, { "name": "Shell", "bytes": "30648" }, { "name": "Yacc", "bytes": "19565" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <!-- Copyright (C) 1988-2016 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with the Invariant Sections being "Funding Free Software", the Front-Cover Texts being (a) (see below), and with the Back-Cover Texts being (b) (see below). A copy of the license is included in the section entitled "GNU Free Documentation License". (a) The FSF's Front-Cover Text is: A GNU Manual (b) The FSF's Back-Cover Text is: You have freedom to copy and modify this GNU Manual, like GNU software. Copies published by the Free Software Foundation raise funds for GNU development. --> <!-- Created by GNU Texinfo 5.2, http://www.gnu.org/software/texinfo/ --> <head> <title>GNU Compiler Collection (GCC) Internals: RTL Objects</title> <meta name="description" content="GNU Compiler Collection (GCC) Internals: RTL Objects"> <meta name="keywords" content="GNU Compiler Collection (GCC) Internals: RTL Objects"> <meta name="resource-type" content="document"> <meta name="distribution" content="global"> <meta name="Generator" content="makeinfo"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link href="index.html#Top" rel="start" title="Top"> <link href="Option-Index.html#Option-Index" rel="index" title="Option Index"> <link href="index.html#SEC_Contents" rel="contents" title="Table of Contents"> <link href="RTL.html#RTL" rel="up" title="RTL"> <link href="RTL-Classes.html#RTL-Classes" rel="next" title="RTL Classes"> <link href="RTL.html#RTL" rel="prev" title="RTL"> <style type="text/css"> <!-- a.summary-letter {text-decoration: none} blockquote.smallquotation {font-size: smaller} div.display {margin-left: 3.2em} div.example {margin-left: 3.2em} div.indentedblock {margin-left: 3.2em} div.lisp {margin-left: 3.2em} div.smalldisplay {margin-left: 3.2em} div.smallexample {margin-left: 3.2em} div.smallindentedblock {margin-left: 3.2em; font-size: smaller} div.smalllisp {margin-left: 3.2em} kbd {font-style:oblique} pre.display {font-family: inherit} pre.format {font-family: inherit} pre.menu-comment {font-family: serif} pre.menu-preformatted {font-family: serif} pre.smalldisplay {font-family: inherit; font-size: smaller} pre.smallexample {font-size: smaller} pre.smallformat {font-family: inherit; font-size: smaller} pre.smalllisp {font-size: smaller} span.nocodebreak {white-space:nowrap} span.nolinebreak {white-space:nowrap} span.roman {font-family:serif; font-weight:normal} span.sansserif {font-family:sans-serif; font-weight:normal} ul.no-bullet {list-style: none} --> </style> </head> <body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000"> <a name="RTL-Objects"></a> <div class="header"> <p> Next: <a href="RTL-Classes.html#RTL-Classes" accesskey="n" rel="next">RTL Classes</a>, Up: <a href="RTL.html#RTL" accesskey="u" rel="up">RTL</a> &nbsp; [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Option-Index.html#Option-Index" title="Index" rel="index">Index</a>]</p> </div> <hr> <a name="RTL-Object-Types"></a> <h3 class="section">13.1 RTL Object Types</h3> <a name="index-RTL-object-types"></a> <a name="index-RTL-integers"></a> <a name="index-RTL-strings"></a> <a name="index-RTL-vectors"></a> <a name="index-RTL-expression"></a> <a name="index-RTX-_0028See-RTL_0029"></a> <p>RTL uses five kinds of objects: expressions, integers, wide integers, strings and vectors. Expressions are the most important ones. An RTL expression (&ldquo;RTX&rdquo;, for short) is a C structure, but it is usually referred to with a pointer; a type that is given the typedef name <code>rtx</code>. </p> <p>An integer is simply an <code>int</code>; their written form uses decimal digits. A wide integer is an integral object whose type is <code>HOST_WIDE_INT</code>; their written form uses decimal digits. </p> <p>A string is a sequence of characters. In core it is represented as a <code>char *</code> in usual C fashion, and it is written in C syntax as well. However, strings in RTL may never be null. If you write an empty string in a machine description, it is represented in core as a null pointer rather than as a pointer to a null character. In certain contexts, these null pointers instead of strings are valid. Within RTL code, strings are most commonly found inside <code>symbol_ref</code> expressions, but they appear in other contexts in the RTL expressions that make up machine descriptions. </p> <p>In a machine description, strings are normally written with double quotes, as you would in C. However, strings in machine descriptions may extend over many lines, which is invalid C, and adjacent string constants are not concatenated as they are in C. Any string constant may be surrounded with a single set of parentheses. Sometimes this makes the machine description easier to read. </p> <p>There is also a special syntax for strings, which can be useful when C code is embedded in a machine description. Wherever a string can appear, it is also valid to write a C-style brace block. The entire brace block, including the outermost pair of braces, is considered to be the string constant. Double quote characters inside the braces are not special. Therefore, if you write string constants in the C code, you need not escape each quote character with a backslash. </p> <p>A vector contains an arbitrary number of pointers to expressions. The number of elements in the vector is explicitly present in the vector. The written form of a vector consists of square brackets (&lsquo;<samp>[&hellip;]</samp>&rsquo;) surrounding the elements, in sequence and with whitespace separating them. Vectors of length zero are not created; null pointers are used instead. </p> <a name="index-expression-codes"></a> <a name="index-codes_002c-RTL-expression"></a> <a name="index-GET_005fCODE"></a> <a name="index-PUT_005fCODE"></a> <p>Expressions are classified by <em>expression codes</em> (also called RTX codes). The expression code is a name defined in <samp>rtl.def</samp>, which is also (in uppercase) a C enumeration constant. The possible expression codes and their meanings are machine-independent. The code of an RTX can be extracted with the macro <code>GET_CODE (<var>x</var>)</code> and altered with <code>PUT_CODE (<var>x</var>, <var>newcode</var>)</code>. </p> <p>The expression code determines how many operands the expression contains, and what kinds of objects they are. In RTL, unlike Lisp, you cannot tell by looking at an operand what kind of object it is. Instead, you must know from its context&mdash;from the expression code of the containing expression. For example, in an expression of code <code>subreg</code>, the first operand is to be regarded as an expression and the second operand as an integer. In an expression of code <code>plus</code>, there are two operands, both of which are to be regarded as expressions. In a <code>symbol_ref</code> expression, there is one operand, which is to be regarded as a string. </p> <p>Expressions are written as parentheses containing the name of the expression type, its flags and machine mode if any, and then the operands of the expression (separated by spaces). </p> <p>Expression code names in the &lsquo;<samp>md</samp>&rsquo; file are written in lowercase, but when they appear in C code they are written in uppercase. In this manual, they are shown as follows: <code>const_int</code>. </p> <a name="index-_0028nil_0029"></a> <a name="index-nil"></a> <p>In a few contexts a null pointer is valid where an expression is normally wanted. The written form of this is <code>(nil)</code>. </p> <hr> <div class="header"> <p> Next: <a href="RTL-Classes.html#RTL-Classes" accesskey="n" rel="next">RTL Classes</a>, Up: <a href="RTL.html#RTL" accesskey="u" rel="up">RTL</a> &nbsp; [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Option-Index.html#Option-Index" title="Index" rel="index">Index</a>]</p> </div> </body> </html>
{ "content_hash": "377273c3a59fefd639f2ca72f7dc418e", "timestamp": "", "source": "github", "line_count": 170, "max_line_length": 323, "avg_line_length": 48.7, "alnum_prop": 0.7430849136369126, "repo_name": "ATM-HSW/mbed_target", "id": "d439cf4d5303f7f862c69f6fc5990cdb72f25e1f", "size": "8279", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "buildtools/gcc-arm-none-eabi-6-2017-q2/share/doc/gcc-arm-none-eabi/html/gccint/RTL-Objects.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "29493" }, { "name": "Batchfile", "bytes": "948" }, { "name": "C", "bytes": "3167609" }, { "name": "C++", "bytes": "12419698" }, { "name": "HTML", "bytes": "27891106" }, { "name": "MATLAB", "bytes": "230413" }, { "name": "Makefile", "bytes": "2798" }, { "name": "Python", "bytes": "225136" }, { "name": "Shell", "bytes": "50803" }, { "name": "XC", "bytes": "9173" }, { "name": "XS", "bytes": "9123" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "0ed586d7502f001751ba27a73f55167a", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "4f995774d4d90fb88b3b27a72cf7e16460409e60", "size": "184", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Scrophulariaceae/Buddleja/Buddleja shaanxiensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!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_72) on Wed May 13 11:47:54 EDT 2015 --> <title>Uses of Class org.apache.cassandra.metrics.RestorableMeter (apache-cassandra API)</title> <meta name="date" content="2015-05-13"> <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="Uses of Class org.apache.cassandra.metrics.RestorableMeter (apache-cassandra 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><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/apache/cassandra/metrics/RestorableMeter.html" title="class in org.apache.cassandra.metrics">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../overview-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>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/cassandra/metrics/class-use/RestorableMeter.html" target="_top">Frames</a></li> <li><a href="RestorableMeter.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"> <h2 title="Uses of Class org.apache.cassandra.metrics.RestorableMeter" class="title">Uses of Class<br>org.apache.cassandra.metrics.RestorableMeter</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../org/apache/cassandra/metrics/RestorableMeter.html" title="class in org.apache.cassandra.metrics">RestorableMeter</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#org.apache.cassandra.db">org.apache.cassandra.db</a></td> <td class="colLast">&nbsp;</td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="#org.apache.cassandra.io.sstable">org.apache.cassandra.io.sstable</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="org.apache.cassandra.db"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/apache/cassandra/metrics/RestorableMeter.html" title="class in org.apache.cassandra.metrics">RestorableMeter</a> in <a href="../../../../../org/apache/cassandra/db/package-summary.html">org.apache.cassandra.db</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../org/apache/cassandra/db/package-summary.html">org.apache.cassandra.db</a> that return <a href="../../../../../org/apache/cassandra/metrics/RestorableMeter.html" title="class in org.apache.cassandra.metrics">RestorableMeter</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static <a href="../../../../../org/apache/cassandra/metrics/RestorableMeter.html" title="class in org.apache.cassandra.metrics">RestorableMeter</a></code></td> <td class="colLast"><span class="strong">SystemKeyspace.</span><code><strong><a href="../../../../../org/apache/cassandra/db/SystemKeyspace.html#getSSTableReadMeter(java.lang.String,%20java.lang.String,%20int)">getSSTableReadMeter</a></strong>(java.lang.String&nbsp;keyspace, java.lang.String&nbsp;table, int&nbsp;generation)</code> <div class="block">Returns a RestorableMeter tracking the average read rate of a particular SSTable, restoring the last-seen rate from values in system.sstable_activity if present.</div> </td> </tr> </tbody> </table> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../org/apache/cassandra/db/package-summary.html">org.apache.cassandra.db</a> with parameters of type <a href="../../../../../org/apache/cassandra/metrics/RestorableMeter.html" title="class in org.apache.cassandra.metrics">RestorableMeter</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code>static void</code></td> <td class="colLast"><span class="strong">SystemKeyspace.</span><code><strong><a href="../../../../../org/apache/cassandra/db/SystemKeyspace.html#persistSSTableReadMeter(java.lang.String,%20java.lang.String,%20int,%20org.apache.cassandra.metrics.RestorableMeter)">persistSSTableReadMeter</a></strong>(java.lang.String&nbsp;keyspace, java.lang.String&nbsp;table, int&nbsp;generation, <a href="../../../../../org/apache/cassandra/metrics/RestorableMeter.html" title="class in org.apache.cassandra.metrics">RestorableMeter</a>&nbsp;meter)</code> <div class="block">Writes the current read rates for a given SSTable to system.sstable_activity</div> </td> </tr> </tbody> </table> </li> <li class="blockList"><a name="org.apache.cassandra.io.sstable"> <!-- --> </a> <h3>Uses of <a href="../../../../../org/apache/cassandra/metrics/RestorableMeter.html" title="class in org.apache.cassandra.metrics">RestorableMeter</a> in <a href="../../../../../org/apache/cassandra/io/sstable/package-summary.html">org.apache.cassandra.io.sstable</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation"> <caption><span>Fields in <a href="../../../../../org/apache/cassandra/io/sstable/package-summary.html">org.apache.cassandra.io.sstable</a> declared as <a href="../../../../../org/apache/cassandra/metrics/RestorableMeter.html" title="class in org.apache.cassandra.metrics">RestorableMeter</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../org/apache/cassandra/metrics/RestorableMeter.html" title="class in org.apache.cassandra.metrics">RestorableMeter</a></code></td> <td class="colLast"><span class="strong">SSTableReader.</span><code><strong><a href="../../../../../org/apache/cassandra/io/sstable/SSTableReader.html#readMeter">readMeter</a></strong></code>&nbsp;</td> </tr> </tbody> </table> </li> </ul> </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><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../org/apache/cassandra/metrics/RestorableMeter.html" title="class in org.apache.cassandra.metrics">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../overview-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>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/cassandra/metrics/class-use/RestorableMeter.html" target="_top">Frames</a></li> <li><a href="RestorableMeter.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 &copy; 2015 The Apache Software Foundation</small></p> </body> </html>
{ "content_hash": "3a8108649c70059406e580c12c47588b", "timestamp": "", "source": "github", "line_count": 201, "max_line_length": 342, "avg_line_length": 48.23880597014925, "alnum_prop": 0.6590346534653465, "repo_name": "anuragkapur/cassandra-2.1.2-ak-skynet", "id": "b64e8f33a46abc68afe485439420146ce4898162", "size": "9696", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "apache-cassandra-2.0.15/javadoc/org/apache/cassandra/metrics/class-use/RestorableMeter.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "59670" }, { "name": "PowerShell", "bytes": "37758" }, { "name": "Python", "bytes": "622552" }, { "name": "Shell", "bytes": "100474" }, { "name": "Thrift", "bytes": "78926" } ], "symlink_target": "" }
package org.apache.spark.sql.streaming import org.scalatest.BeforeAndAfterAll import org.apache.spark.sql.catalyst.plans.physical.{ClusteredDistribution, HashPartitioning, SinglePartition} import org.apache.spark.sql.catalyst.streaming.InternalOutputModes._ import org.apache.spark.sql.execution.streaming.{MemoryStream, StreamingDeduplicateExec} import org.apache.spark.sql.execution.streaming.state.StateStore import org.apache.spark.sql.functions._ import org.apache.spark.sql.internal.SQLConf class StreamingDeduplicationSuite extends StateStoreMetricsTest { import testImplicits._ test("deduplicate with all columns") { val inputData = MemoryStream[String] val result = inputData.toDS().dropDuplicates() testStream(result, Append)( AddData(inputData, "a"), CheckLastBatch("a"), assertNumStateRows(total = 1, updated = 1), AddData(inputData, "a"), CheckLastBatch(), assertNumStateRows(total = 1, updated = 0), AddData(inputData, "b"), CheckLastBatch("b"), assertNumStateRows(total = 2, updated = 1) ) } test("deduplicate with some columns") { val inputData = MemoryStream[(String, Int)] val result = inputData.toDS().dropDuplicates("_1") testStream(result, Append)( AddData(inputData, "a" -> 1), CheckLastBatch("a" -> 1), assertNumStateRows(total = 1, updated = 1, droppedByWatermark = 0), AddData(inputData, "a" -> 2), // Dropped CheckLastBatch(), assertNumStateRows(total = 1, updated = 0, droppedByWatermark = 0), AddData(inputData, "b" -> 1), CheckLastBatch("b" -> 1), assertNumStateRows(total = 2, updated = 1, droppedByWatermark = 0) ) } test("multiple deduplicates") { val inputData = MemoryStream[(String, Int)] val result = inputData.toDS().dropDuplicates().dropDuplicates("_1") testStream(result, Append)( AddData(inputData, "a" -> 1), CheckLastBatch("a" -> 1), assertNumStateRows(total = Seq(1L, 1L), updated = Seq(1L, 1L)), AddData(inputData, "a" -> 2), // Dropped from the second `dropDuplicates` CheckLastBatch(), assertNumStateRows(total = Seq(1L, 2L), updated = Seq(0L, 1L)), AddData(inputData, "b" -> 1), CheckLastBatch("b" -> 1), assertNumStateRows(total = Seq(2L, 3L), updated = Seq(1L, 1L)) ) } test("deduplicate with watermark") { val inputData = MemoryStream[Int] val result = inputData.toDS() .withColumn("eventTime", timestamp_seconds($"value")) .withWatermark("eventTime", "10 seconds") .dropDuplicates() .select($"eventTime".cast("long").as[Long]) testStream(result, Append)( AddData(inputData, (1 to 5).flatMap(_ => (10 to 15)): _*), CheckAnswer(10 to 15: _*), assertNumStateRows(total = 6, updated = 6), AddData(inputData, 25), // Advance watermark to 15 secs, no-data-batch drops rows <= 15 CheckNewAnswer(25), assertNumStateRows(total = 1, updated = 1), AddData(inputData, 10), // Should not emit anything as data less than watermark CheckNewAnswer(), assertNumStateRows(total = 1, updated = 0, droppedByWatermark = 1), AddData(inputData, 45), // Advance watermark to 35 seconds, no-data-batch drops row 25 CheckNewAnswer(45), assertNumStateRows(total = 1, updated = 1) ) } test("deduplicate with aggregate - append mode") { val inputData = MemoryStream[Int] val windowedaggregate = inputData.toDS() .withColumn("eventTime", timestamp_seconds($"value")) .withWatermark("eventTime", "10 seconds") .dropDuplicates() .withWatermark("eventTime", "10 seconds") .groupBy(window($"eventTime", "5 seconds") as 'window) .agg(count("*") as 'count) .select($"window".getField("start").cast("long").as[Long], $"count".as[Long]) testStream(windowedaggregate)( AddData(inputData, (1 to 5).flatMap(_ => (10 to 15)): _*), CheckLastBatch(), // states in aggregate in [10, 14), [15, 20) (2 windows) // states in deduplicate is 10 to 15 assertNumStateRows(total = Seq(2L, 6L), updated = Seq(2L, 6L)), AddData(inputData, 25), // Advance watermark to 15 seconds CheckLastBatch((10 -> 5)), // 5 items (10 to 14) after deduplicate, emitted with no-data-batch // states in aggregate in [15, 20) and [25, 30); no-data-batch removed [10, 14) // states in deduplicate is 25, no-data-batch removed 10 to 14 assertNumStateRows(total = Seq(2L, 1L), updated = Seq(1L, 1L)), AddData(inputData, 10), // Should not emit anything as data less than watermark CheckLastBatch(), assertNumStateRows(total = Seq(2L, 1L), updated = Seq(0L, 0L), droppedByWatermark = Seq(0L, 1L)), AddData(inputData, 40), // Advance watermark to 30 seconds CheckLastBatch((15 -> 1), (25 -> 1)), // states in aggregate is [40, 45); no-data-batch removed [15, 20) and [25, 30) // states in deduplicate is 40; no-data-batch removed 25 assertNumStateRows(total = Seq(1L, 1L), updated = Seq(1L, 1L)) ) } test("deduplicate with aggregate - update mode") { val inputData = MemoryStream[(String, Int)] val result = inputData.toDS() .select($"_1" as "str", $"_2" as "num") .dropDuplicates() .groupBy("str") .agg(sum("num")) .as[(String, Long)] testStream(result, Update)( AddData(inputData, "a" -> 1), CheckLastBatch("a" -> 1L), assertNumStateRows(total = Seq(1L, 1L), updated = Seq(1L, 1L)), AddData(inputData, "a" -> 1), // Dropped CheckLastBatch(), assertNumStateRows(total = Seq(1L, 1L), updated = Seq(0L, 0L)), AddData(inputData, "a" -> 2), CheckLastBatch("a" -> 3L), assertNumStateRows(total = Seq(1L, 2L), updated = Seq(1L, 1L)), AddData(inputData, "b" -> 1), CheckLastBatch("b" -> 1L), assertNumStateRows(total = Seq(2L, 3L), updated = Seq(1L, 1L)) ) } test("deduplicate with aggregate - complete mode") { val inputData = MemoryStream[(String, Int)] val result = inputData.toDS() .select($"_1" as "str", $"_2" as "num") .dropDuplicates() .groupBy("str") .agg(sum("num")) .as[(String, Long)] testStream(result, Complete)( AddData(inputData, "a" -> 1), CheckLastBatch("a" -> 1L), assertNumStateRows(total = Seq(1L, 1L), updated = Seq(1L, 1L)), AddData(inputData, "a" -> 1), // Dropped CheckLastBatch("a" -> 1L), assertNumStateRows(total = Seq(1L, 1L), updated = Seq(0L, 0L)), AddData(inputData, "a" -> 2), CheckLastBatch("a" -> 3L), assertNumStateRows(total = Seq(1L, 2L), updated = Seq(1L, 1L)), AddData(inputData, "b" -> 1), CheckLastBatch("a" -> 3L, "b" -> 1L), assertNumStateRows(total = Seq(2L, 3L), updated = Seq(1L, 1L)) ) } test("deduplicate with file sink") { withTempDir { output => withTempDir { checkpointDir => val outputPath = output.getAbsolutePath val inputData = MemoryStream[String] val result = inputData.toDS().dropDuplicates() val q = result.writeStream .format("parquet") .outputMode(Append) .option("checkpointLocation", checkpointDir.getPath) .start(outputPath) try { inputData.addData("a") q.processAllAvailable() checkDataset(spark.read.parquet(outputPath).as[String], "a") inputData.addData("a") // Dropped q.processAllAvailable() checkDataset(spark.read.parquet(outputPath).as[String], "a") inputData.addData("b") q.processAllAvailable() checkDataset(spark.read.parquet(outputPath).as[String], "a", "b") } finally { q.stop() } } } } test("SPARK-19841: watermarkPredicate should filter based on keys") { val input = MemoryStream[(Int, Int)] val df = input.toDS.toDF("time", "id") .withColumn("time", timestamp_seconds($"time")) .withWatermark("time", "1 second") .dropDuplicates("id", "time") // Change the column positions .select($"id") testStream(df)( AddData(input, 1 -> 1, 1 -> 1, 1 -> 2), CheckAnswer(1, 2), AddData(input, 1 -> 1, 2 -> 3, 2 -> 4), CheckNewAnswer(3, 4), AddData(input, 1 -> 0, 1 -> 1, 3 -> 5, 3 -> 6), // Drop (1 -> 0, 1 -> 1) due to watermark CheckNewAnswer(5, 6), AddData(input, 1 -> 0, 4 -> 7), // Drop (1 -> 0) due to watermark CheckNewAnswer(7) ) } test("SPARK-21546: dropDuplicates should ignore watermark when it's not a key") { val input = MemoryStream[(Int, Int)] val df = input.toDS.toDF("id", "time") .withColumn("time", timestamp_seconds($"time")) .withWatermark("time", "1 second") .dropDuplicates("id") .select($"id", $"time".cast("long")) testStream(df)( AddData(input, 1 -> 1, 1 -> 2, 2 -> 2), CheckAnswer(1 -> 1, 2 -> 2) ) } test("test no-data flag") { val flagKey = SQLConf.STREAMING_NO_DATA_MICRO_BATCHES_ENABLED.key def testWithFlag(flag: Boolean): Unit = withClue(s"with $flagKey = $flag") { val inputData = MemoryStream[Int] val result = inputData.toDS() .withColumn("eventTime", timestamp_seconds($"value")) .withWatermark("eventTime", "10 seconds") .dropDuplicates() .select($"eventTime".cast("long").as[Long]) testStream(result, Append)( StartStream(additionalConfs = Map(flagKey -> flag.toString)), AddData(inputData, 10, 11, 12, 13, 14, 15), CheckAnswer(10, 11, 12, 13, 14, 15), assertNumStateRows(total = 6, updated = 6), AddData(inputData, 25), // Advance watermark to 15 seconds CheckNewAnswer(25), { // State should have been cleaned if flag is set, otherwise should not have been cleaned if (flag) assertNumStateRows(total = 1, updated = 1) else assertNumStateRows(total = 7, updated = 1) }, AssertOnQuery { q => eventually(timeout(streamingTimeout)) { q.lastProgress.sink.numOutputRows == 0L true } } ) } testWithFlag(true) testWithFlag(false) } }
{ "content_hash": "ac38bb0fd3f26f6614eff5e9f6e5907d", "timestamp": "", "source": "github", "line_count": 282, "max_line_length": 110, "avg_line_length": 36.50354609929078, "alnum_prop": 0.6133670099086846, "repo_name": "dbtsai/spark", "id": "1f346aac8d2c236b1821c4c2eb340f8abb271257", "size": "11094", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "sql/core/src/test/scala/org/apache/spark/sql/streaming/StreamingDeduplicationSuite.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "50618" }, { "name": "Batchfile", "bytes": "25784" }, { "name": "C", "bytes": "1493" }, { "name": "CSS", "bytes": "24294" }, { "name": "Dockerfile", "bytes": "9379" }, { "name": "HTML", "bytes": "40561" }, { "name": "HiveQL", "bytes": "1890746" }, { "name": "Java", "bytes": "4198061" }, { "name": "JavaScript", "bytes": "218079" }, { "name": "Makefile", "bytes": "1591" }, { "name": "PLSQL", "bytes": "7551" }, { "name": "PLpgSQL", "bytes": "389397" }, { "name": "PowerShell", "bytes": "3879" }, { "name": "Python", "bytes": "3311071" }, { "name": "R", "bytes": "1237863" }, { "name": "Roff", "bytes": "36728" }, { "name": "SQLPL", "bytes": "9325" }, { "name": "Scala", "bytes": "34000517" }, { "name": "Shell", "bytes": "217951" }, { "name": "TSQL", "bytes": "481083" }, { "name": "Thrift", "bytes": "67584" }, { "name": "q", "bytes": "79845" } ], "symlink_target": "" }
class GameModule { public: static std::shared_ptr<Input> input; static std::shared_ptr<ResourceManager> resources; static std::mt19937 random_gen; static void Init(); };
{ "content_hash": "4d69b647545b2919424e10712d61659c", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 51, "avg_line_length": 19.333333333333332, "alnum_prop": 0.7471264367816092, "repo_name": "DevRaptor/OpenGL_tutorial", "id": "24e08dc0458aeafb8821e6ab2bc5a40010a31a05", "size": "274", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "tutorial_03-lighting/src/modules/GameModule.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2674715" }, { "name": "C++", "bytes": "2191069" }, { "name": "CMake", "bytes": "21448" }, { "name": "GLSL", "bytes": "897" }, { "name": "Objective-C", "bytes": "8426" } ], "symlink_target": "" }
package org.terasology.input; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import org.terasology.config.BindsConfig; import org.terasology.config.Config; import org.terasology.engine.SimpleUri; import org.terasology.engine.Time; import org.terasology.engine.module.ModuleManager; import org.terasology.engine.subsystem.DisplayDevice; import org.terasology.entitySystem.entity.EntityRef; import org.terasology.entitySystem.systems.BaseComponentSystem; import org.terasology.input.cameraTarget.CameraTargetSystem; import org.terasology.input.device.InputAction; import org.terasology.input.device.KeyboardDevice; import org.terasology.input.device.MouseDevice; import org.terasology.input.device.nulldevices.NullKeyboardDevice; import org.terasology.input.device.nulldevices.NullMouseDevice; import org.terasology.input.events.InputEvent; import org.terasology.input.events.KeyDownEvent; import org.terasology.input.events.KeyEvent; import org.terasology.input.events.KeyRepeatEvent; import org.terasology.input.events.KeyUpEvent; import org.terasology.input.events.LeftMouseDownButtonEvent; import org.terasology.input.events.LeftMouseUpButtonEvent; import org.terasology.input.events.MouseAxisEvent; import org.terasology.input.events.MouseButtonEvent; import org.terasology.input.events.MouseDownButtonEvent; import org.terasology.input.events.MouseUpButtonEvent; import org.terasology.input.events.MouseWheelEvent; import org.terasology.input.events.MouseXAxisEvent; import org.terasology.input.events.MouseYAxisEvent; import org.terasology.input.events.RightMouseDownButtonEvent; import org.terasology.input.events.RightMouseUpButtonEvent; import org.terasology.input.internal.BindableAxisImpl; import org.terasology.input.internal.BindableButtonImpl; import org.terasology.logic.players.LocalPlayer; import org.terasology.math.geom.Vector2i; import org.terasology.registry.In; import java.util.List; import java.util.Map; /** * This system processes input, sending it out as events against the LocalPlayer entity. * <br><br> * In addition to raw keyboard and mouse input, the system handles Bind Buttons and Bind Axis, which can be mapped * to one or more inputs. */ public class InputSystem extends BaseComponentSystem { @In private Config config; @In private DisplayDevice display; @In private Time time; @In private LocalPlayer localPlayer; @In private CameraTargetSystem targetSystem; @In private ModuleManager moduleManager; private MouseDevice mouse = new NullMouseDevice(); private KeyboardDevice keyboard = new NullKeyboardDevice(); private Map<String, BindableAxisImpl> axisLookup = Maps.newHashMap(); private Map<SimpleUri, BindableButtonImpl> buttonLookup = Maps.newHashMap(); private List<BindableAxisImpl> axisBinds = Lists.newArrayList(); private List<BindableButtonImpl> buttonBinds = Lists.newArrayList(); // Links between primitive inputs and bind buttons private Map<Integer, BindableButtonImpl> keyBinds = Maps.newHashMap(); private Map<MouseInput, BindableButtonImpl> mouseButtonBinds = Maps.newHashMap(); private BindableButtonImpl mouseWheelUpBind; private BindableButtonImpl mouseWheelDownBind; private boolean capturingMouse = true; public void setMouseDevice(MouseDevice mouseDevice) { this.mouse = mouseDevice; } public void setKeyboardDevice(KeyboardDevice keyboardDevice) { this.keyboard = keyboardDevice; } public MouseDevice getMouseDevice() { return mouse; } public KeyboardDevice getKeyboard() { return keyboard; } public BindableButton registerBindButton(SimpleUri bindId, String displayName) { return registerBindButton(bindId, displayName, new BindButtonEvent()); } @Override public void initialise() { BindsConfig bindsConfig = config.getInput().getBinds(); bindsConfig.applyBinds(this, moduleManager); } public BindableButton registerBindButton(SimpleUri bindId, String displayName, BindButtonEvent event) { BindableButtonImpl bind = new BindableButtonImpl(bindId, displayName, event, time); buttonLookup.put(bindId, bind); buttonBinds.add(bind); return bind; } public void clearBinds() { buttonLookup.clear(); buttonBinds.clear(); axisLookup.clear(); axisBinds.clear(); keyBinds.clear(); mouseButtonBinds.clear(); mouseWheelUpBind = null; mouseWheelDownBind = null; } public BindableButton getBindButton(SimpleUri bindId) { return buttonLookup.get(bindId); } public void linkBindButtonToInput(Input input, SimpleUri bindId) { switch (input.getType()) { case KEY: linkBindButtonToKey(input.getId(), bindId); break; case MOUSE_BUTTON: MouseInput button = MouseInput.find(input.getType(), input.getId()); linkBindButtonToMouse(button, bindId); break; case MOUSE_WHEEL: linkBindButtonToMouseWheel(input.getId(), bindId); break; default: break; } } public void linkBindButtonToInput(InputEvent input, SimpleUri bindId) { if (input instanceof KeyEvent) { linkBindButtonToKey(((KeyEvent) input).getKey().getId(), bindId); } else if (input instanceof MouseButtonEvent) { linkBindButtonToMouse(((MouseButtonEvent) input).getButton(), bindId); } else if (input instanceof MouseWheelEvent) { linkBindButtonToMouseWheel(((MouseWheelEvent) input).getWheelTurns(), bindId); } } public void linkBindButtonToKey(int key, SimpleUri bindId) { BindableButtonImpl bindInfo = buttonLookup.get(bindId); keyBinds.put(key, bindInfo); } public void linkBindButtonToMouse(MouseInput mouseButton, SimpleUri bindId) { BindableButtonImpl bindInfo = buttonLookup.get(bindId); mouseButtonBinds.put(mouseButton, bindInfo); } public void linkBindButtonToMouseWheel(int direction, SimpleUri bindId) { if (direction > 0) { mouseWheelDownBind = buttonLookup.get(bindId); } else if (direction < 0) { mouseWheelUpBind = buttonLookup.get(bindId); } } public BindableAxis registerBindAxis(String id, BindableButton positiveButton, BindableButton negativeButton) { return registerBindAxis(id, new BindAxisEvent(), positiveButton, negativeButton); } public BindableAxis registerBindAxis(String id, BindAxisEvent event, SimpleUri positiveButtonId, SimpleUri negativeButtonId) { return registerBindAxis(id, event, getBindButton(positiveButtonId), getBindButton(negativeButtonId)); } public BindableAxis registerBindAxis(String id, BindAxisEvent event, BindableButton positiveButton, BindableButton negativeButton) { BindableAxisImpl axis = new BindableAxisImpl(id, event, positiveButton, negativeButton); axisBinds.add(axis); axisLookup.put(id, axis); return axis; } public void update(float delta) { processMouseInput(delta); processKeyboardInput(delta); processBindRepeats(delta); processBindAxis(delta); } public boolean isCapturingMouse() { return capturingMouse && display.hasFocus(); } public void setCapturingMouse(boolean capturingMouse) { this.capturingMouse = capturingMouse; } private void processMouseInput(float delta) { if (!isCapturingMouse()) { return; } Vector2i deltaMouse = mouse.getDelta(); //process mouse movement x axis if (deltaMouse.x != 0) { MouseAxisEvent event = new MouseXAxisEvent(deltaMouse.x * config.getInput().getMouseSensitivity(), delta); setupTarget(event); for (EntityRef entity : getInputEntities()) { entity.send(event); if (event.isConsumed()) { break; } } } //process mouse movement y axis if (deltaMouse.y != 0) { int yMovement = config.getInput().isMouseYAxisInverted() ? deltaMouse.y * -1 : deltaMouse.y; MouseAxisEvent event = new MouseYAxisEvent(yMovement * config.getInput().getMouseSensitivity(), delta); setupTarget(event); for (EntityRef entity : getInputEntities()) { entity.send(event); if (event.isConsumed()) { break; } } } //process mouse clicks for (InputAction action : mouse.getInputQueue()) { switch (action.getInput().getType()) { case MOUSE_BUTTON: int id = action.getInput().getId(); if (id != -1) { MouseInput button = MouseInput.find(action.getInput().getType(), action.getInput().getId()); boolean consumed = sendMouseEvent(button, action.getState().isDown(), action.getMousePosition(), delta); BindableButtonImpl bind = mouseButtonBinds.get(button); if (bind != null) { bind.updateBindState( action.getInput(), action.getState().isDown(), delta, getInputEntities(), targetSystem.getTarget(), targetSystem.getTargetBlockPosition(), targetSystem.getHitPosition(), targetSystem.getHitNormal(), consumed ); } } break; case MOUSE_WHEEL: int dir = action.getInput().getId(); if (dir != 0 && action.getTurns() != 0) { boolean consumed = sendMouseWheelEvent(action.getMousePosition(), dir * action.getTurns(), delta); BindableButtonImpl bind = (dir == 1) ? mouseWheelUpBind : mouseWheelDownBind; if (bind != null) { for (int i = 0; i < action.getTurns(); ++i) { bind.updateBindState( action.getInput(), true, delta, getInputEntities(), targetSystem.getTarget(), targetSystem.getTargetBlockPosition(), targetSystem.getHitPosition(), targetSystem.getHitNormal(), consumed ); bind.updateBindState( action.getInput(), false, delta, getInputEntities(), targetSystem.getTarget(), targetSystem.getTargetBlockPosition(), targetSystem.getHitPosition(), targetSystem.getHitNormal(), consumed ); } } } break; case KEY: break; } } } private void setupTarget(InputEvent event) { if (targetSystem.isTargetAvailable()) { event.setTargetInfo(targetSystem.getTarget(), targetSystem.getTargetBlockPosition(), targetSystem.getHitPosition(), targetSystem.getHitNormal()); } } private void processKeyboardInput(float delta) { for (InputAction action : keyboard.getInputQueue()) { boolean consumed = sendKeyEvent(action.getInput(), action.getInputChar(), action.getState(), delta); // Update bind BindableButtonImpl bind = keyBinds.get(action.getInput().getId()); if (bind != null && action.getState() != ButtonState.REPEAT) { bind.updateBindState( action.getInput(), (action.getState() == ButtonState.DOWN), delta, getInputEntities(), targetSystem.getTarget(), targetSystem.getTargetBlockPosition(), targetSystem.getHitPosition(), targetSystem.getHitNormal(), consumed ); } } } private void processBindAxis(float delta) { for (BindableAxisImpl axis : axisBinds) { axis.update(getInputEntities(), delta, targetSystem.getTarget(), targetSystem.getTargetBlockPosition(), targetSystem.getHitPosition(), targetSystem.getHitNormal()); } } private void processBindRepeats(float delta) { for (BindableButtonImpl button : buttonBinds) { button.update(getInputEntities(), delta, targetSystem.getTarget(), targetSystem.getTargetBlockPosition(), targetSystem.getHitPosition(), targetSystem.getHitNormal()); } } private boolean sendKeyEvent(Input key, char keyChar, ButtonState state, float delta) { KeyEvent event; switch (state) { case UP: event = KeyUpEvent.create(key, keyChar, delta); break; case DOWN: event = KeyDownEvent.create(key, keyChar, delta); break; case REPEAT: event = KeyRepeatEvent.create(key, keyChar, delta); break; default: return false; } setupTarget(event); for (EntityRef entity : getInputEntities()) { entity.send(event); if (event.isConsumed()) { break; } } boolean consumed = event.isConsumed(); event.reset(); return consumed; } private boolean sendMouseEvent(MouseInput button, boolean buttonDown, Vector2i position, float delta) { MouseButtonEvent event; switch (button) { case NONE: return false; case MOUSE_LEFT: event = (buttonDown) ? LeftMouseDownButtonEvent.create(position, delta) : LeftMouseUpButtonEvent.create(position, delta); break; case MOUSE_RIGHT: event = (buttonDown) ? RightMouseDownButtonEvent.create(position, delta) : RightMouseUpButtonEvent.create(position, delta); break; default: event = (buttonDown) ? MouseDownButtonEvent.create(button, position, delta) : MouseUpButtonEvent.create(button, position, delta); break; } setupTarget(event); for (EntityRef entity : getInputEntities()) { entity.send(event); if (event.isConsumed()) { break; } } boolean consumed = event.isConsumed(); event.reset(); return consumed; } private boolean sendMouseWheelEvent(Vector2i pos, int wheelTurns, float delta) { MouseWheelEvent mouseWheelEvent = new MouseWheelEvent(pos, wheelTurns, delta); setupTarget(mouseWheelEvent); for (EntityRef entity : getInputEntities()) { entity.send(mouseWheelEvent); if (mouseWheelEvent.isConsumed()) { break; } } return mouseWheelEvent.isConsumed(); } private EntityRef[] getInputEntities() { return new EntityRef[]{localPlayer.getClientEntity(), localPlayer.getCharacterEntity()}; } }
{ "content_hash": "8e7be1f023c992c55985bfd9012d1c48", "timestamp": "", "source": "github", "line_count": 421, "max_line_length": 157, "avg_line_length": 38.94061757719715, "alnum_prop": 0.5937538123703794, "repo_name": "jacklotusho/Terasology", "id": "496fefedf433a94d41c407549492ae9296eb75fa", "size": "16990", "binary": false, "copies": "4", "ref": "refs/heads/develop", "path": "engine/src/main/java/org/terasology/input/InputSystem.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "38" }, { "name": "GLSL", "bytes": "109450" }, { "name": "Groovy", "bytes": "1996" }, { "name": "Java", "bytes": "6402121" }, { "name": "Protocol Buffer", "bytes": "9493" }, { "name": "Shell", "bytes": "7873" } ], "symlink_target": "" }
Implementation of the PageRank algorithm in Python and Java. # Pseudo Code http://www.ccs.neu.edu/course/cs6200f13/proj1.html
{ "content_hash": "5125c2c36b510e44509a67ac0290cdda", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 60, "avg_line_length": 31.75, "alnum_prop": 0.7952755905511811, "repo_name": "kish1/PageRank", "id": "622553c58f910f0e340213aa61d89381251860b2", "size": "138", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "7888" }, { "name": "Python", "bytes": "2474" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"><meta charset="utf-8" /> <title>Ultimate Boot CD - Overview - Reflections</title> <meta name="description" content="Default Page Description" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="http://blog.shiv.me/css/latex.css" /> <link rel="stylesheet" href="http://blog.shiv.me/css/main.css" /> <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script> <meta name="generator" content="Hugo 0.75.1" /><body> <header> <nav class="navbar"> <div class="nav"> <ul class="nav-links"> </ul> </div> </nav> <div class="intro-header"> <div class="container"> <div class="post-heading"> <h1>Ultimate Boot CD - Overview</h1> </div> </div> </div> </header> <div id="content"> <div class="container" role="main"> <article class="article" class="blog-post"> <div class="postmeta"> <span class="meta-post"> <i class="fa fa-calendar-alt"></i>Oct 7, 2004 </span> </div> <br> <p><a href="http://www.ultimatebootcd.com/">ultimate boot cd</a></p> <p>Check out this link!! Really useful for those like me who invariably end up doing something to their OS that they have to reimage their pc atleast once in two months!! I have CD writer and I back up most of my work, so I get to fiddle with whatever, but my data is safe!!!</p> </article> </div> </div><footer> <div class="container"> <p class="credits copyright"> <p class="credits theme-by"> Powered By <a href="https://gohugo.io">Hugo</a>&nbsp;/&nbsp;Theme&nbsp;<a href="https://github.com/7ma7X/HugoTeX">HugoTeX</a> <br> <a href="http://blog.shiv.me/about">Shiva Velmurugan</a> &copy; 2016 </p> </div> </footer></body> </html>
{ "content_hash": "50a46aadfd5f54cf15faa7ec25f12136", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 279, "avg_line_length": 26.626666666666665, "alnum_prop": 0.6054081121682524, "repo_name": "shiva/shiva.github.io", "id": "03f92b30d730a2863fe40201703cdf7256309f04", "size": "1997", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "2004/10/07/ultimate-boot-cd-overview/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "24620" }, { "name": "HTML", "bytes": "1863844" }, { "name": "Shell", "bytes": "2974" } ], "symlink_target": "" }
<?php /** * SlideDeck What's New Section * * More information on this project: * http://www.slidedeck.com/ * * Full Usage Documentation: http://www.slidedeck.com/usage-documentation * * @package SlideDeck * @subpackage SlideDeck 2 Pro for WordPress * @author dtelepathy */ /* Copyright 2012 digital-telepathy (email : [email protected]) This file is part of SlideDeck. SlideDeck is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SlideDeck is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with SlideDeck. If not, see <http://www.gnu.org/licenses/>. */ ?> <h3>Welcome to SlideDeck 2 for WordPress!</h3> <p><strong>Changelog:</strong></p> <ul> <li>Complete rewrite of SlideDeck core to be OOP</li> <li>Re-organization of how many AJAX actions are processed</li> <li>Consolidation of CSS and JavaScript loading methods into logical sub-routines</li> <li>Completely modularized SlideDeck core and made all CRUD and display systems hookable to accommodate for a variety of SlideDeck content types and building interfaces</li> <li>Converted vertical slide content storage for Legacy SlideDecks to use base64_encode() method to better preserve serialized data when using multibyte strings</li> <li>Re-wrote some lens JavaScript architecture to work properly with new preview method</li> <li>Created a lens management section for copying, deleting, editing and uploading SlideDeck lenses with a syntax highlighted source code editor</li> </ul>
{ "content_hash": "e32acf91ed6aa3839cfa7deee35e6299", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 177, "avg_line_length": 43.59090909090909, "alnum_prop": 0.7659019812304484, "repo_name": "mandino/www.bloggingshakespeare.com", "id": "90b4fc784e1213b426f919479cb1a33c3f249583", "size": "1918", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "wp-content/plugins/slidedeck2-personal/views/help/whats-new.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "5211957" }, { "name": "CoffeeScript", "bytes": "552" }, { "name": "HTML", "bytes": "525757" }, { "name": "JavaScript", "bytes": "6055696" }, { "name": "Modelica", "bytes": "10338" }, { "name": "PHP", "bytes": "44197755" }, { "name": "Perl", "bytes": "2554" }, { "name": "Ruby", "bytes": "3917" }, { "name": "Smarty", "bytes": "27821" }, { "name": "XSLT", "bytes": "34552" } ], "symlink_target": "" }
/* jshint node:true */ var BuildTask = require('ember-cli/lib/tasks/build'); var RSVP = require('rsvp'); var publisher = require('publish'); // Create promise friendly versions of the methods we want to use var start = RSVP.denodeify(publisher.start); var publish = RSVP.denodeify(publisher.publish); module.exports = { // Build the project in the production environment, outputting to dist/ beforeCommit: function(project) { var task = new BuildTask({ project: project, ui: project.ui, analytics: project.cli.analytics }); return task.run({ environment: 'production', outputPath: 'dist/' }); }, // Publish the new release to NPM after a successful push afterPush: function() { return start().then(function() { return publish(); }); } };
{ "content_hash": "1672fb794810b3d78c1cfb6e6456c505", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 73, "avg_line_length": 25.46875, "alnum_prop": 0.6613496932515337, "repo_name": "jackweinbender/ember-data.model-fragments", "id": "824914d26257d922fe9f0ede9aed669810d67e13", "size": "815", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "config/release.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "237128" } ], "symlink_target": "" }
require 'spec_helper' describe Chef::Resource::Template do include_context Chef::Resource::File let(:file_base) { "template_spec" } let(:expected_content) { "slappiness is a warm gun" } let(:node) do node = Chef::Node.new node[:slappiness] = "a warm gun" node end def create_resource cookbook_repo = File.expand_path(File.join(CHEF_SPEC_DATA, "cookbooks")) Chef::Cookbook::FileVendor.on_create { |manifest| Chef::Cookbook::FileSystemFileVendor.new(manifest, cookbook_repo) } cookbook_collection = Chef::CookbookCollection.new(Chef::CookbookLoader.new(cookbook_repo)) events = Chef::EventDispatch::Dispatcher.new run_context = Chef::RunContext.new(node, cookbook_collection, events) resource = Chef::Resource::Template.new(path, run_context) resource.source('openldap_stuff.conf.erb') resource.cookbook('openldap') resource end let!(:resource) do create_resource end it_behaves_like "a file resource" context "when the target file does not exist" do it "creates the template with the rendered content using the variable attribute when the :create action is run" do resource.source('openldap_variable_stuff.conf.erb') resource.variables(:secret => "nutella") resource.run_action(:create) IO.read(path).should == "super secret is nutella" end it "creates the template with the rendered content using a local erb file when the :create action is run" do resource.source(File.expand_path(File.join(CHEF_SPEC_DATA,'cookbooks','openldap','templates','default','openldap_stuff.conf.erb'))) resource.cookbook(nil) resource.local(true) resource.run_action(:create) IO.read(path).should == expected_content end end end
{ "content_hash": "9af488a9aac438cb46915435a2dc0d72", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 137, "avg_line_length": 35.24, "alnum_prop": 0.7060158910329172, "repo_name": "aspiers/chef", "id": "c44e798b88af5bf89ca76cc2cf9a16a9170a72e3", "size": "2451", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "chef/spec/functional/resource/template_spec.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "92560" }, { "name": "Perl", "bytes": "948" }, { "name": "Python", "bytes": "8568" }, { "name": "Ruby", "bytes": "4159744" }, { "name": "Shell", "bytes": "18881" } ], "symlink_target": "" }
/* Package genschema provides a generator for the JSON schema controller. The schema controller responds to GET /schema requests with the API JSON Hyper-schema. This JSON schema can be used to generate API documentation, ruby and Go API clients. See the blog post (https://blog.heroku.com/archives/2014/1/8/json_schema_for_heroku_platform_api) describing how Heroku leverages the JSON Hyper-schema standard (http://json-schema.org/latest/json-schema-hypermedia.html) for more information. */ package genschema
{ "content_hash": "1bd218c1aaee8e1ff80ab7beb58549c8", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 122, "avg_line_length": 56.666666666666664, "alnum_prop": 0.803921568627451, "repo_name": "smessier/goa", "id": "acffdd39a6bb07b5d2bedad03921e7fdc7dcfcb4", "size": "510", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "goagen/gen_schema/doc.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "1403575" }, { "name": "Makefile", "bytes": "1582" } ], "symlink_target": "" }
<div class="filters"> <div class="filter-toggle"> <span ng-hide="ctrl.filterConfig.show" ng-click="ctrl.toggleShowFilters()" class="link show-filters">Show filters</span> <span ng-show="ctrl.filterConfig.show" ng-click="ctrl.toggleShowFilters()" class="link hide-filters">Hide filters</span> </div> <div ng-show="ctrl.filterConfig.show" class="filter-select"> <div class="row filter-field"> <div class="small-3 medium-2 columns"> <label>Limit to open/closed</label> </div> <div class="small-9 medium-10 columns"> <select ng-model="ctrl.filterConfig.filters['open']"> <option value="1">open</option> <option value="0">closed</option> </select> </div> </div> <div class="row filter-field"> <div class="small-3 medium-2 columns"> <label>Order type</label> </div> <div class="small-9 medium-10 columns"> <select ng-model="ctrl.filterConfig.filters['order_type_id']" ng-change="ctrl.resetOrderSubTypeFilter()"> <option ng-repeat="orderType in ctrl.controlledValues['order_type']" value="{{ orderType.id }}">{{ orderType.label }}</option> </select> </div> </div> <div class="row filter-field" ng-if="ctrl.filterConfig.filters['order_type_id']"> <div class="small-3 medium-2 columns"> <label>Order sub-type</label> </div> <div class="small-9 medium-10 columns"> <span ng-repeat="orderSubType in ctrl.controlledValues['order_sub_type'] | filter:{ order_type_id: ctrl.filterConfig.filters['order_type_id'] }" class="radio-inline"> <input type="radio" ng-model="ctrl.filterConfig.filters['order_sub_type_id']" value="orderSubType.id" ng-value="orderSubType.id"/> {{ orderSubType.label }} </span> </div> </div> <div class="row filter-field"> <div class="small-3 medium-2 columns"> <label>Status</label> </div> <div class="small-9 medium-10 columns"> <select ng-model="ctrl.filterConfig.filters['state']"> <option ng-repeat="stateEvent in ctrl.orderStatesEvents" value="{{ stateEvent['to_state'] }}">{{ stateEvent['to_state'] | removeUnderscores }}</option> </select> </div> </div> <div class="row filter-field"> <div class="small-3 medium-2 columns"> <label>Item status</label> </div> <div class="small-9 medium-10 columns"> <select ng-model="ctrl.filterConfig.filters['item_state']"> <option ng-repeat="stateEvent in ctrl.itemStatesEvents['physical']" value="{{ stateEvent['to_state'] }}">{{ stateEvent['to_state'] | removeUnderscores }}</option> </select> </div> </div> <div class="row filter-field"> <div class="small-3 medium-2 columns"> <label>Researcher email</label> </div> <div class="small-9 medium-10 columns"> <div class="row collapse" ng-hide="ctrl.userSelect['loading']"> <div ng-show="ctrl.filterConfig.filters['user_email']" class="selected-value"> {{ ctrl.filterConfig.filters['user_email'] }} <i class="fas fa-times-circle link" ng-click="ctrl.resetFilter('user_email')"></i> </div> <div ng-hide="ctrl.filterConfig.filters['user_email']" class="user-select"> <input type="text" ng-model="ctrl.userSelect.q" ng-keyup="ctrl.updateUserSelectList()" placeholder="Enter user name or email" /> <div class="user-select-list" ng-show="ctrl.userSelect.list.length > 0"> <ul> <li ng-repeat="user in ctrl.userSelect.list" ng-class="$last ? 'last' : ''" ng-click="ctrl.addUserFilter(user)"> {{ user['display_name'] }} ( {{ user['email'] }} ) </li> </ul> </div> </div> </div> </div> </div> <div class="row filter-field"> <div class="small-3 medium-2 columns"> <label>Assignee email</label> </div> <div class="small-9 medium-10 columns"> <div class="row collapse" ng-hide="ctrl.assigneeSelect['loading']"> <div ng-show="ctrl.filterConfig.filters['assignee_email']" class="selected-value"> {{ ctrl.filterConfig.filters['assignee_email'] }} <i class="fas fa-times-circle link" ng-click="ctrl.resetFilter('assignee_email')"></i> </div> <div ng-hide="ctrl.filterConfig.filters['assignee_email']" class="user-select"> <input type="text" ng-model="ctrl.assigneeSelect.q" ng-keyup="ctrl.updateAssigneeSelectList()" placeholder="Enter user name or email" /> <div class="user-select-list" ng-show="ctrl.assigneeSelect.list.length > 0"> <ul> <li ng-repeat="user in ctrl.assigneeSelect.list" ng-class="$last ? 'last' : ''" ng-click="ctrl.addAssigneeFilter(user)"> {{ user['display_name'] }} ( {{ user['email'] }} ) </li> </ul> </div> </div> </div> </div> </div> <div class="row filter-field date-range"> <div class="small-3 medium-2 columns"> <label>Access dates:</label> </div> <div class="small-9 medium-10 columns"> <span class="date-range-point date-range-from"> <label>after</label> <input type="text" datepicker allow-past-dates="1" ng-model="ctrl.filterConfig.options['access_date_from']" ng-change="ctrl.setDateFilter()" class="datepicker-input"/> </span> <span class="date-range-point date-range-to"> <label>before</label> <input type="text" datepicker allow-past-dates="1" ng-model="ctrl.filterConfig.options['access_date_to']" ng-change="ctrl.setDateFilter()" class="datepicker-input"/> </span> </div> </div> <span class="button small" ng-click="ctrl.applyFilters()">Apply filters</span> </div> </div> <div class="active-filters" ng-show="ctrl.filterConfig.filtersApplied"> <label>Filters:</label> <span ng-repeat="(filter, value) in ctrl.filterConfig.appliedFilters" class="filter"> <span ng-if="filter=='open' && value">Open: {{ value | booleanString }}</span> <span ng-if="filter=='order_type_id'">Order type: {{ ctrl.getControlledValueLabel(ctrl.controlledValues['order_type'], value) }}</span> <span ng-if="filter=='order_sub_type_id'">Order sub-type: {{ ctrl.getControlledValueLabel(ctrl.controlledValues['order_sub_type'], value) }}</span> <span ng-if="filter=='user_email'">Researcher: {{ value }}</span> <span ng-if="filter=='assignee_email'">Assignee: {{ value }}</span> <span ng-if="filter=='access_dates'">Access dates: {{ value }}</span> <span ng-if="filter=='state'">Status: {{ value | removeUnderscores }}</span> <span ng-if="filter=='item_state'">Item status: {{ value | removeUnderscores }}</span> <span ng-include="ctrl.templateUrl('common/remove_list_filter')"/> </span> <span class="link action" ng-click="ctrl.resetFilters();">Clear all filters</span> </div>
{ "content_hash": "26a7d03ce7e710775ea9cfa86580ab02", "timestamp": "", "source": "github", "line_count": 197, "max_line_length": 177, "avg_line_length": 37.65989847715736, "alnum_prop": 0.5785146246124815, "repo_name": "NCSU-Libraries/circa", "id": "42d144acd36c1900863bca37683a3f209fa54716", "size": "7419", "binary": false, "copies": "1", "ref": "refs/heads/dependabot/bundler/nokogiri-1.11.4", "path": "public/templates/orders/list_filters.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "36551" }, { "name": "Dockerfile", "bytes": "1740" }, { "name": "HTML", "bytes": "202552" }, { "name": "JavaScript", "bytes": "43466" }, { "name": "Python", "bytes": "313" }, { "name": "Ruby", "bytes": "361746" }, { "name": "Shell", "bytes": "1373" } ], "symlink_target": "" }
package com.intellij.debugger.impl; import com.intellij.debugger.DebugEnvironment; import com.intellij.debugger.DebuggerBundle; import com.intellij.debugger.DebuggerInvocationUtil; import com.intellij.debugger.SourcePosition; import com.intellij.debugger.engine.*; import com.intellij.debugger.engine.evaluation.EvaluateException; import com.intellij.debugger.engine.evaluation.EvaluationListener; import com.intellij.debugger.engine.events.SuspendContextCommandImpl; import com.intellij.debugger.engine.jdi.StackFrameProxy; import com.intellij.debugger.engine.requests.RequestManagerImpl; import com.intellij.debugger.jdi.StackFrameProxyImpl; import com.intellij.debugger.jdi.ThreadReferenceProxyImpl; import com.intellij.debugger.ui.breakpoints.Breakpoint; import com.intellij.debugger.ui.breakpoints.BreakpointWithHighlighter; import com.intellij.debugger.ui.breakpoints.LineBreakpoint; import com.intellij.execution.ExecutionException; import com.intellij.execution.ExecutionResult; import com.intellij.execution.configurations.RemoteConnection; import com.intellij.execution.configurations.RemoteState; import com.intellij.execution.configurations.RunProfileState; import com.intellij.execution.process.ProcessHandler; import com.intellij.execution.process.ProcessOutputTypes; import com.intellij.idea.ActionsBundle; import com.intellij.notification.Notification; import com.intellij.notification.NotificationListener; import com.intellij.notification.NotificationType; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.registry.Registry; import com.intellij.psi.PsiCompiledElement; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.unscramble.ThreadState; import com.intellij.util.Alarm; import com.intellij.util.TimeoutUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.UIUtil; import com.intellij.xdebugger.AbstractDebuggerSession; import com.intellij.xdebugger.XDebugSession; import com.intellij.xdebugger.XSourcePosition; import com.intellij.xdebugger.impl.XDebugSessionImpl; import com.intellij.xdebugger.impl.actions.XDebuggerActions; import com.intellij.xdebugger.impl.evaluate.quick.common.ValueLookupManager; import com.sun.jdi.ObjectCollectedException; import com.sun.jdi.ThreadReference; import com.sun.jdi.request.EventRequest; import com.sun.jdi.request.StepRequest; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.event.HyperlinkEvent; import java.util.Collection; import java.util.List; import java.util.Set; public class DebuggerSession implements AbstractDebuggerSession { private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.impl.DebuggerSession"); // flags private final MyDebuggerStateManager myContextManager; public enum State {STOPPED, RUNNING, WAITING_ATTACH, PAUSED, WAIT_EVALUATION, DISPOSED} public enum Event {ATTACHED, DETACHED, RESUME, STEP, PAUSE, REFRESH, CONTEXT, START_WAIT_ATTACH, DISPOSE, REFRESH_VIEWS_ONLY, THREADS_REFRESH} private volatile boolean myIsEvaluating; private volatile int myIgnoreFiltersFrameCountThreshold = 0; private DebuggerSessionState myState = null; private final String mySessionName; private final DebugProcessImpl myDebugProcess; private final GlobalSearchScope mySearchScope; private final DebuggerContextImpl SESSION_EMPTY_CONTEXT; //Thread, user is currently stepping through private final Set<ThreadReferenceProxyImpl> mySteppingThroughThreads = ContainerUtil.newConcurrentSet(); protected final Alarm myUpdateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD); private boolean myModifiedClassesScanRequired = false; public boolean isSteppingThrough(ThreadReferenceProxyImpl threadProxy) { return mySteppingThroughThreads.contains(threadProxy); } public boolean setSteppingThrough(ThreadReferenceProxyImpl threadProxy) { if (threadProxy != null) { return mySteppingThroughThreads.add(threadProxy); } return false; } @NotNull public GlobalSearchScope getSearchScope() { return mySearchScope; } public boolean isModifiedClassesScanRequired() { return myModifiedClassesScanRequired; } public void setModifiedClassesScanRequired(boolean modifiedClassesScanRequired) { myModifiedClassesScanRequired = modifiedClassesScanRequired; } private class MyDebuggerStateManager extends DebuggerStateManager { private DebuggerContextImpl myDebuggerContext; MyDebuggerStateManager() { myDebuggerContext = SESSION_EMPTY_CONTEXT; } @Override public DebuggerContextImpl getContext() { return myDebuggerContext; } /** * actually state changes not in the same sequence as you call setState * the 'resuming' setState with context.getSuspendContext() == null may be set prior to * the setState for the context with context.getSuspendContext() * * in this case we assume that the latter setState is ignored * since the thread was resumed */ @Override public void setState(final DebuggerContextImpl context, final State state, final Event event, final String description) { ApplicationManager.getApplication().assertIsDispatchThread(); final DebuggerSession session = context.getDebuggerSession(); LOG.assertTrue(session == DebuggerSession.this || session == null); final Runnable setStateRunnable = new Runnable() { @Override public void run() { LOG.assertTrue(myDebuggerContext.isInitialised()); myDebuggerContext = context; if (LOG.isDebugEnabled()) { LOG.debug("DebuggerSession state = " + state + ", event = " + event); } myIsEvaluating = false; myState = new DebuggerSessionState(state, description); fireStateChanged(context, event); } }; if(context.getSuspendContext() == null) { setStateRunnable.run(); } else { getProcess().getManagerThread().schedule(new SuspendContextCommandImpl(context.getSuspendContext()) { @Override public void contextAction() throws Exception { context.initCaches(); DebuggerInvocationUtil.swingInvokeLater(getProject(), setStateRunnable); } }); } } } static DebuggerSession create(String sessionName, @NotNull final DebugProcessImpl debugProcess, DebugEnvironment environment) throws ExecutionException { DebuggerSession session = new DebuggerSession(sessionName, debugProcess, environment); try { session.attach(environment); } catch (ExecutionException e) { session.dispose(); throw e; } return session; } private DebuggerSession(String sessionName, @NotNull final DebugProcessImpl debugProcess, DebugEnvironment environment) { mySessionName = sessionName; myDebugProcess = debugProcess; SESSION_EMPTY_CONTEXT = DebuggerContextImpl.createDebuggerContext(this, null, null, null); myContextManager = new MyDebuggerStateManager(); myState = new DebuggerSessionState(State.STOPPED, null); myDebugProcess.addDebugProcessListener(new MyDebugProcessListener(debugProcess)); myDebugProcess.addEvaluationListener(new MyEvaluationListener()); ValueLookupManager.getInstance(getProject()).startListening(); mySearchScope = environment.getSearchScope(); } @NotNull public DebuggerStateManager getContextManager() { return myContextManager; } public Project getProject() { return getProcess().getProject(); } public String getSessionName() { return mySessionName; } @NotNull public DebugProcessImpl getProcess() { return myDebugProcess; } private static class DebuggerSessionState { final State myState; final String myDescription; public DebuggerSessionState(State state, String description) { myState = state; myDescription = description; } } public State getState() { return myState.myState; } public String getStateDescription() { if (myState.myDescription != null) { return myState.myDescription; } switch (myState.myState) { case STOPPED: return DebuggerBundle.message("status.debug.stopped"); case RUNNING: return DebuggerBundle.message("status.app.running"); case WAITING_ATTACH: RemoteConnection connection = getProcess().getConnection(); final String addressDisplayName = DebuggerBundle.getAddressDisplayName(connection); final String transportName = DebuggerBundle.getTransportName(connection); return connection.isServerMode() ? DebuggerBundle.message("status.listening", addressDisplayName, transportName) : DebuggerBundle.message("status.connecting", addressDisplayName, transportName); case PAUSED: return DebuggerBundle.message("status.paused"); case WAIT_EVALUATION: return DebuggerBundle.message("status.waiting.evaluation.result"); case DISPOSED: return DebuggerBundle.message("status.debug.stopped"); } return null; } /* Stepping */ private void resumeAction(final DebugProcessImpl.ResumeCommand command, Event event) { getContextManager().setState(SESSION_EMPTY_CONTEXT, State.WAIT_EVALUATION, event, null); myDebugProcess.getManagerThread().schedule(command); } public void stepOut(int stepSize) { SuspendContextImpl suspendContext = getSuspendContext(); DebugProcessImpl.ResumeCommand cmd = null; for (JvmSteppingCommandProvider handler : JvmSteppingCommandProvider.EP_NAME.getExtensions()) { cmd = handler.getStepOutCommand(suspendContext, stepSize); if (cmd != null) break; } if (cmd == null) { cmd = myDebugProcess.createStepOutCommand(suspendContext, stepSize); } setSteppingThrough(cmd.getContextThread()); resumeAction(cmd, Event.STEP); } public void stepOut() { stepOut(StepRequest.STEP_LINE); } public void stepOver(boolean ignoreBreakpoints, int stepSize) { SuspendContextImpl suspendContext = getSuspendContext(); DebugProcessImpl.ResumeCommand cmd = null; for (JvmSteppingCommandProvider handler : JvmSteppingCommandProvider.EP_NAME.getExtensions()) { cmd = handler.getStepOverCommand(suspendContext, ignoreBreakpoints, stepSize); if (cmd != null) break; } if (cmd == null) { cmd = myDebugProcess.createStepOverCommand(suspendContext, ignoreBreakpoints, stepSize); } setSteppingThrough(cmd.getContextThread()); resumeAction(cmd, Event.STEP); } public void stepOver(boolean ignoreBreakpoints) { stepOver(ignoreBreakpoints, StepRequest.STEP_LINE); } public void stepInto(final boolean ignoreFilters, final @Nullable MethodFilter smartStepFilter, int stepSize) { final SuspendContextImpl suspendContext = getSuspendContext(); DebugProcessImpl.ResumeCommand cmd = null; for (JvmSteppingCommandProvider handler : JvmSteppingCommandProvider.EP_NAME.getExtensions()) { cmd = handler.getStepIntoCommand(suspendContext, ignoreFilters, smartStepFilter, stepSize); if (cmd != null) break; } if (cmd == null) { cmd = myDebugProcess.createStepIntoCommand(suspendContext, ignoreFilters, smartStepFilter, stepSize); } setSteppingThrough(cmd.getContextThread()); resumeAction(cmd, Event.STEP); } public void stepInto(final boolean ignoreFilters, final @Nullable MethodFilter smartStepFilter) { stepInto(ignoreFilters, smartStepFilter, StepRequest.STEP_LINE); } public void runToCursor(@NotNull XSourcePosition position, final boolean ignoreBreakpoints) { try { DebugProcessImpl.ResumeCommand runToCursorCommand = myDebugProcess.createRunToCursorCommand(getSuspendContext(), position, ignoreBreakpoints); setSteppingThrough(runToCursorCommand.getContextThread()); resumeAction(runToCursorCommand, Event.STEP); } catch (EvaluateException e) { Messages.showErrorDialog(e.getMessage(), UIUtil.removeMnemonic(ActionsBundle.actionText(XDebuggerActions.RUN_TO_CURSOR))); } } public void resume() { final SuspendContextImpl suspendContext = getSuspendContext(); if(suspendContext != null) { if (suspendContext.getSuspendPolicy() == EventRequest.SUSPEND_ALL) { mySteppingThroughThreads.clear(); } else { mySteppingThroughThreads.remove(suspendContext.getThread()); } resetIgnoreStepFiltersFlag(); resumeAction(myDebugProcess.createResumeCommand(suspendContext), Event.RESUME); } } public void resetIgnoreStepFiltersFlag() { myIgnoreFiltersFrameCountThreshold = 0; } public void setIgnoreStepFiltersFlag(int currentStackFrameCount) { if (myIgnoreFiltersFrameCountThreshold <= 0) { myIgnoreFiltersFrameCountThreshold = currentStackFrameCount; } else { myIgnoreFiltersFrameCountThreshold = Math.min(myIgnoreFiltersFrameCountThreshold, currentStackFrameCount); } } public boolean shouldIgnoreSteppingFilters() { return myIgnoreFiltersFrameCountThreshold > 0; } public void pause() { myDebugProcess.getManagerThread().schedule(myDebugProcess.createPauseCommand()); } /*Presentation*/ public void showExecutionPoint() { getContextManager().setState(DebuggerContextUtil.createDebuggerContext(this, getSuspendContext()), State.PAUSED, Event.REFRESH, null); } public void refresh(final boolean refreshViewsOnly) { final State state = getState(); DebuggerContextImpl context = myContextManager.getContext(); DebuggerContextImpl newContext = DebuggerContextImpl.createDebuggerContext(this, context.getSuspendContext(), context.getThreadProxy(), context.getFrameProxy()); myContextManager.setState(newContext, state, refreshViewsOnly ? Event.REFRESH_VIEWS_ONLY : Event.REFRESH , null); } public void dispose() { getProcess().dispose(); Disposer.dispose(myUpdateAlarm); DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { @Override public void run() { getContextManager().setState(SESSION_EMPTY_CONTEXT, State.DISPOSED, Event.DISPOSE, null); } }); } // ManagerCommands @Override public boolean isStopped() { return getState() == State.STOPPED; } public boolean isAttached() { return !isStopped() && getState() != State.WAITING_ATTACH; } @Override public boolean isPaused() { return getState() == State.PAUSED; } public boolean isConnecting() { return getState() == State.WAITING_ATTACH; } public boolean isEvaluating() { return myIsEvaluating; } public boolean isRunning() { return getState() == State.RUNNING && !getProcess().getProcessHandler().isProcessTerminated(); } private SuspendContextImpl getSuspendContext() { ApplicationManager.getApplication().assertIsDispatchThread(); return getContextManager().getContext().getSuspendContext(); } @Nullable private ExecutionResult attach(DebugEnvironment environment) throws ExecutionException { RemoteConnection remoteConnection = environment.getRemoteConnection(); final String addressDisplayName = DebuggerBundle.getAddressDisplayName(remoteConnection); final String transportName = DebuggerBundle.getTransportName(remoteConnection); final ExecutionResult executionResult = myDebugProcess.attachVirtualMachine(environment, this); getContextManager().setState(SESSION_EMPTY_CONTEXT, State.WAITING_ATTACH, Event.START_WAIT_ATTACH, DebuggerBundle.message("status.waiting.attach", addressDisplayName, transportName)); return executionResult; } private class MyDebugProcessListener extends DebugProcessAdapterImpl { private final DebugProcessImpl myDebugProcess; public MyDebugProcessListener(final DebugProcessImpl debugProcess) { myDebugProcess = debugProcess; } //executed in manager thread @Override public void connectorIsReady() { DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { @Override public void run() { RemoteConnection connection = myDebugProcess.getConnection(); final String addressDisplayName = DebuggerBundle.getAddressDisplayName(connection); final String transportName = DebuggerBundle.getTransportName(connection); final String connectionStatusMessage = connection.isServerMode() ? DebuggerBundle.message("status.listening", addressDisplayName, transportName) : DebuggerBundle.message("status.connecting", addressDisplayName, transportName); getContextManager().setState(SESSION_EMPTY_CONTEXT, State.WAITING_ATTACH, Event.START_WAIT_ATTACH, connectionStatusMessage); } }); } @Override public void paused(final SuspendContextImpl suspendContext) { if (LOG.isDebugEnabled()) { LOG.debug("paused"); } if (!shouldSetAsActiveContext(suspendContext)) { DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { @Override public void run() { getContextManager().fireStateChanged(getContextManager().getContext(), Event.THREADS_REFRESH); } }); final ThreadReferenceProxyImpl thread = suspendContext.getThread(); if (thread != null) { List<Pair<Breakpoint, com.sun.jdi.event.Event>> descriptors = DebuggerUtilsEx.getEventDescriptors(suspendContext); if (!descriptors.isEmpty()) { XDebugSessionImpl.NOTIFICATION_GROUP.createNotification( DebuggerBundle.message("status.breakpoint.reached.in.thread", thread.name()), DebuggerBundle.message("status.breakpoint.reached.in.thread.switch"), NotificationType.INFORMATION, new NotificationListener() { @Override public void hyperlinkUpdate(@NotNull Notification notification, @NotNull HyperlinkEvent event) { if (event.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { notification.expire(); getProcess().getManagerThread().schedule(new SuspendContextCommandImpl(suspendContext) { @Override public void contextAction() throws Exception { final DebuggerContextImpl debuggerContext = DebuggerContextImpl.createDebuggerContext(DebuggerSession.this, suspendContext, thread, null); DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { @Override public void run() { getContextManager().setState(debuggerContext, State.PAUSED, Event.PAUSE, null); } }); } }); } } }).notify(getProject()); } } return; } ThreadReferenceProxyImpl currentThread = suspendContext.getThread(); final StackFrameContext positionContext; if (currentThread == null) { //Pause pressed LOG.assertTrue(suspendContext.getSuspendPolicy() == EventRequest.SUSPEND_ALL); SuspendContextImpl oldContext = getProcess().getSuspendManager().getPausedContext(); if (oldContext != null) { currentThread = oldContext.getThread(); } if(currentThread == null) { final Collection<ThreadReferenceProxyImpl> allThreads = getProcess().getVirtualMachineProxy().allThreads(); // heuristics: try to pre-select EventDispatchThread for (final ThreadReferenceProxyImpl thread : allThreads) { if (ThreadState.isEDT(thread.name())) { currentThread = thread; break; } } if (currentThread == null) { // heuristics: display the first thread with RUNNABLE status for (final ThreadReferenceProxyImpl thread : allThreads) { currentThread = thread; if (currentThread.status() == ThreadReference.THREAD_STATUS_RUNNING) { break; } } } } StackFrameProxyImpl proxy = null; if (currentThread != null) { try { while (!currentThread.isSuspended()) { // wait until thread is considered suspended. Querying data from a thread immediately after VM.suspend() // may result in IncompatibleThreadStateException, most likely some time after suspend() VM erroneously thinks that thread is still running TimeoutUtil.sleep(10); } proxy = (currentThread.frameCount() > 0) ? currentThread.frame(0) : null; } catch (ObjectCollectedException ignored) { proxy = null; } catch (EvaluateException e) { proxy = null; LOG.error(e); } } positionContext = new SimpleStackFrameContext(proxy, myDebugProcess); } else { positionContext = suspendContext; } if (currentThread != null) { try { final int frameCount = currentThread.frameCount(); if (frameCount == 0 || (frameCount <= myIgnoreFiltersFrameCountThreshold)) { resetIgnoreStepFiltersFlag(); } } catch (EvaluateException e) { LOG.info(e); resetIgnoreStepFiltersFlag(); } } SourcePosition position = PsiDocumentManager.getInstance(getProject()).commitAndRunReadAction(new Computable<SourcePosition>() { @Override public @Nullable SourcePosition compute() { return ContextUtil.getSourcePosition(positionContext); } }); if (position != null) { final List<Pair<Breakpoint, com.sun.jdi.event.Event>> eventDescriptors = DebuggerUtilsEx.getEventDescriptors(suspendContext); final RequestManagerImpl requestsManager = suspendContext.getDebugProcess().getRequestsManager(); final PsiFile foundFile = position.getFile(); final boolean sourceMissing = foundFile instanceof PsiCompiledElement; for (Pair<Breakpoint, com.sun.jdi.event.Event> eventDescriptor : eventDescriptors) { Breakpoint breakpoint = eventDescriptor.getFirst(); if (breakpoint instanceof LineBreakpoint) { final SourcePosition breakpointPosition = ((BreakpointWithHighlighter)breakpoint).getSourcePosition(); if (breakpointPosition == null || (!sourceMissing && breakpointPosition.getLine() != position.getLine())) { requestsManager.deleteRequest(breakpoint); requestsManager.setInvalid(breakpoint, DebuggerBundle.message("error.invalid.breakpoint.source.changed")); breakpoint.updateUI(); } else if (sourceMissing) { // adjust position to be position of the breakpoint in order to show the real originator of the event position = breakpointPosition; final StackFrameProxy frameProxy = positionContext.getFrameProxy(); String className; try { className = frameProxy != null? frameProxy.location().declaringType().name() : ""; } catch (EvaluateException ignored) { className = ""; } requestsManager.setInvalid(breakpoint, DebuggerBundle.message("error.invalid.breakpoint.source.not.found", className)); breakpoint.updateUI(); } } } } final DebuggerContextImpl debuggerContext = DebuggerContextImpl.createDebuggerContext(DebuggerSession.this, suspendContext, currentThread, null); debuggerContext.setPositionCache(position); DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { @Override public void run() { getContextManager().setState(debuggerContext, State.PAUSED, Event.PAUSE, null); } }); } private boolean shouldSetAsActiveContext(final SuspendContextImpl suspendContext) { final ThreadReferenceProxyImpl newThread = suspendContext.getThread(); if (newThread == null || suspendContext.getSuspendPolicy() == EventRequest.SUSPEND_ALL || isSteppingThrough(newThread)) { return true; } final SuspendContextImpl currentSuspendContext = getContextManager().getContext().getSuspendContext(); if (currentSuspendContext == null) { return true; } if (enableBreakpointsDuringEvaluation()) { final ThreadReferenceProxyImpl currentThread = currentSuspendContext.getThread(); return currentThread == null || Comparing.equal(currentThread.getThreadReference(), newThread.getThreadReference()); } return false; } @Override public void resumed(final SuspendContextImpl suspendContext) { final SuspendContextImpl currentContext = suspendContext != null && isSteppingThrough(suspendContext.getThread()) ? null : getProcess().getSuspendManager().getPausedContext(); DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { @Override public void run() { if (currentContext != null) { getContextManager().setState(DebuggerContextUtil.createDebuggerContext(DebuggerSession.this, currentContext), State.PAUSED, Event.CONTEXT, null); } else { getContextManager().setState(SESSION_EMPTY_CONTEXT, State.RUNNING, Event.CONTEXT, null); } } }); } @Override public void processAttached(final DebugProcessImpl process) { final RemoteConnection connection = getProcess().getConnection(); final String addressDisplayName = DebuggerBundle.getAddressDisplayName(connection); final String transportName = DebuggerBundle.getTransportName(connection); final String message = DebuggerBundle.message("status.connected", addressDisplayName, transportName); process.printToConsole(message + "\n"); DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { @Override public void run() { getContextManager().setState(SESSION_EMPTY_CONTEXT, State.RUNNING, Event.ATTACHED, message); } }); } @Override public void attachException(final RunProfileState state, final ExecutionException exception, final RemoteConnection remoteConnection) { DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { @Override public void run() { String message = ""; if (state instanceof RemoteState) { message = DebuggerBundle.message("status.connect.failed", DebuggerBundle.getAddressDisplayName(remoteConnection), DebuggerBundle.getTransportName(remoteConnection)); } message += exception.getMessage(); getContextManager().setState(SESSION_EMPTY_CONTEXT, State.STOPPED, Event.DETACHED, message); } }); } @Override public void processDetached(final DebugProcessImpl debugProcess, boolean closedByUser) { if (!closedByUser) { ProcessHandler processHandler = debugProcess.getProcessHandler(); if(processHandler != null) { final RemoteConnection connection = getProcess().getConnection(); final String addressDisplayName = DebuggerBundle.getAddressDisplayName(connection); final String transportName = DebuggerBundle.getTransportName(connection); processHandler.notifyTextAvailable(DebuggerBundle.message("status.disconnected", addressDisplayName, transportName) + "\n", ProcessOutputTypes.SYSTEM); } } DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { @Override public void run() { final RemoteConnection connection = getProcess().getConnection(); final String addressDisplayName = DebuggerBundle.getAddressDisplayName(connection); final String transportName = DebuggerBundle.getTransportName(connection); getContextManager().setState(SESSION_EMPTY_CONTEXT, State.STOPPED, Event.DETACHED, DebuggerBundle.message("status.disconnected", addressDisplayName, transportName)); } }); mySteppingThroughThreads.clear(); } @Override public void threadStarted(DebugProcess proc, ThreadReference thread) { notifyThreadsRefresh(); } @Override public void threadStopped(DebugProcess proc, ThreadReference thread) { notifyThreadsRefresh(); } private void notifyThreadsRefresh() { if (!myUpdateAlarm.isDisposed()) { myUpdateAlarm.cancelAllRequests(); myUpdateAlarm.addRequest(new Runnable() { @Override public void run() { final DebuggerStateManager contextManager = getContextManager(); contextManager.fireStateChanged(contextManager.getContext(), Event.THREADS_REFRESH); } }, 100, ModalityState.NON_MODAL); } } } private class MyEvaluationListener implements EvaluationListener { @Override public void evaluationStarted(SuspendContextImpl context) { myIsEvaluating = true; } @Override public void evaluationFinished(final SuspendContextImpl context) { myIsEvaluating = false; // seems to be not required after move to xdebugger //DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() { // @Override // public void run() { // if (context != getSuspendContext()) { // getContextManager().setState(DebuggerContextUtil.createDebuggerContext(DebuggerSession.this, context), STATE_PAUSED, REFRESH, null); // } // } //}); } } public static boolean enableBreakpointsDuringEvaluation() { return Registry.is("debugger.enable.breakpoints.during.evaluation"); } @Nullable public XDebugSession getXDebugSession() { JavaDebugProcess process = myDebugProcess.getXdebugProcess(); return process != null ? process.getSession() : null; } }
{ "content_hash": "d2a3c66b6f72c89289b29f3990a2d41b", "timestamp": "", "source": "github", "line_count": 767, "max_line_length": 236, "avg_line_length": 40.43285528031291, "alnum_prop": 0.6990519798787566, "repo_name": "ftomassetti/intellij-community", "id": "d7cf1f2516cb0224b5819326d654832f1052f590", "size": "31612", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "java/debugger/impl/src/com/intellij/debugger/impl/DebuggerSession.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "20665" }, { "name": "AspectJ", "bytes": "182" }, { "name": "Batchfile", "bytes": "63518" }, { "name": "C", "bytes": "214180" }, { "name": "C#", "bytes": "1538" }, { "name": "C++", "bytes": "190455" }, { "name": "CSS", "bytes": "111474" }, { "name": "CoffeeScript", "bytes": "1759" }, { "name": "Cucumber", "bytes": "14382" }, { "name": "Erlang", "bytes": "10" }, { "name": "FLUX", "bytes": "57" }, { "name": "Groff", "bytes": "35232" }, { "name": "Groovy", "bytes": "2259229" }, { "name": "HTML", "bytes": "1734217" }, { "name": "J", "bytes": "5050" }, { "name": "Java", "bytes": "149763564" }, { "name": "JavaScript", "bytes": "125292" }, { "name": "Kotlin", "bytes": "806294" }, { "name": "Lex", "bytes": "166177" }, { "name": "Makefile", "bytes": "2352" }, { "name": "NSIS", "bytes": "86875" }, { "name": "Objective-C", "bytes": "28878" }, { "name": "Perl6", "bytes": "26" }, { "name": "Protocol Buffer", "bytes": "6570" }, { "name": "Python", "bytes": "21472809" }, { "name": "Ruby", "bytes": "1213" }, { "name": "Scala", "bytes": "11698" }, { "name": "Shell", "bytes": "63392" }, { "name": "Smalltalk", "bytes": "64" }, { "name": "TeX", "bytes": "60798" }, { "name": "TypeScript", "bytes": "6152" }, { "name": "XSLT", "bytes": "113040" } ], "symlink_target": "" }
#ifndef _LINUX_VIRTIO_BLK_H #define _LINUX_VIRTIO_BLK_H #include <linux/types.h> #include <linux/virtio_ids.h> #include <linux/virtio_config.h> #include <linux/virtio_types.h> /* Feature bits */ #define VIRTIO_BLK_F_SIZE_MAX 1 /* Indicates maximum segment size */ #define VIRTIO_BLK_F_SEG_MAX 2 /* Indicates maximum # of segments */ #define VIRTIO_BLK_F_GEOMETRY 4 /* Legacy geometry available */ #define VIRTIO_BLK_F_RO 5 /* Disk is read-only */ #define VIRTIO_BLK_F_BLK_SIZE 6 /* Block size of disk is available*/ #define VIRTIO_BLK_F_TOPOLOGY 10 /* Topology information is available */ #define VIRTIO_BLK_F_MQ 12 /* support more than one vq */ /* Legacy feature bits */ #ifndef VIRTIO_BLK_NO_LEGACY #define VIRTIO_BLK_F_BARRIER 0 /* Does host support barriers? */ #define VIRTIO_BLK_F_SCSI 7 /* Supports scsi command passthru */ #define VIRTIO_BLK_F_FLUSH 9 /* Flush command supported */ #define VIRTIO_BLK_F_CONFIG_WCE 11 /* Writeback mode available in config */ /* Old (deprecated) name for VIRTIO_BLK_F_FLUSH. */ #define VIRTIO_BLK_F_WCE VIRTIO_BLK_F_FLUSH #endif /* !VIRTIO_BLK_NO_LEGACY */ #define VIRTIO_BLK_ID_BYTES 20 /* ID string length */ struct virtio_blk_config { /* The capacity (in 512-byte sectors). */ __u64 capacity; /* The maximum segment size (if VIRTIO_BLK_F_SIZE_MAX) */ __u32 size_max; /* The maximum number of segments (if VIRTIO_BLK_F_SEG_MAX) */ __u32 seg_max; /* geometry of the device (if VIRTIO_BLK_F_GEOMETRY) */ struct virtio_blk_geometry { __u16 cylinders; __u8 heads; __u8 sectors; } geometry; /* block size of device (if VIRTIO_BLK_F_BLK_SIZE) */ __u32 blk_size; /* the next 4 entries are guarded by VIRTIO_BLK_F_TOPOLOGY */ /* exponent for physical block per logical block. */ __u8 physical_block_exp; /* alignment offset in logical blocks. */ __u8 alignment_offset; /* minimum I/O size without performance penalty in logical blocks. */ __u16 min_io_size; /* optimal sustained I/O size in logical blocks. */ __u32 opt_io_size; /* writeback mode (if VIRTIO_BLK_F_CONFIG_WCE) */ __u8 wce; __u8 unused; /* number of vqs, only available when VIRTIO_BLK_F_MQ is set */ __u16 num_queues; } __attribute__((packed)); /* * Command types * * Usage is a bit tricky as some bits are used as flags and some are not. * * Rules: * VIRTIO_BLK_T_OUT may be combined with VIRTIO_BLK_T_SCSI_CMD or * VIRTIO_BLK_T_BARRIER. VIRTIO_BLK_T_FLUSH is a command of its own * and may not be combined with any of the other flags. */ /* These two define direction. */ #define VIRTIO_BLK_T_IN 0 #define VIRTIO_BLK_T_OUT 1 #ifndef VIRTIO_BLK_NO_LEGACY /* This bit says it's a scsi command, not an actual read or write. */ #define VIRTIO_BLK_T_SCSI_CMD 2 #endif /* VIRTIO_BLK_NO_LEGACY */ /* Cache flush command */ #define VIRTIO_BLK_T_FLUSH 4 /* Get device ID command */ #define VIRTIO_BLK_T_GET_ID 8 #ifndef VIRTIO_BLK_NO_LEGACY /* Barrier before this op. */ #define VIRTIO_BLK_T_BARRIER 0x80000000 #endif /* !VIRTIO_BLK_NO_LEGACY */ /* * This comes first in the read scatter-gather list. * For legacy virtio, if VIRTIO_F_ANY_LAYOUT is not negotiated, * this is the first element of the read scatter-gather list. */ struct virtio_blk_outhdr { /* VIRTIO_BLK_T* */ __virtio32 type; /* io priority. */ __virtio32 ioprio; /* Sector (ie. 512 byte offset) */ __virtio64 sector; }; #ifndef VIRTIO_BLK_NO_LEGACY struct virtio_scsi_inhdr { __virtio32 errors; __virtio32 data_len; __virtio32 sense_len; __virtio32 residual; }; #endif /* !VIRTIO_BLK_NO_LEGACY */ /* And this is the final byte of the write scatter-gather list. */ #define VIRTIO_BLK_S_OK 0 #define VIRTIO_BLK_S_IOERR 1 #define VIRTIO_BLK_S_UNSUPP 2 #endif /* _LINUX_VIRTIO_BLK_H */
{ "content_hash": "25ad3733bb553c67f166630603b85aa3", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 75, "avg_line_length": 30.32520325203252, "alnum_prop": 0.6924932975871314, "repo_name": "raulgrell/zig", "id": "caca5fffe1039050da792f4f66f4fac8db6ab1e3", "size": "5318", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/libc/include/any-linux-any/linux/virtio_blk.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1187" }, { "name": "C", "bytes": "187893" }, { "name": "C++", "bytes": "3749750" }, { "name": "CMake", "bytes": "38091" }, { "name": "HTML", "bytes": "15836" }, { "name": "JavaScript", "bytes": "73253" }, { "name": "Shell", "bytes": "17887" }, { "name": "Zig", "bytes": "17407339" } ], "symlink_target": "" }
tQuery.World.registerInstance('enablePhysics', function(opts){ var world = this; var tScene = world.tScene(); opts = opts || {}; opts = tQuery.extend(opts, { maxSteps : 5, // see "Custom simulation steps" at https://github.com/chandlerprall/Physijs/wiki/Scene-Configuration pathWorker : '../vendor/physijs/physijs_worker.js', xScene : null }); Physijs.scripts.worker = opts.pathWorker; console.assert(tScene._xScene === undefined) // TODO use tQuery.data for that tScene._xScene = new Physijs.xScene(opts.xScene); world.loop().hook(function(delta, now){ tScene._xScene.simulate(delta, opts.maxSteps); }); }) tQuery.World.registerInstance('physics', function(){ console.assert( this.hasPhysics() ); return world.tScene()._xScene; }); tQuery.World.registerInstance('hasPhysics', function(){ return world.tScene()._xScene ? true : false; }); ////////////////////////////////////////////////////////////////////////////////// // tQuery.Mesh // ////////////////////////////////////////////////////////////////////////////////// tQuery.Mesh.registerInstance('enablePhysics', function(opts){ opts = opts || {}; var mesh = this; var tMesh = mesh.get(0); console.assert(tMesh._xMesh === undefined) console.assert(tMesh._physijs === undefined) tMesh._xMesh = new Physijs.xMesh(tMesh.geometry, opts.mass).back(this); tMesh._physijs = tMesh._xMesh._physijs; // init the geometry var tGeometry = opts.tGeometry || tMesh.geometry; if( tGeometry instanceof THREE.CubeGeometry ){ tGeometry.computeBoundingBox(); tMesh._xMesh._boxGeometryInit(tGeometry, opts.mass) }else if( tGeometry instanceof THREE.SphereGeometry ){ tGeometry.computeBoundingSphere(); tMesh._xMesh._sphereGeometryInit(tGeometry, opts.mass) }else if( tGeometry instanceof THREE.PlaneGeometry ){ tGeometry.computeBoundingBox(); tMesh._xMesh._planeGeometryInit(tGeometry, opts.mass) }else if( tGeometry instanceof THREE.CylinderGeometry ){ tGeometry.computeBoundingBox(); tMesh._xMesh._cylinderGeometryInit(tGeometry, opts.mass) }else{ console.assert(false, "unknown geometry type"); } // init the material // TODO does it have to be the actual mesh.material ? can it be another struct ? var tMaterial = tMesh.material; tMaterial._xMaterial = new Physijs.xMaterial(tMaterial, opts.friction, opts.restitution); if( tMaterial._physijs === undefined){ tMaterial._physijs = tMaterial._xMaterial._physijs; } // TODO to remove hardcoded // - possible solution: here if attached, get the scene to this world // - if not yet attached, hook the scene.add function to add the physics world too // - TODO this mechanism to hook .add.remove in a scene isnt yet availble var tScene = tQuery.world.tScene(); tScene._xScene.add(tMesh, function(){ //console.log("this tMesh has been added") }); return this; // for chained API }) tQuery.Mesh.registerInstance('hasPhysics', function(){ return this.get(0)._xMesh ? true : false; }); tQuery.Mesh.registerInstance('physics', function(){ return this.get(0)._xMesh; });
{ "content_hash": "d247dd54c7a1065f229efc786c4c8f47", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 117, "avg_line_length": 33.582417582417584, "alnum_prop": 0.6822643979057592, "repo_name": "jackmillerstudent/Top-Gear-Racer", "id": "38ba709184ac478dff1ffad1bb8a939084842992", "size": "3543", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "plugins/physics/tquery.physijs.js", "mode": "33261", "license": "mit", "language": [ { "name": "Java", "bytes": "553" }, { "name": "JavaScript", "bytes": "2942391" }, { "name": "PHP", "bytes": "1435" }, { "name": "Perl", "bytes": "15724" }, { "name": "Python", "bytes": "6114" }, { "name": "Racket", "bytes": "906" }, { "name": "Ruby", "bytes": "1587" }, { "name": "Shell", "bytes": "10367" } ], "symlink_target": "" }
package org.ovirt.engine.core.dao; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import org.junit.Test; import org.ovirt.engine.core.common.businessentities.VmInit; import org.ovirt.engine.core.common.businessentities.VmStatic; import org.ovirt.engine.core.compat.Guid; public class VmInitDAOTest extends BaseDAOTestCase { private static final Guid EXISTING_VM = FixturesTool.VM_RHEL5_POOL_57; private VmInit vmInit; private VmInitDAO vmInitDao; private VmStaticDAO vmStaticDao; private VmStatic vmStatic; @Override public void setUp() throws Exception { super.setUp(); vmInitDao = dbFacade.getVmInitDao(); vmInit = new VmInit(); vmInit.setId(EXISTING_VM); vmStaticDao = dbFacade.getVmStaticDao(); vmStatic = vmStaticDao.get(EXISTING_VM); vmStatic.setVmInit(vmInit); } /** * Ensures that get requires a valid id. */ @Test public void testGetWithInvalidId() { VmInit result = vmInitDao.get(Guid.newGuid()); assertNull(result); } @Test public void testGet() { VmInit result = vmInitDao.get(EXISTING_VM); assertNotNull(result != null); } @Test public void testSave() { addVmInit(); VmInit result = vmInitDao.get(EXISTING_VM); assertNotNull(result); assertEquals("hostname", result.getHostname()); } private void addVmInit() { VmInit init = new VmInit(); init.setId(EXISTING_VM); init.setHostname("hostname"); vmInitDao.save(init); } @Test public void testUpdate() { addVmInit(); VmInit init = vmInitDao.get(EXISTING_VM); init.setHostname("newhostname"); vmInitDao.update(init); VmInit result = vmInitDao.get(init.getId()); assertNotNull(result); assertEquals("newhostname", result.getHostname()); } @Test public void testRemove() { addVmInit(); VmInit result = vmInitDao.get(EXISTING_VM); assertNotNull(result); vmInitDao.remove(EXISTING_VM); result = vmInitDao.get(EXISTING_VM); assertNull(result); } }
{ "content_hash": "f564db8b4df76263b27660461299735c", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 74, "avg_line_length": 26.453488372093023, "alnum_prop": 0.6452747252747253, "repo_name": "halober/ovirt-engine", "id": "01f3a8a2a1d9eb6a10f5522720726d86ca0a091a", "size": "2275", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "backend/manager/modules/dal/src/test/java/org/ovirt/engine/core/dao/VmInitDAOTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "251848" }, { "name": "Java", "bytes": "26541598" }, { "name": "JavaScript", "bytes": "890" }, { "name": "Python", "bytes": "698283" }, { "name": "Shell", "bytes": "105362" }, { "name": "XSLT", "bytes": "54683" } ], "symlink_target": "" }
The language we are making is an interpreted one. This means that we basically need to implement two things: a **parser** and an **evaluator**. In this first part, we implement the parser. The job of the parser is to convert the program into something the evaluator understands. The evaluator evaluates whatever the parser produces, and returns the result. Here is a nice diagram to explain everything: ``` +-----------+ +-------------+ text | | AST | | result +-------->| parser |+------>| evaluator |+--------> | | | | +-----------+ +-------------+ ``` The format produced by the parser is called the *abstract syntax tree* (AST) of the program. ### Our AST So what does our AST look like? Lets have a sneak peek. ```julia julia> using Parser julia> program = " (define fact ;; Factorial function (lambda (n) (if (eq n 0) 1 ; Factorial of 0 is 1, and we deny ; the existence of negative numbers (* n (fact (- n 1)))))) " julia> parse(program) 3-element Array{Any,1}: "define" "fact" {"lambda",{"n"},{"if",{"eq","n",0},1,{"*","n",{"fact",{"-","n",1}}}}} ``` The AST, then, is created as follows: - Comments are removed. - Symbols are represented as strings. + `"foo"` parses to `"foo"` - The symbols `#t` and `#f` are represented by Julia's `true` and `false`, respectively. + `"#t"` parses to `true` - Integers are represented as Julia integers. + `"42"` parses to `42` - The Lisp list expressions are represented as Julia lists. `"(foo #f 100)"` parses to `{"foo",false,100}` - Nested expressions are parsed accordingly. + `"((+ (- 1 2) (* (- 4 1) 42)))"` parses to `{{"+",{"-",1,2},{"*",{"-",4,1},42}}}` ### Your turn The parsing is done in `Parser.jl`. It is your job to implement the `parse` function here. A lot of the gritty work of counting parentheses and such has been done for you, but you must stitch everything together. - Have a look at the provided functions in `diylisp/Parser.jl` before you start. These should prove useful. - The following command runs the tests, stopping at the first one failed. ```bash julia tests/test_1_parsing.jl ``` - Run the tests and hack away until the tests are passing. Each test has a description, and you should probably read it if you get stuck. ### What's next? Go to [part 2](2.md) where we evaluate some simple expressions.
{ "content_hash": "43b819114af738f050958c7ae61a09dd", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 213, "avg_line_length": 40.54545454545455, "alnum_prop": 0.5676382660687593, "repo_name": "qhfgva/diy-lisp-julia", "id": "ebc4b9cb22e78225d13d409993841e2b5390879d", "size": "2696", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "parts/1.md", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Julia", "bytes": "41263" }, { "name": "Python", "bytes": "127" }, { "name": "Shell", "bytes": "478" } ], "symlink_target": "" }
'use strict'; var util = require('../util'); var common = require('./common'); var bignum = util.bignum; var PACKET_HEADER_LENGTH = common.PACKET_HEADER_LENGTH; module.exports = MessageBuffer; function MessageBuffer() { this.length = 0; this.header = undefined; this.data = undefined; } MessageBuffer.prototype.isReady = function () { return this.header && this.length >= this.header.length; }; MessageBuffer.prototype.push = function push(chunk) { if (!chunk || !chunk.length) { return; } this.length += chunk.length; if (!this.data) { this.data = chunk; } else if (Buffer.isBuffer(this.data)) { this.data = [this.data, chunk]; } else { this.data.push(chunk); } if (!this.header && this.length >= PACKET_HEADER_LENGTH) { this.readHeader(); } }; MessageBuffer.prototype.getData = function getData() { if (util.isArray(this.data)) { return Buffer.concat(this.data, this.length); } return this.data; }; MessageBuffer.prototype.readHeader = function readHeader() { var buffer = this.getData(); this.header = { sessionId: bignum.readUInt64LE(buffer, 0), packetCount: buffer.readUInt32LE(8), length: buffer.readUInt32LE(12) }; this.data = buffer.slice(PACKET_HEADER_LENGTH); this.length -= PACKET_HEADER_LENGTH; }; MessageBuffer.prototype.clear = function clear() { this.length = 0; this.header = undefined; this.data = undefined; };
{ "content_hash": "724acb62b9ff6e3e775a0646a44972a5", "timestamp": "", "source": "github", "line_count": 59, "max_line_length": 60, "avg_line_length": 24.06779661016949, "alnum_prop": 0.6746478873239437, "repo_name": "SAP/node-hdb", "id": "51a79e92763c13ea261d171434c100dc0d2db5e8", "size": "2001", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/protocol/MessageBuffer.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "598989" }, { "name": "Makefile", "bytes": "834" } ], "symlink_target": "" }
package edu.gemini.spModel.gemini.gpi; import edu.gemini.spModel.target.offset.OffsetPosBase; import edu.gemini.spModel.telescope.IssPort; /** * Enforces the range limit (-1 to 1) */ public final class GpiOffsetPos extends OffsetPosBase { public static final Factory<GpiOffsetPos> FACTORY = new Factory<GpiOffsetPos>() { public GpiOffsetPos create(String tag) { return new GpiOffsetPos(tag); } public GpiOffsetPos create(String tag, double p, double q) { return new GpiOffsetPos(tag, p, q); } }; private static double clip(double d) { if (d < -1) return -1; if (d > 1) return 1; return d; } public GpiOffsetPos(String tag, double xaxis, double yaxis) { super(tag, clip(xaxis), clip(yaxis)); } public GpiOffsetPos(String tag) { super(tag); } /** * Override clone to make sure the position is correctly * initialized. */ public Object clone() { return super.clone(); } @Override public void setXAxis(double xAxis) { super.setXAxis(clip(xAxis)); } @Override public void setYAxis(double yAxis) { super.setYAxis(clip(yAxis)); } @Override public void setXY(double xaxis, double yaxis, IssPort port) { super.setXY(clip(xaxis), clip(yaxis), port); } @Override public void noNotifySetXY(double xaxis, double yaxis, IssPort port) { super.noNotifySetXY(clip(xaxis), clip(yaxis), port); } }
{ "content_hash": "0f9a61afb06de8fe4c21cfaeea5f3634", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 85, "avg_line_length": 24.396825396825395, "alnum_prop": 0.620039037085231, "repo_name": "arturog8m/ocs", "id": "1175c4d0a2ba005f3b64787987518e3ce0e739d9", "size": "1537", "binary": false, "copies": "9", "ref": "refs/heads/develop", "path": "bundle/edu.gemini.pot/src/main/java/edu/gemini/spModel/gemini/gpi/GpiOffsetPos.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "7919" }, { "name": "HTML", "bytes": "490242" }, { "name": "Java", "bytes": "14504312" }, { "name": "JavaScript", "bytes": "7962" }, { "name": "Scala", "bytes": "4967047" }, { "name": "Shell", "bytes": "4989" }, { "name": "Tcl", "bytes": "2841" } ], "symlink_target": "" }
package org.apache.hadoop.hbase.regionserver.wal; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.io.crypto.KeyProviderForTesting; import org.apache.hadoop.hbase.testclassification.MediumTests; import org.apache.hadoop.hbase.testclassification.RegionServerTests; import org.apache.hadoop.hbase.wal.AsyncFSWALProvider.AsyncWriter; import org.apache.hadoop.hbase.wal.WAL.Reader; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.experimental.categories.Category; @Category({ RegionServerTests.class, MediumTests.class }) public class TestSecureAsyncWALReplay extends TestAsyncWALReplay { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestSecureAsyncWALReplay.class); @BeforeClass public static void setUpBeforeClass() throws Exception { Configuration conf = AbstractTestWALReplay.TEST_UTIL.getConfiguration(); conf.set(HConstants.CRYPTO_KEYPROVIDER_CONF_KEY, KeyProviderForTesting.class.getName()); conf.set(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY, "hbase"); conf.setClass("hbase.regionserver.hlog.reader.impl", SecureProtobufLogReader.class, Reader.class); conf.setClass("hbase.regionserver.hlog.async.writer.impl", SecureAsyncProtobufLogWriter.class, AsyncWriter.class); conf.setBoolean(HConstants.ENABLE_WAL_ENCRYPTION, true); TestAsyncWALReplay.setUpBeforeClass(); } }
{ "content_hash": "107b333715c5fbbbbe2ebcfe4052262a", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 98, "avg_line_length": 43.6, "alnum_prop": 0.809305373525557, "repo_name": "ChinmaySKulkarni/hbase", "id": "d63ac7716bb532d4c6e42dd1220bcbb38972c80a", "size": "2332", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "hbase-server/src/test/java/org/apache/hadoop/hbase/regionserver/wal/TestSecureAsyncWALReplay.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "25330" }, { "name": "C", "bytes": "28534" }, { "name": "C++", "bytes": "56085" }, { "name": "CMake", "bytes": "13186" }, { "name": "CSS", "bytes": "37063" }, { "name": "Dockerfile", "bytes": "4842" }, { "name": "Groovy", "bytes": "37692" }, { "name": "HTML", "bytes": "17275" }, { "name": "Java", "bytes": "35158950" }, { "name": "JavaScript", "bytes": "2694" }, { "name": "Makefile", "bytes": "1359" }, { "name": "PHP", "bytes": "8385" }, { "name": "Perl", "bytes": "383739" }, { "name": "Python", "bytes": "90226" }, { "name": "Ruby", "bytes": "664576" }, { "name": "Shell", "bytes": "254684" }, { "name": "Thrift", "bytes": "52351" }, { "name": "XSLT", "bytes": "6764" } ], "symlink_target": "" }
package io.datakernel.jmx.api.attribute; import org.jetbrains.annotations.Nullable; import java.util.List; import java.util.Objects; import java.util.function.Function; import java.util.stream.DoubleStream; import java.util.stream.LongStream; import static java.util.stream.Collectors.toList; @SuppressWarnings("OptionalGetWithoutIsPresent") public final class JmxReducers { public static final class JmxReducerDistinct implements JmxReducer<Object> { @Override public Object reduce(List<?> list) { if (list.size() == 0) return null; Object firstValue = list.get(0); return list.stream().allMatch(value -> Objects.equals(firstValue, value)) ? firstValue : null; } } public static final class JmxReducerSum implements JmxReducer<Number> { @Override public Number reduce(List<? extends Number> list) { return reduceNumbers(list, DoubleStream::sum, LongStream::sum); } } public static final class JmxReducerMin implements JmxReducer<Number> { @Override public Number reduce(List<? extends Number> list) { return reduceNumbers(list, s -> s.min().getAsDouble(), s -> s.min().getAsLong()); } } public static final class JmxReducerMax implements JmxReducer<Number> { @Override public Number reduce(List<? extends Number> list) { return reduceNumbers(list, s -> s.max().getAsDouble(), s -> s.max().getAsLong()); } } @Nullable private static Number reduceNumbers(List<? extends Number> list, Function<DoubleStream, Double> opDouble, Function<LongStream, Long> opLong) { list = list.stream().filter(Objects::nonNull).collect(toList()); if (list.isEmpty()) return null; Class<?> numberClass = list.get(0).getClass(); if (isFloatingPointNumber(numberClass)) { return convert(numberClass, opDouble.apply(list.stream().mapToDouble(Number::doubleValue))); } else if (isIntegerNumber(numberClass)) { return convert(numberClass, opLong.apply(list.stream().mapToLong(Number::longValue))); } else { throw new IllegalArgumentException( "Unsupported objects of type: " + numberClass.getName()); } } private static boolean isFloatingPointNumber(Class<?> numberClass) { return Float.class.isAssignableFrom(numberClass) || Double.class.isAssignableFrom(numberClass); } private static boolean isIntegerNumber(Class<?> numberClass) { return Byte.class.isAssignableFrom(numberClass) || Short.class.isAssignableFrom(numberClass) || Integer.class.isAssignableFrom(numberClass) || Long.class.isAssignableFrom(numberClass); } private static Number convert(Class<?> targetClass, Number number) { if (Byte.class.isAssignableFrom(targetClass)) { return number.byteValue(); } else if (Short.class.isAssignableFrom(targetClass)) { return number.shortValue(); } else if (Integer.class.isAssignableFrom(targetClass)) { return number.intValue(); } else if (Long.class.isAssignableFrom(targetClass)) { return number.longValue(); } else if (Float.class.isAssignableFrom(targetClass)) { return number.floatValue(); } else if (Double.class.isAssignableFrom(targetClass)) { return number.doubleValue(); } else { throw new IllegalArgumentException("target class is not a number class"); } } }
{ "content_hash": "d2c4408957d11e485fc6cd3bbfbdf129", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 97, "avg_line_length": 33.78947368421053, "alnum_prop": 0.738006230529595, "repo_name": "softindex/datakernel", "id": "b04ef8742bd0bfcc4ec55153bab28a6ac42f0470", "size": "3807", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "boot-jmx-api/src/main/java/io/datakernel/jmx/api/attribute/JmxReducers.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "438" }, { "name": "HTML", "bytes": "1244" }, { "name": "Java", "bytes": "5078460" }, { "name": "Shell", "bytes": "55" }, { "name": "TSQL", "bytes": "1305" } ], "symlink_target": "" }
package org.unitime.timetable.dataexchange; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.Vector; import org.unitime.commons.Email; import org.unitime.timetable.defaults.ApplicationProperty; import org.unitime.timetable.model.Meeting; import org.unitime.timetable.model.Session; import org.unitime.timetable.util.CalendarUtils; import org.unitime.timetable.util.Constants; /** * @author Stephanie Schluttenhofer, Tomas Muller * */ public abstract class EventRelatedImports extends BaseImport { protected String timeFormat = null; protected Vector<String> changeList = new Vector<String>(); protected TreeSet<String> missingLocations = new TreeSet<String>(); protected Vector<String> notes = new Vector<String>(); protected String dateFormat = null; protected boolean trimLeadingZerosFromExternalId = false; protected Session session = null; protected abstract String getEmailSubject(); /** * */ public EventRelatedImports() { } protected void addNote(String note){ notes.add(note); } protected void clearNotes(){ notes = new Vector<String>(); } protected void updateChangeList(boolean changed){ if(changed && notes != null) { changeList.addAll(notes); String note = null; for(Iterator<String> it = notes.iterator(); it.hasNext(); ){ note = (String) it.next(); info(note); } } clearNotes(); } protected void addMissingLocation(String location){ missingLocations.add(location); } protected void reportMissingLocations(){ if (!missingLocations.isEmpty()) { changeList.add("\nMissing Locations\n"); info("\nMissing Locations\n"); for(Iterator<String> it = missingLocations.iterator(); it.hasNext();){ String location = (String) it.next(); changeList.add("\t" + location); info("\t" + location); } } } protected void mailLoadResults(){ try { Email email = Email.createEmail(); email.setSubject("UniTime (Data Import): " + getEmailSubject()); String mail = ""; for (Iterator<String> it = changeList.iterator(); it.hasNext(); ){ mail += (String) it.next() + "\n"; } email.setText(mail); email.addRecipient(getManager().getEmailAddress(), getManager().getName()); if (ApplicationProperty.EmailNotificationDataExchange.isTrue()) email.addNotifyCC(); email.send(); } catch (Exception e) { sLog.error(e.getMessage(), e); } } protected Session findSession(String academicInitiative, String academicYear, String academicTerm){ return(Session) this. getHibSession(). createQuery("from Session as s where s.academicInitiative = :academicInititive and s.academicYear = :academicYear and s.academicTerm = :academicTerm"). setString("academicInititive", academicInitiative). setString("academicYear", academicYear). setString("academicTerm", academicTerm). setCacheable(true). uniqueResult(); } protected List findNonUniversityLocationsWithIdOrName(String id, String name){ if (id != null) { return(this. getHibSession(). createQuery("select distinct l from NonUniversityLocation as l where l.externalUniqueId=:id and l.session.uniqueId=:sessionId"). setLong("sessionId", session.getUniqueId().longValue()). setString("id", id). setCacheable(true). list()); } if (name != null) { return(this. getHibSession(). createQuery("select distinct l from NonUniversityLocation as l where l.name=:name and l.session.uniqueId=:sessionId"). setLong("sessionId", session.getUniqueId().longValue()). setString("name", name). setCacheable(true). list()); } return(new ArrayList()); } protected List findNonUniversityLocationsWithName(String name){ if (name != null) { return(this. getHibSession(). createQuery("select distinct l from NonUniversityLocation as l where l.name=:name and l.session.uniqueId=:sessionId"). setLong("sessionId", session.getUniqueId().longValue()). setString("name", name). setCacheable(true). list()); } return(new ArrayList()); } protected class TimeObject { private Integer startPeriod; private Integer endPeriod; private Set<Integer> days; TimeObject(String startTime, String endTime, String daysOfWeek) throws Exception{ startPeriod = str2Slot(startTime); endPeriod = str2Slot(endTime); if (endPeriod == 0){ // if the end period is midnight then the meeting ends at the end of the day i.e. last slot endPeriod = Constants.SLOTS_PER_DAY; } if (startPeriod >= endPeriod){ throw new Exception("Invalid time '"+startTime+"' must be before ("+endTime+")."); } if (daysOfWeek == null || daysOfWeek.length() == 0){ return; } setDaysOfWeek(daysOfWeek); } private void setDaysOfWeek(String daysOfWeek){ days = new TreeSet<Integer>(); String tmpDays = daysOfWeek; if(tmpDays.contains("Th")){ days.add(Calendar.THURSDAY); tmpDays = tmpDays.replace("Th", ".."); } if(tmpDays.contains("R")){ days.add(Calendar.THURSDAY); tmpDays = tmpDays.replace("R", ".."); } if (tmpDays.contains("Su")){ days.add(Calendar.SUNDAY); tmpDays = tmpDays.replace("Su", ".."); } if (tmpDays.contains("U")){ days.add(Calendar.SUNDAY); tmpDays = tmpDays.replace("U", ".."); } if (tmpDays.contains("M")){ days.add(Calendar.MONDAY); tmpDays = tmpDays.replace("M", "."); } if (tmpDays.contains("T")){ days.add(Calendar.TUESDAY); tmpDays = tmpDays.replace("T", "."); } if (tmpDays.contains("W")){ days.add(Calendar.WEDNESDAY); tmpDays = tmpDays.replace("W", "."); } if (tmpDays.contains("F")){ days.add(Calendar.FRIDAY); tmpDays = tmpDays.replace("F", "."); } if (tmpDays.contains("S")){ days.add(Calendar.SATURDAY); tmpDays = tmpDays.replace("S", "."); } } public Integer getStartPeriod() { return startPeriod; } public void setStartPeriod(Integer startPeriod) { this.startPeriod = startPeriod; } public Integer getEndPeriod() { return endPeriod; } public void setEndPeriod(Integer endPeriod) { this.endPeriod = endPeriod; } public Set<Integer> getDays() { return days; } public void setDays(Set<Integer> days) { this.days = days; } public Meeting asMeeting(){ Meeting meeting = new Meeting(); meeting.setClassCanOverride(new Boolean(true)); meeting.setStartOffset(new Integer(0)); meeting.setStartPeriod(this.getStartPeriod()); meeting.setStopOffset(new Integer(0)); meeting.setStopPeriod(this.getEndPeriod()); meeting.setStatus(Meeting.Status.PENDING); return(meeting); } public Integer str2Slot(String timeString) throws Exception { int slot = -1; try { Date date = CalendarUtils.getDate(timeString, timeFormat); SimpleDateFormat df = new SimpleDateFormat("HHmm"); int time = Integer.parseInt(df.format(date)); int hour = time/100; int min = time%100; if (hour>=24) throw new Exception("Invalid time '"+timeString+"' -- hour ("+hour+") must be between 0 and 23."); if (min>=60) throw new Exception("Invalid time '"+timeString+"' -- minute ("+min+") must be between 0 and 59."); if ((min%Constants.SLOT_LENGTH_MIN)!=0){ min = min - (min%Constants.SLOT_LENGTH_MIN); //throw new Exception("Invalid time '"+timeString+"' -- minute ("+min+") must be divisible by "+Constants.SLOT_LENGTH_MIN+"."); } slot = (hour*60+min - Constants.FIRST_SLOT_TIME_MIN)/Constants.SLOT_LENGTH_MIN; } catch (NumberFormatException ex) { throw new Exception("Invalid time '"+timeString+"' -- not a number."); } if (slot<0) throw new Exception("Invalid time '"+timeString+"', did not meet format: " + timeFormat); return(slot); } } }
{ "content_hash": "7b7ed00eddf5d98ab1c8a82a212f61ae", "timestamp": "", "source": "github", "line_count": 270, "max_line_length": 154, "avg_line_length": 29.8, "alnum_prop": 0.6690280884911758, "repo_name": "maciej-zygmunt/unitime", "id": "2b7ef675634950b36f7c2a4d66a7b9b9901fc932", "size": "8852", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "JavaSource/org/unitime/timetable/dataexchange/EventRelatedImports.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "174280" }, { "name": "FreeMarker", "bytes": "40754" }, { "name": "HTML", "bytes": "48" }, { "name": "Java", "bytes": "23582793" }, { "name": "JavaScript", "bytes": "446284" } ], "symlink_target": "" }
// in_win.c -- windows 95 mouse and joystick code // 02/21/97 JCB Added extended DirectInput code to support external controllers. #include "../client/client.h" #include "winquake.h" extern unsigned sys_msg_time; // joystick defines and variables // where should defines be moved? #define JOY_ABSOLUTE_AXIS 0x00000000 // control like a joystick #define JOY_RELATIVE_AXIS 0x00000010 // control like a mouse, spinner, trackball #define JOY_MAX_AXES 6 // X, Y, Z, R, U, V #define JOY_AXIS_X 0 #define JOY_AXIS_Y 1 #define JOY_AXIS_Z 2 #define JOY_AXIS_R 3 #define JOY_AXIS_U 4 #define JOY_AXIS_V 5 enum _ControlList { AxisNada = 0, AxisForward, AxisLook, AxisSide, AxisTurn, AxisUp }; DWORD dwAxisFlags[JOY_MAX_AXES] = { JOY_RETURNX, JOY_RETURNY, JOY_RETURNZ, JOY_RETURNR, JOY_RETURNU, JOY_RETURNV }; DWORD dwAxisMap[JOY_MAX_AXES]; DWORD dwControlMap[JOY_MAX_AXES]; PDWORD pdwRawValue[JOY_MAX_AXES]; cvar_t *in_mouse; cvar_t *in_joystick; // none of these cvars are saved over a session // this means that advanced controller configuration needs to be executed // each time. this avoids any problems with getting back to a default usage // or when changing from one controller to another. this way at least something // works. cvar_t *joy_name; cvar_t *joy_advanced; cvar_t *joy_advaxisx; cvar_t *joy_advaxisy; cvar_t *joy_advaxisz; cvar_t *joy_advaxisr; cvar_t *joy_advaxisu; cvar_t *joy_advaxisv; cvar_t *joy_forwardthreshold; cvar_t *joy_sidethreshold; cvar_t *joy_pitchthreshold; cvar_t *joy_yawthreshold; cvar_t *joy_forwardsensitivity; cvar_t *joy_sidesensitivity; cvar_t *joy_pitchsensitivity; cvar_t *joy_yawsensitivity; cvar_t *joy_upthreshold; cvar_t *joy_upsensitivity; qboolean joy_avail, joy_advancedinit, joy_haspov; DWORD joy_oldbuttonstate, joy_oldpovstate; int joy_id; DWORD joy_flags; DWORD joy_numbuttons; static JOYINFOEX ji; qboolean in_appactive; // forward-referenced functions void IN_StartupJoystick (void); void Joy_AdvancedUpdate_f (void); void IN_JoyMove (usercmd_t *cmd); /* ============================================================ MOUSE CONTROL ============================================================ */ // mouse variables cvar_t *m_filter; qboolean mlooking; void IN_MLookDown (void) { mlooking = true; } void IN_MLookUp (void) { mlooking = false; if (!freelook->value && lookspring->value) IN_CenterView (); } int mouse_buttons; int mouse_oldbuttonstate; POINT current_pos; int mouse_x, mouse_y, old_mouse_x, old_mouse_y, mx_accum, my_accum; int old_x, old_y; qboolean mouseactive; // false when not focus app qboolean restore_spi; qboolean mouseinitialized; int originalmouseparms[3], newmouseparms[3] = {0, 0, 1}; qboolean mouseparmsvalid; int window_center_x, window_center_y; RECT window_rect; /* =========== IN_ActivateMouse Called when the window gains focus or changes in some way =========== */ void IN_ActivateMouse (void) { int width, height; if (!mouseinitialized) return; if (!in_mouse->value) { mouseactive = false; return; } if (mouseactive) return; mouseactive = true; if (mouseparmsvalid) restore_spi = SystemParametersInfo (SPI_SETMOUSE, 0, newmouseparms, 0); width = GetSystemMetrics (SM_CXSCREEN); height = GetSystemMetrics (SM_CYSCREEN); GetWindowRect ( cl_hwnd, &window_rect); if (window_rect.left < 0) window_rect.left = 0; if (window_rect.top < 0) window_rect.top = 0; if (window_rect.right >= width) window_rect.right = width-1; if (window_rect.bottom >= height-1) window_rect.bottom = height-1; window_center_x = (window_rect.right + window_rect.left)/2; window_center_y = (window_rect.top + window_rect.bottom)/2; SetCursorPos (window_center_x, window_center_y); old_x = window_center_x; old_y = window_center_y; SetCapture ( cl_hwnd ); ClipCursor (&window_rect); while (ShowCursor (FALSE) >= 0) ; } /* =========== IN_DeactivateMouse Called when the window loses focus =========== */ void IN_DeactivateMouse (void) { if (!mouseinitialized) return; if (!mouseactive) return; if (restore_spi) SystemParametersInfo (SPI_SETMOUSE, 0, originalmouseparms, 0); mouseactive = false; ClipCursor (NULL); ReleaseCapture (); while (ShowCursor (TRUE) < 0) ; } /* =========== IN_StartupMouse =========== */ void IN_StartupMouse (void) { cvar_t *cv; cv = Cvar_Get ("in_initmouse", "1", CVAR_NOSET); if ( !cv->value ) return; mouseinitialized = true; mouseparmsvalid = SystemParametersInfo (SPI_GETMOUSE, 0, originalmouseparms, 0); mouse_buttons = 3; } /* =========== IN_MouseEvent =========== */ void IN_MouseEvent (int mstate) { int i; if (!mouseinitialized) return; // perform button actions for (i=0 ; i<mouse_buttons ; i++) { if ( (mstate & (1<<i)) && !(mouse_oldbuttonstate & (1<<i)) ) { Key_Event (K_MOUSE1 + i, true, sys_msg_time); } if ( !(mstate & (1<<i)) && (mouse_oldbuttonstate & (1<<i)) ) { Key_Event (K_MOUSE1 + i, false, sys_msg_time); } } mouse_oldbuttonstate = mstate; } /* =========== IN_MouseMove =========== */ void IN_MouseMove (usercmd_t *cmd) { int mx, my; if (!mouseactive) return; // find mouse movement if (!GetCursorPos (&current_pos)) return; mx = current_pos.x - window_center_x; my = current_pos.y - window_center_y; #if 0 if (!mx && !my) return; #endif if (m_filter->value) { mouse_x = (mx + old_mouse_x) * 0.5; mouse_y = (my + old_mouse_y) * 0.5; } else { mouse_x = mx; mouse_y = my; } old_mouse_x = mx; old_mouse_y = my; mouse_x *= sensitivity->value; mouse_y *= sensitivity->value; // add mouse X/Y movement to cmd if ( (in_strafe.state & 1) || (lookstrafe->value && mlooking )) cmd->sidemove += m_side->value * mouse_x; else cl.viewangles[YAW] -= m_yaw->value * mouse_x; if ( (mlooking || freelook->value) && !(in_strafe.state & 1)) { cl.viewangles[PITCH] += m_pitch->value * mouse_y; } else { cmd->forwardmove -= m_forward->value * mouse_y; } // force the mouse to the center, so there's room to move if (mx || my) SetCursorPos (window_center_x, window_center_y); } /* ========================================================================= VIEW CENTERING ========================================================================= */ cvar_t *v_centermove; cvar_t *v_centerspeed; /* =========== IN_Init =========== */ void IN_Init (void) { // mouse variables m_filter = Cvar_Get ("m_filter", "0", 0); in_mouse = Cvar_Get ("in_mouse", "1", CVAR_ARCHIVE); // joystick variables in_joystick = Cvar_Get ("in_joystick", "0", CVAR_ARCHIVE); joy_name = Cvar_Get ("joy_name", "joystick", 0); joy_advanced = Cvar_Get ("joy_advanced", "0", 0); joy_advaxisx = Cvar_Get ("joy_advaxisx", "0", 0); joy_advaxisy = Cvar_Get ("joy_advaxisy", "0", 0); joy_advaxisz = Cvar_Get ("joy_advaxisz", "0", 0); joy_advaxisr = Cvar_Get ("joy_advaxisr", "0", 0); joy_advaxisu = Cvar_Get ("joy_advaxisu", "0", 0); joy_advaxisv = Cvar_Get ("joy_advaxisv", "0", 0); joy_forwardthreshold = Cvar_Get ("joy_forwardthreshold", "0.15", 0); joy_sidethreshold = Cvar_Get ("joy_sidethreshold", "0.15", 0); joy_upthreshold = Cvar_Get ("joy_upthreshold", "0.15", 0); joy_pitchthreshold = Cvar_Get ("joy_pitchthreshold", "0.15", 0); joy_yawthreshold = Cvar_Get ("joy_yawthreshold", "0.15", 0); joy_forwardsensitivity = Cvar_Get ("joy_forwardsensitivity", "-1", 0); joy_sidesensitivity = Cvar_Get ("joy_sidesensitivity", "-1", 0); joy_upsensitivity = Cvar_Get ("joy_upsensitivity", "-1", 0); joy_pitchsensitivity = Cvar_Get ("joy_pitchsensitivity", "1", 0); joy_yawsensitivity = Cvar_Get ("joy_yawsensitivity", "-1", 0); // centering v_centermove = Cvar_Get ("v_centermove", "0.15", 0); v_centerspeed = Cvar_Get ("v_centerspeed", "500", 0); Cmd_AddCommand ("+mlook", IN_MLookDown); Cmd_AddCommand ("-mlook", IN_MLookUp); Cmd_AddCommand ("joy_advancedupdate", Joy_AdvancedUpdate_f); IN_StartupMouse (); IN_StartupJoystick (); } /* =========== IN_Shutdown =========== */ void IN_Shutdown (void) { IN_DeactivateMouse (); } /* =========== IN_Activate Called when the main window gains or loses focus. The window may have been destroyed and recreated between a deactivate and an activate. =========== */ void IN_Activate (qboolean active) { in_appactive = active; mouseactive = !active; // force a new window check or turn off } /* ================== IN_Frame Called every frame, even if not generating commands ================== */ void IN_Frame (void) { if (!mouseinitialized) return; if (!in_mouse || !in_appactive) { IN_DeactivateMouse (); return; } if ( !cl.refresh_prepped || cls.key_dest == key_console || cls.key_dest == key_menu) { // temporarily deactivate if in fullscreen if (Cvar_VariableValue ("vid_fullscreen") == 0) { IN_DeactivateMouse (); return; } } IN_ActivateMouse (); } /* =========== IN_Move =========== */ void IN_Move (usercmd_t *cmd) { IN_MouseMove (cmd); if (ActiveApp) IN_JoyMove (cmd); } /* =================== IN_ClearStates =================== */ void IN_ClearStates (void) { mx_accum = 0; my_accum = 0; mouse_oldbuttonstate = 0; } /* ========================================================================= JOYSTICK ========================================================================= */ /* =============== IN_StartupJoystick =============== */ void IN_StartupJoystick (void) { int numdevs; JOYCAPS jc; MMRESULT mmr; cvar_t *cv; // assume no joystick joy_avail = false; // abort startup if user requests no joystick cv = Cvar_Get ("in_initjoy", "1", CVAR_NOSET); if ( !cv->value ) return; // verify joystick driver is present if ((numdevs = joyGetNumDevs ()) == 0) { // Com_Printf ("\njoystick not found -- driver not present\n\n"); return; } // cycle through the joystick ids for the first valid one for (joy_id=0 ; joy_id<numdevs ; joy_id++) { memset (&ji, 0, sizeof(ji)); ji.dwSize = sizeof(ji); ji.dwFlags = JOY_RETURNCENTERED; if ((mmr = joyGetPosEx (joy_id, &ji)) == JOYERR_NOERROR) break; } // abort startup if we didn't find a valid joystick if (mmr != JOYERR_NOERROR) { Com_Printf ("\njoystick not found -- no valid joysticks (%x)\n\n", mmr); return; } // get the capabilities of the selected joystick // abort startup if command fails memset (&jc, 0, sizeof(jc)); if ((mmr = joyGetDevCaps (joy_id, &jc, sizeof(jc))) != JOYERR_NOERROR) { Com_Printf ("\njoystick not found -- invalid joystick capabilities (%x)\n\n", mmr); return; } // save the joystick's number of buttons and POV status joy_numbuttons = jc.wNumButtons; joy_haspov = jc.wCaps & JOYCAPS_HASPOV; // old button and POV states default to no buttons pressed joy_oldbuttonstate = joy_oldpovstate = 0; // mark the joystick as available and advanced initialization not completed // this is needed as cvars are not available during initialization joy_avail = true; joy_advancedinit = false; Com_Printf ("\njoystick detected\n\n"); } /* =========== RawValuePointer =========== */ PDWORD RawValuePointer (int axis) { switch (axis) { case JOY_AXIS_X: return &ji.dwXpos; case JOY_AXIS_Y: return &ji.dwYpos; case JOY_AXIS_Z: return &ji.dwZpos; case JOY_AXIS_R: return &ji.dwRpos; case JOY_AXIS_U: return &ji.dwUpos; case JOY_AXIS_V: return &ji.dwVpos; } } /* =========== Joy_AdvancedUpdate_f =========== */ void Joy_AdvancedUpdate_f (void) { // called once by IN_ReadJoystick and by user whenever an update is needed // cvars are now available int i; DWORD dwTemp; // initialize all the maps for (i = 0; i < JOY_MAX_AXES; i++) { dwAxisMap[i] = AxisNada; dwControlMap[i] = JOY_ABSOLUTE_AXIS; pdwRawValue[i] = RawValuePointer(i); } if( joy_advanced->value == 0.0) { // default joystick initialization // 2 axes only with joystick control dwAxisMap[JOY_AXIS_X] = AxisTurn; // dwControlMap[JOY_AXIS_X] = JOY_ABSOLUTE_AXIS; dwAxisMap[JOY_AXIS_Y] = AxisForward; // dwControlMap[JOY_AXIS_Y] = JOY_ABSOLUTE_AXIS; } else { if (strcmp (joy_name->string, "joystick") != 0) { // notify user of advanced controller Com_Printf ("\n%s configured\n\n", joy_name->string); } // advanced initialization here // data supplied by user via joy_axisn cvars dwTemp = (DWORD) joy_advaxisx->value; dwAxisMap[JOY_AXIS_X] = dwTemp & 0x0000000f; dwControlMap[JOY_AXIS_X] = dwTemp & JOY_RELATIVE_AXIS; dwTemp = (DWORD) joy_advaxisy->value; dwAxisMap[JOY_AXIS_Y] = dwTemp & 0x0000000f; dwControlMap[JOY_AXIS_Y] = dwTemp & JOY_RELATIVE_AXIS; dwTemp = (DWORD) joy_advaxisz->value; dwAxisMap[JOY_AXIS_Z] = dwTemp & 0x0000000f; dwControlMap[JOY_AXIS_Z] = dwTemp & JOY_RELATIVE_AXIS; dwTemp = (DWORD) joy_advaxisr->value; dwAxisMap[JOY_AXIS_R] = dwTemp & 0x0000000f; dwControlMap[JOY_AXIS_R] = dwTemp & JOY_RELATIVE_AXIS; dwTemp = (DWORD) joy_advaxisu->value; dwAxisMap[JOY_AXIS_U] = dwTemp & 0x0000000f; dwControlMap[JOY_AXIS_U] = dwTemp & JOY_RELATIVE_AXIS; dwTemp = (DWORD) joy_advaxisv->value; dwAxisMap[JOY_AXIS_V] = dwTemp & 0x0000000f; dwControlMap[JOY_AXIS_V] = dwTemp & JOY_RELATIVE_AXIS; } // compute the axes to collect from DirectInput joy_flags = JOY_RETURNCENTERED | JOY_RETURNBUTTONS | JOY_RETURNPOV; for (i = 0; i < JOY_MAX_AXES; i++) { if (dwAxisMap[i] != AxisNada) { joy_flags |= dwAxisFlags[i]; } } } /* =========== IN_Commands =========== */ void IN_Commands (void) { int i, key_index; DWORD buttonstate, povstate; if (!joy_avail) { return; } // loop through the joystick buttons // key a joystick event or auxillary event for higher number buttons for each state change buttonstate = ji.dwButtons; for (i=0 ; i < joy_numbuttons ; i++) { if ( (buttonstate & (1<<i)) && !(joy_oldbuttonstate & (1<<i)) ) { key_index = (i < 4) ? K_JOY1 : K_AUX1; Key_Event (key_index + i, true, 0); } if ( !(buttonstate & (1<<i)) && (joy_oldbuttonstate & (1<<i)) ) { key_index = (i < 4) ? K_JOY1 : K_AUX1; Key_Event (key_index + i, false, 0); } } joy_oldbuttonstate = buttonstate; if (joy_haspov) { // convert POV information into 4 bits of state information // this avoids any potential problems related to moving from one // direction to another without going through the center position povstate = 0; if(ji.dwPOV != JOY_POVCENTERED) { if (ji.dwPOV == JOY_POVFORWARD) povstate |= 0x01; if (ji.dwPOV == JOY_POVRIGHT) povstate |= 0x02; if (ji.dwPOV == JOY_POVBACKWARD) povstate |= 0x04; if (ji.dwPOV == JOY_POVLEFT) povstate |= 0x08; } // determine which bits have changed and key an auxillary event for each change for (i=0 ; i < 4 ; i++) { if ( (povstate & (1<<i)) && !(joy_oldpovstate & (1<<i)) ) { Key_Event (K_AUX29 + i, true, 0); } if ( !(povstate & (1<<i)) && (joy_oldpovstate & (1<<i)) ) { Key_Event (K_AUX29 + i, false, 0); } } joy_oldpovstate = povstate; } } /* =============== IN_ReadJoystick =============== */ qboolean IN_ReadJoystick (void) { memset (&ji, 0, sizeof(ji)); ji.dwSize = sizeof(ji); ji.dwFlags = joy_flags; if (joyGetPosEx (joy_id, &ji) == JOYERR_NOERROR) { return true; } else { // read error occurred // turning off the joystick seems too harsh for 1 read error,\ // but what should be done? // Com_Printf ("IN_ReadJoystick: no response\n"); // joy_avail = false; return false; } } /* =========== IN_JoyMove =========== */ void IN_JoyMove (usercmd_t *cmd) { float speed, aspeed; float fAxisValue; int i; // complete initialization if first time in // this is needed as cvars are not available at initialization time if( joy_advancedinit != true ) { Joy_AdvancedUpdate_f(); joy_advancedinit = true; } // verify joystick is available and that the user wants to use it if (!joy_avail || !in_joystick->value) { return; } // collect the joystick data, if possible if (IN_ReadJoystick () != true) { return; } if ( (in_speed.state & 1) ^ (int)cl_run->value) speed = 2; else speed = 1; aspeed = speed * cls.frametime; // loop through the axes for (i = 0; i < JOY_MAX_AXES; i++) { // get the floating point zero-centered, potentially-inverted data for the current axis fAxisValue = (float) *pdwRawValue[i]; // move centerpoint to zero fAxisValue -= 32768.0; // convert range from -32768..32767 to -1..1 fAxisValue /= 32768.0; switch (dwAxisMap[i]) { case AxisForward: if ((joy_advanced->value == 0.0) && mlooking) { // user wants forward control to become look control if (fabs(fAxisValue) > joy_pitchthreshold->value) { // if mouse invert is on, invert the joystick pitch value // only absolute control support here (joy_advanced is false) if (m_pitch->value < 0.0) { cl.viewangles[PITCH] -= (fAxisValue * joy_pitchsensitivity->value) * aspeed * cl_pitchspeed->value; } else { cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity->value) * aspeed * cl_pitchspeed->value; } } } else { // user wants forward control to be forward control if (fabs(fAxisValue) > joy_forwardthreshold->value) { cmd->forwardmove += (fAxisValue * joy_forwardsensitivity->value) * speed * cl_forwardspeed->value; } } break; case AxisSide: if (fabs(fAxisValue) > joy_sidethreshold->value) { cmd->sidemove += (fAxisValue * joy_sidesensitivity->value) * speed * cl_sidespeed->value; } break; case AxisUp: if (fabs(fAxisValue) > joy_upthreshold->value) { cmd->upmove += (fAxisValue * joy_upsensitivity->value) * speed * cl_upspeed->value; } break; case AxisTurn: if ((in_strafe.state & 1) || (lookstrafe->value && mlooking)) { // user wants turn control to become side control if (fabs(fAxisValue) > joy_sidethreshold->value) { cmd->sidemove -= (fAxisValue * joy_sidesensitivity->value) * speed * cl_sidespeed->value; } } else { // user wants turn control to be turn control if (fabs(fAxisValue) > joy_yawthreshold->value) { if(dwControlMap[i] == JOY_ABSOLUTE_AXIS) { cl.viewangles[YAW] += (fAxisValue * joy_yawsensitivity->value) * aspeed * cl_yawspeed->value; } else { cl.viewangles[YAW] += (fAxisValue * joy_yawsensitivity->value) * speed * 180.0; } } } break; case AxisLook: if (mlooking) { if (fabs(fAxisValue) > joy_pitchthreshold->value) { // pitch movement detected and pitch movement desired by user if(dwControlMap[i] == JOY_ABSOLUTE_AXIS) { cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity->value) * aspeed * cl_pitchspeed->value; } else { cl.viewangles[PITCH] += (fAxisValue * joy_pitchsensitivity->value) * speed * 180.0; } } } break; default: break; } } }
{ "content_hash": "d90a83eb30e2b3bca31a4a9b7bd326bc", "timestamp": "", "source": "github", "line_count": 871, "max_line_length": 105, "avg_line_length": 21.879448909299654, "alnum_prop": 0.6216613317940914, "repo_name": "00wendi00/MyProject", "id": "7ec577ee4a5e0954b38739fbe5d28f521cf51417", "size": "19786", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "W_eclipse1_3/ch07.QuakeII/jni/quake2-3.21/win32/in_win.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "430521" }, { "name": "C", "bytes": "17868156" }, { "name": "C++", "bytes": "5054355" }, { "name": "CMake", "bytes": "7325" }, { "name": "CSS", "bytes": "3874611" }, { "name": "Groff", "bytes": "409306" }, { "name": "HTML", "bytes": "7833410" }, { "name": "Java", "bytes": "13395187" }, { "name": "JavaScript", "bytes": "2319278" }, { "name": "Logos", "bytes": "6864" }, { "name": "M", "bytes": "20108" }, { "name": "Makefile", "bytes": "2540551" }, { "name": "Objective-C", "bytes": "546363" }, { "name": "Perl", "bytes": "11763" }, { "name": "Python", "bytes": "3285" }, { "name": "R", "bytes": "8138" }, { "name": "Rebol", "bytes": "3080" }, { "name": "Shell", "bytes": "1020448" }, { "name": "SuperCollider", "bytes": "8013" }, { "name": "XSLT", "bytes": "220483" } ], "symlink_target": "" }
/* add tunling rebot support */ var request = require("sync-request") var endpoint = "http://www.tuling123.com/openapi/api" var commonRequest = function(){ this.key = process.env.key this.useid = "slack" } commonRequest.prototype.gen = function(info){ this.info = info return { key:this.key, userid:this.useid, info:this.info } } function reply(words){ if (words == undefined) { return } var req = new commonRequest(); var reqBody = req.gen(words); var res = request("POST",endpoint,{json:reqBody}); return res.getBody('utf8'); } var tuling = { reply:reply } module.exports = tuling
{ "content_hash": "763803112392a7c7482acd54215c83e5", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 53, "avg_line_length": 16.68421052631579, "alnum_prop": 0.6577287066246057, "repo_name": "ringtail/newtwon", "id": "8959b73312415fb00d3c6fa49a51aaa8c4db7456", "size": "634", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/tuling.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "7740" } ], "symlink_target": "" }
from . import Arduino from . import ARDUINO_GROVE_I2C __author__ = "Marco Rabozzi, Luca Cerina, Giuseppe Natale" __copyright__ = "Copyright 2016, NECST Laboratory, Politecnico di Milano" ARDUINO_GROVE_HAPTIC_MOTOR_PROGRAM = "arduino_grove_haptic_motor.bin" CONFIG_IOP_SWITCH = 0x1 START_WAVEFORM = 0x2 STOP_WAVEFORM = 0x3 READ_IS_PLAYING = 0x4 class Grove_HapticMotor(object): """This class controls the Grove Haptic Motor based on the DRV2605L. Hardware version v0.9. Attributes ---------- microblaze : Arduino Microblaze processor instance used by this module. """ def __init__(self, mb_info, gr_pin): """Return a new instance of an Grove_Haptic_Motor object. Parameters ---------- mb_info : dict A dictionary storing Microblaze information, such as the IP name and the reset name. gr_pin: list A group of pins on arduino-grove shield. """ if gr_pin not in [ARDUINO_GROVE_I2C]: raise ValueError("Group number can only be I2C.") self.microblaze = Arduino(mb_info, ARDUINO_GROVE_HAPTIC_MOTOR_PROGRAM) self.microblaze.write_blocking_command(CONFIG_IOP_SWITCH) def play(self, effect): """Play a vibration effect on the Grove Haptic Motor peripheral. Valid effect identifiers are in the range [1, 127]. Parameters ---------- effect : int An integer that specifies the effect. Returns ------- None """ if (effect < 1) or (effect > 127): raise ValueError("Valid effect identifiers are within 1 and 127.") self.microblaze.write_mailbox(0, [effect, 0]) self.microblaze.write_blocking_command(START_WAVEFORM) def play_sequence(self, sequence): """Play a sequence of effects possibly separated by pauses. At most 8 effects or pauses can be specified at a time. Pauses are defined using negative integer values in the range [-1, -127] that correspond to a pause length in the range [10, 1270] ms Valid effect identifiers are in the range [1, 127] As an example, in the following sequence example: [4,-20,5] effect 4 is played and after a pause of 200 ms effect 5 is played Parameters ---------- sequence : list At most 8 values specifying effects and pauses. Returns ------- None """ length = len(sequence) if length < 1: raise ValueError("The sequence must contain at least one value.") if length > 8: raise ValueError("The sequence cannot contain more than 8 values.") for i in range(length): if sequence[i] < 0: if sequence[i] < -127: raise ValueError("Pause value must be smaller than -127") sequence[i] = -sequence[i] + 128 else: if (sequence[i] < 1) or (sequence[i] > 127): raise ValueError("Valid effect identifiers are within " + "1 and 127.") sequence += [0] * (8 - length) self.microblaze.write_mailbox(0, sequence) self.microblaze.write_blocking_command(START_WAVEFORM) def stop(self): """Stop an effect or a sequence on the motor peripheral. Returns ------- None """ self.microblaze.write_blocking_command(STOP_WAVEFORM) def is_playing(self): """Check if a vibration effect is running on the motor. Returns ------- bool True if a vibration effect is playing, false otherwise """ self.microblaze.write_blocking_command(READ_IS_PLAYING) flag = self.microblaze.read_mailbox(0) return flag == 1
{ "content_hash": "cbee1e122bae1a0a95e461a774f0638d", "timestamp": "", "source": "github", "line_count": 128, "max_line_length": 79, "avg_line_length": 30.875, "alnum_prop": 0.5789473684210527, "repo_name": "schelleg/PYNQ", "id": "b42bef17bc5650c803824b1df50df26c0876cac5", "size": "5600", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "pynq/lib/arduino/arduino_grove_haptic_motor.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "51" }, { "name": "BitBake", "bytes": "1840" }, { "name": "C", "bytes": "1062607" }, { "name": "C++", "bytes": "76769" }, { "name": "CMake", "bytes": "578" }, { "name": "JavaScript", "bytes": "239958" }, { "name": "Jupyter Notebook", "bytes": "17148467" }, { "name": "Makefile", "bytes": "165279" }, { "name": "Python", "bytes": "1388540" }, { "name": "Shell", "bytes": "67192" }, { "name": "SystemVerilog", "bytes": "53374" }, { "name": "Tcl", "bytes": "1383109" }, { "name": "VHDL", "bytes": "738710" }, { "name": "Verilog", "bytes": "284588" } ], "symlink_target": "" }
class ReadResponse { id: string name: string fileBinary: any }
{ "content_hash": "fcf25a0ce209b3d69051af0e3e5ca0c2", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 20, "avg_line_length": 14.8, "alnum_prop": 0.6486486486486487, "repo_name": "somi92/snoo-shelf", "id": "6ddec37b61f69860e8f3dd1032fadaa0ec37e4f2", "size": "74", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/entities/ReadResponse.ts", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1519" }, { "name": "TypeScript", "bytes": "7473" } ], "symlink_target": "" }
/** * @format */ import {uniqueIDToImageID} from '../util/ids.js'; import {Copier} from './Copier.js'; export class ThumbnailControl { constructor(options) { this._imageText = this._createText('Image: '); this._clusterText = this._createText('Cluster: '); this._clusterURL = this._createText('URL: '); this._thumb = this._createThumb(); const container = this._createContainer(); container.appendChild(this._thumb); container.appendChild(this._imageText.element); container.appendChild(this._clusterText.element); container.appendChild(this._clusterURL.element); this._container = container; this._visible = options.visible; this._provider = options.provider; this._image = null; } get container() { return this._container; } hide() { if (!this._visible) { return; } this._container.classList.add('opensfm-hidden'); this._visible = false; } update(image) { this._image = image; this._render(); } show() { if (this._visible) { return; } this._container.classList.remove('opensfm-hidden'); this._visible = true; this._render(); } _createContainer() { const header = document.createElement('span'); header.classList.add('opensfm-info-text', 'opensfm-info-text-header'); header.textContent = 'Thumbnail'; const container = document.createElement('div'); container.classList.add('opensfm-control-container', 'opensfm-hidden'); container.appendChild(header); return container; } _createText(prefix) { const document = window.document; const element = document.createElement('span'); element.classList.add('opensfm-info-text', 'opensfm-info-inline'); const copier = new Copier({container: element, copyText: null}); return {copier, element, prefix}; } _createThumb() { const thumb = document.createElement('img'); thumb.classList.add('opensfm-thumb'); return thumb; } _setTextContent(textItem, content) { textItem.element.textContent = textItem.prefix + content; textItem.copier.setCopyText(content); } _render() { if (!this._image || !this._visible) { return; } const image = this._image; this._thumb.src = image.image.src; const clusterId = image.clusterId; const clusterURL = this._provider.rawData[clusterId].url; const imageId = uniqueIDToImageID(image.id); this._setTextContent(this._clusterURL, clusterURL); this._setTextContent(this._clusterText, clusterId); this._setTextContent(this._imageText, imageId); } }
{ "content_hash": "a2e99be6707450cda08977c35f39ffc0", "timestamp": "", "source": "github", "line_count": 94, "max_line_length": 75, "avg_line_length": 27.574468085106382, "alnum_prop": 0.6604938271604939, "repo_name": "oscarlorentzon/OpenSfM", "id": "b2604a3ec5ec156afe6fb4f71b21e05caec61040", "size": "2592", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "viewer/src/control/ThumbnailControl.js", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C++", "bytes": "56886" }, { "name": "CMake", "bytes": "57630" }, { "name": "HTML", "bytes": "51060" }, { "name": "JavaScript", "bytes": "968358" }, { "name": "Python", "bytes": "275728" }, { "name": "Shell", "bytes": "1780" } ], "symlink_target": "" }
{% load competition_tags %} <table class="table table-condensed table-hover table-border"> <thead> </thead> <tbody> <tr> <th>Starting Time</th> <td>{{ competition.start_time }}</td> </tr> <tr> <th>Ending Time</th> <td>{{ competition.end_time }}</td> </tr> <tr> <th>Is open?</th> <td> <span class="label label-{% if competition.is_open %}success{% else %}danger{% endif %}"> {{ competition.is_open|yesno:"Yep!,Nope.," }} </span> </td> </tr> <tr> <th>Is running?</th> <td> <span class="label label-{% if competition.is_running %}success{% else %}danger{% endif %}"> {{ competition.is_running|yesno:"Yep!,Nope.," }} </span> </td> </tr> <tr> {% if competition.payment_option == competition.PER_PERSON_PAYMENT %} <th>Cost per person:</th> {% endif %} {% if competition.payment_option == competition.PER_TEAM_PAYMENT %} <th>Cost per team:</th> {% endif %} <td>${{ competition.cost|floatformat:2 }}</td> </tr> {% if competition.min_num_team_members == competition.max_num_team_members %} <tr> <th>Team size</th> <td>{{ competition.min_num_team_members }}</td> </tr> {% else %} <tr> <th>Minimum team size</th> <td>{{ competition.min_num_team_members }}</td> </tr> <tr> <th>Maximum team size</th> <td>{{ competition.max_num_team_members }}</td> </tr> {% endif %} <tr> <th>Number of registered competitors</th> <td>{% registered_users_count competition %}</td> </tr> </tbody> </table>
{ "content_hash": "cfbaa9102997effc5343f062bd531088", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 100, "avg_line_length": 27.983606557377048, "alnum_prop": 0.5196250732278852, "repo_name": "michaelwisely/django-competition", "id": "9bebd39c7eb41993e08729fcc0d901ca303cd959", "size": "1707", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/competition/templates/competition/competition/_competition_detail.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "3975" }, { "name": "Cucumber", "bytes": "1592" }, { "name": "HTML", "bytes": "41099" }, { "name": "JavaScript", "bytes": "2111" }, { "name": "Makefile", "bytes": "782" }, { "name": "Python", "bytes": "290534" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="pl"> <head> <meta http-equiv="Content-Type" content="text/html" charset="UTF-8"> <title>Uses of Interface com.google.code.play2.provider.api.Play2Provider (Play! 2.x Provider API 1.0.0-alpha6 API)</title> <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="Uses of Interface com.google.code.play2.provider.api.Play2Provider (Play! 2.x Provider API 1.0.0-alpha6 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="../../../../../../../com/google/code/play2/provider/api/package-summary.html">Package</a></li> <li><a href="../../../../../../../com/google/code/play2/provider/api/Play2Provider.html" title="interface in com.google.code.play2.provider.api">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-all.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?com/google/code/play2/provider/api/class-use/Play2Provider.html" target="_top">Frames</a></li> <li><a href="Play2Provider.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"> <h2 title="Uses of Interface com.google.code.play2.provider.api.Play2Provider" class="title">Uses of Interface<br>com.google.code.play2.provider.api.Play2Provider</h2> </div> <div class="classUseContainer">No usage of com.google.code.play2.provider.api.Play2Provider</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="../../../../../../../com/google/code/play2/provider/api/package-summary.html">Package</a></li> <li><a href="../../../../../../../com/google/code/play2/provider/api/Play2Provider.html" title="interface in com.google.code.play2.provider.api">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-all.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?com/google/code/play2/provider/api/class-use/Play2Provider.html" target="_top">Frames</a></li> <li><a href="Play2Provider.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; 2013&#x2013;2014. All rights reserved.</small></p> </body> </html>
{ "content_hash": "728e398a5c93875b7ee26af05e816ae2", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 167, "avg_line_length": 39.389380530973455, "alnum_prop": 0.6135699842731971, "repo_name": "play2-maven-plugin/play2-maven-plugin.github.io", "id": "45da82be1d6df689dc8ec000366b36a295ab48d5", "size": "4451", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "play2-maven-plugin/1.0.0-alpha6/play2-provider-api/apidocs/com/google/code/play2/provider/api/class-use/Play2Provider.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2793124" }, { "name": "HTML", "bytes": "178221432" }, { "name": "JavaScript", "bytes": "120742" } ], "symlink_target": "" }
package org.eclipse.winery.repository.resources._support.dataadapter; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.eclipse.winery.model.tosca.TNodeTemplate; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "InjectorReplaceData") public class InjectorReplaceData { @XmlJavaTypeAdapter(value = InjectionDataMapAdapter.class) public Map<String, TNodeTemplate> injections; public void setInjections (Map<String, TNodeTemplate> injections) { this.injections = injections; } }
{ "content_hash": "d21ce5e170d5508970e08802fb571c5d", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 69, "avg_line_length": 28.14814814814815, "alnum_prop": 0.8105263157894737, "repo_name": "YannicSowoidnich/winery", "id": "0e8fd4d8b2f124cd966489ed73ec7b28a8594f23", "size": "1374", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "org.eclipse.winery.repository/src/main/java/org/eclipse/winery/repository/resources/_support/dataadapter/InjectorReplaceData.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "770" }, { "name": "CSS", "bytes": "96676" }, { "name": "HTML", "bytes": "273259" }, { "name": "Java", "bytes": "1743710" }, { "name": "JavaScript", "bytes": "85796" }, { "name": "Shell", "bytes": "1174" }, { "name": "TypeScript", "bytes": "458830" } ], "symlink_target": "" }
<?php require_once '../_theme/util.inc.php'; chk_login(); $MasterPage = 'page_main.php';?> <?php sb('title');?> Liver flushing registry <?php eb();?> <?php sb('js_and_css_head'); ?> <style type="text/css"> #show_content { margin: 0 auto; width: 95%; } </style> <?php eb();?> <?php sb('notifications');?> <?php include_once '../notifications.php'; ?> <?php eb();?> <?php include_once "../_connection/db_base.php"; ?> <?php isset($_GET['schedule_id']) ? $schedule_id = $_GET['schedule_id'] : $schedule_id = ''; ?> <?php sb('content');?> <!-- Content Header (Page header) --> <section class="content-header"> <h1> รายละเอียดการจ่ายเงิน <small>รายละเอียดการจ่ายเงิน</small> </h1> <ol class="breadcrumb"> <li><a href="#"><i class="fa fa-dashboard"></i> Home</a></li> <li class="active">รายละเอียดการจ่ายเงิน</li> </ol> </section> <!-- Main content --> <section class="content"> <div class="box box-default"> <div class="box-body"> <div class="row"> <div class="col-sm-offset-5 col-sm-2 text-center"> <div class="btn-group"> <a href="../schedules.php" class="btn btn-block btn-primary btn-lg btn-flat">กลับหน้าหลักสูตร</a> </div> </div> </div> <p></p> <?php $result = $mysqli->query("SELECT schedule_payment FROM site_schedule WHERE id = '$schedule_id'"); $row = $result->fetch_assoc(); echo "<textarea class='form-control' id='detail' rows='50' id='scheduledesc' placeholder='รายละเอียดหลักสูตร'>".html_entity_decode($row['schedule_payment'])."</textarea>"; //echo $row['schedule_payment']; ?> </div><!-- /.box-body --> </div><!-- /.box --> </section><!-- /.content --> <?php eb();?> <?php sb('js_and_css_footer');?> <link rel="stylesheet" type="text/css" href="../_plugins/edit/minified/themes/default.min.css"> <script src="../_plugins/edit/minified/jquery.sceditor.bbcode.min.js"></script> <script type="text/javascript" src="../_plugins/datepicker/bootstrap-datepicker.js"></script> <script> $(document).ready(function(){ $("#detail").sceditor({ plugins: 'bbcode', width: '98%', toolbar: 'justify', readOnly: 'true', resizeEnabled: false, style: 'edit/minified/jquery.sceditor.default.min.css' }); }); </script> <?php eb();?> <?php render($MasterPage);?>
{ "content_hash": "7687fd3fb0546af85c47142ae6f68613", "timestamp": "", "source": "github", "line_count": 87, "max_line_length": 179, "avg_line_length": 27.96551724137931, "alnum_prop": 0.5709001233045623, "repo_name": "damasac/detoxthai_lte", "id": "a12f2b849b0e3cc03feb1ce4da8c0657137709f3", "size": "2627", "binary": false, "copies": "1", "ref": "refs/heads/Develop", "path": "schedule/payment_detail.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "305" }, { "name": "CSS", "bytes": "1027708" }, { "name": "HTML", "bytes": "3804297" }, { "name": "JavaScript", "bytes": "4276746" }, { "name": "PHP", "bytes": "1883720" } ], "symlink_target": "" }
 #pragma once #include <aws/lexv2-models/LexModelsV2_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/lexv2-models/model/BotRecommendationStatus.h> #include <aws/core/utils/DateTime.h> #include <aws/lexv2-models/model/TranscriptSourceSetting.h> #include <aws/lexv2-models/model/EncryptionSetting.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace LexModelsV2 { namespace Model { class AWS_LEXMODELSV2_API UpdateBotRecommendationResult { public: UpdateBotRecommendationResult(); UpdateBotRecommendationResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); UpdateBotRecommendationResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>The unique identifier of the bot containing the bot recommendation that has * been updated.</p> */ inline const Aws::String& GetBotId() const{ return m_botId; } /** * <p>The unique identifier of the bot containing the bot recommendation that has * been updated.</p> */ inline void SetBotId(const Aws::String& value) { m_botId = value; } /** * <p>The unique identifier of the bot containing the bot recommendation that has * been updated.</p> */ inline void SetBotId(Aws::String&& value) { m_botId = std::move(value); } /** * <p>The unique identifier of the bot containing the bot recommendation that has * been updated.</p> */ inline void SetBotId(const char* value) { m_botId.assign(value); } /** * <p>The unique identifier of the bot containing the bot recommendation that has * been updated.</p> */ inline UpdateBotRecommendationResult& WithBotId(const Aws::String& value) { SetBotId(value); return *this;} /** * <p>The unique identifier of the bot containing the bot recommendation that has * been updated.</p> */ inline UpdateBotRecommendationResult& WithBotId(Aws::String&& value) { SetBotId(std::move(value)); return *this;} /** * <p>The unique identifier of the bot containing the bot recommendation that has * been updated.</p> */ inline UpdateBotRecommendationResult& WithBotId(const char* value) { SetBotId(value); return *this;} /** * <p>The version of the bot containing the bot recommendation that has been * updated.</p> */ inline const Aws::String& GetBotVersion() const{ return m_botVersion; } /** * <p>The version of the bot containing the bot recommendation that has been * updated.</p> */ inline void SetBotVersion(const Aws::String& value) { m_botVersion = value; } /** * <p>The version of the bot containing the bot recommendation that has been * updated.</p> */ inline void SetBotVersion(Aws::String&& value) { m_botVersion = std::move(value); } /** * <p>The version of the bot containing the bot recommendation that has been * updated.</p> */ inline void SetBotVersion(const char* value) { m_botVersion.assign(value); } /** * <p>The version of the bot containing the bot recommendation that has been * updated.</p> */ inline UpdateBotRecommendationResult& WithBotVersion(const Aws::String& value) { SetBotVersion(value); return *this;} /** * <p>The version of the bot containing the bot recommendation that has been * updated.</p> */ inline UpdateBotRecommendationResult& WithBotVersion(Aws::String&& value) { SetBotVersion(std::move(value)); return *this;} /** * <p>The version of the bot containing the bot recommendation that has been * updated.</p> */ inline UpdateBotRecommendationResult& WithBotVersion(const char* value) { SetBotVersion(value); return *this;} /** * <p>The identifier of the language and locale of the bot recommendation to * update. The string must match one of the supported locales. For more * information, see <a * href="https://docs.aws.amazon.com/lexv2/latest/dg/how-languages.html">Supported * languages</a> </p> */ inline const Aws::String& GetLocaleId() const{ return m_localeId; } /** * <p>The identifier of the language and locale of the bot recommendation to * update. The string must match one of the supported locales. For more * information, see <a * href="https://docs.aws.amazon.com/lexv2/latest/dg/how-languages.html">Supported * languages</a> </p> */ inline void SetLocaleId(const Aws::String& value) { m_localeId = value; } /** * <p>The identifier of the language and locale of the bot recommendation to * update. The string must match one of the supported locales. For more * information, see <a * href="https://docs.aws.amazon.com/lexv2/latest/dg/how-languages.html">Supported * languages</a> </p> */ inline void SetLocaleId(Aws::String&& value) { m_localeId = std::move(value); } /** * <p>The identifier of the language and locale of the bot recommendation to * update. The string must match one of the supported locales. For more * information, see <a * href="https://docs.aws.amazon.com/lexv2/latest/dg/how-languages.html">Supported * languages</a> </p> */ inline void SetLocaleId(const char* value) { m_localeId.assign(value); } /** * <p>The identifier of the language and locale of the bot recommendation to * update. The string must match one of the supported locales. For more * information, see <a * href="https://docs.aws.amazon.com/lexv2/latest/dg/how-languages.html">Supported * languages</a> </p> */ inline UpdateBotRecommendationResult& WithLocaleId(const Aws::String& value) { SetLocaleId(value); return *this;} /** * <p>The identifier of the language and locale of the bot recommendation to * update. The string must match one of the supported locales. For more * information, see <a * href="https://docs.aws.amazon.com/lexv2/latest/dg/how-languages.html">Supported * languages</a> </p> */ inline UpdateBotRecommendationResult& WithLocaleId(Aws::String&& value) { SetLocaleId(std::move(value)); return *this;} /** * <p>The identifier of the language and locale of the bot recommendation to * update. The string must match one of the supported locales. For more * information, see <a * href="https://docs.aws.amazon.com/lexv2/latest/dg/how-languages.html">Supported * languages</a> </p> */ inline UpdateBotRecommendationResult& WithLocaleId(const char* value) { SetLocaleId(value); return *this;} /** * <p>The status of the bot recommendation.</p> <p>If the status is Failed, then * the reasons for the failure are listed in the failureReasons field. </p> */ inline const BotRecommendationStatus& GetBotRecommendationStatus() const{ return m_botRecommendationStatus; } /** * <p>The status of the bot recommendation.</p> <p>If the status is Failed, then * the reasons for the failure are listed in the failureReasons field. </p> */ inline void SetBotRecommendationStatus(const BotRecommendationStatus& value) { m_botRecommendationStatus = value; } /** * <p>The status of the bot recommendation.</p> <p>If the status is Failed, then * the reasons for the failure are listed in the failureReasons field. </p> */ inline void SetBotRecommendationStatus(BotRecommendationStatus&& value) { m_botRecommendationStatus = std::move(value); } /** * <p>The status of the bot recommendation.</p> <p>If the status is Failed, then * the reasons for the failure are listed in the failureReasons field. </p> */ inline UpdateBotRecommendationResult& WithBotRecommendationStatus(const BotRecommendationStatus& value) { SetBotRecommendationStatus(value); return *this;} /** * <p>The status of the bot recommendation.</p> <p>If the status is Failed, then * the reasons for the failure are listed in the failureReasons field. </p> */ inline UpdateBotRecommendationResult& WithBotRecommendationStatus(BotRecommendationStatus&& value) { SetBotRecommendationStatus(std::move(value)); return *this;} /** * <p>The unique identifier of the bot recommendation to be updated.</p> */ inline const Aws::String& GetBotRecommendationId() const{ return m_botRecommendationId; } /** * <p>The unique identifier of the bot recommendation to be updated.</p> */ inline void SetBotRecommendationId(const Aws::String& value) { m_botRecommendationId = value; } /** * <p>The unique identifier of the bot recommendation to be updated.</p> */ inline void SetBotRecommendationId(Aws::String&& value) { m_botRecommendationId = std::move(value); } /** * <p>The unique identifier of the bot recommendation to be updated.</p> */ inline void SetBotRecommendationId(const char* value) { m_botRecommendationId.assign(value); } /** * <p>The unique identifier of the bot recommendation to be updated.</p> */ inline UpdateBotRecommendationResult& WithBotRecommendationId(const Aws::String& value) { SetBotRecommendationId(value); return *this;} /** * <p>The unique identifier of the bot recommendation to be updated.</p> */ inline UpdateBotRecommendationResult& WithBotRecommendationId(Aws::String&& value) { SetBotRecommendationId(std::move(value)); return *this;} /** * <p>The unique identifier of the bot recommendation to be updated.</p> */ inline UpdateBotRecommendationResult& WithBotRecommendationId(const char* value) { SetBotRecommendationId(value); return *this;} /** * <p>A timestamp of the date and time that the bot recommendation was created.</p> */ inline const Aws::Utils::DateTime& GetCreationDateTime() const{ return m_creationDateTime; } /** * <p>A timestamp of the date and time that the bot recommendation was created.</p> */ inline void SetCreationDateTime(const Aws::Utils::DateTime& value) { m_creationDateTime = value; } /** * <p>A timestamp of the date and time that the bot recommendation was created.</p> */ inline void SetCreationDateTime(Aws::Utils::DateTime&& value) { m_creationDateTime = std::move(value); } /** * <p>A timestamp of the date and time that the bot recommendation was created.</p> */ inline UpdateBotRecommendationResult& WithCreationDateTime(const Aws::Utils::DateTime& value) { SetCreationDateTime(value); return *this;} /** * <p>A timestamp of the date and time that the bot recommendation was created.</p> */ inline UpdateBotRecommendationResult& WithCreationDateTime(Aws::Utils::DateTime&& value) { SetCreationDateTime(std::move(value)); return *this;} /** * <p>A timestamp of the date and time that the bot recommendation was last * updated.</p> */ inline const Aws::Utils::DateTime& GetLastUpdatedDateTime() const{ return m_lastUpdatedDateTime; } /** * <p>A timestamp of the date and time that the bot recommendation was last * updated.</p> */ inline void SetLastUpdatedDateTime(const Aws::Utils::DateTime& value) { m_lastUpdatedDateTime = value; } /** * <p>A timestamp of the date and time that the bot recommendation was last * updated.</p> */ inline void SetLastUpdatedDateTime(Aws::Utils::DateTime&& value) { m_lastUpdatedDateTime = std::move(value); } /** * <p>A timestamp of the date and time that the bot recommendation was last * updated.</p> */ inline UpdateBotRecommendationResult& WithLastUpdatedDateTime(const Aws::Utils::DateTime& value) { SetLastUpdatedDateTime(value); return *this;} /** * <p>A timestamp of the date and time that the bot recommendation was last * updated.</p> */ inline UpdateBotRecommendationResult& WithLastUpdatedDateTime(Aws::Utils::DateTime&& value) { SetLastUpdatedDateTime(std::move(value)); return *this;} /** * <p>The object representing the Amazon S3 bucket containing the transcript, as * well as the associated metadata.</p> */ inline const TranscriptSourceSetting& GetTranscriptSourceSetting() const{ return m_transcriptSourceSetting; } /** * <p>The object representing the Amazon S3 bucket containing the transcript, as * well as the associated metadata.</p> */ inline void SetTranscriptSourceSetting(const TranscriptSourceSetting& value) { m_transcriptSourceSetting = value; } /** * <p>The object representing the Amazon S3 bucket containing the transcript, as * well as the associated metadata.</p> */ inline void SetTranscriptSourceSetting(TranscriptSourceSetting&& value) { m_transcriptSourceSetting = std::move(value); } /** * <p>The object representing the Amazon S3 bucket containing the transcript, as * well as the associated metadata.</p> */ inline UpdateBotRecommendationResult& WithTranscriptSourceSetting(const TranscriptSourceSetting& value) { SetTranscriptSourceSetting(value); return *this;} /** * <p>The object representing the Amazon S3 bucket containing the transcript, as * well as the associated metadata.</p> */ inline UpdateBotRecommendationResult& WithTranscriptSourceSetting(TranscriptSourceSetting&& value) { SetTranscriptSourceSetting(std::move(value)); return *this;} /** * <p>The object representing the passwords that were used to encrypt the data * related to the bot recommendation results, as well as the KMS key ARN used to * encrypt the associated metadata.</p> */ inline const EncryptionSetting& GetEncryptionSetting() const{ return m_encryptionSetting; } /** * <p>The object representing the passwords that were used to encrypt the data * related to the bot recommendation results, as well as the KMS key ARN used to * encrypt the associated metadata.</p> */ inline void SetEncryptionSetting(const EncryptionSetting& value) { m_encryptionSetting = value; } /** * <p>The object representing the passwords that were used to encrypt the data * related to the bot recommendation results, as well as the KMS key ARN used to * encrypt the associated metadata.</p> */ inline void SetEncryptionSetting(EncryptionSetting&& value) { m_encryptionSetting = std::move(value); } /** * <p>The object representing the passwords that were used to encrypt the data * related to the bot recommendation results, as well as the KMS key ARN used to * encrypt the associated metadata.</p> */ inline UpdateBotRecommendationResult& WithEncryptionSetting(const EncryptionSetting& value) { SetEncryptionSetting(value); return *this;} /** * <p>The object representing the passwords that were used to encrypt the data * related to the bot recommendation results, as well as the KMS key ARN used to * encrypt the associated metadata.</p> */ inline UpdateBotRecommendationResult& WithEncryptionSetting(EncryptionSetting&& value) { SetEncryptionSetting(std::move(value)); return *this;} private: Aws::String m_botId; Aws::String m_botVersion; Aws::String m_localeId; BotRecommendationStatus m_botRecommendationStatus; Aws::String m_botRecommendationId; Aws::Utils::DateTime m_creationDateTime; Aws::Utils::DateTime m_lastUpdatedDateTime; TranscriptSourceSetting m_transcriptSourceSetting; EncryptionSetting m_encryptionSetting; }; } // namespace Model } // namespace LexModelsV2 } // namespace Aws
{ "content_hash": "4624510139b5c4e73fa7bffc4b64e92b", "timestamp": "", "source": "github", "line_count": 399, "max_line_length": 165, "avg_line_length": 39.68671679197995, "alnum_prop": 0.6919482159772655, "repo_name": "aws/aws-sdk-cpp", "id": "9f8f86c07b1b8e9eea6fe6d5fd540ecbaf2b9ded", "size": "15954", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "aws-cpp-sdk-lexv2-models/include/aws/lexv2-models/model/UpdateBotRecommendationResult.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "309797" }, { "name": "C++", "bytes": "476866144" }, { "name": "CMake", "bytes": "1245180" }, { "name": "Dockerfile", "bytes": "11688" }, { "name": "HTML", "bytes": "8056" }, { "name": "Java", "bytes": "413602" }, { "name": "Python", "bytes": "79245" }, { "name": "Shell", "bytes": "9246" } ], "symlink_target": "" }
using System.Data.Entity.ModelConfiguration; namespace AprendendoEF.DAL.Configurations { public class ProdutoConfig : EntityTypeConfiguration<Produto> { public ProdutoConfig() { ToTable("Produtos"); HasRequired(p => p.GrupoProduto) .WithMany(g=> g.Produtos) .HasForeignKey(x => x.GrupoProduto_Id); } } }
{ "content_hash": "1d3c4f213241b5854b00bb333dc811bf", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 65, "avg_line_length": 26.533333333333335, "alnum_prop": 0.5954773869346733, "repo_name": "leonardoacoelho/cadastro", "id": "632bb2848ac5a7a12da24637b3f1e960239be194", "size": "400", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "AprendendoEF/AprendendoEF.DAL/Configurations/ProdutoConfig.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "92994" } ], "symlink_target": "" }
namespace gpu { namespace raster { namespace { class Serializer { public: Serializer(char* memory, uint32_t memory_size) : memory_(memory), memory_size_(memory_size) {} ~Serializer() = default; template <typename T> void Write(const T* val) { static_assert(base::is_trivially_copyable<T>::value, ""); WriteData(val, sizeof(T), alignof(T)); } void WriteData(const void* input, uint32_t bytes, size_t alignment) { AlignMemory(bytes, alignment); if (bytes == 0) return; memcpy(memory_, input, bytes); memory_ += bytes; bytes_written_ += bytes; } private: void AlignMemory(uint32_t size, size_t alignment) { // Due to the math below, alignment must be a power of two. DCHECK_GT(alignment, 0u); DCHECK_EQ(alignment & (alignment - 1), 0u); uintptr_t memory = reinterpret_cast<uintptr_t>(memory_); size_t padding = ((memory + alignment - 1) & ~(alignment - 1)) - memory; DCHECK_LE(bytes_written_ + size + padding, memory_size_); memory_ += padding; bytes_written_ += padding; } char* memory_ = nullptr; uint32_t memory_size_ = 0u; uint32_t bytes_written_ = 0u; }; } // namespace ClientFontManager::ClientFontManager(Client* client, CommandBuffer* command_buffer) : client_(client), command_buffer_(command_buffer), strike_server_(this) {} ClientFontManager::~ClientFontManager() = default; SkDiscardableHandleId ClientFontManager::createHandle() { auto client_handle = client_discardable_manager_.CreateHandle(command_buffer_); if (client_handle.is_null()) return kInvalidSkDiscardableHandleId; SkDiscardableHandleId handle_id = ++last_allocated_handle_id_; discardable_handle_map_[handle_id] = client_handle; // Handles start with a ref-count. locked_handles_.insert(handle_id); return handle_id; } bool ClientFontManager::lockHandle(SkDiscardableHandleId handle_id) { // Already locked. if (locked_handles_.find(handle_id) != locked_handles_.end()) return true; auto it = discardable_handle_map_.find(handle_id); if (it == discardable_handle_map_.end()) return false; bool locked = client_discardable_manager_.LockHandle(it->second); if (locked) { locked_handles_.insert(handle_id); return true; } discardable_handle_map_.erase(it); return false; } bool ClientFontManager::isHandleDeleted(SkDiscardableHandleId handle_id) { auto it = discardable_handle_map_.find(handle_id); if (it == discardable_handle_map_.end()) return true; if (client_discardable_manager_.HandleIsDeleted(it->second)) { discardable_handle_map_.erase(it); return true; } return false; } void ClientFontManager::Serialize() { // TODO(khushalsagar): May be skia can track the size required so we avoid // this copy. std::vector<uint8_t> strike_data; strike_server_.writeStrikeData(&strike_data); const uint32_t num_handles_created = last_allocated_handle_id_ - last_serialized_handle_id_; if (strike_data.size() == 0u && num_handles_created == 0u && locked_handles_.size() == 0u) { // No font data to serialize. return; } // Size required for serialization. base::CheckedNumeric<uint32_t> checked_bytes_required = 0; // Skia data size. checked_bytes_required += sizeof(uint32_t) + alignof(uint32_t) + 16; checked_bytes_required += strike_data.size(); // num of handles created + SerializableHandles. checked_bytes_required += sizeof(uint32_t) + alignof(uint32_t) + alignof(SerializableSkiaHandle); checked_bytes_required += base::CheckMul(num_handles_created, sizeof(SerializableSkiaHandle)); // num of handles locked + DiscardableHandleIds. checked_bytes_required += sizeof(uint32_t) + alignof(uint32_t) + alignof(SkDiscardableHandleId); checked_bytes_required += base::CheckMul(locked_handles_.size(), sizeof(SkDiscardableHandleId)); uint32_t bytes_required = 0; if (!checked_bytes_required.AssignIfValid(&bytes_required)) { DLOG(FATAL) << "ClientFontManager::Serialize: font buffer overflow"; return; } // Allocate memory. void* memory = client_->MapFontBuffer(bytes_required); if (!memory) { // We are likely in a context loss situation if mapped memory allocation // for font buffer failed. return; } Serializer serializer(reinterpret_cast<char*>(memory), bytes_required); // Serialize all new handles. serializer.Write<uint32_t>(&num_handles_created); for (SkDiscardableHandleId handle_id = last_serialized_handle_id_ + 1; handle_id <= last_allocated_handle_id_; handle_id++) { auto it = discardable_handle_map_.find(handle_id); DCHECK(it != discardable_handle_map_.end()); // We must have a valid |client_handle| here since all new handles are // currently in locked state. auto client_handle = client_discardable_manager_.GetHandle(it->second); DCHECK(client_handle.IsValid()); SerializableSkiaHandle handle(handle_id, client_handle.shm_id(), client_handle.byte_offset()); serializer.Write<SerializableSkiaHandle>(&handle); } // Serialize all locked handle ids, so the raster unlocks them when done. DCHECK(base::IsValueInRangeForNumericType<uint32_t>(locked_handles_.size())); const uint32_t num_locked_handles = locked_handles_.size(); serializer.Write<uint32_t>(&num_locked_handles); for (auto handle_id : locked_handles_) serializer.Write<SkDiscardableHandleId>(&handle_id); // Serialize skia data. DCHECK(base::IsValueInRangeForNumericType<uint32_t>(strike_data.size())); const uint32_t skia_data_size = strike_data.size(); serializer.Write<uint32_t>(&skia_data_size); serializer.WriteData(strike_data.data(), strike_data.size(), 16); // Reset all state for what has been serialized. last_serialized_handle_id_ = last_allocated_handle_id_; locked_handles_.clear(); return; } } // namespace raster } // namespace gpu
{ "content_hash": "5d0a3edd3a8193b7114abea2a359ed7b", "timestamp": "", "source": "github", "line_count": 183, "max_line_length": 79, "avg_line_length": 32.666666666666664, "alnum_prop": 0.6878554700568752, "repo_name": "endlessm/chromium-browser", "id": "6dc6f269cdb30383665476571bbc381489ca0704", "size": "6208", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "gpu/command_buffer/client/client_font_manager.cc", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
layout: post title: "Java Proxy" date: 2022-11-08 tags: [note] --- 在 RPC 框架中,很多时候,调用方仅需要引用 Interface 就能方便地调用远程的 RPC 服务。所以,简单看一下这里的实现原理。 # 使用 这里以 [Spring Dubbo](https://github.com/apache/dubbo-spring-boot-project) 为例 ```java @EnableAutoConfiguration public class DubboAutoConfigurationConsumerBootstrap { private final Logger logger = LoggerFactory.getLogger(getClass()); @DubboReference(version = "1.0.0", url = "dubbo://127.0.0.1:12345") private DemoService demoService; public static void main(String[] args) { SpringApplication.run(DubboAutoConfigurationConsumerBootstrap.class).close(); } @Bean public ApplicationRunner runner() { return args -> { logger.info(demoService.sayHello("mercyblitz")); }; } } ``` # 原理 这里比较好奇,为什么注解注入的对象,能给 Interface 对象正常使用。通过文档的查阅,发现 Java 有 [Proxy](https://xperti.io/blogs/java-dynamic-proxies-introduction/) 的能力,和 JavaScript 的 Proxy 一致。 ```java package com.alibaba.faas; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class Test { interface Hello { void hi(); } static class Handler implements InvocationHandler { public Object invoke(Object proxy, Method method, Object[] args) { //method.invoke() System.out.println("invoke"); return null; } } public static void main(String[] args) { Handler handler = new Handler(); Hello hello = (Hello) Proxy.newProxyInstance(Hello.class.getClassLoader(), new Class[] { Hello.class }, handler); hello.hi(); } } ```
{ "content_hash": "a4f3fb464c451c42447bcef2b491ecea", "timestamp": "", "source": "github", "line_count": 68, "max_line_length": 154, "avg_line_length": 24.38235294117647, "alnum_prop": 0.6670687575392038, "repo_name": "zhoukekestar/notes", "id": "d1ca789bb1736c9b55dea66d62945279bafb7720", "size": "1868", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2022-10~12/2022-11-08-java-proxy.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "269688" }, { "name": "JavaScript", "bytes": "961" }, { "name": "Ruby", "bytes": "837" }, { "name": "SCSS", "bytes": "18148" } ], "symlink_target": "" }
static const int CLIENT_VERSION = 1000000 * CLIENT_VERSION_MAJOR + 10000 * CLIENT_VERSION_MINOR + 100 * CLIENT_VERSION_REVISION + 1 * CLIENT_VERSION_BUILD; extern const std::string CLIENT_NAME; extern const std::string CLIENT_BUILD; extern const std::string CLIENT_DATE; // // database format versioning // static const int DATABASE_VERSION = 70508; // // network protocol versioning // static const int PROTOCOL_VERSION = 60014; // earlier versions not supported as of Feb 2012, and are disconnected static const int MIN_PROTO_VERSION = 60014; // nTime field added to CAddress, starting with this version; // if possible, avoid requesting addresses nodes older than this static const int CADDR_TIME_VERSION = 31402; // only request blocks from nodes outside this range of versions static const int NOBLKS_VERSION_START = 60002; static const int NOBLKS_VERSION_END = 60013; // BIP 0031, pong message, is enabled for all versions AFTER this one static const int BIP0031_VERSION = 60000; // "mempool" command, enhanced "getdata" behavior starts with this version: static const int MEMPOOL_GD_VERSION = 60002; #endif
{ "content_hash": "f6c1347f0ca6daa54dd3ec7563b2f56d", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 75, "avg_line_length": 31.743589743589745, "alnum_prop": 0.6938610662358643, "repo_name": "compounddev/Compound-Coin", "id": "cf270b74ee0bfb3eb1818aa9709d13848013be3b", "size": "1553", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/version.h", "mode": "33261", "license": "mit", "language": [ { "name": "Assembly", "bytes": "51312" }, { "name": "C", "bytes": "705098" }, { "name": "C++", "bytes": "2531701" }, { "name": "CSS", "bytes": "1127" }, { "name": "HTML", "bytes": "50620" }, { "name": "Makefile", "bytes": "12658" }, { "name": "NSIS", "bytes": "5914" }, { "name": "Objective-C", "bytes": "858" }, { "name": "Objective-C++", "bytes": "5932" }, { "name": "Python", "bytes": "2819" }, { "name": "QMake", "bytes": "14410" }, { "name": "Shell", "bytes": "8509" } ], "symlink_target": "" }