text
stringlengths
2
1.04M
meta
dict
package v1alpha1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" ) // SchemeGroupVersion is group version used to register these objects var SchemeGroupVersion = schema.GroupVersion{Group: "poc.autoscaling.k8s.io", Version: "v1alpha1"} // Resource takes an unqualified resource and returns a Group qualified GroupResource func Resource(resource string) schema.GroupResource { return SchemeGroupVersion.WithResource(resource).GroupResource() } var ( // SchemeBuilder points to a list of functions added to Scheme. SchemeBuilder runtime.SchemeBuilder localSchemeBuilder = &SchemeBuilder // AddToScheme applies all the stored functions to the scheme. AddToScheme = localSchemeBuilder.AddToScheme ) func init() { // We only register manually written functions here. The registration of the // generated functions takes place in the generated files. The separation // makes the code compile even when the generated files are missing. localSchemeBuilder.Register(addKnownTypes) } // Adds the list of known types to api.Scheme. func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes(SchemeGroupVersion, &VerticalPodAutoscaler{}, &VerticalPodAutoscalerList{}, ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil }
{ "content_hash": "5b312e277bc2ed973dc4b97a8568541a", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 98, "avg_line_length": 32.214285714285715, "alnum_prop": 0.7915742793791575, "repo_name": "KarolKraskiewicz/autoscaler", "id": "e3ddc65d748c2d9d2911f0530824b3c9e15df1ba", "size": "1922", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "vertical-pod-autoscaler/pkg/apis/poc.autoscaling.k8s.io/v1alpha1/register.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "2067446" }, { "name": "Makefile", "bytes": "7179" }, { "name": "Python", "bytes": "18766" }, { "name": "Shell", "bytes": "27642" } ], "symlink_target": "" }
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace FCT.LLC.BusinessService.Entities { [Table("tblDocumentProvConfig")] public partial class tblDocumentProvConfig { [Key] [StringLength(2)] public string Province { get; set; } public bool IsArchivable { get; set; } } }
{ "content_hash": "ecf84d25455674a0034d02e19f4cb143", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 51, "avg_line_length": 24.933333333333334, "alnum_prop": 0.6925133689839572, "repo_name": "ygrinev/ygrinev", "id": "2fefdf0041f6a7eec6138db95bc8b004fb4c88bf", "size": "374", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "LLC/Source Code/FCT.LLC.BusinessService/Entities/tblDocumentProvConfig.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "52500" }, { "name": "Batchfile", "bytes": "55480" }, { "name": "C#", "bytes": "4763975" }, { "name": "CSS", "bytes": "873906" }, { "name": "HTML", "bytes": "2429022" }, { "name": "Java", "bytes": "9095" }, { "name": "JavaScript", "bytes": "8614632" }, { "name": "PHP", "bytes": "4319" }, { "name": "Pascal", "bytes": "402824" }, { "name": "PowerShell", "bytes": "1379876" }, { "name": "Puppet", "bytes": "2916" }, { "name": "Shell", "bytes": "306" }, { "name": "TypeScript", "bytes": "549603" }, { "name": "Visual Basic", "bytes": "9214" }, { "name": "XSLT", "bytes": "110282" } ], "symlink_target": "" }
/* * decaffeinate suggestions: * DS102: Remove unnecessary code created because of implicit returns * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md */ ELMO.Views.FormSettingsView = class FormSettingsView extends ELMO.Views.ApplicationView { get el() { return 'form.form_form'; } get events() { return { 'click .more-settings': 'show_setting_fields', 'click .less-settings': 'hide_setting_fields', 'click #form_smsable': 'show_hide_sms_settings', 'click #form_sms_relay': 'show_hide_recipients', }; } initialize(options) { this.show_fields_with_errors(); this.show_hide_sms_settings(); this.show_hide_recipients(); this.recipient_options_url = options.recipient_options_url; return this.init_recipient_select(); } show_setting_fields(event) { if (event) { event.preventDefault(); } $('.more-settings').hide(); $('.less-settings').show(); return $('.setting-fields').show(); } hide_setting_fields(event) { if (event) { event.preventDefault(); } $('.more-settings').show(); $('.less-settings').hide(); return $('.setting-fields').hide(); } show_fields_with_errors() { if (this.$('.setting-fields .form-field.has-errors').length > 0) { return this.show_setting_fields(); } } show_hide_sms_settings() { let m; const read_only = this.$('#smsable div.ro-val').length > 0; if (read_only) { m = this.$('#smsable div.ro-val').data('val') ? 'show' : 'hide'; } else { m = this.$('#form_smsable').is(':checked') ? 'show' : 'hide'; } return this.$('.sms-fields')[m](); } show_hide_recipients() { let m; const read_only = this.$('#sms_relay div.ro-val').length > 0; if (read_only) { m = this.$('#sms_relay div.ro-val').data('val') ? 'show' : 'hide'; } else { m = this.$('#form_sms_relay').is(':checked') ? 'show' : 'hide'; } return this.$('.form_recipient_ids')[m](); } init_recipient_select() { return this.$('#form_recipient_ids').select2({ ajax: (new ELMO.Utils.Select2OptionBuilder()).ajax(this.recipient_options_url) }); } };
{ "content_hash": "410efff535339a31d4e784f188462c1b", "timestamp": "", "source": "github", "line_count": 73, "max_line_length": 133, "avg_line_length": 29.863013698630137, "alnum_prop": 0.6050458715596331, "repo_name": "thecartercenter/elmo", "id": "c1710125e7653016625a1a8eee4cb0785e047c19", "size": "2180", "binary": false, "copies": "1", "ref": "refs/heads/12085_prevent_dupes", "path": "app/assets/javascripts/views/form_settings_view.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "97107" }, { "name": "CoffeeScript", "bytes": "57714" }, { "name": "HTML", "bytes": "144925" }, { "name": "JavaScript", "bytes": "194066" }, { "name": "Ruby", "bytes": "1756251" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in Graphis Scripta 19(1): 7 (2007) #### Original name Stigmidium leprariae Zhurb., 2007 ### Remarks null
{ "content_hash": "1af87da9c38950463c2e53669258fb8d", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 14.615384615384615, "alnum_prop": 0.7105263157894737, "repo_name": "mdoering/backbone", "id": "5e3d4f9a147471f679e90b79d2f46a4e7314bfe2", "size": "247", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Dothideomycetes/Capnodiales/Mycosphaerellaceae/Stigmidium/Stigmidium leprariae/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
using System; using FullSerializer; using UnityEngine; using Object = UnityEngine.Object; namespace SerializableActions.Internal { /// <summary> /// This is a serializable wrapper for an argument. It contains both the value of the argument, /// and information about the parameter the argument is for. /// </summary> [Serializable] public class SerializableArgument { private static readonly fsSerializer _serializer = new fsSerializer(); [SerializeField] private string parameterName; [SerializeField] private SerializableSystemType parameterType; [SerializeField] private SerializableSystemType argumentType; /// <summary> /// Name of the parameter in the method declaration. Only used for display purposes /// </summary> public string Name { get { return parameterName; } } /// <summary> /// The type of the parameter in the method declaration /// </summary> public SerializableSystemType ParameterType { get { return parameterType; } } /// <summary> /// The type of the serialized argument. It's always assignable to ParameterType /// </summary> public SerializableSystemType ArgumentType { get { return argumentType; } } /// <summary> /// Is the argument a UnityEngine.Object? In that case, we insert it into a ScriptableObject for serialization. /// </summary> [SerializeField] private bool isUnityObject; /// <summary> /// Serialized JSON version of the argument. This is how the argument is serialized if it is not an UnityEngine.Object. /// If the argument is a UnityEngine.Object, this is an empty string /// </summary> [SerializeField] private string paramAsJson; /// <summary> /// This stores the argument if it is a UnityEngine.Object. /// If the argument is something else, this is null /// </summary> [SerializeField] private Object objectArgument; /// <summary> /// The runtime value of the argument. /// </summary> private object argumentValue; public SerializableArgument(object argument, Type parameterType, string parameterName) { this.parameterType = parameterType; this.parameterName = parameterName; argumentType = argument == null ? parameterType : argument.GetType(); SetArgumentValue(argument); } /// <returns>The runtime value of the argument</returns> public object UnpackParameter() { if (argumentValue == null) { if (isUnityObject) { argumentValue = objectArgument; } else { var parsed = fsJsonParser.Parse(paramAsJson); _serializer.TryDeserialize(parsed, argumentType.SystemType, ref argumentValue).AssertSuccess(); } } return argumentValue; } /// <summary> /// Set the value of the serialized argument. /// Note that this runs the serialization process, so it is not fast. /// </summary> /// <param name="argument">Argument to set</param> /// <exception cref="ArgumentException">If the argument is not assignable to the parameter type</exception> public void SetArgumentValue(object argument) { if (parameterType.SystemType.IsValueType) { if (argument == null) throw new ArgumentException("Trying to set null as parameter value for a SerializeableParameter, but the parameter's type is the " + "value type " + parameterType.Name + "!"); if (argument.GetType() != parameterType.SystemType) throw new ArgumentException("Trying to assign " + argument + " of value type " + argument.GetType() + " to a SerializeableParameter that expects a value" + "of value type " + parameterType.Name); } else { if (argument != null && !parameterType.SystemType.IsInstanceOfType(argument)) throw new ArgumentException("Trying to assign " + argument + " of type " + argument.GetType().Name + " to SerializeableParameter expecting type " + parameterType.Name + ", which is not valid! Use the type or a subtype"); } if (argument == null) argumentType = parameterType; else argumentType = argument.GetType(); argumentValue = argument; isUnityObject = argument is Object; if (isUnityObject) { paramAsJson = ""; objectArgument = argument as UnityEngine.Object; } else { if (objectArgument != null) { if (Application.isPlaying) Object.Destroy(objectArgument); else Object.DestroyImmediate(objectArgument); } objectArgument = null; fsData data; _serializer.TrySerialize(argumentType, argument, out data).AssertSuccess(); paramAsJson = fsJsonPrinter.CompressedJson(data); } } } }
{ "content_hash": "dba27812b6d23caddae0221cf748101e", "timestamp": "", "source": "github", "line_count": 148, "max_line_length": 152, "avg_line_length": 38.777027027027025, "alnum_prop": 0.5549747342742638, "repo_name": "Baste-RainGames/SerializableAction_Unity", "id": "06c0bc8ba67b20f3700c02b8cc0e2c4928a4e579", "size": "5741", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Plugins/Scripts/SerializableArgument.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "77345" } ], "symlink_target": "" }
package com.aqnote.app.barcode.core.oned; import com.aqnote.app.barcode.core.BarcodeFormat; import com.aqnote.app.barcode.core.ChecksumException; import com.aqnote.app.barcode.core.DecodeHintType; import com.aqnote.app.barcode.core.FormatException; import com.aqnote.app.barcode.core.NotFoundException; import com.aqnote.app.barcode.core.ReaderException; import com.aqnote.app.barcode.core.Result; import com.aqnote.app.barcode.core.ResultMetadataType; import com.aqnote.app.barcode.core.ResultPoint; import com.aqnote.app.barcode.core.ResultPointCallback; import com.aqnote.app.barcode.core.common.BitArray; import java.util.Arrays; import java.util.Map; /** * <p>Encapsulates functionality and implementation that is common to UPC and EAN families * of one-dimensional barcodes.</p> * * @author dswitkin@google.com (Daniel Switkin) * @author Sean Owen * @author alasdair@google.com (Alasdair Mackintosh) */ public abstract class UPCEANReader extends OneDReader { // These two values are critical for determining how permissive the decoding will be. // We've arrived at these values through a lot of trial and error. Setting them any higher // lets false positives creep in quickly. private static final float MAX_AVG_VARIANCE = 0.48f; private static final float MAX_INDIVIDUAL_VARIANCE = 0.7f; /** * Start/end guard pattern. */ static final int[] START_END_PATTERN = {1, 1, 1,}; /** * Pattern marking the middle of a UPC/EAN pattern, separating the two halves. */ static final int[] MIDDLE_PATTERN = {1, 1, 1, 1, 1}; /** * end guard pattern. */ static final int[] END_PATTERN = {1, 1, 1, 1, 1, 1}; /** * "Odd", or "L" patterns used to encode UPC/EAN digits. */ static final int[][] L_PATTERNS = { {3, 2, 1, 1}, // 0 {2, 2, 2, 1}, // 1 {2, 1, 2, 2}, // 2 {1, 4, 1, 1}, // 3 {1, 1, 3, 2}, // 4 {1, 2, 3, 1}, // 5 {1, 1, 1, 4}, // 6 {1, 3, 1, 2}, // 7 {1, 2, 1, 3}, // 8 {3, 1, 1, 2} // 9 }; /** * As above but also including the "even", or "G" patterns used to encode UPC/EAN digits. */ static final int[][] L_AND_G_PATTERNS; static { L_AND_G_PATTERNS = new int[20][]; System.arraycopy(L_PATTERNS, 0, L_AND_G_PATTERNS, 0, 10); for (int i = 10; i < 20; i++) { int[] widths = L_PATTERNS[i - 10]; int[] reversedWidths = new int[widths.length]; for (int j = 0; j < widths.length; j++) { reversedWidths[j] = widths[widths.length - j - 1]; } L_AND_G_PATTERNS[i] = reversedWidths; } } private final StringBuilder decodeRowStringBuffer; private final UPCEANExtensionSupport extensionReader; private final EANManufacturerOrgSupport eanManSupport; protected UPCEANReader() { decodeRowStringBuffer = new StringBuilder(20); extensionReader = new UPCEANExtensionSupport(); eanManSupport = new EANManufacturerOrgSupport(); } static int[] findStartGuardPattern(BitArray row) throws NotFoundException { boolean foundStart = false; int[] startRange = null; int nextStart = 0; int[] counters = new int[START_END_PATTERN.length]; while (!foundStart) { Arrays.fill(counters, 0, START_END_PATTERN.length, 0); startRange = findGuardPattern(row, nextStart, false, START_END_PATTERN, counters); int start = startRange[0]; nextStart = startRange[1]; // Make sure there is a quiet zone at least as big as the start pattern before the barcode. // If this check would run off the left edge of the image, do not accept this barcode, // as it is very likely to be a false positive. int quietStart = start - (nextStart - start); if (quietStart >= 0) { foundStart = row.isRange(quietStart, start, false); } } return startRange; } @Override public Result decodeRow(int rowNumber, BitArray row, Map<DecodeHintType,?> hints) throws NotFoundException, ChecksumException, FormatException { return decodeRow(rowNumber, row, findStartGuardPattern(row), hints); } /** * <p>Like {@link #decodeRow(int, BitArray, Map)}, but * allows caller to inform method about where the UPC/EAN start pattern is * found. This allows this to be computed once and reused across many implementations.</p> * * @param rowNumber row index into the image * @param row encoding of the row of the barcode image * @param startGuardRange start/end column where the opening start pattern was found * @param hints optional hints that influence decoding * @return {@link Result} encapsulating the result of decoding a barcode in the row * @throws NotFoundException if no potential barcode is found * @throws ChecksumException if a potential barcode is found but does not pass its checksum * @throws FormatException if a potential barcode is found but format is invalid */ public Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, Map<DecodeHintType,?> hints) throws NotFoundException, ChecksumException, FormatException { ResultPointCallback resultPointCallback = hints == null ? null : (ResultPointCallback) hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK); if (resultPointCallback != null) { resultPointCallback.foundPossibleResultPoint(new ResultPoint( (startGuardRange[0] + startGuardRange[1]) / 2.0f, rowNumber )); } StringBuilder result = decodeRowStringBuffer; result.setLength(0); int endStart = decodeMiddle(row, startGuardRange, result); if (resultPointCallback != null) { resultPointCallback.foundPossibleResultPoint(new ResultPoint( endStart, rowNumber )); } int[] endRange = decodeEnd(row, endStart); if (resultPointCallback != null) { resultPointCallback.foundPossibleResultPoint(new ResultPoint( (endRange[0] + endRange[1]) / 2.0f, rowNumber )); } // Make sure there is a quiet zone at least as big as the end pattern after the barcode. The // spec might want more whitespace, but in practice this is the maximum we can count on. int end = endRange[1]; int quietEnd = end + (end - endRange[0]); if (quietEnd >= row.getSize() || !row.isRange(end, quietEnd, false)) { throw NotFoundException.getNotFoundInstance(); } String resultString = result.toString(); // UPC/EAN should never be less than 8 chars anyway if (resultString.length() < 8) { throw FormatException.getFormatInstance(); } if (!checkChecksum(resultString)) { throw ChecksumException.getChecksumInstance(); } float left = (startGuardRange[1] + startGuardRange[0]) / 2.0f; float right = (endRange[1] + endRange[0]) / 2.0f; BarcodeFormat format = getBarcodeFormat(); Result decodeResult = new Result(resultString, null, // no natural byte representation for these barcodes new ResultPoint[]{ new ResultPoint(left, rowNumber), new ResultPoint(right, rowNumber)}, format); int extensionLength = 0; try { Result extensionResult = extensionReader.decodeRow(rowNumber, row, endRange[1]); decodeResult.putMetadata(ResultMetadataType.UPC_EAN_EXTENSION, extensionResult.getText()); decodeResult.putAllMetadata(extensionResult.getResultMetadata()); decodeResult.addResultPoints(extensionResult.getResultPoints()); extensionLength = extensionResult.getText().length(); } catch (ReaderException re) { // continue } int[] allowedExtensions = hints == null ? null : (int[]) hints.get(DecodeHintType.ALLOWED_EAN_EXTENSIONS); if (allowedExtensions != null) { boolean valid = false; for (int length : allowedExtensions) { if (extensionLength == length) { valid = true; break; } } if (!valid) { throw NotFoundException.getNotFoundInstance(); } } if (format == BarcodeFormat.EAN_13 || format == BarcodeFormat.UPC_A) { String countryID = eanManSupport.lookupCountryIdentifier(resultString); if (countryID != null) { decodeResult.putMetadata(ResultMetadataType.POSSIBLE_COUNTRY, countryID); } } return decodeResult; } /** * @param s string of digits to check * @return {@link #checkStandardUPCEANChecksum(CharSequence)} * @throws FormatException if the string does not contain only digits */ boolean checkChecksum(String s) throws FormatException { return checkStandardUPCEANChecksum(s); } /** * Computes the UPC/EAN checksum on a string of digits, and reports * whether the checksum is correct or not. * * @param s string of digits to check * @return true iff string of digits passes the UPC/EAN checksum algorithm * @throws FormatException if the string does not contain only digits */ static boolean checkStandardUPCEANChecksum(CharSequence s) throws FormatException { int length = s.length(); if (length == 0) { return false; } int check = Character.digit(s.charAt(length - 1), 10); return getStandardUPCEANChecksum(s.subSequence(0, length - 1)) == check; } static int getStandardUPCEANChecksum(CharSequence s) throws FormatException { int length = s.length(); int sum = 0; for (int i = length - 1; i >= 0; i -= 2) { int digit = s.charAt(i) - '0'; if (digit < 0 || digit > 9) { throw FormatException.getFormatInstance(); } sum += digit; } sum *= 3; for (int i = length - 2; i >= 0; i -= 2) { int digit = s.charAt(i) - '0'; if (digit < 0 || digit > 9) { throw FormatException.getFormatInstance(); } sum += digit; } return (1000 - sum) % 10; } int[] decodeEnd(BitArray row, int endStart) throws NotFoundException { return findGuardPattern(row, endStart, false, START_END_PATTERN); } static int[] findGuardPattern(BitArray row, int rowOffset, boolean whiteFirst, int[] pattern) throws NotFoundException { return findGuardPattern(row, rowOffset, whiteFirst, pattern, new int[pattern.length]); } /** * @param row row of black/white values to search * @param rowOffset position to start search * @param whiteFirst if true, indicates that the pattern specifies white/black/white/... * pixel counts, otherwise, it is interpreted as black/white/black/... * @param pattern pattern of counts of number of black and white pixels that are being * searched for as a pattern * @param counters array of counters, as long as pattern, to re-use * @return start/end horizontal offset of guard pattern, as an array of two ints * @throws NotFoundException if pattern is not found */ private static int[] findGuardPattern(BitArray row, int rowOffset, boolean whiteFirst, int[] pattern, int[] counters) throws NotFoundException { int width = row.getSize(); rowOffset = whiteFirst ? row.getNextUnset(rowOffset) : row.getNextSet(rowOffset); int counterPosition = 0; int patternStart = rowOffset; int patternLength = pattern.length; boolean isWhite = whiteFirst; for (int x = rowOffset; x < width; x++) { if (row.get(x) ^ isWhite) { counters[counterPosition]++; } else { if (counterPosition == patternLength - 1) { if (patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE) < MAX_AVG_VARIANCE) { return new int[]{patternStart, x}; } patternStart += counters[0] + counters[1]; System.arraycopy(counters, 2, counters, 0, patternLength - 2); counters[patternLength - 2] = 0; counters[patternLength - 1] = 0; counterPosition--; } else { counterPosition++; } counters[counterPosition] = 1; isWhite = !isWhite; } } throw NotFoundException.getNotFoundInstance(); } /** * Attempts to decode a single UPC/EAN-encoded digit. * * @param row row of black/white values to decode * @param counters the counts of runs of observed black/white/black/... values * @param rowOffset horizontal offset to start decoding from * @param patterns the set of patterns to use to decode -- sometimes different encodings * for the digits 0-9 are used, and this indicates the encodings for 0 to 9 that should * be used * @return horizontal offset of first pixel beyond the decoded digit * @throws NotFoundException if digit cannot be decoded */ static int decodeDigit(BitArray row, int[] counters, int rowOffset, int[][] patterns) throws NotFoundException { recordPattern(row, rowOffset, counters); float bestVariance = MAX_AVG_VARIANCE; // worst variance we'll accept int bestMatch = -1; int max = patterns.length; for (int i = 0; i < max; i++) { int[] pattern = patterns[i]; float variance = patternMatchVariance(counters, pattern, MAX_INDIVIDUAL_VARIANCE); if (variance < bestVariance) { bestVariance = variance; bestMatch = i; } } if (bestMatch >= 0) { return bestMatch; } else { throw NotFoundException.getNotFoundInstance(); } } /** * Get the format of this decoder. * * @return The 1D format. */ abstract BarcodeFormat getBarcodeFormat(); /** * Subclasses override this to decode the portion of a barcode between the start * and end guard patterns. * * @param row row of black/white values to search * @param startRange start/end offset of start guard pattern * @param resultString {@link StringBuilder} to append decoded chars to * @return horizontal offset of first pixel after the "middle" that was decoded * @throws NotFoundException if decoding could not complete successfully */ protected abstract int decodeMiddle(BitArray row, int[] startRange, StringBuilder resultString) throws NotFoundException; }
{ "content_hash": "d6b559d2039cbb3e6c540e5fa749ff73", "timestamp": "", "source": "github", "line_count": 389, "max_line_length": 100, "avg_line_length": 36.86632390745501, "alnum_prop": 0.6518373893033959, "repo_name": "aqnote/AndroidTest", "id": "eeddf3cffc6be08fa41881fdf6be725ec3c43829", "size": "14938", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app-barcode/src/main/java/com/aqnote/app/barcode/core/oned/UPCEANReader.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "340" }, { "name": "HTML", "bytes": "82796" }, { "name": "Java", "bytes": "1748797" } ], "symlink_target": "" }
@interface GWPlaceholderTextView() @property (nonatomic, weak) UILabel *placeholderLabel; @end @implementation GWPlaceholderTextView - (UILabel *)placeholderLabel { if (!_placeholderLabel) { // 添加一个用来显示占位文字的label UILabel *placeholderLabel = [[UILabel alloc] init]; placeholderLabel.numberOfLines = 0; placeholderLabel.x = 4; // 预估的数字 placeholderLabel.y = 7; // 预估的数字 [self addSubview:placeholderLabel]; _placeholderLabel = placeholderLabel; } return _placeholderLabel; } - (instancetype)initWithFrame:(CGRect)frame { if (self = [super initWithFrame:frame]) { // 垂直方向上永远有弹簧效果 self.alwaysBounceVertical = YES; // 默认字体 self.font = [UIFont systemFontOfSize:15]; // 默认的占位文字颜色 self.placeholderColor = [UIColor grayColor]; // 监听事件 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textDidChange) name:UITextViewTextDidChangeNotification object:nil]; } return self; } - (void)textDidChange { // 有文字的时候隐藏 self.placeholderLabel.hidden = self.hasText; } - (void)dealloc { [[NSNotificationCenter defaultCenter] removeObserver:self]; } - (void)layoutSubviews { [super layoutSubviews]; // 计算placeholderLabel的尺寸 self.placeholderLabel.width = self.width - self.placeholderLabel.x * 2; [self.placeholderLabel sizeToFit]; } #pragma mark - 重写setter方法 - (void)setPlaceholder:(NSString *)placeholder { _placeholder = [placeholder copy]; self.placeholderLabel.text = placeholder; // 向系统声明需要更新尺寸,系统会在恰当的时刻调用layoutSubViews更新尺寸 [self setNeedsLayout]; } - (void)setPlaceholderColor:(UIColor *)placeholderColor { _placeholderColor = placeholderColor; self.placeholderLabel.textColor = placeholderColor; } - (void)setFont:(UIFont *)font { [super setFont:font]; self.placeholderLabel.font = font; // 向系统声明需要更新尺寸,系统会在恰当的时刻调用layoutSubViews更新尺寸 [self setNeedsLayout]; } - (void)setText:(NSString *)text { [super setText:text]; [self textDidChange]; } - (void)setAttributedText:(NSAttributedString *)attributedText { [super setAttributedText:attributedText]; [self textDidChange]; } @end
{ "content_hash": "d9765e31f8130fcf4f9e41895870187c", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 150, "avg_line_length": 22.87, "alnum_prop": 0.6768692610406646, "repo_name": "gongqiuwei/object-c-projects", "id": "127232a423fc2f26fc37cbaafe68772515c3a2bb", "size": "2724", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "仿百思不得姐/仿百思不得姐/Classes/Publish/View/GWPlaceholderTextView.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "698" }, { "name": "C++", "bytes": "54683" }, { "name": "Objective-C", "bytes": "847260" }, { "name": "Objective-C++", "bytes": "102447" } ], "symlink_target": "" }
package hex.genmodel.easy; import hex.genmodel.GenModel; import java.util.HashMap; import java.util.Map; public class OneHotEncoderDomainMapConstructor extends DomainMapConstructor { public OneHotEncoderDomainMapConstructor(GenModel m, Map<String, Integer> columnNameToIndex) { super(m, columnNameToIndex); } @Override public Map<Integer, CategoricalEncoder> create() { Map<Integer, CategoricalEncoder> domainMap = new HashMap<>(); String[] columnNames = _m.getOrigNames(); String[][] domainValues = _m.getOrigDomainValues(); for (int i = 0; i < _m.getOrigNumCols(); i++) { String[] colDomainValues = domainValues[i]; int targetOffsetIndex = _columnNameToIndex.get(columnNames[i]); if (colDomainValues != null) { domainMap.put(targetOffsetIndex, new OneHotEncoder(columnNames[i], targetOffsetIndex, colDomainValues)); } } return domainMap; } }
{ "content_hash": "353e67d4d40bbcade751185ad49bfa61", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 112, "avg_line_length": 30.7, "alnum_prop": 0.7155266015200868, "repo_name": "h2oai/h2o-3", "id": "dc9665b90f41346e69455e6729deee651607b7ae", "size": "921", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "h2o-genmodel/src/main/java/hex/genmodel/easy/OneHotEncoderDomainMapConstructor.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "12803" }, { "name": "CSS", "bytes": "882321" }, { "name": "CoffeeScript", "bytes": "7550" }, { "name": "DIGITAL Command Language", "bytes": "106" }, { "name": "Dockerfile", "bytes": "10459" }, { "name": "Emacs Lisp", "bytes": "2226" }, { "name": "Groovy", "bytes": "205646" }, { "name": "HCL", "bytes": "36232" }, { "name": "HTML", "bytes": "8018117" }, { "name": "HiveQL", "bytes": "3985" }, { "name": "Java", "bytes": "15981357" }, { "name": "JavaScript", "bytes": "148426" }, { "name": "Jupyter Notebook", "bytes": "20638329" }, { "name": "Makefile", "bytes": "46043" }, { "name": "PHP", "bytes": "800" }, { "name": "Python", "bytes": "8188608" }, { "name": "R", "bytes": "4149977" }, { "name": "Ruby", "bytes": "64" }, { "name": "Sass", "bytes": "23790" }, { "name": "Scala", "bytes": "4845" }, { "name": "Shell", "bytes": "214495" }, { "name": "Smarty", "bytes": "1792" }, { "name": "TeX", "bytes": "554940" } ], "symlink_target": "" }
layout: projects --- <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <link rel="shortcut icon" href="../favicon.ico"> <link rel="stylesheet" type="text/css" href="css/default.css" /> <link rel="stylesheet" type="text/css" href="css/component.css" /> <script src="js/modernizr.custom.js"></script> </head> <body> <div class="container"> <header class="clearfix"> <h1>Software<span>Python, Java, C</span></h1> </header> <div class="main"> <ul id="og-grid" class="og-grid"> <li> <a href="https://github.com/sdh31/BranchPredictionComparison" data-largesrc="images/perceptron.jpg" data-title="Branch Prediction" data-description="ECE 552 Final Project: Implementing machine learning based branch prediction algorithms - perceptron and piecewise linear - to compare performance."> <img src="images/thumbs/perceptron.jpg" alt="Branch Prediction"/> </a> </li> <li> <a href="http://www3.gehealthcare.com/en/global_gateway" data-largesrc="images/ecg.jpg" data-title="ECG" data-description="GE Healthcare CT Electronics Team Project: Linux-based event detection algorithm for the Cardiac Module of the Revolution CT."> <img src="images/thumbs/ecg.jpg" alt="ECG"/> </a> </li> </ul> </div> </div><!-- /container --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="js/grid.js"></script> <script> $(function() { Grid.init(); }); </script> </body> </html>
{ "content_hash": "596b67d44462c8fe2a93106bfadedd43", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 322, "avg_line_length": 38.549019607843135, "alnum_prop": 0.5274669379450662, "repo_name": "Yitaek/yitaek.github.io", "id": "59722758a101ca9e7d17b53f755ee93ab6fcc58e", "size": "1970", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "software/index.html", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "36061" }, { "name": "HTML", "bytes": "153364" }, { "name": "JavaScript", "bytes": "108557" }, { "name": "Ruby", "bytes": "2490" }, { "name": "Shell", "bytes": "214" } ], "symlink_target": "" }
"use strict"; module.exports = function() { var makeSelfResolutionError = function () { return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a"); }; var reflectHandler = function() { return new Promise.PromiseInspection(this._target()); }; var apiRejection = function(msg) { return Promise.reject(new TypeError(msg)); }; function Proxyable() {} var UNDEFINED_BINDING = {}; var util = require("./util"); var getDomain; if (util.isNode) { getDomain = function() { var ret = process.domain; if (ret === undefined) ret = null; return ret; }; } else { getDomain = function() { return null; }; } util.notEnumerableProp(Promise, "_getDomain", getDomain); var es5 = require("./es5"); var Async = require("./async"); var async = new Async(); es5.defineProperty(Promise, "_async", {value: async}); var errors = require("./errors"); var TypeError = Promise.TypeError = errors.TypeError; Promise.RangeError = errors.RangeError; var CancellationError = Promise.CancellationError = errors.CancellationError; Promise.TimeoutError = errors.TimeoutError; Promise.OperationalError = errors.OperationalError; Promise.RejectionError = errors.OperationalError; Promise.AggregateError = errors.AggregateError; var INTERNAL = function(){}; var APPLY = {}; var NEXT_FILTER = {}; var tryConvertToPromise = require("./thenables")(Promise, INTERNAL); var PromiseArray = require("./promise_array")(Promise, INTERNAL, tryConvertToPromise, apiRejection, Proxyable); var Context = require("./context")(Promise); /*jshint unused:false*/ var createContext = Context.create; var debug = require("./debuggability")(Promise, Context); var CapturedTrace = debug.CapturedTrace; var PassThroughHandlerContext = require("./finally")(Promise, tryConvertToPromise, NEXT_FILTER); var catchFilter = require("./catch_filter")(NEXT_FILTER); var nodebackForPromise = require("./nodeback"); var errorObj = util.errorObj; var tryCatch = util.tryCatch; function check(self, executor) { if (self == null || self.constructor !== Promise) { throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a"); } if (typeof executor !== "function") { throw new TypeError("expecting a function but got " + util.classString(executor)); } } function Promise(executor) { if (executor !== INTERNAL) { check(this, executor); } this._bitField = 0; this._fulfillmentHandler0 = undefined; this._rejectionHandler0 = undefined; this._promise0 = undefined; this._receiver0 = undefined; this._resolveFromExecutor(executor); this._promiseCreated(); this._fireEvent("promiseCreated", this); } Promise.prototype.toString = function () { return "[object Promise]"; }; Promise.prototype.caught = Promise.prototype["catch"] = function (fn) { var len = arguments.length; if (len > 1) { var catchInstances = new Array(len - 1), j = 0, i; for (i = 0; i < len - 1; ++i) { var item = arguments[i]; if (util.isObject(item)) { catchInstances[j++] = item; } else { return apiRejection("Catch statement predicate: " + "expecting an object but got " + util.classString(item)); } } catchInstances.length = j; fn = arguments[i]; return this.then(undefined, catchFilter(catchInstances, fn, this)); } return this.then(undefined, fn); }; Promise.prototype.reflect = function () { return this._then(reflectHandler, reflectHandler, undefined, this, undefined); }; Promise.prototype.then = function (didFulfill, didReject) { if (debug.warnings() && arguments.length > 0 && typeof didFulfill !== "function" && typeof didReject !== "function") { var msg = ".then() only accepts functions but was passed: " + util.classString(didFulfill); if (arguments.length > 1) { msg += ", " + util.classString(didReject); } this._warn(msg); } return this._then(didFulfill, didReject, undefined, undefined, undefined); }; Promise.prototype.done = function (didFulfill, didReject) { var promise = this._then(didFulfill, didReject, undefined, undefined, undefined); promise._setIsFinal(); }; Promise.prototype.spread = function (fn) { if (typeof fn !== "function") { return apiRejection("expecting a function but got " + util.classString(fn)); } return this.all()._then(fn, undefined, undefined, APPLY, undefined); }; Promise.prototype.toJSON = function () { var ret = { isFulfilled: false, isRejected: false, fulfillmentValue: undefined, rejectionReason: undefined }; if (this.isFulfilled()) { ret.fulfillmentValue = this.value(); ret.isFulfilled = true; } else if (this.isRejected()) { ret.rejectionReason = this.reason(); ret.isRejected = true; } return ret; }; Promise.prototype.all = function () { if (arguments.length > 0) { this._warn(".all() was passed arguments but it does not take any"); } return new PromiseArray(this).promise(); }; Promise.prototype.error = function (fn) { return this.caught(util.originatesFromRejection, fn); }; Promise.getNewLibraryCopy = module.exports; Promise.is = function (val) { return val instanceof Promise; }; Promise.fromNode = Promise.fromCallback = function(fn) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs : false; var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs)); if (result === errorObj) { ret._rejectCallback(result.e, true); } if (!ret._isFateSealed()) ret._setAsyncGuaranteed(); return ret; }; Promise.all = function (promises) { return new PromiseArray(promises).promise(); }; Promise.cast = function (obj) { var ret = tryConvertToPromise(obj); if (!(ret instanceof Promise)) { ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._setFulfilled(); ret._rejectionHandler0 = obj; } return ret; }; Promise.resolve = Promise.fulfilled = Promise.cast; Promise.reject = Promise.rejected = function (reason) { var ret = new Promise(INTERNAL); ret._captureStackTrace(); ret._rejectCallback(reason, true); return ret; }; Promise.setScheduler = function(fn) { if (typeof fn !== "function") { throw new TypeError("expecting a function but got " + util.classString(fn)); } return async.setScheduler(fn); }; Promise.prototype._then = function ( didFulfill, didReject, _, receiver, internalData ) { var haveInternalData = internalData !== undefined; var promise = haveInternalData ? internalData : new Promise(INTERNAL); var target = this._target(); var bitField = target._bitField; if (!haveInternalData) { promise._propagateFrom(this, 3); promise._captureStackTrace(); if (receiver === undefined && ((this._bitField & 2097152) !== 0)) { if (!((bitField & 50397184) === 0)) { receiver = this._boundValue(); } else { receiver = target === this ? undefined : this._boundTo; } } this._fireEvent("promiseChained", this, promise); } var domain = getDomain(); if (!((bitField & 50397184) === 0)) { var handler, value, settler = target._settlePromiseCtx; if (((bitField & 33554432) !== 0)) { value = target._rejectionHandler0; handler = didFulfill; } else if (((bitField & 16777216) !== 0)) { value = target._fulfillmentHandler0; handler = didReject; target._unsetRejectionIsUnhandled(); } else { settler = target._settlePromiseLateCancellationObserver; value = new CancellationError("late cancellation observer"); target._attachExtraTrace(value); handler = didReject; } async.invoke(settler, target, { handler: domain === null ? handler : (typeof handler === "function" && util.domainBind(domain, handler)), promise: promise, receiver: receiver, value: value }); } else { target._addCallbacks(didFulfill, didReject, promise, receiver, domain); } return promise; }; Promise.prototype._length = function () { return this._bitField & 65535; }; Promise.prototype._isFateSealed = function () { return (this._bitField & 117506048) !== 0; }; Promise.prototype._isFollowing = function () { return (this._bitField & 67108864) === 67108864; }; Promise.prototype._setLength = function (len) { this._bitField = (this._bitField & -65536) | (len & 65535); }; Promise.prototype._setFulfilled = function () { this._bitField = this._bitField | 33554432; this._fireEvent("promiseFulfilled", this); }; Promise.prototype._setRejected = function () { this._bitField = this._bitField | 16777216; this._fireEvent("promiseRejected", this); }; Promise.prototype._setFollowing = function () { this._bitField = this._bitField | 67108864; this._fireEvent("promiseResolved", this); }; Promise.prototype._setIsFinal = function () { this._bitField = this._bitField | 4194304; }; Promise.prototype._isFinal = function () { return (this._bitField & 4194304) > 0; }; Promise.prototype._unsetCancelled = function() { this._bitField = this._bitField & (~65536); }; Promise.prototype._setCancelled = function() { this._bitField = this._bitField | 65536; this._fireEvent("promiseCancelled", this); }; Promise.prototype._setWillBeCancelled = function() { this._bitField = this._bitField | 8388608; }; Promise.prototype._setAsyncGuaranteed = function() { if (async.hasCustomScheduler()) return; this._bitField = this._bitField | 134217728; }; Promise.prototype._receiverAt = function (index) { var ret = index === 0 ? this._receiver0 : this[ index * 4 - 4 + 3]; if (ret === UNDEFINED_BINDING) { return undefined; } else if (ret === undefined && this._isBound()) { return this._boundValue(); } return ret; }; Promise.prototype._promiseAt = function (index) { return this[ index * 4 - 4 + 2]; }; Promise.prototype._fulfillmentHandlerAt = function (index) { return this[ index * 4 - 4 + 0]; }; Promise.prototype._rejectionHandlerAt = function (index) { return this[ index * 4 - 4 + 1]; }; Promise.prototype._boundValue = function() {}; Promise.prototype._migrateCallback0 = function (follower) { var bitField = follower._bitField; var fulfill = follower._fulfillmentHandler0; var reject = follower._rejectionHandler0; var promise = follower._promise0; var receiver = follower._receiverAt(0); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, promise, receiver, null); }; Promise.prototype._migrateCallbackAt = function (follower, index) { var fulfill = follower._fulfillmentHandlerAt(index); var reject = follower._rejectionHandlerAt(index); var promise = follower._promiseAt(index); var receiver = follower._receiverAt(index); if (receiver === undefined) receiver = UNDEFINED_BINDING; this._addCallbacks(fulfill, reject, promise, receiver, null); }; Promise.prototype._addCallbacks = function ( fulfill, reject, promise, receiver, domain ) { var index = this._length(); if (index >= 65535 - 4) { index = 0; this._setLength(0); } if (index === 0) { this._promise0 = promise; this._receiver0 = receiver; if (typeof fulfill === "function") { this._fulfillmentHandler0 = domain === null ? fulfill : util.domainBind(domain, fulfill); } if (typeof reject === "function") { this._rejectionHandler0 = domain === null ? reject : util.domainBind(domain, reject); } } else { var base = index * 4 - 4; this[base + 2] = promise; this[base + 3] = receiver; if (typeof fulfill === "function") { this[base + 0] = domain === null ? fulfill : util.domainBind(domain, fulfill); } if (typeof reject === "function") { this[base + 1] = domain === null ? reject : util.domainBind(domain, reject); } } this._setLength(index + 1); return index; }; Promise.prototype._proxy = function (proxyable, arg) { this._addCallbacks(undefined, undefined, arg, proxyable, null); }; Promise.prototype._resolveCallback = function(value, shouldBind) { if (((this._bitField & 117506048) !== 0)) return; if (value === this) return this._rejectCallback(makeSelfResolutionError(), false); var maybePromise = tryConvertToPromise(value, this); if (!(maybePromise instanceof Promise)) return this._fulfill(value); if (shouldBind) this._propagateFrom(maybePromise, 2); var promise = maybePromise._target(); if (promise === this) { this._reject(makeSelfResolutionError()); return; } var bitField = promise._bitField; if (((bitField & 50397184) === 0)) { var len = this._length(); if (len > 0) promise._migrateCallback0(this); for (var i = 1; i < len; ++i) { promise._migrateCallbackAt(this, i); } this._setFollowing(); this._setLength(0); this._setFollowee(promise); } else if (((bitField & 33554432) !== 0)) { this._fulfill(promise._value()); } else if (((bitField & 16777216) !== 0)) { this._reject(promise._reason()); } else { var reason = new CancellationError("late cancellation observer"); promise._attachExtraTrace(reason); this._reject(reason); } }; Promise.prototype._rejectCallback = function(reason, synchronous, ignoreNonErrorWarnings) { var trace = util.ensureErrorObject(reason); var hasStack = trace === reason; if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) { var message = "a promise was rejected with a non-error: " + util.classString(reason); this._warn(message, true); } this._attachExtraTrace(trace, synchronous ? hasStack : false); this._reject(reason); }; Promise.prototype._resolveFromExecutor = function (executor) { if (executor === INTERNAL) return; var promise = this; this._captureStackTrace(); this._pushContext(); var synchronous = true; var r = this._execute(executor, function(value) { promise._resolveCallback(value); }, function (reason) { promise._rejectCallback(reason, synchronous); }); synchronous = false; this._popContext(); if (r !== undefined) { promise._rejectCallback(r, true); } }; Promise.prototype._settlePromiseFromHandler = function ( handler, receiver, value, promise ) { var bitField = promise._bitField; if (((bitField & 65536) !== 0)) return; promise._pushContext(); var x; if (receiver === APPLY) { if (!value || typeof value.length !== "number") { x = errorObj; x.e = new TypeError("cannot .spread() a non-array: " + util.classString(value)); } else { x = tryCatch(handler).apply(this._boundValue(), value); } } else { x = tryCatch(handler).call(receiver, value); } var promiseCreated = promise._popContext(); bitField = promise._bitField; if (((bitField & 65536) !== 0)) return; if (x === NEXT_FILTER) { promise._reject(value); } else if (x === errorObj) { promise._rejectCallback(x.e, false); } else { debug.checkForgottenReturns(x, promiseCreated, "", promise, this); promise._resolveCallback(x); } }; Promise.prototype._target = function() { var ret = this; while (ret._isFollowing()) ret = ret._followee(); return ret; }; Promise.prototype._followee = function() { return this._rejectionHandler0; }; Promise.prototype._setFollowee = function(promise) { this._rejectionHandler0 = promise; }; Promise.prototype._settlePromise = function(promise, handler, receiver, value) { var isPromise = promise instanceof Promise; var bitField = this._bitField; var asyncGuaranteed = ((bitField & 134217728) !== 0); if (((bitField & 65536) !== 0)) { if (isPromise) promise._invokeInternalOnCancel(); if (receiver instanceof PassThroughHandlerContext && receiver.isFinallyHandler()) { receiver.cancelPromise = promise; if (tryCatch(handler).call(receiver, value) === errorObj) { promise._reject(errorObj.e); } } else if (handler === reflectHandler) { promise._fulfill(reflectHandler.call(receiver)); } else if (receiver instanceof Proxyable) { receiver._promiseCancelled(promise); } else if (isPromise || promise instanceof PromiseArray) { promise._cancel(); } else { receiver.cancel(); } } else if (typeof handler === "function") { if (!isPromise) { handler.call(receiver, value, promise); } else { if (asyncGuaranteed) promise._setAsyncGuaranteed(); this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (receiver instanceof Proxyable) { if (!receiver._isResolved()) { if (((bitField & 33554432) !== 0)) { receiver._promiseFulfilled(value, promise); } else { receiver._promiseRejected(value, promise); } } } else if (isPromise) { if (asyncGuaranteed) promise._setAsyncGuaranteed(); if (((bitField & 33554432) !== 0)) { promise._fulfill(value); } else { promise._reject(value); } } }; Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) { var handler = ctx.handler; var promise = ctx.promise; var receiver = ctx.receiver; var value = ctx.value; if (typeof handler === "function") { if (!(promise instanceof Promise)) { handler.call(receiver, value, promise); } else { this._settlePromiseFromHandler(handler, receiver, value, promise); } } else if (promise instanceof Promise) { promise._reject(value); } }; Promise.prototype._settlePromiseCtx = function(ctx) { this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value); }; Promise.prototype._settlePromise0 = function(handler, value, bitField) { var promise = this._promise0; var receiver = this._receiverAt(0); this._promise0 = undefined; this._receiver0 = undefined; this._settlePromise(promise, handler, receiver, value); }; Promise.prototype._clearCallbackDataAtIndex = function(index) { var base = index * 4 - 4; this[base + 2] = this[base + 3] = this[base + 0] = this[base + 1] = undefined; }; Promise.prototype._fulfill = function (value) { var bitField = this._bitField; if (((bitField & 117506048) >>> 16)) return; if (value === this) { var err = makeSelfResolutionError(); this._attachExtraTrace(err); return this._reject(err); } this._setFulfilled(); this._rejectionHandler0 = value; if ((bitField & 65535) > 0) { if (((bitField & 134217728) !== 0)) { this._settlePromises(); } else { async.settlePromises(this); } this._dereferenceTrace(); } }; Promise.prototype._reject = function (reason) { var bitField = this._bitField; if (((bitField & 117506048) >>> 16)) return; this._setRejected(); this._fulfillmentHandler0 = reason; if (this._isFinal()) { return async.fatalError(reason, util.isNode); } if ((bitField & 65535) > 0) { async.settlePromises(this); } else { this._ensurePossibleRejectionHandled(); } }; Promise.prototype._fulfillPromises = function (len, value) { for (var i = 1; i < len; i++) { var handler = this._fulfillmentHandlerAt(i); var promise = this._promiseAt(i); var receiver = this._receiverAt(i); this._clearCallbackDataAtIndex(i); this._settlePromise(promise, handler, receiver, value); } }; Promise.prototype._rejectPromises = function (len, reason) { for (var i = 1; i < len; i++) { var handler = this._rejectionHandlerAt(i); var promise = this._promiseAt(i); var receiver = this._receiverAt(i); this._clearCallbackDataAtIndex(i); this._settlePromise(promise, handler, receiver, reason); } }; Promise.prototype._settlePromises = function () { var bitField = this._bitField; var len = (bitField & 65535); if (len > 0) { if (((bitField & 16842752) !== 0)) { var reason = this._fulfillmentHandler0; this._settlePromise0(this._rejectionHandler0, reason, bitField); this._rejectPromises(len, reason); } else { var value = this._rejectionHandler0; this._settlePromise0(this._fulfillmentHandler0, value, bitField); this._fulfillPromises(len, value); } this._setLength(0); } this._clearCancellationData(); }; Promise.prototype._settledValue = function() { var bitField = this._bitField; if (((bitField & 33554432) !== 0)) { return this._rejectionHandler0; } else if (((bitField & 16777216) !== 0)) { return this._fulfillmentHandler0; } }; function deferResolve(v) {this.promise._resolveCallback(v);} function deferReject(v) {this.promise._rejectCallback(v, false);} Promise.defer = Promise.pending = function() { debug.deprecated("Promise.defer", "new Promise"); var promise = new Promise(INTERNAL); return { promise: promise, resolve: deferResolve, reject: deferReject }; }; util.notEnumerableProp(Promise, "_makeSelfResolutionError", makeSelfResolutionError); require("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug); require("./bind")(Promise, INTERNAL, tryConvertToPromise, debug); require("./cancel")(Promise, PromiseArray, apiRejection, debug); require("./direct_resolve")(Promise); require("./synchronous_inspection")(Promise); require("./join")( Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain); Promise.Promise = Promise; Promise.version = "3.5.2"; require('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); require('./call_get.js')(Promise); require('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext, INTERNAL, debug); require('./timers.js')(Promise, INTERNAL, debug); require('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise, Proxyable, debug); require('./nodeify.js')(Promise); require('./promisify.js')(Promise, INTERNAL); require('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection); require('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection); require('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL, debug); require('./settle.js')(Promise, PromiseArray, debug); require('./some.js')(Promise, PromiseArray, apiRejection); require('./filter.js')(Promise, INTERNAL); require('./each.js')(Promise, INTERNAL); require('./any.js')(Promise); util.toFastProperties(Promise); util.toFastProperties(Promise.prototype); function fillTypes(value) { var p = new Promise(INTERNAL); p._fulfillmentHandler0 = value; p._rejectionHandler0 = value; p._promise0 = value; p._receiver0 = value; } // Complete slack tracking, opt out of field-type tracking and // stabilize map fillTypes({a: 1}); fillTypes({b: 2}); fillTypes({c: 3}); fillTypes(1); fillTypes(function(){}); fillTypes(undefined); fillTypes(false); fillTypes(new Promise(INTERNAL)); debug.setBounds(Async.firstLineError, util.lastLineError); return Promise; };
{ "content_hash": "51a0f9f7d0706b86543a196afc001c3a", "timestamp": "", "source": "github", "line_count": 776, "max_line_length": 128, "avg_line_length": 33.27577319587629, "alnum_prop": 0.5948803345984045, "repo_name": "vamtech/vamtech.github.io", "id": "eeac47e4769a1c60fef4d52b579c96f9cd2cb249", "size": "25822", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "node_modules/bluebird/js/release/promise.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "54036" }, { "name": "HTML", "bytes": "46583" }, { "name": "JavaScript", "bytes": "34089" } ], "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="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `default` mod in crate `syntax`."> <meta name="keywords" content="rust, rustlang, rust-lang, default"> <title>syntax::ext::deriving::default - Rust</title> <link rel="stylesheet" type="text/css" href="../../../../main.css"> <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <section class="sidebar"> <a href='../../../../syntax/index.html'><img src='http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png' alt='' width='100'></a> <p class='location'><a href='../../../index.html'>syntax</a>::<wbr><a href='../../index.html'>ext</a>::<wbr><a href='../index.html'>deriving</a></p><script>window.sidebarCurrent = {name: 'default', ty: 'mod', relpath: '../'};</script><script defer src="../sidebar-items.js"></script> </section> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press 'S' to search, '?' for more options..." type="search"> </div> </form> </nav> <section id='main' class="content mod"> <h1 class='fqn'><span class='in-band'>Module <a href='../../../index.html'>syntax</a>::<wbr><a href='../../index.html'>ext</a>::<wbr><a href='../index.html'>deriving</a>::<wbr><a class='mod' href=''>default</a><wbr><a class='stability Unstable' title=''>Unstable</a></span><span class='out-of-band'><span id='render-detail'> <a id="collapse-all" href="#">[-]</a>&nbsp;<a id="expand-all" href="#">[+]</a> </span><a id='src-233131' href='../../../../src/syntax/ext/deriving/default.rs.html#11-88'>[src]</a></span></h1> <h2 id='functions' class='section-header'><a href="#functions">Functions</a></h2> <table> <tr> <td><a class='stability Unstable' title='Unstable'></a><a class='fn' href='fn.expand_deriving_default.html' title='syntax::ext::deriving::default::expand_deriving_default'>expand_deriving_default</a></td> <td class='docblock short'></td> </tr> </table></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <div id="help" class="hidden"> <div class="shortcuts"> <h1>Keyboard shortcuts</h1> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> </dl> </div> <div class="infos"> <h1>Search tricks</h1> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>typedef</code> (or <code>tdef</code>). </p> </div> </div> <script> window.rootPath = "../../../../"; window.currentCrate = "syntax"; window.playgroundUrl = ""; </script> <script src="../../../../jquery.js"></script> <script src="../../../../main.js"></script> <script async src="../../../../search-index.js"></script> </body> </html>
{ "content_hash": "f61dd8d91c4c5d53299e46766dcef259", "timestamp": "", "source": "github", "line_count": 102, "max_line_length": 324, "avg_line_length": 41.529411764705884, "alnum_prop": 0.5195939565627951, "repo_name": "ArcherSys/ArcherSys", "id": "3ff61467e36920fbcfaf97990fda17c020601c21", "size": "4236", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Rust/share/doc/rust/html/syntax/ext/deriving/default/index.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Flavien Auffret - Projet Doodad</title> <!-- Bootstrap Core CSS --> <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css"> <!-- Custom Fonts --> <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'> <link href='http://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'> <link rel="stylesheet" href="font-awesome/css/font-awesome.min.css" type="text/css"> <!-- Plugin CSS --> <link rel="stylesheet" href="css/animate.min.css" type="text/css"> <!-- Custom CSS --> <link rel="stylesheet" href="css/creative.css" type="text/css"> <!-- 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/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body id="page-top"> <nav id="mainNav" class="navbar navbar-default navbar-fixed-top"> <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand page-scroll" href="index.html"><img src="img/logomenu.png" alt="" /></a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li> <a href="index.html">Projets</a> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> <header> <img class="project-media" src="img/portfolio/fonddoodad.png" alt="" /> <div class="header-content"> <div class="header-content-inner"> <h1>Association DOODAD</h1> <hr> <p>Réalisation d'une charte graphique et d'un dossier de présentation pour l'association DOODAD.</p> <a href="#services" class="btn btn-primary btn-xl page-scroll">Lire davantage</a> </div> </div> </header> <section id="services"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">La réalisation d'une identité graphique pour une association nouvelle</h2> <hr class="primary"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-10 col-md-12 col-lg-push-1 text-center"> <p class="text-muted text-justify"> Ma participation au webzine Le Continu m'a permis de démontrer mes capacités créatives à son fondateur. Il a peu de temps après lancé l'association du webzine "Doodad". Il s'est donc naturellement tourné vers moi pour que je réalise le logo et l'univers graphique de l'association qui a pour objectif de promouvoir les initiatives jeunes. J’ai voulu exprimer à travers cette création la fracture causée par les créations entreprise par la jeunesse. </p> <p class="text-muted text-justify"> Je lui ai suggéré qu'il aurait certainement besoin lors de ces démarches pour obtenir des subventions et des partenariats d'avoir un dossier qui soit là pour présenter de manière professionnelle et succincte ce que fait l'association. Une fois son feu vert obtenu, j'ai mobilisé les nombreux cours que l'on a eus pour réaliser dossier de presse et dossier de partenariat. Tout cela dans l'objectif d'obtenir un dossier hybride qui puisse donner un ordre d'idée précis de ce qu'est l'association. </p> </div> </div> </div> </section> <section class="no-padding" id="portfolio"> <div class="container-fluid"> <div class="row no-gutter"> <div class="col-lg-4 col-sm-6"> <img src="img/portfolio/fbdoodad.png" class="img-responsive" alt=""> </div> <div class="col-lg-4 col-sm-6"> <img src="img/ppdoodad.png" class="img-responsive" alt=""> </div> <div class="col-lg-4 col-sm-6"> <img src="img/portfolio/magdoodad3.png" class="img-responsive" alt=""> </div> <div class="col-lg-4 col-sm-6"> <img src="img/portfolio/magdoodad1.png" class="img-responsive" alt=""> </div> <div class="col-lg-4 col-sm-6"> <img src="img/portfolio/arrieremagdoodad.png" class="img-responsive" alt=""> </div> <div class="col-lg-4 col-sm-6"> <img src="img/portfolio/magdoodadface.png" class="img-responsive" alt=""> </div> </div> </div> </section> <aside class="bg-dark"> <div class="container text-center"> <div class="call-to-action"> <h2>Pour télécharger mon CV</h2> <a href="CVAuffretFlavien_2017-Fr-GTG.pdf" class="btn btn-default btn-xl wow tada">C'est juste ici !</a> </div> </div> </aside> <section id="contact"> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2 text-center"> <h2 class="section-heading">Entrons en contact !</h2> <hr class="primary"> <p>Vous voila décidé à me contacter ? Voila plusieurs moyens pour que vos besoins parviennent à mes oreilles !</p> </div> <div class="col-lg-2 col-lg-offset-2 text-center"> <i class="fa fa-twitter fa-3x wow bounceIn"></i> <p> <a href="tps://twitter.com/FlavienAuffret"> @flavienauffret </a></p> </div> <div class="col-lg-2 text-center"> <i class="fa fa-linkedin-square fa-3x wow bounceIn" data-wow-delay=".1s"></i> <p><a href="https://www.linkedin.com/in/flavien-auffret-2287a693"> Linkedin/fauffret</a></p> </div> <div class="col-lg-2 text-center"> <i class="fa fa-envelope fa-3x wow bounceIn" data-wow-delay=".1s"></i> <p><a href="mailto:flavien.auffret@gmail.com"> Envoyer un mail</a></p> </div> <div class="col-lg-2 text-center"> <i class="fa fa-mobile fa-3x wow bounceIn" data-wow-delay=".1s"></i> <p>06.99.29.00.86</p> </div> </div> </div> </section> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Plugin JavaScript --> <script src="js/jquery.easing.min.js"></script> <script src="js/jquery.fittext.js"></script> <script src="js/wow.min.js"></script> <!-- Custom Theme JavaScript --> <script src="js/creative.js"></script> </body> </html>
{ "content_hash": "ecd133f77d95acbb7ce1f2361855ad57", "timestamp": "", "source": "github", "line_count": 175, "max_line_length": 519, "avg_line_length": 47.34285714285714, "alnum_prop": 0.5566686783343392, "repo_name": "Capemol/capemol.github.io", "id": "f9d5d046d8dca89f54ed41fa46bb1c0b853ee075", "size": "8319", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "projetdoodad.html", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "137838" }, { "name": "HTML", "bytes": "114465" }, { "name": "JavaScript", "bytes": "5055" } ], "symlink_target": "" }
/* $Id: log.h 4584 2013-08-30 04:03:22Z bennylp $ */ /* * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org> * * This program 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 2 of the License, or * (at your option) any later version. * * This program 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 this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef __PJ_LOG_H__ #define __PJ_LOG_H__ /** * @file log.h * @brief Logging Utility. */ #include <pj/types.h> #include <stdarg.h> PJ_BEGIN_DECL /** * @defgroup PJ_MISC Miscelaneous */ /** * @defgroup PJ_LOG Logging Facility * @ingroup PJ_MISC * @{ * * The PJLIB logging facility is a configurable, flexible, and convenient * way to write logging or trace information. * * To write to the log, one uses construct like below: * * <pre> * ... * PJ_LOG(3, ("main.c", "Starting hello...")); * ... * PJ_LOG(3, ("main.c", "Hello world from process %d", pj_getpid())); * ... * </pre> * * In the above example, the number @b 3 controls the verbosity level of * the information (which means "information", by convention). The string * "main.c" specifies the source or sender of the message. * * * \section pj_log_quick_sample_sec Examples * * For examples, see: * - @ref page_pjlib_samples_log_c. * */ /** * Log decoration flag, to be specified with #pj_log_set_decor(). */ enum pj_log_decoration { PJ_LOG_HAS_DAY_NAME = 1, /**< Include day name [default: no] */ PJ_LOG_HAS_YEAR = 2, /**< Include year digit [no] */ PJ_LOG_HAS_MONTH = 4, /**< Include month [no] */ PJ_LOG_HAS_DAY_OF_MON = 8, /**< Include day of month [no] */ PJ_LOG_HAS_TIME = 16, /**< Include time [yes] */ PJ_LOG_HAS_MICRO_SEC = 32, /**< Include microseconds [yes] */ PJ_LOG_HAS_SENDER = 64, /**< Include sender in the log [yes] */ PJ_LOG_HAS_NEWLINE = 128, /**< Terminate each call with newline [yes] */ PJ_LOG_HAS_CR = 256, /**< Include carriage return [no] */ PJ_LOG_HAS_SPACE = 512, /**< Include two spaces before log [yes] */ PJ_LOG_HAS_COLOR = 1024, /**< Colorize logs [yes on win32] */ PJ_LOG_HAS_LEVEL_TEXT = 2048, /**< Include level text string [no] */ PJ_LOG_HAS_THREAD_ID = 4096, /**< Include thread identification [no] */ PJ_LOG_HAS_THREAD_SWC = 8192, /**< Add mark when thread has switched [yes]*/ PJ_LOG_HAS_INDENT =16384 /**< Indentation. Say yes! [yes] */ }; /** * Write log message. * This is the main macro used to write text to the logging backend. * * @param level The logging verbosity level. Lower number indicates higher * importance, with level zero indicates fatal error. Only * numeral argument is permitted (e.g. not variable). * @param arg Enclosed 'printf' like arguments, with the first * argument is the sender, the second argument is format * string and the following arguments are variable number of * arguments suitable for the format string. * * Sample: * \verbatim PJ_LOG(2, (__FILE__, "current value is %d", value)); \endverbatim * @hideinitializer */ #define PJ_LOG(level,arg) do { \ if (level <= pj_log_get_level()) \ pj_log_wrapper_##level(arg); \ } while (0) /** * Signature for function to be registered to the logging subsystem to * write the actual log message to some output device. * * @param level Log level. * @param data Log message, which will be NULL terminated. * @param len Message length. */ typedef void pj_log_func(int level, const char *data, int len); /** * Default logging writer function used by front end logger function. * This function will print the log message to stdout only. * Application normally should NOT need to call this function, but * rather use the PJ_LOG macro. * * @param level Log level. * @param buffer Log message. * @param len Message length. */ PJ_DECL(void) pj_log_write(int level, const char *buffer, int len); #if PJ_LOG_MAX_LEVEL >= 1 /** * Write to log. * * @param sender Source of the message. * @param level Verbosity level. * @param format Format. * @param marker Marker. */ PJ_DECL(void) pj_log(const char *sender, int level, const char *format, va_list marker); /** * Change log output function. The front-end logging functions will call * this function to write the actual message to the desired device. * By default, the front-end functions use pj_log_write() to write * the messages, unless it's changed by calling this function. * * @param func The function that will be called to write the log * messages to the desired device. */ PJ_DECL(void) pj_log_set_log_func( pj_log_func *func ); /** * Get the current log output function that is used to write log messages. * * @return Current log output function. */ PJ_DECL(pj_log_func*) pj_log_get_log_func(void); /** * Set maximum log level. Application can call this function to set * the desired level of verbosity of the logging messages. The bigger the * value, the more verbose the logging messages will be printed. However, * the maximum level of verbosity can not exceed compile time value of * PJ_LOG_MAX_LEVEL. * * @param level The maximum level of verbosity of the logging * messages (6=very detailed..1=error only, 0=disabled) */ PJ_DECL(void) pj_log_set_level(int level); /** * Get current maximum log verbositylevel. * * @return Current log maximum level. */ #if 1 PJ_DECL(int) pj_log_get_level(void); #else PJ_DECL_DATA(int) pj_log_max_level; #define pj_log_get_level() pj_log_max_level #endif /** * Set log decoration. The log decoration flag controls what are printed * to output device alongside the actual message. For example, application * can specify that date/time information should be displayed with each * log message. * * @param decor Bitmask combination of #pj_log_decoration to control * the layout of the log message. */ PJ_DECL(void) pj_log_set_decor(unsigned decor); /** * Get current log decoration flag. * * @return Log decoration flag. */ PJ_DECL(unsigned) pj_log_get_decor(void); /** * Add indentation to log message. Indentation will add PJ_LOG_INDENT_CHAR * before the message, and is useful to show the depth of function calls. * * @param indent The indentation to add or substract. Positive value * adds current indent, negative value subtracts current * indent. */ PJ_DECL(void) pj_log_add_indent(int indent); /** * Push indentation to the right by default value (PJ_LOG_INDENT). */ PJ_DECL(void) pj_log_push_indent(void); /** * Pop indentation (to the left) by default value (PJ_LOG_INDENT). */ PJ_DECL(void) pj_log_pop_indent(void); /** * Set color of log messages. * * @param level Log level which color will be changed. * @param color Desired color. */ PJ_DECL(void) pj_log_set_color(int level, pj_color_t color); /** * Get color of log messages. * * @param level Log level which color will be returned. * @return Log color. */ PJ_DECL(pj_color_t) pj_log_get_color(int level); /** * Internal function to be called by pj_init() */ pj_status_t pj_log_init(void); #else /* #if PJ_LOG_MAX_LEVEL >= 1 */ /** * Change log output function. The front-end logging functions will call * this function to write the actual message to the desired device. * By default, the front-end functions use pj_log_write() to write * the messages, unless it's changed by calling this function. * * @param func The function that will be called to write the log * messages to the desired device. */ # define pj_log_set_log_func(func) /** * Write to log. * * @param sender Source of the message. * @param level Verbosity level. * @param format Format. * @param marker Marker. */ # define pj_log(sender, level, format, marker) /** * Set maximum log level. Application can call this function to set * the desired level of verbosity of the logging messages. The bigger the * value, the more verbose the logging messages will be printed. However, * the maximum level of verbosity can not exceed compile time value of * PJ_LOG_MAX_LEVEL. * * @param level The maximum level of verbosity of the logging * messages (6=very detailed..1=error only, 0=disabled) */ # define pj_log_set_level(level) /** * Set log decoration. The log decoration flag controls what are printed * to output device alongside the actual message. For example, application * can specify that date/time information should be displayed with each * log message. * * @param decor Bitmask combination of #pj_log_decoration to control * the layout of the log message. */ # define pj_log_set_decor(decor) /** * Add indentation to log message. Indentation will add PJ_LOG_INDENT_CHAR * before the message, and is useful to show the depth of function calls. * * @param indent The indentation to add or substract. Positive value * adds current indent, negative value subtracts current * indent. */ # define pj_log_add_indent(indent) /** * Push indentation to the right by default value (PJ_LOG_INDENT). */ # define pj_log_push_indent() /** * Pop indentation (to the left) by default value (PJ_LOG_INDENT). */ # define pj_log_pop_indent() /** * Set color of log messages. * * @param level Log level which color will be changed. * @param color Desired color. */ # define pj_log_set_color(level, color) /** * Get current maximum log verbositylevel. * * @return Current log maximum level. */ # define pj_log_get_level() 0 /** * Get current log decoration flag. * * @return Log decoration flag. */ # define pj_log_get_decor() 0 /** * Get color of log messages. * * @param level Log level which color will be returned. * @return Log color. */ # define pj_log_get_color(level) 0 /** * Internal. */ # define pj_log_init() PJ_SUCCESS #endif /* #if PJ_LOG_MAX_LEVEL >= 1 */ /** * @} */ /* **************************************************************************/ /* * Log functions implementation prototypes. * These functions are called by PJ_LOG macros according to verbosity * level specified when calling the macro. Applications should not normally * need to call these functions directly. */ /** * @def pj_log_wrapper_1(arg) * Internal function to write log with verbosity 1. Will evaluate to * empty expression if PJ_LOG_MAX_LEVEL is below 1. * @param arg Log expression. */ #if PJ_LOG_MAX_LEVEL >= 1 #define pj_log_wrapper_1(arg) pj_log_1 arg /** Internal function. */ PJ_DECL(void) pj_log_1(const char *src, const char *format, ...); #else #define pj_log_wrapper_1(arg) #endif /** * @def pj_log_wrapper_2(arg) * Internal function to write log with verbosity 2. Will evaluate to * empty expression if PJ_LOG_MAX_LEVEL is below 2. * @param arg Log expression. */ #if PJ_LOG_MAX_LEVEL >= 2 #define pj_log_wrapper_2(arg) pj_log_2 arg /** Internal function. */ PJ_DECL(void) pj_log_2(const char *src, const char *format, ...); #else #define pj_log_wrapper_2(arg) #endif /** * @def pj_log_wrapper_3(arg) * Internal function to write log with verbosity 3. Will evaluate to * empty expression if PJ_LOG_MAX_LEVEL is below 3. * @param arg Log expression. */ #if PJ_LOG_MAX_LEVEL >= 3 #define pj_log_wrapper_3(arg) pj_log_3 arg /** Internal function. */ PJ_DECL(void) pj_log_3(const char *src, const char *format, ...); #else #define pj_log_wrapper_3(arg) #endif /** * @def pj_log_wrapper_4(arg) * Internal function to write log with verbosity 4. Will evaluate to * empty expression if PJ_LOG_MAX_LEVEL is below 4. * @param arg Log expression. */ #if PJ_LOG_MAX_LEVEL >= 4 #define pj_log_wrapper_4(arg) pj_log_4 arg /** Internal function. */ PJ_DECL(void) pj_log_4(const char *src, const char *format, ...); #else #define pj_log_wrapper_4(arg) #endif /** * @def pj_log_wrapper_5(arg) * Internal function to write log with verbosity 5. Will evaluate to * empty expression if PJ_LOG_MAX_LEVEL is below 5. * @param arg Log expression. */ #if PJ_LOG_MAX_LEVEL >= 5 #define pj_log_wrapper_5(arg) pj_log_5 arg /** Internal function. */ PJ_DECL(void) pj_log_5(const char *src, const char *format, ...); #else #define pj_log_wrapper_5(arg) #endif /** * @def pj_log_wrapper_6(arg) * Internal function to write log with verbosity 6. Will evaluate to * empty expression if PJ_LOG_MAX_LEVEL is below 6. * @param arg Log expression. */ #if PJ_LOG_MAX_LEVEL >= 6 #define pj_log_wrapper_6(arg) pj_log_6 arg /** Internal function. */ PJ_DECL(void) pj_log_6(const char *src, const char *format, ...); #else #define pj_log_wrapper_6(arg) #endif PJ_END_DECL #endif /* __PJ_LOG_H__ */
{ "content_hash": "5ab32d18a28d7b0135d2778a56bded33", "timestamp": "", "source": "github", "line_count": 453, "max_line_length": 80, "avg_line_length": 29.867549668874172, "alnum_prop": 0.6568366592756837, "repo_name": "MaximKeegan/swig", "id": "c9d5c313d581f8a6119504bceb2c0f415733ae48", "size": "13530", "binary": false, "copies": "41", "ref": "refs/heads/master", "path": "Example/Pods/pjsip-ios/Pod/pjsip-include/pj/log.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "4155142" }, { "name": "C++", "bytes": "687802" }, { "name": "Objective-C", "bytes": "873223" }, { "name": "Ruby", "bytes": "2022" }, { "name": "Shell", "bytes": "32596" }, { "name": "Swift", "bytes": "19951" } ], "symlink_target": "" }
namespace chromeos { WizardInProcessBrowserTest::WizardInProcessBrowserTest(const char* screen_name) : screen_name_(screen_name), host_(NULL) { } void WizardInProcessBrowserTest::SetUpCommandLine(CommandLine* command_line) { command_line->AppendSwitch(switches::kNoStartupWindow); } void WizardInProcessBrowserTest::SetUpOnMainThread() { SetUpWizard(); WizardController::SetZeroDelays(); if (!screen_name_.empty()) { ShowLoginWizard(screen_name_, gfx::Size(1024, 600)); host_ = BaseLoginDisplayHost::default_host(); } } void WizardInProcessBrowserTest::CleanUpOnMainThread() { // LoginDisplayHost owns controllers and all windows. MessageLoopForUI::current()->DeleteSoon(FROM_HERE, host_); ui_test_utils::RunMessageLoop(); } } // namespace chromeos
{ "content_hash": "0e8f10222fe8992d99315cbf8888b4da", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 79, "avg_line_length": 26.4, "alnum_prop": 0.7436868686868687, "repo_name": "robclark/chromium", "id": "e43244e3089cb7aceea7a9d3f250b57d60eecd76", "size": "1520", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chrome/browser/chromeos/login/wizard_in_process_browser_test.cc", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Assembly", "bytes": "1178292" }, { "name": "C", "bytes": "74631766" }, { "name": "C++", "bytes": "120828826" }, { "name": "F#", "bytes": "381" }, { "name": "Go", "bytes": "18556" }, { "name": "Java", "bytes": "120805" }, { "name": "JavaScript", "bytes": "16170722" }, { "name": "Objective-C", "bytes": "5449644" }, { "name": "PHP", "bytes": "97796" }, { "name": "Perl", "bytes": "918516" }, { "name": "Python", "bytes": "5989396" }, { "name": "R", "bytes": "524" }, { "name": "Shell", "bytes": "4169796" }, { "name": "Tcl", "bytes": "277077" } ], "symlink_target": "" }
package org.hibernate.validator.interpolator; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.StringTokenizer; import org.hibernate.util.StringHelper; import org.hibernate.validator.MessageInterpolator; import org.hibernate.validator.Validator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Resource bundle based interpolator * Also interpolate annotation parameters inside the message * * @author Emmanuel Bernard */ public class DefaultMessageInterpolator implements MessageInterpolator, Serializable { private static final Logger log = LoggerFactory.getLogger( DefaultMessageInterpolator.class ); private Map<String, Object> annotationParameters = new HashMap<String, Object>(); private transient ResourceBundle messageBundle; private transient ResourceBundle defaultMessageBundle; private String annotationMessage; private String interpolateMessage; //not an interface method public void initialize(ResourceBundle messageBundle, ResourceBundle defaultMessageBundle) { this.messageBundle = messageBundle; this.defaultMessageBundle = defaultMessageBundle; } public void initialize(Annotation annotation, MessageInterpolator defaultInterpolator) { Class clazz = annotation.getClass(); for ( Method method : clazz.getMethods() ) { try { //FIXME remove non serilalization elements on writeObject? if ( method.getReturnType() != void.class && method.getParameterTypes().length == 0 && ! Modifier.isStatic( method.getModifiers() ) ) { //cannot use an exclude list because the parameter name could match a method name annotationParameters.put( method.getName(), method.invoke( annotation ) ); } } catch (IllegalAccessException e) { //really should not happen, but we degrade nicely log.warn( "Unable to access {}", StringHelper.qualify( clazz.toString(), method.getName() ) ); } catch (InvocationTargetException e) { //really should not happen, but we degrade nicely log.warn( "Unable to access {}", StringHelper.qualify( clazz.toString(), method.getName() ) ); } } annotationMessage = (String) annotationParameters.get( "message" ); if (annotationMessage == null) { throw new IllegalArgumentException( "Annotation " + clazz + " does not have an (accessible) message attribute"); } //do not resolve the property eagerly to allow validator.apply to work wo interpolator } private String replace(String message) { StringTokenizer tokens = new StringTokenizer( message, "#{}", true ); StringBuilder buf = new StringBuilder( 30 ); boolean escaped = false; boolean el = false; while ( tokens.hasMoreTokens() ) { String token = tokens.nextToken(); if ( !escaped && "#".equals( token ) ) { el = true; } if ( !el && "{".equals( token ) ) { escaped = true; } else if ( escaped && "}".equals( token ) ) { escaped = false; } else if ( !escaped ) { if ( "{".equals( token ) ) el = false; buf.append( token ); } else { Object variable = annotationParameters.get( token ); if ( variable != null ) { buf.append( variable ); } else { String string = null; try { string = messageBundle != null ? messageBundle.getString( token ) : null; } catch( MissingResourceException e ) { //give a second chance with the default resource bundle } if (string == null) { try { string = defaultMessageBundle.getString( token ); } catch( MissingResourceException e) { //return the unchanged string buf.append('{').append(token).append('}'); } } if ( string != null ) buf.append( replace( string ) ); } } } return buf.toString(); } public String interpolate(String message, Validator validator, MessageInterpolator defaultInterpolator) { if ( annotationMessage.equals( message ) ) { //short cut if (interpolateMessage == null) { interpolateMessage = replace( annotationMessage ); } return interpolateMessage; } else { //TODO keep them in a weak hash map, but this might not even be useful return replace( message ); } } public String getAnnotationMessage() { return annotationMessage; } }
{ "content_hash": "b2d91636e51b9713b503c00b6f1e0ae2", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 115, "avg_line_length": 35.14179104477612, "alnum_prop": 0.6714801444043321, "repo_name": "emmanuelbernard/hibernate-validator", "id": "c2a6698da650eb255fa2473712fc4c51ea36aa66", "size": "4709", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "hibernate-validator-legacy/src/main/java/org/hibernate/validator/interpolator/DefaultMessageInterpolator.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "1336256" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.IO; using System.Globalization; #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) using System.Numerics; #endif using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json { /// <summary> /// Represents a reader that provides fast, non-cached, forward-only access to serialized JSON data. /// </summary> public abstract class JsonReader : IDisposable { /// <summary> /// Specifies the state of the reader. /// </summary> protected internal enum State { /// <summary> /// The Read method has not been called. /// </summary> Start, /// <summary> /// The end of the file has been reached successfully. /// </summary> Complete, /// <summary> /// Reader is at a property. /// </summary> Property, /// <summary> /// Reader is at the start of an object. /// </summary> ObjectStart, /// <summary> /// Reader is in an object. /// </summary> Object, /// <summary> /// Reader is at the start of an array. /// </summary> ArrayStart, /// <summary> /// Reader is in an array. /// </summary> Array, /// <summary> /// The Close method has been called. /// </summary> Closed, /// <summary> /// Reader has just read a value. /// </summary> PostValue, /// <summary> /// Reader is at the start of a constructor. /// </summary> ConstructorStart, /// <summary> /// Reader in a constructor. /// </summary> Constructor, /// <summary> /// An error occurred that prevents the read operation from continuing. /// </summary> Error, /// <summary> /// The end of the file has been reached successfully. /// </summary> Finished } // current Token data private JsonToken _tokenType; private object _value; internal char _quoteChar; internal State _currentState; private JsonPosition _currentPosition; private CultureInfo _culture; private DateTimeZoneHandling _dateTimeZoneHandling; private int? _maxDepth; private bool _hasExceededMaxDepth; internal DateParseHandling _dateParseHandling; internal FloatParseHandling _floatParseHandling; private string _dateFormatString; private List<JsonPosition> _stack; /// <summary> /// Gets the current reader state. /// </summary> /// <value>The current reader state.</value> protected State CurrentState { get { return _currentState; } } /// <summary> /// Gets or sets a value indicating whether the underlying stream or /// <see cref="TextReader"/> should be closed when the reader is closed. /// </summary> /// <value> /// true to close the underlying stream or <see cref="TextReader"/> when /// the reader is closed; otherwise false. The default is true. /// </value> public bool CloseInput { get; set; } /// <summary> /// Gets or sets a value indicating whether multiple pieces of JSON content can /// be read from a continuous stream without erroring. /// </summary> /// <value> /// true to support reading multiple pieces of JSON content; otherwise false. The default is false. /// </value> public bool SupportMultipleContent { get; set; } /// <summary> /// Gets the quotation mark character used to enclose the value of a string. /// </summary> public virtual char QuoteChar { get { return _quoteChar; } protected internal set { _quoteChar = value; } } /// <summary> /// Get or set how <see cref="DateTime"/> time zones are handling when reading JSON. /// </summary> public DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling; } set { if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind) { throw new ArgumentOutOfRangeException(nameof(value)); } _dateTimeZoneHandling = value; } } /// <summary> /// Get or set how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON. /// </summary> public DateParseHandling DateParseHandling { get { return _dateParseHandling; } set { if (value < DateParseHandling.None || #if !NET20 value > DateParseHandling.DateTimeOffset #else value > DateParseHandling.DateTime #endif ) { throw new ArgumentOutOfRangeException(nameof(value)); } _dateParseHandling = value; } } /// <summary> /// Get or set how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text. /// </summary> public FloatParseHandling FloatParseHandling { get { return _floatParseHandling; } set { if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal) { throw new ArgumentOutOfRangeException(nameof(value)); } _floatParseHandling = value; } } /// <summary> /// Get or set how custom date formatted strings are parsed when reading JSON. /// </summary> public string DateFormatString { get { return _dateFormatString; } set { _dateFormatString = value; } } /// <summary> /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>. /// </summary> public int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", nameof(value)); } _maxDepth = value; } } /// <summary> /// Gets the type of the current JSON token. /// </summary> public virtual JsonToken TokenType { get { return _tokenType; } } /// <summary> /// Gets the text value of the current JSON token. /// </summary> public virtual object Value { get { return _value; } } /// <summary> /// Gets The Common Language Runtime (CLR) type for the current JSON token. /// </summary> public virtual Type ValueType { get { return (_value != null) ? _value.GetType() : null; } } /// <summary> /// Gets the depth of the current token in the JSON document. /// </summary> /// <value>The depth of the current token in the JSON document.</value> public virtual int Depth { get { int depth = (_stack != null) ? _stack.Count : 0; if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None) { return depth; } else { return depth + 1; } } } /// <summary> /// Gets the path of the current JSON token. /// </summary> public virtual string Path { get { if (_currentPosition.Type == JsonContainerType.None) { return string.Empty; } bool insideContainer = (_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart); JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null; return JsonPosition.BuildPath(_stack, current); } } /// <summary> /// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>. /// </summary> public CultureInfo Culture { get { return _culture ?? CultureInfo.InvariantCulture; } set { _culture = value; } } internal JsonPosition GetPosition(int depth) { if (_stack != null && depth < _stack.Count) { return _stack[depth]; } return _currentPosition; } /// <summary> /// Initializes a new instance of the <see cref="JsonReader"/> class with the specified <see cref="TextReader"/>. /// </summary> protected JsonReader() { _currentState = State.Start; _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; _dateParseHandling = DateParseHandling.DateTime; _floatParseHandling = FloatParseHandling.Double; CloseInput = true; } private void Push(JsonContainerType value) { UpdateScopeWithFinishedValue(); if (_currentPosition.Type == JsonContainerType.None) { _currentPosition = new JsonPosition(value); } else { if (_stack == null) { _stack = new List<JsonPosition>(); } _stack.Add(_currentPosition); _currentPosition = new JsonPosition(value); // this is a little hacky because Depth increases when first property/value is written but only testing here is faster/simpler if (_maxDepth != null && Depth + 1 > _maxDepth && !_hasExceededMaxDepth) { _hasExceededMaxDepth = true; throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth)); } } } private JsonContainerType Pop() { JsonPosition oldPosition; if (_stack != null && _stack.Count > 0) { oldPosition = _currentPosition; _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { oldPosition = _currentPosition; _currentPosition = new JsonPosition(); } if (_maxDepth != null && Depth <= _maxDepth) { _hasExceededMaxDepth = false; } return oldPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } /// <summary> /// Reads the next JSON token from the stream. /// </summary> /// <returns>true if the next token was read successfully; false if there are no more tokens to read.</returns> public abstract bool Read(); /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Int32}"/>. /// </summary> /// <returns>A <see cref="Nullable{Int32}"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual int? ReadAsInt32() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: if (!(Value is int)) { SetToken(JsonToken.Integer, Convert.ToInt32(Value, CultureInfo.InvariantCulture), false); } return (int)Value; case JsonToken.String: string s = (string)Value; return ReadInt32String(s); } throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal int? ReadInt32String(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } int i; if (int.TryParse(s, NumberStyles.Integer, Culture, out i)) { SetToken(JsonToken.Integer, i, false); return i; } else { SetToken(JsonToken.String, s, false); throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } } /// <summary> /// Reads the next JSON token from the stream as a <see cref="String"/>. /// </summary> /// <returns>A <see cref="String"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual string ReadAsString() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.String: return (string)Value; } if (JsonTokenUtils.IsPrimitiveToken(t)) { if (Value != null) { string s; if (Value is IFormattable) { s = ((IFormattable)Value).ToString(null, Culture); } else if (Value is Uri) { s = ((Uri)Value).OriginalString; } else { s = Value.ToString(); } SetToken(JsonToken.String, s, false); return s; } } throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Byte"/>[]. /// </summary> /// <returns>A <see cref="Byte"/>[] or a null reference if the next JSON token is null. This method will return <c>null</c> at the end of an array.</returns> public virtual byte[] ReadAsBytes() { JsonToken t = GetContentToken(); if (t == JsonToken.None) { return null; } if (TokenType == JsonToken.StartObject) { ReadIntoWrappedTypeObject(); byte[] data = ReadAsBytes(); ReaderReadAndAssert(); if (TokenType != JsonToken.EndObject) { throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } SetToken(JsonToken.Bytes, data, false); return data; } switch (t) { case JsonToken.String: { // attempt to convert possible base 64 or GUID string to bytes // GUID has to have format 00000000-0000-0000-0000-000000000000 string s = (string)Value; byte[] data; Guid g; if (s.Length == 0) { data = new byte[0]; } else if (ConvertUtils.TryConvertGuid(s, out g)) { data = g.ToByteArray(); } else { data = Convert.FromBase64String(s); } SetToken(JsonToken.Bytes, data, false); return data; } case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Bytes: if (ValueType == typeof(Guid)) { byte[] data = ((Guid)Value).ToByteArray(); SetToken(JsonToken.Bytes, data, false); return data; } return (byte[])Value; case JsonToken.StartArray: return ReadArrayIntoByteArray(); } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal byte[] ReadArrayIntoByteArray() { List<byte> buffer = new List<byte>(); while (true) { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: throw JsonReaderException.Create(this, "Unexpected end when reading bytes."); case JsonToken.Integer: buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture)); break; case JsonToken.EndArray: byte[] d = buffer.ToArray(); SetToken(JsonToken.Bytes, d, false); return d; default: throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } } } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>. /// </summary> /// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual double? ReadAsDouble() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: if (!(Value is double)) { double d; #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (Value is BigInteger) { d = (double)(BigInteger)Value; } else #endif { d = Convert.ToDouble(Value, CultureInfo.InvariantCulture); } SetToken(JsonToken.Float, d, false); } return (double)Value; case JsonToken.String: return ReadDoubleString((string)Value); } throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal double? ReadDoubleString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } double d; if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out d)) { SetToken(JsonToken.Float, d, false); return d; } else { SetToken(JsonToken.String, s, false); throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Boolean}"/>. /// </summary> /// <returns>A <see cref="Nullable{Boolean}"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual bool? ReadAsBoolean() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: bool b; #if !(NET20 || NET35 || PORTABLE40 || PORTABLE) if (Value is BigInteger) { b = (BigInteger)Value != 0; } else #endif { b = Convert.ToBoolean(Value, CultureInfo.InvariantCulture); } SetToken(JsonToken.Boolean, b, false); return b; case JsonToken.String: return ReadBooleanString((string)Value); case JsonToken.Boolean: return (bool)Value; } throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal bool? ReadBooleanString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } bool b; if (bool.TryParse(s, out b)) { SetToken(JsonToken.Boolean, b, false); return b; } else { SetToken(JsonToken.String, s, false); throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{Decimal}"/>. /// </summary> /// <returns>A <see cref="Nullable{Decimal}"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual decimal? ReadAsDecimal() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Integer: case JsonToken.Float: if (!(Value is decimal)) { SetToken(JsonToken.Float, Convert.ToDecimal(Value, CultureInfo.InvariantCulture), false); } return (decimal)Value; case JsonToken.String: return ReadDecimalString((string)Value); } throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } internal decimal? ReadDecimalString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } decimal d; if (decimal.TryParse(s, NumberStyles.Number, Culture, out d)) { SetToken(JsonToken.Float, d, false); return d; } else { SetToken(JsonToken.String, s, false); throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } } /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTime}"/>. /// </summary> /// <returns>A <see cref="Nullable{DateTime}"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual DateTime? ReadAsDateTime() { switch (GetContentToken()) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: #if !NET20 if (Value is DateTimeOffset) { SetToken(JsonToken.Date, ((DateTimeOffset)Value).DateTime, false); } #endif return (DateTime)Value; case JsonToken.String: string s = (string)Value; return ReadDateTimeString(s); } throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType)); } internal DateTime? ReadDateTimeString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } DateTime dt; if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, false); return dt; } if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling); SetToken(JsonToken.Date, dt, false); return dt; } throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } #if !NET20 /// <summary> /// Reads the next JSON token from the stream as a <see cref="Nullable{DateTimeOffset}"/>. /// </summary> /// <returns>A <see cref="Nullable{DateTimeOffset}"/>. This method will return <c>null</c> at the end of an array.</returns> public virtual DateTimeOffset? ReadAsDateTimeOffset() { JsonToken t = GetContentToken(); switch (t) { case JsonToken.None: case JsonToken.Null: case JsonToken.EndArray: return null; case JsonToken.Date: if (Value is DateTime) { SetToken(JsonToken.Date, new DateTimeOffset((DateTime)Value), false); } return (DateTimeOffset)Value; case JsonToken.String: string s = (string)Value; return ReadDateTimeOffsetString(s); default: throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t)); } } internal DateTimeOffset? ReadDateTimeOffsetString(string s) { if (string.IsNullOrEmpty(s)) { SetToken(JsonToken.Null, null, false); return null; } DateTimeOffset dt; if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out dt)) { SetToken(JsonToken.Date, dt, false); return dt; } if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt)) { SetToken(JsonToken.Date, dt, false); return dt; } SetToken(JsonToken.String, s, false); throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s)); } #endif internal void ReaderReadAndAssert() { if (!Read()) { throw CreateUnexpectedEndException(); } } internal JsonReaderException CreateUnexpectedEndException() { return JsonReaderException.Create(this, "Unexpected end when reading JSON."); } internal void ReadIntoWrappedTypeObject() { ReaderReadAndAssert(); if (Value.ToString() == JsonTypeReflector.TypePropertyName) { ReaderReadAndAssert(); if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal)) { ReaderReadAndAssert(); if (Value.ToString() == JsonTypeReflector.ValuePropertyName) { return; } } } throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject)); } /// <summary> /// Skips the children of the current token. /// </summary> public void Skip() { if (TokenType == JsonToken.PropertyName) { Read(); } if (JsonTokenUtils.IsStartToken(TokenType)) { int depth = Depth; while (Read() && (depth < Depth)) { } } } /// <summary> /// Sets the current token. /// </summary> /// <param name="newToken">The new token.</param> protected void SetToken(JsonToken newToken) { SetToken(newToken, null, true); } /// <summary> /// Sets the current token and value. /// </summary> /// <param name="newToken">The new token.</param> /// <param name="value">The value.</param> protected void SetToken(JsonToken newToken, object value) { SetToken(newToken, value, true); } internal void SetToken(JsonToken newToken, object value, bool updateIndex) { _tokenType = newToken; _value = value; switch (newToken) { case JsonToken.StartObject: _currentState = State.ObjectStart; Push(JsonContainerType.Object); break; case JsonToken.StartArray: _currentState = State.ArrayStart; Push(JsonContainerType.Array); break; case JsonToken.StartConstructor: _currentState = State.ConstructorStart; Push(JsonContainerType.Constructor); break; case JsonToken.EndObject: ValidateEnd(JsonToken.EndObject); break; case JsonToken.EndArray: ValidateEnd(JsonToken.EndArray); break; case JsonToken.EndConstructor: ValidateEnd(JsonToken.EndConstructor); break; case JsonToken.PropertyName: _currentState = State.Property; _currentPosition.PropertyName = (string)value; break; case JsonToken.Undefined: case JsonToken.Integer: case JsonToken.Float: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Date: case JsonToken.String: case JsonToken.Raw: case JsonToken.Bytes: SetPostValueState(updateIndex); break; } } internal void SetPostValueState(bool updateIndex) { if (Peek() != JsonContainerType.None) { _currentState = State.PostValue; } else { SetFinished(); } if (updateIndex) { UpdateScopeWithFinishedValue(); } } private void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) { _currentPosition.Position++; } } private void ValidateEnd(JsonToken endToken) { JsonContainerType currentObject = Pop(); if (GetTypeForCloseToken(endToken) != currentObject) { throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject)); } if (Peek() != JsonContainerType.None) { _currentState = State.PostValue; } else { SetFinished(); } } /// <summary> /// Sets the state based on current token type. /// </summary> protected void SetStateBasedOnCurrent() { JsonContainerType currentObject = Peek(); switch (currentObject) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Constructor; break; case JsonContainerType.None: SetFinished(); break; default: throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject)); } } private void SetFinished() { if (SupportMultipleContent) { _currentState = State.Start; } else { _currentState = State.Finished; } } private JsonContainerType GetTypeForCloseToken(JsonToken token) { switch (token) { case JsonToken.EndObject: return JsonContainerType.Object; case JsonToken.EndArray: return JsonContainerType.Array; case JsonToken.EndConstructor: return JsonContainerType.Constructor; default: throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token)); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> void IDisposable.Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) { Close(); } } /// <summary> /// Changes the <see cref="State"/> to Closed. /// </summary> public virtual void Close() { _currentState = State.Closed; _tokenType = JsonToken.None; _value = null; } internal void ReadAndAssert() { if (!Read()) { throw JsonSerializationException.Create(this, "Unexpected end when reading JSON."); } } internal bool ReadAndMoveToContent() { return Read() && MoveToContent(); } internal bool MoveToContent() { JsonToken t = TokenType; while (t == JsonToken.None || t == JsonToken.Comment) { if (!Read()) { return false; } t = TokenType; } return true; } private JsonToken GetContentToken() { JsonToken t; do { if (!Read()) { SetToken(JsonToken.None); return JsonToken.None; } else { t = TokenType; } } while (t == JsonToken.Comment); return t; } } }
{ "content_hash": "c231f059c4a268f4aa89443fa6c46bde", "timestamp": "", "source": "github", "line_count": 1160, "max_line_length": 216, "avg_line_length": 33.14224137931034, "alnum_prop": 0.4858369098712446, "repo_name": "pischke/Newtonsoft.Json", "id": "bae24cff1e9cebbcbdcc037a6557dee4dd6046f5", "size": "39597", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Src/Newtonsoft.Json/JsonReader.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "587" }, { "name": "C#", "bytes": "4522448" }, { "name": "PowerShell", "bytes": "74737" } ], "symlink_target": "" }
import gulp from 'gulp'; import gulpif from 'gulp-if'; import plumber from 'gulp-plumber'; import jade from 'gulp-jade'; import inheritance from 'gulp-jade-inheritance'; import cached from 'gulp-cached'; import filter from 'gulp-filter'; import rename from 'gulp-rename'; import prettify from 'gulp-html-prettify'; import inline from 'gulp-inline'; import errorHandler from '../utils/errorHandler'; import settings from '../settings'; let data = { jv0: 'javascript:void(0);', timestamp: +new Date() }; gulp.task('markup', () => { return gulp .src(`${settings.baseSrc}/**/*.jade`) .pipe(plumber({errorHandler: errorHandler})) .pipe(cached('jade')) .pipe(gulpif(global.watch, inheritance({basedir: settings.baseSrc}))) .pipe(filter((file) => /src[\\\/]pages/.test(file.path))) .pipe(jade({data: data})) .pipe(prettify({ brace_style: 'expand', indent_size: 1, indent_char: '\t', indent_inner_html: true, preserve_newlines: true })) .pipe(rename({dirname: '.'})) .pipe(inline({ base: 'static/', disabledTypes: ['css', 'img', 'js'] })) .pipe(gulp.dest(settings.baseDist)); });
{ "content_hash": "5d895917d60870b238614c2d58e55b03", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 77, "avg_line_length": 33.15, "alnum_prop": 0.5641025641025641, "repo_name": "dim2k2006/geekon-main", "id": "92b3d0aab11399b023a4b5a83eaffacb9bd70ac5", "size": "1326", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "gulp/tasks/markup.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "22600" }, { "name": "HTML", "bytes": "19324" }, { "name": "JavaScript", "bytes": "7698" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using Better.UnsafeGeneric; namespace Better { /// <summary> /// Provides the factory method of the better EqualityComparers. /// </summary> public static class EqualityComparerFactory { private static readonly object StringEqualityComparer = new StringEqualityComparer(); private static readonly object StringKeyEqualityComparer = new StringKeyEqualityComparer(); public static IEqualityComparer<T> Create<T>() { var keyType = typeof(T); if (keyType.IsEnum) { // enum Foo : keyType keyType = Enum.GetUnderlyingType(keyType); } if (keyType == typeof(sbyte) || keyType == typeof(byte) || keyType == typeof(short) || keyType == typeof(ushort) || keyType == typeof(int) || keyType == typeof(uint) || keyType == typeof(char)) { return new Int32EqualityComparer<T>(); } if (keyType == typeof(long)) { return new Int64EqualityComparer<T>(); } if (keyType == typeof(ulong)) { return new UInt64EqualityComparer<T>(); } if (keyType == typeof(string)) { return (IEqualityComparer<T>)StringEqualityComparer; } if (keyType == typeof(StringKey)) { return (IEqualityComparer<T>)StringKeyEqualityComparer; } return null; // Use default EqualityComparer } } /// <summary> /// An implementation of <see cref="IEqualityComparer{T}" /> for the <see cref="StringKey" /> type. /// </summary> class StringKeyEqualityComparer : IEqualityComparer<StringKey> { public bool Equals(StringKey x, StringKey y) { return string.Equals(x.Value, y.Value); } public int GetHashCode(StringKey obj) { return obj.HashCode; } } }
{ "content_hash": "7b0ec7b505ad560445b105835fa0370d", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 107, "avg_line_length": 33, "alnum_prop": 0.5252525252525253, "repo_name": "komatus/BetterDictionary", "id": "c8eba765efa8dd66676145270c591fa47f9a83db", "size": "2180", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Assets/Plugins/BetterDictionary/EqualityComparerFactory.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "33112" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <!-- This file documents the BFD library. Copyright (C) 1991-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 "GNU General Public License" and "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>Untitled Document: Symbols</title> <meta name="description" content="Untitled Document: Symbols"> <meta name="keywords" content="Untitled Document: Symbols"> <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="BFD-Index.html#BFD-Index" rel="index" title="BFD Index"> <link href="index.html#SEC_Contents" rel="contents" title="Table of Contents"> <link href="BFD-front-end.html#BFD-front-end" rel="up" title="BFD front end"> <link href="Reading-Symbols.html#Reading-Symbols" rel="next" title="Reading Symbols"> <link href="section-prototypes.html#section-prototypes" rel="prev" title="section prototypes"> <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="Symbols"></a> <div class="header"> <p> Next: <a href="Archives.html#Archives" accesskey="n" rel="next">Archives</a>, Previous: <a href="Sections.html#Sections" accesskey="p" rel="prev">Sections</a>, Up: <a href="BFD-front-end.html#BFD-front-end" accesskey="u" rel="up">BFD front end</a> &nbsp; [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="BFD-Index.html#BFD-Index" title="Index" rel="index">Index</a>]</p> </div> <hr> <a name="Symbols-1"></a> <h3 class="section">2.7 Symbols</h3> <p>BFD tries to maintain as much symbol information as it can when it moves information from file to file. BFD passes information to applications though the <code>asymbol</code> structure. When the application requests the symbol table, BFD reads the table in the native form and translates parts of it into the internal format. To maintain more than the information passed to applications, some targets keep some information &ldquo;behind the scenes&rdquo; in a structure only the particular back end knows about. For example, the coff back end keeps the original symbol table structure as well as the canonical structure when a BFD is read in. On output, the coff back end can reconstruct the output symbol table so that no information is lost, even information unique to coff which BFD doesn&rsquo;t know or understand. If a coff symbol table were read, but were written through an a.out back end, all the coff specific information would be lost. The symbol table of a BFD is not necessarily read in until a canonicalize request is made. Then the BFD back end fills in a table provided by the application with pointers to the canonical information. To output symbols, the application provides BFD with a table of pointers to pointers to <code>asymbol</code>s. This allows applications like the linker to output a symbol as it was read, since the &ldquo;behind the scenes&rdquo; information will be still available. </p><table class="menu" border="0" cellspacing="0"> <tr><td align="left" valign="top">&bull; <a href="Reading-Symbols.html#Reading-Symbols" accesskey="1">Reading Symbols</a>:</td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> </td></tr> <tr><td align="left" valign="top">&bull; <a href="Writing-Symbols.html#Writing-Symbols" accesskey="2">Writing Symbols</a>:</td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> </td></tr> <tr><td align="left" valign="top">&bull; <a href="Mini-Symbols.html#Mini-Symbols" accesskey="3">Mini Symbols</a>:</td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> </td></tr> <tr><td align="left" valign="top">&bull; <a href="typedef-asymbol.html#typedef-asymbol" accesskey="4">typedef asymbol</a>:</td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> </td></tr> <tr><td align="left" valign="top">&bull; <a href="symbol-handling-functions.html#symbol-handling-functions" accesskey="5">symbol handling functions</a>:</td><td>&nbsp;&nbsp;</td><td align="left" valign="top"> </td></tr> </table> <hr> <div class="header"> <p> Next: <a href="Archives.html#Archives" accesskey="n" rel="next">Archives</a>, Previous: <a href="Sections.html#Sections" accesskey="p" rel="prev">Sections</a>, Up: <a href="BFD-front-end.html#BFD-front-end" accesskey="u" rel="up">BFD front end</a> &nbsp; [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="BFD-Index.html#BFD-Index" title="Index" rel="index">Index</a>]</p> </div> </body> </html>
{ "content_hash": "ccfba42aab44df7ebb2c5681db19c88c", "timestamp": "", "source": "github", "line_count": 126, "max_line_length": 420, "avg_line_length": 51.29365079365079, "alnum_prop": 0.7355717159213987, "repo_name": "ATM-HSW/mbed_target", "id": "b34f82168f956bfc10945dae8954bb7dd05818f5", "size": "6463", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "buildtools/gcc-arm-none-eabi-6-2017-q2/share/doc/gcc-arm-none-eabi/html/bfd.html/Symbols.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": "" }
<?php final class PhabricatorManiphestConfigOptions extends PhabricatorApplicationConfigOptions { public function getName() { return pht('Maniphest'); } public function getDescription() { return pht('Configure Maniphest.'); } public function getFontIcon() { return 'fa-anchor'; } public function getGroup() { return 'apps'; } public function getOptions() { $priority_type = 'custom:ManiphestPriorityConfigOptionType'; $priority_defaults = array( 100 => array( 'name' => pht('Unbreak Now!'), 'short' => pht('Unbreak!'), 'color' => 'pink', 'keywords' => array('unbreak'), ), 90 => array( 'name' => pht('Needs Triage'), 'short' => pht('Triage'), 'color' => 'violet', 'keywords' => array('triage'), ), 80 => array( 'name' => pht('High'), 'short' => pht('High'), 'color' => 'red', 'keywords' => array('high'), ), 50 => array( 'name' => pht('Normal'), 'short' => pht('Normal'), 'color' => 'orange', 'keywords' => array('normal'), ), 25 => array( 'name' => pht('Low'), 'short' => pht('Low'), 'color' => 'yellow', 'keywords' => array('low'), ), 0 => array( 'name' => pht('Wishlist'), 'short' => pht('Wish'), 'color' => 'sky', 'keywords' => array('wish', 'wishlist'), ), ); $status_type = 'custom:ManiphestStatusConfigOptionType'; $status_defaults = array( 'open' => array( 'name' => pht('Open'), 'special' => ManiphestTaskStatus::SPECIAL_DEFAULT, 'prefixes' => array( 'open', 'opens', 'reopen', 'reopens', ), ), 'resolved' => array( 'name' => pht('Resolved'), 'name.full' => pht('Closed, Resolved'), 'closed' => true, 'special' => ManiphestTaskStatus::SPECIAL_CLOSED, 'prefixes' => array( 'closed', 'closes', 'close', 'fix', 'fixes', 'fixed', 'resolve', 'resolves', 'resolved', ), 'suffixes' => array( 'as resolved', 'as fixed', ), 'keywords' => array('closed', 'fixed', 'resolved'), ), 'wontfix' => array( 'name' => pht('Wontfix'), 'name.full' => pht('Closed, Wontfix'), 'closed' => true, 'prefixes' => array( 'wontfix', 'wontfixes', 'wontfixed', ), 'suffixes' => array( 'as wontfix', ), ), 'invalid' => array( 'name' => pht('Invalid'), 'name.full' => pht('Closed, Invalid'), 'closed' => true, 'prefixes' => array( 'invalidate', 'invalidates', 'invalidated', ), 'suffixes' => array( 'as invalid', ), ), 'duplicate' => array( 'name' => pht('Duplicate'), 'name.full' => pht('Closed, Duplicate'), 'transaction.icon' => 'fa-files-o', 'special' => ManiphestTaskStatus::SPECIAL_DUPLICATE, 'closed' => true, ), 'spite' => array( 'name' => pht('Spite'), 'name.full' => pht('Closed, Spite'), 'name.action' => pht('Spited'), 'transaction.icon' => 'fa-thumbs-o-down', 'silly' => true, 'closed' => true, 'prefixes' => array( 'spite', 'spites', 'spited', ), 'suffixes' => array( 'out of spite', 'as spite', ), ), ); $status_description = $this->deformat(pht(<<<EOTEXT Allows you to edit, add, or remove the task statuses available in Maniphest, like "Open", "Resolved" and "Invalid". The configuration should contain a map of status constants to status specifications (see defaults below for examples). The constant for each status should be 1-12 characters long and contain only lowercase letters and digits. Valid examples are "open", "closed", and "invalid". Users will not normally see these values. The keys you can provide in a specification are: - `name` //Required string.// Name of the status, like "Invalid". - `name.full` //Optional string.// Longer name, like "Closed, Invalid". This appears on the task detail view in the header. - `name.action` //Optional string.// Action name for email subjects, like "Marked Invalid". - `closed` //Optional bool.// Statuses are either "open" or "closed". Specifying `true` here will mark the status as closed (like "Resolved" or "Invalid"). By default, statuses are open. - `special` //Optional string.// Mark this status as special. The special statuses are: - `default` This is the default status for newly created tasks. You must designate one status as default, and it must be an open status. - `closed` This is the default status for closed tasks (for example, tasks closed via the "!close" action in email or via the quick close button in Maniphest). You must designate one status as the default closed status, and it must be a closed status. - `duplicate` This is the status used when tasks are merged into one another as duplicates. You must designate one status for duplicates, and it must be a closed status. - `transaction.icon` //Optional string.// Allows you to choose a different icon to use for this status when showing status changes in the transaction log. Please see UIExamples, Icons and Images for a list. - `transaction.color` //Optional string.// Allows you to choose a different color to use for this status when showing status changes in the transaction log. - `silly` //Optional bool.// Marks this status as silly, and thus wholly inappropriate for use by serious businesses. - `prefixes` //Optional list<string>.// Allows you to specify a list of text prefixes which will trigger a task transition into this status when mentioned in a commit message. For example, providing "closes" here will allow users to move tasks to this status by writing `Closes T123` in commit messages. - `suffixes` //Optional list<string>.// Allows you to specify a list of text suffixes which will trigger a task transition into this status when mentioned in a commit message, after a valid prefix. For example, providing "as invalid" here will allow users to move tasks to this status by writing `Closes T123 as invalid`, even if another status is selected by the "Closes" prefix. - `keywords` //Optional list<string>.// Allows you to specify a list of keywords which can be used with `!status` commands in email to select this status. - `disabled` //Optional bool.// Marks this status as no longer in use so tasks can not be created or edited to have this status. Existing tasks with this status will not be affected, but you can batch edit them or let them die out on their own. Statuses will appear in the UI in the order specified. Note the status marked `special` as `duplicate` is not settable directly and will not appear in UI elements, and that any status marked `silly` does not appear if Phabricator is configured with `phabricator.serious-business` set to true. Examining the default configuration and examples below will probably be helpful in understanding these options. EOTEXT )); $status_example = array( 'open' => array( 'name' => pht('Open'), 'special' => 'default', ), 'closed' => array( 'name' => pht('Closed'), 'special' => 'closed', 'closed' => true, ), 'duplicate' => array( 'name' => pht('Duplicate'), 'special' => 'duplicate', 'closed' => true, ), ); $json = new PhutilJSON(); $status_example = $json->encodeFormatted($status_example); // This is intentionally blank for now, until we can move more Maniphest // logic to custom fields. $default_fields = array(); foreach ($default_fields as $key => $enabled) { $default_fields[$key] = array( 'disabled' => !$enabled, ); } $custom_field_type = 'custom:PhabricatorCustomFieldConfigOptionType'; $fields_example = array( 'mycompany.estimated-hours' => array( 'name' => pht('Estimated Hours'), 'type' => 'int', 'caption' => pht('Estimated number of hours this will take.'), ), ); $fields_json = id(new PhutilJSON())->encodeFormatted($fields_example); return array( $this->newOption('maniphest.custom-field-definitions', 'wild', array()) ->setSummary(pht('Custom Maniphest fields.')) ->setDescription( pht( 'Array of custom fields for Maniphest tasks. For details on '. 'adding custom fields to Maniphest, see "Configuring Custom '. 'Fields" in the documentation.')) ->addExample($fields_json, pht('Valid setting')), $this->newOption('maniphest.fields', $custom_field_type, $default_fields) ->setCustomData(id(new ManiphestTask())->getCustomFieldBaseClass()) ->setDescription(pht('Select and reorder task fields.')), $this->newOption( 'maniphest.priorities', $priority_type, $priority_defaults) ->setSummary(pht('Configure Maniphest priority names.')) ->setDescription( pht( 'Allows you to edit or override the default priorities available '. 'in Maniphest, like "High", "Normal" and "Low". The configuration '. 'should contain a map of priority constants to priority '. 'specifications (see defaults below for examples).'. "\n\n". 'The keys you can define for a priority are:'. "\n\n". ' - `name` Name of the priority.'."\n". ' - `short` Alternate shorter name, used in UIs where there is '. ' not much space available.'."\n". ' - `color` A color for this priority, like "red" or "blue".'. ' - `keywords` An optional list of keywords which can '. ' be used to select this priority when using `!priority` '. ' commands in email.'."\n". ' - `disabled` Optional boolean to prevent users from choosing '. ' this priority when creating or editing tasks. Existing '. ' tasks will be unaffected, and can be batch edited to a '. ' different priority or left to eventually die out.'. "\n\n". 'You can choose which priority is the default for newly created '. 'tasks with `%s`.', 'maniphest.default-priority')), $this->newOption('maniphest.statuses', $status_type, $status_defaults) ->setSummary(pht('Configure Maniphest task statuses.')) ->setDescription($status_description) ->addExample($status_example, pht('Minimal Valid Config')), $this->newOption('maniphest.default-priority', 'int', 90) ->setSummary(pht('Default task priority for create flows.')) ->setDescription( pht( 'Choose a default priority for newly created tasks. You can '. 'review and adjust available priorities by using the '. '%s configuration option. The default value (`90`) '. 'corresponds to the default "Needs Triage" priority.', 'maniphest.priorities')), $this->newOption( 'metamta.maniphest.subject-prefix', 'string', '[Maniphest]') ->setDescription(pht('Subject prefix for Maniphest mail.')), $this->newOption( 'maniphest.priorities.unbreak-now', 'int', 100) ->setSummary(pht('Priority used to populate "Unbreak Now" on home.')) ->setDescription( pht( 'Temporary setting. If set, this priority is used to populate the '. '"Unbreak Now" panel on the home page. You should adjust this if '. 'you adjust priorities using `%s`.', 'maniphest.priorities')), $this->newOption( 'maniphest.priorities.needs-triage', 'int', 90) ->setSummary(pht('Priority used to populate "Needs Triage" on home.')) ->setDescription( pht( 'Temporary setting. If set, this priority is used to populate the '. '"Needs Triage" panel on the home page. You should adjust this if '. 'you adjust priorities using `%s`.', 'maniphest.priorities')), ); } }
{ "content_hash": "5ab1aef01c3272f9f774f463e12726ca", "timestamp": "", "source": "github", "line_count": 343, "max_line_length": 80, "avg_line_length": 37.13411078717201, "alnum_prop": 0.5842035016094842, "repo_name": "AceMood/phabricator", "id": "a6f1cb79bf621321346dbb5d1dc2e0cf94520d45", "size": "12737", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/applications/maniphest/config/PhabricatorManiphestConfigOptions.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "160255" }, { "name": "CSS", "bytes": "316269" }, { "name": "Groff", "bytes": "30134" }, { "name": "JavaScript", "bytes": "816649" }, { "name": "Makefile", "bytes": "9933" }, { "name": "PHP", "bytes": "13411858" }, { "name": "Python", "bytes": "7385" }, { "name": "Shell", "bytes": "15980" } ], "symlink_target": "" }
<?php namespace Symfony\Component\Security\Guard\Firewall; use Psr\Log\LoggerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Guard\AuthenticatorInterface; use Symfony\Component\Security\Guard\GuardAuthenticatorHandler; use Symfony\Component\Security\Guard\Token\PreAuthenticationGuardToken; use Symfony\Component\Security\Http\Firewall\AbstractListener; use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface; /** * Authentication listener for the "guard" system. * * @author Ryan Weaver <ryan@knpuniversity.com> * @author Amaury Leroux de Lens <amaury@lerouxdelens.com> * * @final */ class GuardAuthenticationListener extends AbstractListener { private $guardHandler; private $authenticationManager; private $providerKey; private $guardAuthenticators; private $logger; private $rememberMeServices; /** * @param string $providerKey The provider (i.e. firewall) key * @param iterable|AuthenticatorInterface[] $guardAuthenticators The authenticators, with keys that match what's passed to GuardAuthenticationProvider */ public function __construct(GuardAuthenticatorHandler $guardHandler, AuthenticationManagerInterface $authenticationManager, string $providerKey, $guardAuthenticators, LoggerInterface $logger = null) { if (empty($providerKey)) { throw new \InvalidArgumentException('$providerKey must not be empty.'); } $this->guardHandler = $guardHandler; $this->authenticationManager = $authenticationManager; $this->providerKey = $providerKey; $this->guardAuthenticators = $guardAuthenticators; $this->logger = $logger; } /** * {@inheritdoc} */ public function supports(Request $request): ?bool { if (null !== $this->logger) { $context = ['firewall_key' => $this->providerKey]; if ($this->guardAuthenticators instanceof \Countable || \is_array($this->guardAuthenticators)) { $context['authenticators'] = \count($this->guardAuthenticators); } $this->logger->debug('Checking for guard authentication credentials.', $context); } $guardAuthenticators = []; foreach ($this->guardAuthenticators as $key => $guardAuthenticator) { if (null !== $this->logger) { $this->logger->debug('Checking support on guard authenticator.', ['firewall_key' => $this->providerKey, 'authenticator' => \get_class($guardAuthenticator)]); } if ($guardAuthenticator->supports($request)) { $guardAuthenticators[$key] = $guardAuthenticator; } elseif (null !== $this->logger) { $this->logger->debug('Guard authenticator does not support the request.', ['firewall_key' => $this->providerKey, 'authenticator' => \get_class($guardAuthenticator)]); } } if (!$guardAuthenticators) { return false; } $request->attributes->set('_guard_authenticators', $guardAuthenticators); return true; } /** * Iterates over each authenticator to see if each wants to authenticate the request. */ public function authenticate(RequestEvent $event) { $request = $event->getRequest(); $guardAuthenticators = $request->attributes->get('_guard_authenticators'); $request->attributes->remove('_guard_authenticators'); foreach ($guardAuthenticators as $key => $guardAuthenticator) { // get a key that's unique to *this* guard authenticator // this MUST be the same as GuardAuthenticationProvider $uniqueGuardKey = $this->providerKey.'_'.$key; $this->executeGuardAuthenticator($uniqueGuardKey, $guardAuthenticator, $event); if ($event->hasResponse()) { if (null !== $this->logger) { $this->logger->debug('The "{authenticator}" authenticator set the response. Any later authenticator will not be called', ['authenticator' => \get_class($guardAuthenticator)]); } break; } } } private function executeGuardAuthenticator(string $uniqueGuardKey, AuthenticatorInterface $guardAuthenticator, RequestEvent $event) { $request = $event->getRequest(); try { if (null !== $this->logger) { $this->logger->debug('Calling getCredentials() on guard authenticator.', ['firewall_key' => $this->providerKey, 'authenticator' => \get_class($guardAuthenticator)]); } // allow the authenticator to fetch authentication info from the request $credentials = $guardAuthenticator->getCredentials($request); if (null === $credentials) { throw new \UnexpectedValueException(sprintf('The return value of "%1$s::getCredentials()" must not be null. Return false from "%1$s::supports()" instead.', \get_class($guardAuthenticator))); } // create a token with the unique key, so that the provider knows which authenticator to use $token = new PreAuthenticationGuardToken($credentials, $uniqueGuardKey); if (null !== $this->logger) { $this->logger->debug('Passing guard token information to the GuardAuthenticationProvider', ['firewall_key' => $this->providerKey, 'authenticator' => \get_class($guardAuthenticator)]); } // pass the token into the AuthenticationManager system // this indirectly calls GuardAuthenticationProvider::authenticate() $token = $this->authenticationManager->authenticate($token); if (null !== $this->logger) { $this->logger->info('Guard authentication successful!', ['token' => $token, 'authenticator' => \get_class($guardAuthenticator)]); } // sets the token on the token storage, etc $this->guardHandler->authenticateWithToken($token, $request, $this->providerKey); } catch (AuthenticationException $e) { // oh no! Authentication failed! if (null !== $this->logger) { $this->logger->info('Guard authentication failed.', ['exception' => $e, 'authenticator' => \get_class($guardAuthenticator)]); } $response = $this->guardHandler->handleAuthenticationFailure($e, $request, $guardAuthenticator, $this->providerKey); if ($response instanceof Response) { $event->setResponse($response); } return; } // success! $response = $this->guardHandler->handleAuthenticationSuccess($token, $request, $guardAuthenticator, $this->providerKey); if ($response instanceof Response) { if (null !== $this->logger) { $this->logger->debug('Guard authenticator set success response.', ['response' => $response, 'authenticator' => \get_class($guardAuthenticator)]); } $event->setResponse($response); } else { if (null !== $this->logger) { $this->logger->debug('Guard authenticator set no success response: request continues.', ['authenticator' => \get_class($guardAuthenticator)]); } } // attempt to trigger the remember me functionality $this->triggerRememberMe($guardAuthenticator, $request, $token, $response); } /** * Should be called if this listener will support remember me. */ public function setRememberMeServices(RememberMeServicesInterface $rememberMeServices) { $this->rememberMeServices = $rememberMeServices; } /** * Checks to see if remember me is supported in the authenticator and * on the firewall. If it is, the RememberMeServicesInterface is notified. */ private function triggerRememberMe(AuthenticatorInterface $guardAuthenticator, Request $request, TokenInterface $token, Response $response = null) { if (null === $this->rememberMeServices) { if (null !== $this->logger) { $this->logger->debug('Remember me skipped: it is not configured for the firewall.', ['authenticator' => \get_class($guardAuthenticator)]); } return; } if (!$guardAuthenticator->supportsRememberMe()) { if (null !== $this->logger) { $this->logger->debug('Remember me skipped: your authenticator does not support it.', ['authenticator' => \get_class($guardAuthenticator)]); } return; } if (!$response instanceof Response) { throw new \LogicException(sprintf('%s::onAuthenticationSuccess *must* return a Response if you want to use the remember me functionality. Return a Response, or set remember_me to false under the guard configuration.', \get_class($guardAuthenticator))); } $this->rememberMeServices->loginSuccess($request, $response, $token); } }
{ "content_hash": "de7e4512324e29b7791609d2e04bb778", "timestamp": "", "source": "github", "line_count": 219, "max_line_length": 264, "avg_line_length": 43.141552511415526, "alnum_prop": 0.6399237933954276, "repo_name": "maidmaid/symfony", "id": "b9c984f21d3343c6d89ac3319b6d2ab7aca33a1d", "size": "9677", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Symfony/Component/Security/Guard/Firewall/GuardAuthenticationListener.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "49607" }, { "name": "HTML", "bytes": "356733" }, { "name": "Hack", "bytes": "26" }, { "name": "JavaScript", "bytes": "27650" }, { "name": "PHP", "bytes": "18475251" }, { "name": "Shell", "bytes": "3136" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <title>ParameterEncoding Protocol Reference</title> <link rel="stylesheet" type="text/css" href="../css/jazzy.css" /> <link rel="stylesheet" type="text/css" href="../css/highlight.css" /> <meta charset="utf-8"> <script src="../js/jquery.min.js" defer></script> <script src="../js/jazzy.js" defer></script> <script src="../js/lunr.min.js" defer></script> <script src="../js/typeahead.jquery.js" defer></script> <script src="../js/jazzy.search.js" defer></script> </head> <body> <a name="//apple_ref/swift/Protocol/ParameterEncoding" class="dashAnchor"></a> <a title="ParameterEncoding Protocol Reference"></a> <header class="header"> <p class="header-col header-col--primary"> <a class="header-link" href="../index.html"> Alamofire 5.4.0 Docs </a> (97% documented) </p> <p class="header-col--secondary"> <form role="search" action="../search.json"> <input type="text" placeholder="Search documentation" data-typeahead> </form> </p> <p class="header-col header-col--secondary"> <a class="header-link" href="https://github.com/Alamofire/Alamofire"> <img class="header-icon" src="../img/gh.png"/> View on GitHub </a> </p> <p class="header-col header-col--secondary"> <a class="header-link" href="dash-feed://https%3A%2F%2Falamofire.github.io%2FAlamofire%2Fdocsets%2FAlamofire.xml"> <img class="header-icon" src="../img/dash.png"/> Install in Dash </a> </p> </header> <p class="breadcrumbs"> <a class="breadcrumb" href="../index.html">Alamofire Reference</a> <img class="carat" src="../img/carat.png" /> ParameterEncoding Protocol Reference </p> <div class="content-wrapper"> <nav class="navigation"> <ul class="nav-groups"> <li class="nav-group-name"> <a class="nav-group-name-link" href="../Classes.html">Classes</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/Adapter.html">Adapter</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/AlamofireNotifications.html">AlamofireNotifications</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/AuthenticationInterceptor.html">AuthenticationInterceptor</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/AuthenticationInterceptor/RefreshWindow.html">– RefreshWindow</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/ClosureEventMonitor.html">ClosureEventMonitor</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/CompositeEventMonitor.html">CompositeEventMonitor</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/CompositeTrustEvaluator.html">CompositeTrustEvaluator</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/ConnectionLostRetryPolicy.html">ConnectionLostRetryPolicy</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/DataRequest.html">DataRequest</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/DataResponseSerializer.html">DataResponseSerializer</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/DataStreamRequest.html">DataStreamRequest</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/DataStreamRequest/Stream.html">– Stream</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/DataStreamRequest/Event.html">– Event</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/DataStreamRequest/Completion.html">– Completion</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/DataStreamRequest/CancellationToken.html">– CancellationToken</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/DecodableResponseSerializer.html">DecodableResponseSerializer</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/DefaultTrustEvaluator.html">DefaultTrustEvaluator</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/DisabledTrustEvaluator.html">DisabledTrustEvaluator</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/DownloadRequest.html">DownloadRequest</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/DownloadRequest/Options.html">– Options</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/DownloadRequest/Downloadable.html">– Downloadable</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/Interceptor.html">Interceptor</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/JSONParameterEncoder.html">JSONParameterEncoder</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/JSONResponseSerializer.html">JSONResponseSerializer</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/MultipartFormData.html">MultipartFormData</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/NetworkReachabilityManager.html">NetworkReachabilityManager</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/NetworkReachabilityManager/NetworkReachabilityStatus.html">– NetworkReachabilityStatus</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/PinnedCertificatesTrustEvaluator.html">PinnedCertificatesTrustEvaluator</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/PublicKeysTrustEvaluator.html">PublicKeysTrustEvaluator</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/Request.html">Request</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/Request/State.html">– State</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/Retrier.html">Retrier</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/RetryPolicy.html">RetryPolicy</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/RevocationTrustEvaluator.html">RevocationTrustEvaluator</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/RevocationTrustEvaluator/Options.html">– Options</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/ServerTrustManager.html">ServerTrustManager</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/Session.html">Session</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/SessionDelegate.html">SessionDelegate</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/StringResponseSerializer.html">StringResponseSerializer</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/URLEncodedFormEncoder.html">URLEncodedFormEncoder</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/URLEncodedFormEncoder/ArrayEncoding.html">– ArrayEncoding</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/URLEncodedFormEncoder/BoolEncoding.html">– BoolEncoding</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/URLEncodedFormEncoder/DataEncoding.html">– DataEncoding</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/URLEncodedFormEncoder/DateEncoding.html">– DateEncoding</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/URLEncodedFormEncoder/KeyEncoding.html">– KeyEncoding</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/URLEncodedFormEncoder/SpaceEncoding.html">– SpaceEncoding</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/URLEncodedFormEncoder/Error.html">– Error</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/URLEncodedFormParameterEncoder.html">URLEncodedFormParameterEncoder</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/URLEncodedFormParameterEncoder/Destination.html">– Destination</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/UploadRequest.html">UploadRequest</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/UploadRequest/Uploadable.html">– Uploadable</a> </li> </ul> </li> <li class="nav-group-name"> <a class="nav-group-name-link" href="../Global%20Variables.html">Global Variables</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Global%20Variables.html#/s:9Alamofire2AFAA7SessionCvp">AF</a> </li> </ul> </li> <li class="nav-group-name"> <a class="nav-group-name-link" href="../Enums.html">Enumerations</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/AFError.html">AFError</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/AFError/MultipartEncodingFailureReason.html">– MultipartEncodingFailureReason</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/AFError/ParameterEncodingFailureReason.html">– ParameterEncodingFailureReason</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/AFError/ParameterEncoderFailureReason.html">– ParameterEncoderFailureReason</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/AFError/ResponseValidationFailureReason.html">– ResponseValidationFailureReason</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/AFError/ResponseSerializationFailureReason.html">– ResponseSerializationFailureReason</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/AFError/ServerTrustFailureReason.html">– ServerTrustFailureReason</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/AFError/URLRequestValidationFailureReason.html">– URLRequestValidationFailureReason</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/AuthenticationError.html">AuthenticationError</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/RetryResult.html">RetryResult</a> </li> </ul> </li> <li class="nav-group-name"> <a class="nav-group-name-link" href="../Extensions.html">Extensions</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions/Array.html">Array</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions.html#/c:objc(cs)NSBundle">Bundle</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions/CharacterSet.html">CharacterSet</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions/Error.html">Error</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions/HTTPURLResponse.html">HTTPURLResponse</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions.html#/s:10Foundation11JSONDecoderC">JSONDecoder</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions/Notification.html">Notification</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions.html#/c:@T@OSStatus">OSStatus</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions.html#/s:10Foundation19PropertyListDecoderC">PropertyListDecoder</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions.html#/c:@T@SecCertificateRef">SecCertificate</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions.html#/c:@T@SecPolicyRef">SecPolicy</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions.html#/c:@T@SecTrustRef">SecTrust</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions.html#/c:@E@SecTrustResultType">SecTrustResultType</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions/String.html">String</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions/URL.html">URL</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions/URLComponents.html">URLComponents</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions/URLRequest.html">URLRequest</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions/URLSessionConfiguration.html">URLSessionConfiguration</a> </li> </ul> </li> <li class="nav-group-name"> <a class="nav-group-name-link" href="../Protocols.html">Protocols</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/AlamofireExtended.html">AlamofireExtended</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/AuthenticationCredential.html">AuthenticationCredential</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/Authenticator.html">Authenticator</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/CachedResponseHandler.html">CachedResponseHandler</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/DataDecoder.html">DataDecoder</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/DataPreprocessor.html">DataPreprocessor</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/DataResponseSerializerProtocol.html">DataResponseSerializerProtocol</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/DataStreamSerializer.html">DataStreamSerializer</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/DownloadResponseSerializerProtocol.html">DownloadResponseSerializerProtocol</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/EmptyResponse.html">EmptyResponse</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/EventMonitor.html">EventMonitor</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/ParameterEncoder.html">ParameterEncoder</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/ParameterEncoding.html">ParameterEncoding</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/RedirectHandler.html">RedirectHandler</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/RequestAdapter.html">RequestAdapter</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/RequestDelegate.html">RequestDelegate</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/RequestInterceptor.html">RequestInterceptor</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/RequestRetrier.html">RequestRetrier</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/ResponseSerializer.html">ResponseSerializer</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/ServerTrustEvaluating.html">ServerTrustEvaluating</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/URLConvertible.html">URLConvertible</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/URLRequestConvertible.html">URLRequestConvertible</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols.html#/s:9Alamofire17UploadConvertibleP">UploadConvertible</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/UploadableConvertible.html">UploadableConvertible</a> </li> </ul> </li> <li class="nav-group-name"> <a class="nav-group-name-link" href="../Structs.html">Structures</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/AlamofireExtension.html">AlamofireExtension</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/DataResponse.html">DataResponse</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/DataResponsePublisher.html">DataResponsePublisher</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/DataStreamPublisher.html">DataStreamPublisher</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/DecodableStreamSerializer.html">DecodableStreamSerializer</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/DownloadResponse.html">DownloadResponse</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/DownloadResponsePublisher.html">DownloadResponsePublisher</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/Empty.html">Empty</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/GoogleXSSIPreprocessor.html">GoogleXSSIPreprocessor</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/HTTPHeader.html">HTTPHeader</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/HTTPHeaders.html">HTTPHeaders</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/HTTPMethod.html">HTTPMethod</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/JSONEncoding.html">JSONEncoding</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/PassthroughPreprocessor.html">PassthroughPreprocessor</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/PassthroughStreamSerializer.html">PassthroughStreamSerializer</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/Redirector.html">Redirector</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/Redirector/Behavior.html">– Behavior</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/ResponseCacher.html">ResponseCacher</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/ResponseCacher/Behavior.html">– Behavior</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/StringStreamSerializer.html">StringStreamSerializer</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/URLEncoding.html">URLEncoding</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/URLEncoding/Destination.html">– Destination</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/URLEncoding/ArrayEncoding.html">– ArrayEncoding</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/URLEncoding/BoolEncoding.html">– BoolEncoding</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Structs/URLResponseSerializer.html">URLResponseSerializer</a> </li> </ul> </li> <li class="nav-group-name"> <a class="nav-group-name-link" href="../Typealiases.html">Type Aliases</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:9Alamofire14AFDataResponsea">AFDataResponse</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:9Alamofire18AFDownloadResponsea">AFDownloadResponse</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:9Alamofire8AFResulta">AFResult</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:9Alamofire12AdaptHandlera">AdaptHandler</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:9Alamofire17DisabledEvaluatora">DisabledEvaluator</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:9Alamofire10Parametersa">Parameters</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:9Alamofire12RetryHandlera">RetryHandler</a> </li> </ul> </li> </ul> </nav> <article class="main-content"> <section class="section"> <div class="section-content top-matter"> <h1>ParameterEncoding</h1> <div class="declaration"> <div class="language"> <pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">protocol</span> <span class="kt">ParameterEncoding</span></code></pre> </div> </div> <p>A type used to define how a set of parameters are applied to a <code>URLRequest</code>.</p> </div> </section> <section class="section"> <div class="section-content"> <div class="task-group"> <ul class="item-container"> <li class="item"> <div> <code> <a name="/s:9Alamofire17ParameterEncodingP6encode_4with10Foundation10URLRequestVAA0G11Convertible_p_SDySSypGSgtKF"></a> <a name="//apple_ref/swift/Method/encode(_:with:)" class="dashAnchor"></a> <a class="token" href="#/s:9Alamofire17ParameterEncodingP6encode_4with10Foundation10URLRequestVAA0G11Convertible_p_SDySSypGSgtKF">encode(_:<wbr>with:<wbr>)</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Creates a <code>URLRequest</code> by encoding parameters and applying them on the passed request.</p> <div class="aside aside-throws"> <p class="aside-title">Throws</p> <p>Any <code>Error</code> produced during parameter encoding.</p> </div> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">func</span> <span class="nf">encode</span><span class="p">(</span><span class="n">_</span> <span class="nv">urlRequest</span><span class="p">:</span> <span class="kt"><a href="../Protocols/URLRequestConvertible.html">URLRequestConvertible</a></span><span class="p">,</span> <span class="n">with</span> <span class="nv">parameters</span><span class="p">:</span> <span class="kt"><a href="../Typealiases.html#/s:9Alamofire10Parametersa">Parameters</a></span><span class="p">?)</span> <span class="k">throws</span> <span class="o">-&gt;</span> <span class="kt">URLRequest</span></code></pre> </div> </div> <div> <h4>Parameters</h4> <table class="graybox"> <tbody> <tr> <td> <code> <em>urlRequest</em> </code> </td> <td> <div> <p><code><a href="../Protocols/URLRequestConvertible.html">URLRequestConvertible</a></code> value onto which parameters will be encoded.</p> </div> </td> </tr> <tr> <td> <code> <em>parameters</em> </code> </td> <td> <div> <p><code><a href="../Typealiases.html#/s:9Alamofire10Parametersa">Parameters</a></code> to encode onto the request.</p> </div> </td> </tr> </tbody> </table> </div> <div> <h4>Return Value</h4> <p>The encoded <code>URLRequest</code>.</p> </div> </section> </div> </li> </ul> </div> </div> </section> </article> </div> <section class="footer"> <p>&copy; 2020 <a class="link" href="http://alamofire.org/" target="_blank" rel="external">Alamofire Software Foundation</a>. All rights reserved. (Last updated: 2020-12-20)</p> <p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy ♪♫ v0.13.6</a>, a <a class="link" href="https://realm.io" target="_blank" rel="external">Realm</a> project.</p> </section> </body> </div> </html>
{ "content_hash": "f38d2573b78ac83f8e2d68fc8582c0f1", "timestamp": "", "source": "github", "line_count": 605, "max_line_length": 666, "avg_line_length": 53.707438016528926, "alnum_prop": 0.5294371095312836, "repo_name": "antigp/Alamofire", "id": "24bb3aa385977d5016aa84825e472460d3a7c070", "size": "32559", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/Protocols/ParameterEncoding.html", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "1297" }, { "name": "Ruby", "bytes": "517" }, { "name": "Swift", "bytes": "131789" } ], "symlink_target": "" }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; using Microsoft.Azure.Test.HttpRecorder; using System; using System.Linq; using System.Collections.Generic; using System.Globalization; using Xunit; namespace Sql.Tests { public class ImportExportScenarioTests { [Fact] public void TestImportExistingDatabase() { string testPrefix = "sqlcrudtest-"; TestImportExport(true, testPrefix, "TestImportExistingDatabase"); } [Fact] public void TestImportNewDatabase() { string testPrefix = "sqlcrudtest-"; TestImportExport(false, testPrefix, "TestImportNewDatabase"); } public void TestImportExport(bool preexistingDatabase, string testPrefix, string testName) { string suiteName = this.GetType().FullName; SqlManagementTestUtilities.RunTestInNewV12Server(suiteName, testName, testPrefix, (resClient, sqlClient, resourceGroup, server) => { string serverNameV12 = SqlManagementTestUtilities.GenerateName(testPrefix); string login = "dummylogin"; string password = "Un53cuRE!"; string version12 = "12.0"; string dbName = SqlManagementTestUtilities.GenerateName(testPrefix); string dbName2 = SqlManagementTestUtilities.GenerateName(testPrefix); string storageAccountName = SqlManagementTestUtilities.GenerateName("sqlcrudstorage"); Dictionary<string, string> tags = new Dictionary<string, string>() { { "tagKey1", "TagValue1" } }; // set server firewall rule sqlClient.FirewallRules.CreateOrUpdate(resourceGroup.Name, server.Name, SqlManagementTestUtilities.GenerateName(testPrefix), new FirewallRule() { StartIpAddress = "0.0.0.0", EndIpAddress = "255.255.255.255" }); // Create 1 or 2 databases sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, new Database() { Location = server.Location }); if (preexistingDatabase) { sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName2, new Database() { Location = server.Location }); // Verify existence of new database Assert.NotNull(sqlClient.Databases.Get(resourceGroup.Name, server.Name, dbName2)); } // Get Storage container credentials HttpRecorderMode testMode = HttpMockServer.GetCurrentMode(); string storageKey = "StorageKey"; string storageKeyType = "StorageAccessKey"; string exportBacpacLink = string.Format(CultureInfo.InvariantCulture, "http://test.blob.core.windows.net/databases/{0}.bacpac", dbName); if (testMode == HttpRecorderMode.Record) { string importBacpacContainer = Environment.GetEnvironmentVariable("TEST_IMPORT_CONTAINER"); storageKey = Environment.GetEnvironmentVariable("TEST_STORAGE_KEY"); exportBacpacLink = string.Format(CultureInfo.InvariantCulture, "{0}/{1}.bacpac", importBacpacContainer, dbName); Assert.False(string.IsNullOrWhiteSpace(storageKey), "Environment variable TEST_STORAGE_KEY has not been set. Set it to storage account key."); Assert.False(string.IsNullOrWhiteSpace(importBacpacContainer), "Environment variable TEST_IMPORT_CONTAINER has not been set. Set it to a valid storage container URL."); } // Export database to bacpac sqlClient.Databases.Export(resourceGroup.Name, server.Name, dbName, new ExportRequest() { AdministratorLogin = login, AdministratorLoginPassword = password, AuthenticationType = AuthenticationType.SQL, StorageKey = storageKey, StorageKeyType = StorageKeyType.StorageAccessKey, StorageUri = exportBacpacLink }); // Import bacpac to new/existing database if (preexistingDatabase) { // Import bacpac to existing database sqlClient.Databases.CreateImportOperation(resourceGroup.Name, server.Name, dbName2, new ImportExtensionRequest() { AdministratorLogin = login, AdministratorLoginPassword = password, AuthenticationType = AuthenticationType.SQL, StorageKey = storageKey, StorageKeyType = StorageKeyType.StorageAccessKey, StorageUri = exportBacpacLink }); } else { sqlClient.Databases.Import(resourceGroup.Name, server.Name, new ImportRequest() { AdministratorLogin = login, AdministratorLoginPassword = password, AuthenticationType = AuthenticationType.SQL, StorageKey = storageKey, StorageKeyType = StorageKeyType.StorageAccessKey, StorageUri = exportBacpacLink, DatabaseName = dbName2, Edition = SqlTestConstants.DefaultDatabaseEdition, ServiceObjectiveName = ServiceObjectiveName.Basic, MaxSizeBytes = (2 * 1024L * 1024L * 1024L).ToString(), }); } }); } } }
{ "content_hash": "35f5d4e9fd091024db297abdf2cabbc3", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 189, "avg_line_length": 47.12781954887218, "alnum_prop": 0.5741863433312061, "repo_name": "JasonYang-MSFT/azure-sdk-for-net", "id": "ee8fa1b0164f8dbd5ba062f606d8635072609ffc", "size": "6270", "binary": false, "copies": "6", "ref": "refs/heads/vs17Dev", "path": "src/SDKs/SqlManagement/Sql.Tests/ImportExportScenarioTests.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "118" }, { "name": "Batchfile", "bytes": "33797" }, { "name": "C#", "bytes": "49260345" }, { "name": "CSS", "bytes": "685" }, { "name": "JavaScript", "bytes": "7875" }, { "name": "PowerShell", "bytes": "24250" }, { "name": "Shell", "bytes": "20492" }, { "name": "XSLT", "bytes": "6114" } ], "symlink_target": "" }
from yapsy.IPlugin import IPlugin from logbook.Importer import Plugin from messages import TimeSeriesData,TimeSeriesMetaData,LogMetaData,UIData,TimeSeries from sqlalchemy import * import logging from tools.profiling import timing from PyQt5.QtWidgets import QLabel, QFormLayout, QLineEdit class Swimming(IPlugin,Plugin): def __init__(self,log_name=None,metadata=None): self._actions=['import'] self._type=['swimming'] self.logging = logging.getLogger(__name__) self._filename = log_name self.file_table = None if metadata: self._metadata = LogMetaData(file_hash=metadata.file_hash, date=metadata.creation_date, name=metadata.event_name, maintype=metadata.event_type, subtype=metadata.event_subtype ) self._formdata = [] self._formdata.append(TimeSeriesMetaData("Lap length",0,"m")) self._formdata.append(TimeSeriesMetaData("Total Length",0,"m")) self._formdata.append(TimeSeriesMetaData("Time per 100m","%.1f" %0,"s")) self._formdata.append(TimeSeriesMetaData("average speed","%.1f" %0,"m/s")) self._formdata.append(TimeSeriesMetaData("Total calories",0,"kcal")) self._formdata.append(TimeSeriesMetaData("Event duration","%.1f" %0,"min")) def open_logbook(self,filename): self._filename = filename self._alchemy_logbook = create_engine('sqlite:///'+self._filename) _metadata = MetaData(bind=self._alchemy_logbook) self.file_table = Table('file', _metadata, autoload=True) self.swim_table = Table("event_swimming",_metadata, Column('event_swimming_id',Integer,primary_key=True), Column('f_id',Integer,ForeignKey("file.file_id"), nullable=False), Column('timestamp',DateTime), Column('start_time',DateTime), Column('swim_stroke',String(30)), Column('total_calories',Integer), Column('total_elapsed_time',Float), Column('total_strokes',Integer), Column('distance',Integer) ) self.swim_table.create(checkfirst=True) @timing def import_fit(self,fitfile=None): stmt = self.file_table.select(self.file_table.c.file_hash==fitfile.digest) row = stmt.execute().fetchone() file_id = row.file_id for record in fitfile.get_messages(["length"]): event_timestamp = None start_time = None swim_stroke = None total_calories = None total_elapsed_time = None total_strokes = None distance=None data = [] fields=0 for record_data in record: if record_data.name == "timestamp": event_timestamp = record_data.value fields +=1 if record_data.name =="start_time": start_time = record_data.value fields +=1 if record_data.name == "swim_stroke": swim_stroke = record_data.value fields +=1 if record_data.name == "total_calories": total_calories = record_data.value fields +=1 if record_data.name == "total_strokes": total_strokes = record_data.value fields +=1 if record_data.name == "total_elapsed_time": total_elapsed_time = record_data.value fields +=1 if fields == 6: data.append({'f_id':file_id,'timestamp':event_timestamp, 'start_time':start_time,'swim_stroke':swim_stroke, 'total_calories':total_calories,'total_elapsed_time':total_elapsed_time, 'total_strokes':total_strokes}) self._alchemy_logbook.execute(self.swim_table.insert(),data) data=[] for record in fitfile.get_messages(["record"]): event_timestamp = None distance = None for record_data in record: if record_data.name == "timestamp": event_timestamp = record_data.value if record_data.name == "distance": distance = record_data.value if event_timestamp and distance: data.append({'evtimestamp':event_timestamp,'distance':distance}) stmt = self.swim_table.update().\ where(self.swim_table.c.timestamp==bindparam('evtimestamp')).\ values(distance=bindparam('distance')) self._alchemy_logbook.execute(stmt,data) @timing def get_data(self,filehash): s = self.swim_table.join(self.file_table).\ select().where(self.file_table.c.file_hash==filehash) strokes_data = TimeSeriesData(name="strokes" ,labels=[],data=[],unit=None,xlabel="duration(min)") avg_strokes = TimeSeriesData(name="avg strokes",labels=[],data=[],unit="Strokes/lap",xlabel="duration(min)") calories_data = TimeSeriesData(name="calories",labels=[],data=[],unit=None,xlabel="duration(min)") speed_data = TimeSeriesData(name="speed" ,labels=[],data=[],unit="min/100m",xlabel="duration(min)") rows = 0 total_calories = 0 event_duration = 0 strokes_data.data.append(0) strokes_data.labels.append(0) avg_strokes.data.append(0) avg_strokes.labels.append(0) calories_data.data.append(0) calories_data.labels.append(0) speed_data.data.append(0) speed_data.labels.append(0) stro = 0 last_ts = 0 row = None for row in self._alchemy_logbook.execute(s): if row.total_strokes and row.distance and row.total_calories and row.total_elapsed_time: rows = rows + 1 if last_ts == 0: last_ts = row.timestamp ts = ((row.timestamp-last_ts).seconds/60) strokes_data.data.append(row.total_strokes) strokes_data.labels.append(ts) # strokes_data.labels.append(row.distance) stro = stro + row.total_strokes avg_strokes.data.append((stro/row.distance)*50) avg_strokes.labels.append(ts) # avg_strokes.labels.append(row.distance) calories_data.data.append(row.total_calories) calories_data.labels.append(ts) # calories_data.labels.append(row.distance) speed_data.data.append(((row.total_elapsed_time/50)*100)/60) #FIXME speed_data.labels.append(ts) # speed_data.labels.append(row.distance) total_calories = total_calories + row.total_calories event_duration = event_duration + row.total_elapsed_time if row: lap_distance = int(row.distance / rows) total_length = row.distance total_time = row.start_time self._data = [strokes_data,calories_data,speed_data,avg_strokes] time_per_hundred = (100/lap_distance)*(event_duration/lap_distance) formdata = [] formdata.append(TimeSeriesMetaData("Lap length",lap_distance,"m")) formdata.append(TimeSeriesMetaData("Total Length",total_length,"m")) formdata.append(TimeSeriesMetaData("Time per 100m","%.1f" %time_per_hundred,"s")) formdata.append(TimeSeriesMetaData("average speed","%.1f" %(total_length/event_duration),"m/s")) formdata.append(TimeSeriesMetaData("Total calories",total_calories,"kcal")) formdata.append(TimeSeriesMetaData("Event duration","%.1f" %(event_duration/60),"min")) return TimeSeries(data=self._data,metadata=formdata) @property def ui(self): layout = QFormLayout() labels=[] fields=[] if self._formdata: for i in range(len(self._formdata)): labels.append(QLabel(self._formdata[i].name+" ("+self._formdata[i].unit+")")) fields.append(QLineEdit(str(self._formdata[i].value))) layout.addRow(labels[-1], fields[-1]) return UIData(ui=layout,labels=labels,fields=fields)
{ "content_hash": "871da583e7ee588996c5c3ddd086829a", "timestamp": "", "source": "github", "line_count": 216, "max_line_length": 118, "avg_line_length": 43.33796296296296, "alnum_prop": 0.516718299326995, "repo_name": "romses/FitView", "id": "b91d249b7244981c0a637c3ad04b0ae685fc7620", "size": "9361", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "logbook/Importer/swimming.py", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "Python", "bytes": "499695" } ], "symlink_target": "" }
define :user_ulimit, :filehandle_limit => nil, :process_limit => nil, :memory_limit => nil do template "/etc/security/limits.d/#{params[:name]}_limits.conf" do source "ulimit.erb" cookbook "ulimit" owner "root" group "root" mode 0644 variables( :ulimit_user => params[:name], :filehandle_limit => params[:filehandle_limit], :process_limit => params[:process_limit], :memory_limit => params[:memory_limit] ) end end
{ "content_hash": "9fdb7682fc25f88ea9de8242bdc86fe0", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 93, "avg_line_length": 31.4, "alnum_prop": 0.6305732484076433, "repo_name": "citrusoft/chef-repo", "id": "b45731075256c8e1700d122e51a157df2ef626e0", "size": "643", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "cookbooks/ulimit/definitions/user_ulimit.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "184" }, { "name": "Perl", "bytes": "848" }, { "name": "Ruby", "bytes": "281044" } ], "symlink_target": "" }
using System; using Mono.Debugging.Client; namespace Mono.Debugging.Backend { public interface IRawValueArray: IDebuggerBackendObject { object GetValue (int[] index); Array GetValues (int[] index, int count); void SetValue (int[] index, object value); int[] Dimensions { get; } Array ToArray (); } }
{ "content_hash": "c8ecb5fc5f564ea99a4cf77744f7955e", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 56, "avg_line_length": 22.428571428571427, "alnum_prop": 0.7197452229299363, "repo_name": "joj/debugger-libs", "id": "d963e740906225163974f498ae680dc6e8fc7f39", "size": "1509", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "Mono.Debugging/Mono.Debugging.Backend/IRawValueArray.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "2174189" }, { "name": "Makefile", "bytes": "173" }, { "name": "Shell", "bytes": "319" } ], "symlink_target": "" }
<?php if ( ! defined( 'ABSPATH' ) ) { die( '-1' ); } return array( 'name' => __( 'Posts Slider', 'js_composer' ), 'base' => 'vc_posts_slider', 'icon' => 'icon-wpb-slideshow', 'category' => __( 'Content', 'js_composer' ), 'description' => __( 'Slider with WP Posts', 'js_composer' ), 'params' => array( array( 'type' => 'textfield', 'heading' => __( 'Widget title', 'js_composer' ), 'param_name' => 'title', 'description' => __( 'Enter text used as widget title (Note: located above content element).', 'js_composer' ), ), array( 'type' => 'dropdown', 'heading' => __( 'Slider type', 'js_composer' ), 'param_name' => 'type', 'admin_label' => true, 'value' => array( __( 'Flex slider fade', 'js_composer' ) => 'flexslider_fade', __( 'Flex slider slide', 'js_composer' ) => 'flexslider_slide', __( 'Nivo slider', 'js_composer' ) => 'nivo', ), 'description' => __( 'Select slider type.', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => __( 'Slider count', 'js_composer' ), 'param_name' => 'count', 'value' => 3, 'description' => __( 'Enter number of slides to display (Note: Enter "All" to display all slides).', 'js_composer' ), ), array( 'type' => 'dropdown', 'heading' => __( 'Auto rotate', 'js_composer' ), 'param_name' => 'interval', 'value' => array( 3, 5, 10, 15, __( 'Disable', 'js_composer' ) => 0, ), 'description' => __( 'Auto rotate slides each X seconds.', 'js_composer' ), ), array( 'type' => 'posttypes', 'heading' => __( 'Post types', 'js_composer' ), 'param_name' => 'posttypes', 'description' => __( 'Select source for slider.', 'js_composer' ), ), array( 'type' => 'dropdown', 'heading' => __( 'Description', 'js_composer' ), 'param_name' => 'slides_content', 'value' => array( __( 'No description', 'js_composer' ) => '', __( 'Teaser (Excerpt)', 'js_composer' ) => 'teaser', ), 'description' => __( 'Select source to use for description (Note: some sliders do not support it).', 'js_composer' ), 'dependency' => array( 'element' => 'type', 'value' => array( 'flexslider_fade', 'flexslider_slide', ), ), ), array( 'type' => 'checkbox', 'heading' => __( 'Output post title?', 'js_composer' ), 'param_name' => 'slides_title', 'description' => __( 'If selected, title will be printed before the teaser text.', 'js_composer' ), 'value' => array( __( 'Yes', 'js_composer' ) => true ), 'dependency' => array( 'element' => 'slides_content', 'value' => array( 'teaser' ), ), ), array( 'type' => 'dropdown', 'heading' => __( 'Link', 'js_composer' ), 'param_name' => 'link', 'value' => array( __( 'Link to post', 'js_composer' ) => 'link_post', __( 'Link to bigger image', 'js_composer' ) => 'link_image', __( 'Open custom links', 'js_composer' ) => 'custom_link', __( 'No link', 'js_composer' ) => 'link_no', ), 'description' => __( 'Link type.', 'js_composer' ), ), array( 'type' => 'exploded_textarea_safe', 'heading' => __( 'Custom links', 'js_composer' ), 'param_name' => 'custom_links', 'value' => site_url() . '/', 'dependency' => array( 'element' => 'link', 'value' => 'custom_link', ), 'description' => __( 'Enter links for each slide here. Divide links with linebreaks (Enter).', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => __( 'Thumbnail size', 'js_composer' ), 'param_name' => 'thumb_size', 'value' => 'medium', 'description' => __( 'Enter thumbnail size. Example: thumbnail, medium, large, full or other sizes defined by current theme. Alternatively enter image size in pixels: 200x100 (Width x Height) . ', 'js_composer' ), ), array( 'type' => 'textfield', 'heading' => __( 'Post/Page IDs', 'js_composer' ), 'param_name' => 'posts_in', 'description' => __( 'Enter page/posts IDs to display only those records (Note: separate values by commas (,)). Use this field in conjunction with "Post types" field.', 'js_composer' ), ), array( 'type' => 'exploded_textarea_safe', 'heading' => __( 'Categories', 'js_composer' ), 'param_name' => 'categories', 'description' => __( 'Enter categories by names to narrow output (Note: only listed categories will be displayed, divide categories with linebreak (Enter)).', 'js_composer' ), ), array( 'type' => 'dropdown', 'heading' => __( 'Order by', 'js_composer' ), 'param_name' => 'orderby', 'value' => array( '', __( 'Date', 'js_composer' ) => 'date', __( 'ID', 'js_composer' ) => 'ID', __( 'Author', 'js_composer' ) => 'author', __( 'Title', 'js_composer' ) => 'title', __( 'Modified', 'js_composer' ) => 'modified', __( 'Random', 'js_composer' ) => 'rand', __( 'Comment count', 'js_composer' ) => 'comment_count', __( 'Menu order', 'js_composer' ) => 'menu_order', ), 'description' => sprintf( __( 'Select how to sort retrieved posts. More at %s.', 'js_composer' ), '<a href="http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'dropdown', 'heading' => __( 'Sort order', 'js_composer' ), 'param_name' => 'order', 'value' => array( __( 'Descending', 'js_composer' ) => 'DESC', __( 'Ascending', 'js_composer' ) => 'ASC', ), 'description' => sprintf( __( 'Select ascending or descending order. More at %s.', 'js_composer' ), '<a href="http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters" target="_blank">WordPress codex page</a>' ), ), array( 'type' => 'textfield', 'heading' => __( 'Extra class name', 'js_composer' ), 'param_name' => 'el_class', 'description' => __( 'Style particular content element differently - add a class name and refer to it in custom CSS.', 'js_composer' ), ), array( 'type' => 'css_editor', 'heading' => __( 'CSS box', 'js_composer' ), 'param_name' => 'css', 'group' => __( 'Design Options', 'js_composer' ), ), ), );
{ "content_hash": "6ca9e1d3c1f341161f5953305b01e47b", "timestamp": "", "source": "github", "line_count": 167, "max_line_length": 239, "avg_line_length": 36.70059880239521, "alnum_prop": 0.5545766030347529, "repo_name": "chrispydizzle/miklas-alive", "id": "c7107200394347993d95ca33bee8831bbb413f0b", "size": "6129", "binary": false, "copies": "10", "ref": "refs/heads/master", "path": "plugins/js_composer/config/content/shortcode-vc-posts-slider.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "629" }, { "name": "CSS", "bytes": "1725299" }, { "name": "HTML", "bytes": "53281" }, { "name": "JavaScript", "bytes": "991330" }, { "name": "PHP", "bytes": "8385658" }, { "name": "Shell", "bytes": "513" }, { "name": "Smarty", "bytes": "33" } ], "symlink_target": "" }
import unittest from framework import TestCase from earth.category import Category class TestCategoryCase(TestCase): def test_category(self): # ADD ctg_name = '社区' ctg = Category.add(name=ctg_name) assert ctg.id assert ctg.name == ctg_name assert ctg.pid == None # UPDATE ctg_movie = Category.add(name='电影社区', pid=ctg.id) assert ctg_movie.pid == ctg.id new_pid = 3 other_name = '其他社区' ctg_movie.pid = 3 ctg_movie.name = other_name ctg_movie.update() ctg_get = Category.get_by_name(other_name) assert ctg_get.id == ctg_movie.id assert ctg_get.name == other_name if __name__ == '__main__': unittest.main()
{ "content_hash": "11b2e17b688bcbf3baa6e3f335100820", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 57, "avg_line_length": 22.939393939393938, "alnum_prop": 0.5772787318361955, "repo_name": "tottily/terabithia", "id": "f7a953bf9a4231184e7d491d942a955786ec9db0", "size": "802", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "monster/test_category.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "4364" }, { "name": "Python", "bytes": "17015" } ], "symlink_target": "" }
// WARNING: this file is generated and will be overwritten // Generated on Mon May 12 2014 10:36:47 GMT-0700 (PDT) // if you're checking out this file, you should check us out too. // http://jobs.appcelerator.com /** * JSC implementation for UIKit/UIGestureRecognizer */ @import JavaScriptCore; @import UIKit; #import <hyperloop.h> #import <ti_coremotion_converters.h> @import Foundation; @import UIKit; // export typdefs we use typedef id (*Function_id__P__id__SEL______)(id,SEL,...); // export methods we use extern Class HyperloopJSValueRefToClass(JSContextRef,JSValueRef,JSValueRef*,bool*); extern JSValueRef HyperloopCGPointToJSValueRef(JSContextRef,CGPoint *); extern JSValueRef HyperloopClassToJSValueRef(JSContextRef,Class); extern JSValueRef HyperloopNSArrayToJSValueRef(JSContextRef,NSArray *); extern JSValueRef HyperloopNSMethodSignatureToJSValueRef(JSContextRef,NSMethodSignature *); extern JSValueRef HyperloopNSSetToJSValueRef(JSContextRef,NSSet *); extern JSValueRef HyperloopNSStringToJSValueRef(JSContextRef,NSString *); extern JSValueRef HyperloopUIGestureRecognizerStateToJSValueRef(JSContextRef,UIGestureRecognizerState); extern JSValueRef HyperloopUIGestureRecognizerToJSValueRef(JSContextRef,UIGestureRecognizer *); extern JSValueRef HyperloopUIViewToJSValueRef(JSContextRef,UIView *); extern JSValueRef HyperloopboolToJSValueRef(JSContextRef,bool); extern JSValueRef Hyperloopid_UIGestureRecognizerDelegate_ToJSValueRef(JSContextRef,id<UIGestureRecognizerDelegate>); extern JSValueRef Hyperloopid__P__id__SEL______ToJSValueRef(JSContextRef,Function_id__P__id__SEL______); extern JSValueRef HyperloopintToJSValueRef(JSContextRef,int); extern JSValueRef Hyperloopunsigned_intToJSValueRef(JSContextRef,unsigned int); extern NSString * HyperloopJSValueRefToNSString(JSContextRef,JSValueRef,JSValueRef*,bool*); extern SEL HyperloopJSValueRefToSEL(JSContextRef,JSValueRef,JSValueRef*,bool*); extern UIGestureRecognizer * HyperloopJSValueRefToUIGestureRecognizer(JSContextRef,JSValueRef,JSValueRef*,bool*); extern UIView * HyperloopJSValueRefToUIView(JSContextRef,JSValueRef,JSValueRef*,bool*); extern bool HyperloopJSValueRefTobool(JSContextRef,JSValueRef,JSValueRef*,bool*); extern id HyperloopJSValueRefToid(JSContextRef,JSValueRef,JSValueRef*,bool*); extern id<UIGestureRecognizerDelegate> HyperloopJSValueRefToid_UIGestureRecognizerDelegate_(JSContextRef,JSValueRef,JSValueRef*,bool*); extern int HyperloopJSValueRefToint(JSContextRef,JSValueRef,JSValueRef*,bool*); extern struct _NSZone * HyperloopJSValueRefTostruct__NSZone_P(JSContextRef,JSValueRef,JSValueRef*,bool*); extern unsigned int HyperloopJSValueRefTounsigned_int(JSContextRef,JSValueRef,JSValueRef*,bool*);
{ "content_hash": "e3ed496c3a3146590e43ec4fea1c97b2", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 135, "avg_line_length": 57.4468085106383, "alnum_prop": 0.8396296296296296, "repo_name": "cheekiatng/ti.coremotion", "id": "179c0b4c6d4ffd7a8d503322c5264825f403394c", "size": "3018", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ios/xcode/ti.coremotion/src/js_UIKit/js_UIGestureRecognizer_P.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "9911" }, { "name": "C++", "bytes": "69772" }, { "name": "JavaScript", "bytes": "61443" }, { "name": "Objective-C", "bytes": "8969002" }, { "name": "Shell", "bytes": "3427" } ], "symlink_target": "" }
package com.google.common.math; import static com.google.common.base.Preconditions.checkState; import static com.google.common.primitives.Doubles.isFinite; import static java.lang.Double.NaN; import static java.lang.Double.isNaN; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtIncompatible; /** * A mutable object which accumulates paired double values (e.g. points on a plane) and tracks some * basic statistics over all the values added so far. This class is not thread safe. * * @author Pete Gillin * @since 20.0 */ @Beta @GwtIncompatible public final class PairedStatsAccumulator { // These fields must satisfy the requirements of PairedStats' constructor as well as those of the // stat methods of this class. private final StatsAccumulator xStats = new StatsAccumulator(); private final StatsAccumulator yStats = new StatsAccumulator(); private double sumOfProductsOfDeltas = 0.0; /** * Adds the given pair of values to the dataset. */ public void add(double x, double y) { // We extend the recursive expression for the one-variable case at Art of Computer Programming // vol. 2, Knuth, 4.2.2, (16) to the two-variable case. We have two value series x_i and y_i. // We define the arithmetic means X_n = 1/n \sum_{i=1}^n x_i, and Y_n = 1/n \sum_{i=1}^n y_i. // We also define the sum of the products of the differences from the means // C_n = \sum_{i=1}^n x_i y_i - n X_n Y_n // for all n >= 1. Then for all n > 1: // C_{n-1} = \sum_{i=1}^{n-1} x_i y_i - (n-1) X_{n-1} Y_{n-1} // C_n - C_{n-1} = x_n y_n - n X_n Y_n + (n-1) X_{n-1} Y_{n-1} // = x_n y_n - X_n [ y_n + (n-1) Y_{n-1} ] + [ n X_n - x_n ] Y_{n-1} // = x_n y_n - X_n y_n - x_n Y_{n-1} + X_n Y_{n-1} // = (x_n - X_n) (y_n - Y_{n-1}) xStats.add(x); if (isFinite(x) && isFinite(y)) { if (xStats.count() > 1) { sumOfProductsOfDeltas += (x - xStats.mean()) * (y - yStats.mean()); } } else { sumOfProductsOfDeltas = NaN; } yStats.add(y); } /** * Adds the given statistics to the dataset, as if the individual values used to compute the * statistics had been added directly. */ public void addAll(PairedStats values) { if (values.count() == 0) { return; } xStats.addAll(values.xStats()); if (yStats.count() == 0) { sumOfProductsOfDeltas = values.sumOfProductsOfDeltas(); } else { // This is a generalized version of the calculation in add(double, double) above. Note that // non-finite inputs will have sumOfProductsOfDeltas = NaN, so non-finite values will result // in NaN naturally. sumOfProductsOfDeltas += values.sumOfProductsOfDeltas() + (values.xStats().mean() - xStats.mean()) * (values.yStats().mean() - yStats.mean()) * values.count(); } yStats.addAll(values.yStats()); } /** * Returns an immutable snapshot of the current statistics. */ public PairedStats snapshot() { return new PairedStats(xStats.snapshot(), yStats.snapshot(), sumOfProductsOfDeltas); } /** * Returns the number of pairs in the dataset. */ public long count() { return xStats.count(); } /** * Returns an immutable snapshot of the statistics on the {@code x} values alone. */ public Stats xStats() { return xStats.snapshot(); } /** * Returns an immutable snapshot of the statistics on the {@code y} values alone. */ public Stats yStats() { return yStats.snapshot(); } /** * Returns the population covariance of the values. The count must be non-zero. * * <p>This is guaranteed to return zero if the dataset contains a single pair of finite values. It * is not guaranteed to return zero when the dataset consists of the same pair of values multiple * times, due to numerical errors. * * <h3>Non-finite values</h3> * * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, * {@link Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}. * * @throws IllegalStateException if the dataset is empty */ public double populationCovariance() { checkState(count() != 0); return sumOfProductsOfDeltas / count(); } /** * Returns the sample covariance of the values. The count must be greater than one. * * <p>This is not guaranteed to return zero when the dataset consists of the same pair of values * multiple times, due to numerical errors. * * <h3>Non-finite values</h3> * * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, * {@link Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}. * * @throws IllegalStateException if the dataset is empty or contains a single pair of values */ public final double sampleCovariance() { checkState(count() > 1); return sumOfProductsOfDeltas / (count() - 1); } /** * Returns the <a href="http://mathworld.wolfram.com/CorrelationCoefficient.html">Pearson's or * product-moment correlation coefficient</a> of the values. The count must greater than one, and * the {@code x} and {@code y} values must both have non-zero population variance (i.e. * {@code xStats().populationVariance() > 0.0 && yStats().populationVariance() > 0.0}). The result * is not guaranteed to be exactly +/-1 even when the data are perfectly (anti-)correlated, due to * numerical errors. However, it is guaranteed to be in the inclusive range [-1, +1]. * * <h3>Non-finite values</h3> * * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, * {@link Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is {@link Double#NaN}. * * @throws IllegalStateException if the dataset is empty or contains a single pair of values, or * either the {@code x} and {@code y} dataset has zero population variance */ public final double pearsonsCorrelationCoefficient() { checkState(count() > 1); if (isNaN(sumOfProductsOfDeltas)) { return NaN; } double xSumOfSquaresOfDeltas = xStats.sumOfSquaresOfDeltas(); double ySumOfSquaresOfDeltas = yStats.sumOfSquaresOfDeltas(); checkState(xSumOfSquaresOfDeltas > 0.0); checkState(ySumOfSquaresOfDeltas > 0.0); // The product of two positive numbers can be zero if the multiplication underflowed. We // force a positive value by effectively rounding up to MIN_VALUE. double productOfSumsOfSquaresOfDeltas = ensurePositive(xSumOfSquaresOfDeltas * ySumOfSquaresOfDeltas); return ensureInUnitRange(sumOfProductsOfDeltas / Math.sqrt(productOfSumsOfSquaresOfDeltas)); } /** * Returns a linear transformation giving the best fit to the data according to * <a href="http://mathworld.wolfram.com/LeastSquaresFitting.html">Ordinary Least Squares linear * regression</a> of {@code y} as a function of {@code x}. The count must be greater than one, and * either the {@code x} or {@code y} data must have a non-zero population variance (i.e. * {@code xStats().populationVariance() > 0.0 || yStats().populationVariance() > 0.0}). The result * is guaranteed to be horizontal if there is variance in the {@code x} data but not the {@code y} * data, and vertical if there is variance in the {@code y} data but not the {@code x} data. * * <p>This fit minimizes the root-mean-square error in {@code y} as a function of {@code x}. This * error is defined as the square root of the mean of the squares of the differences between the * actual {@code y} values of the data and the values predicted by the fit for the {@code x} * values (i.e. it is the square root of the mean of the squares of the vertical distances between * the data points and the best fit line). For this fit, this error is a fraction * {@code sqrt(1 - R*R)} of the population standard deviation of {@code y}, where {@code R} is the * Pearson's correlation coefficient (as given by {@link #pearsonsCorrelationCoefficient()}). * * <p>The corresponding root-mean-square error in {@code x} as a function of {@code y} is a * fraction {@code sqrt(1/(R*R) - 1)} of the population standard deviation of {@code x}. This fit * does not normally minimize that error: to do that, you should swap the roles of {@code x} and * {@code y}. * * <h3>Non-finite values</h3> * * <p>If the dataset contains any non-finite values ({@link Double#POSITIVE_INFINITY}, * {@link Double#NEGATIVE_INFINITY}, or {@link Double#NaN}) then the result is * {@link LinearTransformation#forNaN()}. * * @throws IllegalStateException if the dataset is empty or contains a single pair of values, or * both the {@code x} and {@code y} dataset have zero population variance */ public final LinearTransformation leastSquaresFit() { checkState(count() > 1); if (isNaN(sumOfProductsOfDeltas)) { return LinearTransformation.forNaN(); } double xSumOfSquaresOfDeltas = xStats.sumOfSquaresOfDeltas(); if (xSumOfSquaresOfDeltas > 0.0) { if (yStats.sumOfSquaresOfDeltas() > 0.0) { return LinearTransformation.mapping(xStats.mean(), yStats.mean()) .withSlope(sumOfProductsOfDeltas / xSumOfSquaresOfDeltas); } else { return LinearTransformation.horizontal(yStats.mean()); } } else { checkState(yStats.sumOfSquaresOfDeltas() > 0.0); return LinearTransformation.vertical(xStats.mean()); } } private double ensurePositive(double value) { if (value > 0.0) { return value; } else { return Double.MIN_VALUE; } } private static double ensureInUnitRange(double value) { if (value >= 1.0) { return 1.0; } if (value <= -1.0) { return -1.0; } return value; } }
{ "content_hash": "a73b00b33ceea1d2ed36ed9d30a15e4e", "timestamp": "", "source": "github", "line_count": 245, "max_line_length": 100, "avg_line_length": 40.795918367346935, "alnum_prop": 0.662631315657829, "repo_name": "antlr/codebuff", "id": "9af811a5f370400b212393edb6653eb639404acc", "size": "10589", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "corpus/java/training/guava/math/PairedStatsAccumulator.java", "mode": "33261", "license": "bsd-2-clause", "language": [ { "name": "ANTLR", "bytes": "1479752" }, { "name": "GAP", "bytes": "146955" }, { "name": "Java", "bytes": "32484822" }, { "name": "Python", "bytes": "113118" }, { "name": "SQLPL", "bytes": "605792" }, { "name": "Shell", "bytes": "445" } ], "symlink_target": "" }
local assert = assert local ipairs = ipairs local pairs = pairs local rawequal = rawequal ----------- -- Imports ----------- local CollectArgsInto = varops.CollectArgsInto local Weak = table_ex.Weak ---------------------- -- Unique member keys ---------------------- local _forbids = {} local _is_blacklist = {} local _key = {} local _permissions = {} ----------------------------- -- Sealable class definition ----------------------------- class.Define("Sealable", function(MT) -- Looks up a permissions list -- S: Sealable handle -- id: Lookup ID -- Returns: List, if available ------------------------------- local function GetPermissionsList (S, id) assert(id ~= nil, "id == nil") local permissions = S[_permissions] return permissions and permissions[id] end -- Indicates whether a client has a given permission -- id: Lookup ID -- what: Permission to query -- Returns: If true, client has permission ----------------------------------------------------- function MT:HasPermission (id, what) assert(what ~= nil, "what == nil") local permissions = assert(GetPermissionsList(self, id), "Invalid client ID") -- If no changes have yet been made, the client has full permissions. Otherwise, -- search for the query among the permissions. In blacklist mode, permission is -- granted if the query fails; in whitelist mode, the query must succeed. return permissions == "" or permissions[_is_blacklist] == not permissions[what] end -- key: Key to test -- Returns: If true, key is the access key ------------------------------------------- function MT:MatchesKey (key) return rawequal(self[_key], key) end -- Cache methods for internal use. local HasPermission = MT.HasPermission local MatchesKey = MT.MatchesKey -- Adds a new client with configurable permissions -- key: Access key, for validation -- Returns: Lookup ID --------------------------------------------------- function MT:AddClient (key) assert(MatchesKey(self, key), "Key mismatch") -- Install a client list if this is the first one. Generate a unique ID. local permissions = self[_permissions] or Weak("k") local id = {} -- Load the client. Give it full permissions by default. self[_permissions] = permissions permissions[id] = "" return id end ---------------------------- -- Valid permission options ---------------------------- local Options = table_ex.MakeSet{ "blacklist", "whitelist", "+", "-" } -- Changes a client's permissions -- key: Access key, for validation -- id: Lookup ID -- how: Type of change to apply -- ...: Changes to apply ----------------------------------- function MT:ChangePermissions (key, id, how, ...) assert(MatchesKey(self, key), "Key mismatch") assert(how ~= nil and Options[how], "Invalid permission option") -- Validate the changes. local count, changes = CollectArgsInto(nil, ...) for i = 1, count do assert(changes[i] ~= nil, "Nil change") assert(changes[i] == changes[i], "NaN change") end -- If a new whitelist or blacklist is requested, build it. New clients have full -- permissions, and thus implicitly have empty blacklists; if additions or removals -- are to be made, make this explicit. local permissions = assert(GetPermissionsList(self, id), "Invalid client ID") if permissions == "" or how == "blacklist" or how == "whitelist" then permissions = { [_is_blacklist] = how ~= "whitelist" } -- Replace the old list. self[_permissions][id] = permissions end -- For additions/removals, the following holds: -- > Add: Add to whitelist or remove from blacklist -- > Remove: Add to blacklist or remove from whitelist local should_add = true if how == "+" or how == "-" then should_add = (how == "+" ~= permissions[_is_blacklist]) or nil end -- Apply the changes. A removal will clear an entry. for _, change in ipairs(changes) do permissions[change] = should_add end end -- id: Lookup id -- Returns: Blacklist boolean, list ------------------------------------ function MT:GetPermissions (id) local permissions = assert(GetPermissionsList(self, id), "Invalid client ID") local is_blaclist = true local t = {} if permissions ~= "" then is_blaclist = permissions[_is_blacklist] for k in pairs(permissions) do t[#t + 1] = k end end return is_blaclist, t end -- what: Property to test -- Returns: If true, property change is allowed ------------------------------------------------ function MT:IsAllowed (what) assert(what ~= nil, "what == nil") local forbids = self[_forbids] return (forbids and forbids[what]) == nil end -- id: Lookup ID -- Returns: If true, lookup ID belongs to a client --------------------------------------------------- function MT:IsClient (id) return id ~= nil and GetPermissionsList(self, id) ~= nil end -- Sets allowance for future changes to a property -- what: Property change (requires corresponding permission) -- id_or_key: Lookup ID or access key, for validation -- bAllow: If true, allow future changes ------------------------------------------------------------- function MT:SetAllowed (what, id_or_key, bAllow) assert(what == what, "what is NaN") assert(MatchesKey(self, id_or_key) or HasPermission(self, id_or_key, what), "Key mismatch or forbidden client") local forbids = self[_forbids] if not bAllow then forbids = forbids or {} self[_forbids] = forbids forbids[what] = true elseif forbids then forbids[what] = nil end end -- new: Access key to assign -- old: Current key, for validation -- Returns: If true, key was set ------------------------------------ function MT:SetKey (new, old) local is_match = MatchesKey(self, old) if is_match then self[_key] = new end return is_match end end, -- Constructor --------------- funcops.NoOp)
{ "content_hash": "e24d5ecd6224c4a14804fdbf9fe42d66", "timestamp": "", "source": "github", "line_count": 210, "max_line_length": 113, "avg_line_length": 27.85238095238095, "alnum_prop": 0.6108736536160028, "repo_name": "ggcrunchy/Old-Love2D-Demo", "id": "bf61292404d99a7e95b8f38481210d70b05f9c10", "size": "6001", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Scripts/Class/Mixins/Sealable.lua", "mode": "33188", "license": "mit", "language": [ { "name": "Lua", "bytes": "338224" } ], "symlink_target": "" }
module Azure::CognitiveServices::TextAnalytics::V2_1_preview module Models # # Model object. # # class BatchInput include MsRestAzure # @return [Array<Input>] attr_accessor :documents # # Mapper for BatchInput class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'BatchInput', type: { name: 'Composite', class_name: 'BatchInput', model_properties: { documents: { client_side_validation: true, required: false, serialized_name: 'documents', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'InputElementType', type: { name: 'Composite', class_name: 'Input' } } } } } } } end end end end
{ "content_hash": "5ebb614383b5e939570ff2ca0bd6f137", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 60, "avg_line_length": 24.823529411764707, "alnum_prop": 0.4344391785150079, "repo_name": "Azure/azure-sdk-for-ruby", "id": "d777ddd6dfba13604fa8ac61324506a1658df1da", "size": "1430", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "data/azure_cognitiveservices_textanalytics/lib/v2.1-preview/generated/azure_cognitiveservices_textanalytics/models/batch_input.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "345216400" }, { "name": "Shell", "bytes": "305" } ], "symlink_target": "" }
/* $NetBSD: ypprot_err.c,v 1.6 2012/06/25 22:32:46 abs Exp $ */ /* * Copyright (c) 1992, 1993 Theo de Raadt <deraadt@fsa.ca> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <sys/cdefs.h> #if defined(LIBC_SCCS) && !defined(lint) __RCSID("$NetBSD: ypprot_err.c,v 1.6 2012/06/25 22:32:46 abs Exp $"); #endif #include "namespace.h" #include <rpc/rpc.h> #include <rpcsvc/yp_prot.h> #include <rpcsvc/ypclnt.h> #ifdef __weak_alias __weak_alias(ypprot_err,_ypprot_err) #endif int ypprot_err(unsigned int incode) { switch (incode) { case YP_TRUE: return 0; case YP_FALSE: return YPERR_YPBIND; case YP_NOMORE: return YPERR_NOMORE; case YP_NOMAP: return YPERR_MAP; case YP_NODOM: return YPERR_NODOM; case YP_NOKEY: return YPERR_KEY; case YP_BADOP: return YPERR_YPERR; case YP_BADDB: return YPERR_BADDB; case YP_YPERR: return YPERR_YPERR; case YP_BADARGS: return YPERR_BADARGS; case YP_VERS: return YPERR_VERS; } return YPERR_YPERR; }
{ "content_hash": "0d2a597fc7d9e6e4e3ef7a93420af9c0", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 77, "avg_line_length": 31.112676056338028, "alnum_prop": 0.7315527387958353, "repo_name": "evrom/bsdlibc", "id": "af42f059dc0bc3d2b29e0e82dc382654ec56508e", "size": "2209", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "src/lib/libc/yp/ypprot_err.c", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "Assembly", "bytes": "1125004" }, { "name": "Awk", "bytes": "9877" }, { "name": "C", "bytes": "6142692" }, { "name": "C++", "bytes": "50528" }, { "name": "Objective-C", "bytes": "19498" }, { "name": "Shell", "bytes": "6700" } ], "symlink_target": "" }
package com.sen.vov.utils; import android.animation.Animator; import android.animation.AnimatorInflater; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Context; import android.util.Log; import android.view.View; import android.view.animation.AccelerateInterpolator; import android.view.animation.DecelerateInterpolator; import com.sen.vov.R; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 动画实现类 * Created by Sen on 2016/3/21. */ public class AnimationsUtil { private final static int radius = 300;//圆半径 private static int duration = 500;//动画时间 public static void inCrossShowChildAnimation(View... view){ AnimatorSet set = new AnimatorSet(); int length = view.length; for (int i=0;i<length;i++){ View viewChild = view[i]; int x,y;//位移的圆心坐标 if(i == 0){ x = radius; y = 0; }else if(i == length - 1){ x = 0; y = -radius; }else{ float angle = (-90 / (length - 1)) * i;//计算偏移角度 x = (int) (radius * Math.cos(Math.toRadians(angle))); y = (int) (radius * Math.sin(Math.toRadians(angle))); // Log.e("angle:",""+angle); } // Log.e("x:"+x,"y:"+y); ObjectAnimator translationX = ObjectAnimator.ofFloat(viewChild, "translationX", 0, -x); ObjectAnimator translationY = ObjectAnimator.ofFloat(viewChild, "translationY", 0, y); ObjectAnimator scaleX = ObjectAnimator.ofFloat(viewChild, "scaleX", 0, 1f); ObjectAnimator scaleY = ObjectAnimator.ofFloat(viewChild, "scaleY", 0, 1f); ObjectAnimator rotation = ObjectAnimator.ofFloat(viewChild, "rotation", 0, 360f); set.playTogether(translationX,translationY,scaleX,scaleY); set.play(rotation); } set.setDuration(duration); set.start(); } public static void outCrossShowChildAnimation(View... view){ AnimatorSet set = new AnimatorSet(); int length = view.length; for (int i=0;i<length;i++) { View viewChild = view[i]; ObjectAnimator rotation = ObjectAnimator.ofFloat(viewChild, "rotation", 360f, 0f); ObjectAnimator translationX = ObjectAnimator.ofFloat(viewChild, "translationX", viewChild.getTranslationX(),0); ObjectAnimator translationY = ObjectAnimator.ofFloat(viewChild, "translationY", viewChild.getTranslationY(),0); ObjectAnimator scaleX = ObjectAnimator.ofFloat(viewChild, "scaleX", 1f, 0f); ObjectAnimator scaleY = ObjectAnimator.ofFloat(viewChild, "scaleY", 1f, 0f); set.playTogether(rotation,translationX,translationY,scaleX,scaleY); } set.setInterpolator(new DecelerateInterpolator(2f));//先快后慢 set.setDuration(duration); set.start(); } /** * 调用animator文件夹下的动画 * @param context * @param id * @param view * @return animator对象,方便开启动画并对动画的start end做监听 */ public static Animator xmlFileLoadAnimator(Context context,int id, View view ){ Animator animator = AnimatorInflater.loadAnimator(context, id); animator.setTarget(view); return animator; } }
{ "content_hash": "696dd030e3323770a0a086afdfb8c265", "timestamp": "", "source": "github", "line_count": 86, "max_line_length": 123, "avg_line_length": 39.51162790697674, "alnum_prop": 0.6265450264861684, "repo_name": "PengSen/VoV", "id": "20fd5a5d58d1fd12d1bc1f88f18f7e542d74fb39", "size": "3508", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/sen/vov/utils/AnimationsUtil.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "435318" }, { "name": "Makefile", "bytes": "1048" } ], "symlink_target": "" }
<?php namespace PDepend\Bugs; /** * Test case for the parent keyword type hint bug no #87. * * http://tracker.pdepend.org/pdepend/issue_tracker/issue/87 * * @copyright 2008-2017 Manuel Pichler. All rights reserved. * @license http://www.opensource.org/licenses/bsd-license.php BSD License * * @covers \stdClass * @group regressiontest */ class ParentKeywordAsParameterTypeHintBug087Test extends AbstractRegressionTest { /** * Tests that the parser handles the parent type hint as expected. * * @return void */ public function testParserSetsExpectedParentTypeHintReference() { $parameters = $this->parseCodeResourceForTest() ->current() ->getClasses() ->current() ->getMethods() ->current() ->getParameters(); $this->assertSame('Bar', $parameters[0]->getClass()->getName()); } /** * Tests that the parser throws an exception when the parent keyword is used * within a function signature. * * @return void */ public function testParserThrowsExpectedExceptionForParentTypeHintInFunction() { $this->setExpectedException( '\\PDepend\\Source\\Parser\\InvalidStateException', 'The keyword "parent" was used as type hint but the parameter ' . 'declaration is not in a class scope.' ); $this->parseCodeResourceForTest(); } /** * testParserThrowsExpectedExceptionForParentTypeHintWithRootClass * * @return void */ public function testParserThrowsExpectedExceptionForParentTypeHintWithRootClass() { $this->setExpectedException( '\\PDepend\\Source\\Parser\\InvalidStateException', 'The keyword "parent" was used as type hint but the ' . 'class "Baz" does not declare a parent.' ); $this->parseCodeResourceForTest(); } }
{ "content_hash": "700b50d7eff2b009c9b810e7fc85741e", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 85, "avg_line_length": 28.217391304347824, "alnum_prop": 0.6317411402157165, "repo_name": "pdepend/pdepend", "id": "1c45a8629545861d9e40a81a97ce378cd7aeca71", "size": "3766", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/php/PDepend/Bugs/ParentKeywordAsParameterTypeHintBug087Test.php", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Batchfile", "bytes": "1923" }, { "name": "CSS", "bytes": "11302" }, { "name": "PHP", "bytes": "4326327" }, { "name": "Shell", "bytes": "512" }, { "name": "XSLT", "bytes": "1544" } ], "symlink_target": "" }
<html dir="LTR"> <head> <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" /> <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" /> <title>Neuron.inputWithBiasProp Property</title> <xml> </xml> <link rel="stylesheet" type="text/css" href="MSDN.css" /> </head> <body id="bodyID" class="dtBODY"> <div id="nsbanner"> <div id="bannerrow1"> <table class="bannerparthead" cellspacing="0"> <tr id="hdr"> <td class="runninghead">Multilayer Perzeptron and Learning Algorhims</td> <td class="product"> </td> </tr> </table> </div> <div id="TitleRow"> <h1 class="dtH1">Neuron.inputWithBiasProp Property </h1> </div> </div> <div id="nstext"> <p> Returns the input with the bias and sets the input including the bias on-state (last value in the vector) </p> <div class="syntax">public <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemSingleClassTopic.asp">float[]</a> inputWithBiasProp {get; set;}</div> <p> </p> <h4 class="dtH4">See Also</h4> <p> <a href="MultilayerNet.Neuron.html">Neuron Class</a> | <a href="MultilayerNet.html">MultilayerNet Namespace</a></p> <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;"> <param name="Keyword" value="inputWithBiasProp property"> </param> <param name="Keyword" value="inputWithBiasProp property, Neuron class"> </param> <param name="Keyword" value="Neuron.inputWithBiasProp property"> </param> </object> <hr /> <div id="footer"> <p> <a href="mailto:mlp@rene-schulte.info?subject=Multilayer%20Perzeptron%20and%20Learning%20Algorhims%20Documentation%20Feedback:%20Neuron.inputWithBiasProp%20Property&#xD;&#xA; ">Send comments on this topic.</a> </p> <p> <a>(c) 2004 Rene Schulte and Torsten Baer</a> </p> <p> </p> </div> </div> </body> </html>
{ "content_hash": "44921d53823e1501936001b6f3cde9f0", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 224, "avg_line_length": 40.163636363636364, "alnum_prop": 0.6075147125396106, "repo_name": "teichgraf/MuLaPeGASim", "id": "d5952e0d1d22912e8c4932c54bc938469b8c4dfb", "size": "2209", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "web/docs/Net/MultilayerNet.Neuron.inputWithBiasProp.html", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "265668" }, { "name": "CSS", "bytes": "19976" }, { "name": "HTML", "bytes": "1899083" }, { "name": "JavaScript", "bytes": "14231" }, { "name": "Smalltalk", "bytes": "483058" } ], "symlink_target": "" }
<?php if (!defined('APPLICATION')) exit(); ?> <div class="Box BoxDrafts"> <h4><?php echo T('My Drafts'); ?></h4> <ul class="PanelInfo PanelDiscussions"> <?php foreach ($this->Data->Result() as $Draft) { $EditUrl = !is_numeric($Draft->DiscussionID) || $Draft->DiscussionID <= 0 ? '/post/editdiscussion/0/'.$Draft->DraftID : '/post/editcomment/0/'.$Draft->DraftID; ?> <li> <strong><?php echo Anchor($Draft->Name, $EditUrl); ?></strong> <?php echo Anchor(SliceString(Gdn_Format::Text($Draft->Body), 200), $EditUrl, 'DraftCommentLink'); ?> </li> <?php } ?> <li class="ShowAll"><?php echo Anchor(T('↳ Show All'), 'drafts'); ?></li> </ul> </div>
{ "content_hash": "ea6987ff66d4b22d486e9cadd66b0929", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 168, "avg_line_length": 42.588235294117645, "alnum_prop": 0.56353591160221, "repo_name": "sorrowgrave/NothingToSeeHere", "id": "2b05a0c6106daa907ec72a3cbe5d111835fb7144", "size": "726", "binary": false, "copies": "61", "ref": "refs/heads/master", "path": "vanilla/applications/vanilla/views/modules/drafts.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "910" }, { "name": "CSS", "bytes": "277402" }, { "name": "HTML", "bytes": "5611472" }, { "name": "JavaScript", "bytes": "910939" }, { "name": "PHP", "bytes": "5294180" }, { "name": "Smarty", "bytes": "8998" } ], "symlink_target": "" }
void foo() { } #if __cplusplus >= 201103L // expected-note@+2 4 {{declared here}} #endif bool foobool(int argc) { return argc; } struct S1; // expected-note {{declared here}} template <class T, typename S, int N, int ST> // expected-note {{declared here}} T tmain(T argc, S **argv) { //expected-note 2 {{declared here}} #pragma omp target teams distribute parallel for simd collapse // expected-error {{expected '(' after 'collapse'}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute parallel for simd collapse ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute parallel for simd collapse () // expected-error {{expected expression}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // expected-error@+2 2 {{expression is not an integral constant expression}} // expected-note@+1 2 {{read of non-const variable 'argc' is not allowed in a constant expression}} #pragma omp target teams distribute parallel for simd collapse (argc for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error@+1 2 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute parallel for simd collapse (ST // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute parallel for simd collapse (1)) // expected-warning {{extra tokens at the end of '#pragma omp target teams distribute parallel for simd' are ignored}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute parallel for simd collapse ((ST > 0) ? 1 + ST : 2) // expected-note 2 {{as specified in 'collapse' clause}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; // expected-error 2 {{expected 2 for loops after '#pragma omp target teams distribute parallel for simd', but found only 1}} #if __cplusplus >= 201103L // expected-note@+5 2 {{non-constexpr function 'foobool' cannot be used}} #endif // expected-error@+3 2 {{directive '#pragma omp target teams distribute parallel for simd' cannot contain more than one 'collapse' clause}} // expected-error@+2 {{argument to 'collapse' clause must be a strictly positive integer value}} // expected-error@+1 2 {{expression is not an integral constant expression}} #pragma omp target teams distribute parallel for simd collapse (foobool(argc)), collapse (true), collapse (-5) for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute parallel for simd collapse (S) // expected-error {{'S' does not refer to a value}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #if __cplusplus >= 201103L // expected-error@+4 2 {{integral constant expression must have integral or unscoped enumeration type}} #else // expected-error@+2 2 {{expression is not an integral constant expression}} #endif #pragma omp target teams distribute parallel for simd collapse (argv[1]=2) // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute parallel for simd collapse (1) for (int i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute parallel for simd collapse (N) // expected-error {{argument to 'collapse' clause must be a strictly positive integer value}} for (T i = ST; i < N; i++) argv[0][i] = argv[0][i] - argv[0][i-ST]; #pragma omp target teams distribute parallel for simd collapse (2) // expected-note {{as specified in 'collapse' clause}} foo(); // expected-error {{expected 2 for loops after '#pragma omp target teams distribute parallel for simd'}} return argc; } int main(int argc, char **argv) { #pragma omp target teams distribute parallel for simd collapse // expected-error {{expected '(' after 'collapse'}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #pragma omp target teams distribute parallel for simd collapse ( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #pragma omp target teams distribute parallel for simd collapse () // expected-error {{expected expression}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #pragma omp target teams distribute parallel for simd collapse (4 // expected-error {{expected ')'}} expected-note {{to match this '('}} expected-note {{as specified in 'collapse' clause}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for simd', but found only 1}} #pragma omp target teams distribute parallel for simd collapse (2+2)) // expected-warning {{extra tokens at the end of '#pragma omp target teams distribute parallel for simd' are ignored}} expected-note {{as specified in 'collapse' clause}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error {{expected 4 for loops after '#pragma omp target teams distribute parallel for simd', but found only 1}} #if __cplusplus >= 201103L // expected-note@+2 {{non-constexpr function 'foobool' cannot be used}} #endif #pragma omp target teams distribute parallel for simd collapse (foobool(1) > 0 ? 1 : 2) // expected-error {{expression is not an integral constant expression}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #if __cplusplus >= 201103L // expected-note@+5 {{non-constexpr function 'foobool' cannot be used}} #endif // expected-error@+3 {{expression is not an integral constant expression}} // expected-error@+2 2 {{directive '#pragma omp target teams distribute parallel for simd' cannot contain more than one 'collapse' clause}} // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp target teams distribute parallel for simd collapse (foobool(argc)), collapse (true), collapse (-5) for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #pragma omp target teams distribute parallel for simd collapse (S1) // expected-error {{'S1' does not refer to a value}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; #if __cplusplus >= 201103L // expected-error@+4 {{integral constant expression must have integral or unscoped enumeration type}} #else // expected-error@+2 {{expression is not an integral constant expression}} #endif #pragma omp target teams distribute parallel for simd collapse (argv[1]=2) // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = 4; i < 12; i++) argv[0][i] = argv[0][i] - argv[0][i-4]; // expected-error@+3 {{statement after '#pragma omp target teams distribute parallel for simd' must be a for loop}} // expected-note@+1 {{in instantiation of function template specialization 'tmain<int, char, -1, -2>' requested here}} #pragma omp target teams distribute parallel for simd collapse(collapse(tmain<int, char, -1, -2>(argc, argv) // expected-error 2 {{expected ')'}} expected-note 2 {{to match this '('}} foo(); #pragma omp target teams distribute parallel for simd collapse (2) // expected-note {{as specified in 'collapse' clause}} foo(); // expected-error {{expected 2 for loops after '#pragma omp target teams distribute parallel for simd'}} // expected-note@+1 {{in instantiation of function template specialization 'tmain<int, char, 1, 0>' requested here}} return tmain<int, char, 1, 0>(argc, argv); }
{ "content_hash": "e5eb4b406d740ff4f0e9ab61b2b1573e", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 241, "avg_line_length": 55.63448275862069, "alnum_prop": 0.6716251394570473, "repo_name": "apple/swift-clang", "id": "4ca7a8ca9adfa6c48ae6cced26f7ac1ab8171a27", "size": "8362", "binary": false, "copies": "1", "ref": "refs/heads/stable", "path": "test/OpenMP/target_teams_distribute_parallel_for_simd_collapse_messages.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AppleScript", "bytes": "1429" }, { "name": "Assembly", "bytes": "48411" }, { "name": "Batchfile", "bytes": "73" }, { "name": "C", "bytes": "21215199" }, { "name": "C#", "bytes": "27472" }, { "name": "C++", "bytes": "72404163" }, { "name": "CMake", "bytes": "175348" }, { "name": "CSS", "bytes": "8395" }, { "name": "Cool", "bytes": "22451" }, { "name": "Cuda", "bytes": "413843" }, { "name": "Dockerfile", "bytes": "2083" }, { "name": "Emacs Lisp", "bytes": "17001" }, { "name": "Forth", "bytes": "925" }, { "name": "Fortran", "bytes": "8180" }, { "name": "HTML", "bytes": "986812" }, { "name": "JavaScript", "bytes": "42269" }, { "name": "LLVM", "bytes": "27231" }, { "name": "M", "bytes": "4660" }, { "name": "MATLAB", "bytes": "69036" }, { "name": "Makefile", "bytes": "8489" }, { "name": "Mathematica", "bytes": "15066" }, { "name": "Mercury", "bytes": "1193" }, { "name": "Objective-C", "bytes": "3626772" }, { "name": "Objective-C++", "bytes": "1033408" }, { "name": "Perl", "bytes": "96256" }, { "name": "Python", "bytes": "784542" }, { "name": "RenderScript", "bytes": "741" }, { "name": "Roff", "bytes": "10932" }, { "name": "Rust", "bytes": "200" }, { "name": "Shell", "bytes": "10663" } ], "symlink_target": "" }
package evernote_to_markdown; import java.io.IOException; import java.util.LinkedList; import java.util.List; import evernote_to_markdown.load.EvernoteExport; import evernote_to_markdown.load.Note; import evernote_to_markdown.save.TagspacesSaver; import nu.xom.Document; import nu.xom.Node; import nu.xom.Nodes; import nu.xom.ParsingException; import nu.xom.ValidityException; public class Main { public static void main(String[] args) { try { System.out.println("\nConverting Evernotes to Markdown files...\n"); List<Note> convertedNotes = loadEvernoteNotes(); // Output all notes to STOUT for debugging // print(convertedNotes); saveToFile(convertedNotes); } catch (ParsingException | IOException e) { System.out.println("I am sorry, there is something wrong. Please see details below.\nCheck https://github.com/MathiasRenner/evernote_to_markdown/ for help.\n"); e.printStackTrace(); } } private static void saveToFile(List<Note> convertedNotes) throws IOException { new TagspacesSaver().save(convertedNotes); System.out.println("Finished! :-)\n"); } private static void print(List<Note> convertedNotes) { for (Note note : convertedNotes) { System.out.println(note.toString()); } } private static List<Note> loadEvernoteNotes() throws ValidityException, ParsingException, IOException { List<Note> convertedNotes = new LinkedList<>(); Document document = new EvernoteExport().getDocument(); Nodes notes = document.getRootElement().query("./child::note"); for (Node note : notes) { Nodes title = note.query("./child::title/text()"); Nodes tags = note.query("./child::tag"); Nodes content = note.query("./child::content/text()"); convertedNotes.add(new Note(title, content, tags)); } return convertedNotes; } }
{ "content_hash": "8f5bd93d67c19a7bc7e150bbdc490fcd", "timestamp": "", "source": "github", "line_count": 56, "max_line_length": 163, "avg_line_length": 31.982142857142858, "alnum_prop": 0.7303182579564489, "repo_name": "MathiasRenner/evernote_to_markdown", "id": "db64c7b5e91a9a4b0e9a85f716f8c870b326ad30", "size": "1791", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/evernote_to_markdown/Main.java", "mode": "33261", "license": "mit", "language": [ { "name": "Java", "bytes": "6383" } ], "symlink_target": "" }
<?php if (!defined('FIXTURE_ATTRIBUTE_USER_DEFINED_CUSTOMER_NAME')) { define('FIXTURE_ATTRIBUTE_USER_DEFINED_CUSTOMER_NAME', 'user_attribute'); define('FIXTURE_ATTRIBUTE_USER_DEFINED_CUSTOMER_FRONTEND_LABEL', 'frontend_label'); } /** @var Magento\Customer\Model\Attribute $model */ $model = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\Customer\Model\Attribute'); $model->setName( FIXTURE_ATTRIBUTE_USER_DEFINED_CUSTOMER_NAME )->setEntityTypeId( 1 )->setIsUserDefined( 1 )->setAttributeSetId( 1 )->setAttributeGroupId( 1 )->setFrontendInput( 'text' )->setFrontendLabel( FIXTURE_ATTRIBUTE_USER_DEFINED_CUSTOMER_FRONTEND_LABEL )->setSortOrder( 1221 ); $model->save();
{ "content_hash": "9e36369e465ef83060ccf2b9ff4c29a2", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 113, "avg_line_length": 24.766666666666666, "alnum_prop": 0.7200538358008075, "repo_name": "florentinaa/magento", "id": "9ddb1b115ac09e1f75c93f3ba19cc9cb61d9196f", "size": "841", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "store/dev/tests/integration/testsuite/Magento/Customer/_files/attribute_user_defined_customer.php", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "23874" }, { "name": "CSS", "bytes": "3779785" }, { "name": "HTML", "bytes": "6149486" }, { "name": "JavaScript", "bytes": "4396691" }, { "name": "PHP", "bytes": "22079463" }, { "name": "Shell", "bytes": "6072" }, { "name": "XSLT", "bytes": "19889" } ], "symlink_target": "" }
namespace google { namespace cloud { namespace dataproc_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN AutoscalingPolicyServiceMetadata::AutoscalingPolicyServiceMetadata( std::shared_ptr<AutoscalingPolicyServiceStub> child) : child_(std::move(child)), api_client_header_( google::cloud::internal::ApiClientHeader("generator")) {} StatusOr<google::cloud::dataproc::v1::AutoscalingPolicy> AutoscalingPolicyServiceMetadata::CreateAutoscalingPolicy( grpc::ClientContext& context, google::cloud::dataproc::v1::CreateAutoscalingPolicyRequest const& request) { SetMetadata(context, "parent=" + request.parent()); return child_->CreateAutoscalingPolicy(context, request); } StatusOr<google::cloud::dataproc::v1::AutoscalingPolicy> AutoscalingPolicyServiceMetadata::UpdateAutoscalingPolicy( grpc::ClientContext& context, google::cloud::dataproc::v1::UpdateAutoscalingPolicyRequest const& request) { SetMetadata(context, "policy.name=" + request.policy().name()); return child_->UpdateAutoscalingPolicy(context, request); } StatusOr<google::cloud::dataproc::v1::AutoscalingPolicy> AutoscalingPolicyServiceMetadata::GetAutoscalingPolicy( grpc::ClientContext& context, google::cloud::dataproc::v1::GetAutoscalingPolicyRequest const& request) { SetMetadata(context, "name=" + request.name()); return child_->GetAutoscalingPolicy(context, request); } StatusOr<google::cloud::dataproc::v1::ListAutoscalingPoliciesResponse> AutoscalingPolicyServiceMetadata::ListAutoscalingPolicies( grpc::ClientContext& context, google::cloud::dataproc::v1::ListAutoscalingPoliciesRequest const& request) { SetMetadata(context, "parent=" + request.parent()); return child_->ListAutoscalingPolicies(context, request); } Status AutoscalingPolicyServiceMetadata::DeleteAutoscalingPolicy( grpc::ClientContext& context, google::cloud::dataproc::v1::DeleteAutoscalingPolicyRequest const& request) { SetMetadata(context, "name=" + request.name()); return child_->DeleteAutoscalingPolicy(context, request); } void AutoscalingPolicyServiceMetadata::SetMetadata( grpc::ClientContext& context, std::string const& request_params) { context.AddMetadata("x-goog-request-params", request_params); SetMetadata(context); } void AutoscalingPolicyServiceMetadata::SetMetadata( grpc::ClientContext& context) { context.AddMetadata("x-goog-api-client", api_client_header_); auto const& options = internal::CurrentOptions(); if (options.has<UserProjectOption>()) { context.AddMetadata("x-goog-user-project", options.get<UserProjectOption>()); } auto const& authority = options.get<AuthorityOption>(); if (!authority.empty()) context.set_authority(authority); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace dataproc_internal } // namespace cloud } // namespace google
{ "content_hash": "b59a6da6688b49668f029ff7e5f57000", "timestamp": "", "source": "github", "line_count": 76, "max_line_length": 78, "avg_line_length": 38.21052631578947, "alnum_prop": 0.7527548209366391, "repo_name": "googleapis/google-cloud-cpp", "id": "a9da090228376ff7f20447bb592b4916ff98d1fa", "size": "3949", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "google/cloud/dataproc/internal/autoscaling_policy_metadata_decorator.cc", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "2387" }, { "name": "Batchfile", "bytes": "3052" }, { "name": "C", "bytes": "21004" }, { "name": "C++", "bytes": "41174129" }, { "name": "CMake", "bytes": "1350320" }, { "name": "Dockerfile", "bytes": "111570" }, { "name": "Makefile", "bytes": "138270" }, { "name": "PowerShell", "bytes": "41266" }, { "name": "Python", "bytes": "21338" }, { "name": "Shell", "bytes": "249894" }, { "name": "Starlark", "bytes": "722015" } ], "symlink_target": "" }
body,html{background:#f5f5f5;overflow-x:hidden;font-family: "Hiragino Sans GB","Hiragino Sans GB W3","Microsoft YaHei","微软雅黑",tahoma,arial,simsun,"宋体";} .dr_mod1w{width:1030px;position:relative;} .swiper-pagination-bullet {width:8px;height: 8px;display: inline-block;border-radius: 100%;background: #000;opacity: .3;} .swiper-pagination-bullet-active {opacity: 1;background: #ff4c35;} .swiper-button-prev1{height:120px;width:120px;text-indent:-9999px;background:url(../images/20160811165632_311.png) 0px 0px no-repeat;position:absolute;left:-120px;top:112px;} .swiper-button-prev1:hover{background-position:0px -120px;} .swiper-button-next1{height:120px;width:120px;text-indent:-9999px;background:url(../images/20160811165632_311.png) -120px 0px no-repeat;position:absolute;right:-120px;top:112px;} .swiper-button-next1:hover{background-position:-120px -120px;} .dr_mod1{width:1030px;margin:40px auto 0px;height:344px;background:#fff;} .mod1_img{display:block;height:344px;width:1030px;} .mod1_img img{display:block;height:344px;width:1030px;} .dr_mod2{height:140px;width:1030px;background:#fff;margin:40px auto 0px;text-align:center;font-size:0px;} .dr_mod2_item{width:92px;height:140px;position:relative;border-right:1px solid #f5f5f5;display:inline-block;vertical-align:top;} .dr_mod2_item:last-child{border-right:0px;} .dr_mod2_item a{display:block;position:absolute;left:0px;top:0px;width:92px;height:140px;transition:all ease 0.3s;padding:0px;} .dr_mod2_item a img{width:64px;height:64px;border-radius:32px;margin:20px auto 0px;display:block;} .dr_mod2_item a strong{display:inline-block;height:24px;padding:0px 8px;color:#fff;font-size:12px;border-radius:2px;line-height:24px;margin:12px auto 0px;transition:all ease 0.3s;} .dr_mod2_item a.tag1:hover{background:#ff7c7c;} .dr_mod2_item a.tag2:hover{background:#ff4233;} .dr_mod2_item a.tag3:hover{background:#ffc533;} .dr_mod2_item a.tag4:hover{background:#77bf2e;} .dr_mod2_item a.tag5:hover{background:#39c45d;} .dr_mod2_item a.tag6:hover{background:#33ddaf;} .dr_mod2_item a.tag7:hover{background:#33d9fd;} .dr_mod2_item a.tag8:hover{background:#3357b5;} .dr_mod2_item a.tag9:hover{background:#6933ab;} .dr_mod2_item a.tag10:hover{background:#b933be;} .dr_mod2_item a.tag11:hover{background:#fa74dd;} .dr_mod2_item a:hover{top:-10px;padding:10px 0px;} .dr_mod2_item a:hover strong{background:#fff;} .tag1 strong{background:#ff7c7c;} .tag2 strong{background:#ff4233;} .tag3 strong{background:#ffc533;} .tag4 strong{background:#77bf2e;} .tag5 strong{background:#39c45d;} .tag6 strong{background:#33ddaf;} .tag7 strong{background:#33d9fd;} .tag8 strong{background:#3357b5;} .tag9 strong{background:#6933ab;} .tag10 strong{background:#b933be;} .tag11 strong{background:#fa74dd;} .tag1:hover strong{color:#ff7c7c;} .tag2:hover strong{color:#ff4233;} .tag3:hover strong{color:#ffc533;} .tag4:hover strong{color:#77bf2e;} .tag5:hover strong{color:#39c45d;} .tag6:hover strong{color:#33ddaf;} .tag7:hover strong{color:#33d9fd;} .tag8:hover strong{color:#3357b5;} .tag9:hover strong{color:#6933ab;} .tag10:hover strong{color:#b933be;} .tag11:hover strong{color:#fa74dd;} .dr_btitle{font-size:24px;color:#333;height:84px;line-height:84px;text-align:center;padding-top:36px;} .dr_mod3list{width:1050px;margin:0px auto;font-size:0px;} .dr_mod3{background:#fff;width:330px;display:inline-block;margin:0px 10px 20px;transition:all ease 0.3s;box-shadow:0px;} .dr_mod3:hover{box-shadow:0px 10px 20px rgba(0,0,0,0.3);} .dr_mod3 .img,.dr_mod3 .img img{display:block;height:186px;width:330px;display:block;} .dr_mod3 .info{background:#fff;width:290px;padding:12px 20px 16px;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;} .dr_mod3 .info .title{font-size:18px;color:#333;line-height:30px;height:30px;display:block;width:100%;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;} .dr_mod3 .info .title:hover{color:#ff4c35;} .dr_mod3 .info .i{font-size:12px;color:#999;line-height:22px;height:22px;} .dr_mod3 .info .i img{display:inline-block;vertical-align:top;margin-right:2px;} .dr_mod3 .info .aun{height:22px;line-height:22px;color:#ff4c35;} .dr_mod3 .info .aun:hover{text-decoration:underline;} .dr_mod3 .info .des{font-size:14px;color:#666;padding:5px 0px 0px;margin-bottom:5px;line-height:22px;height:44px;white-space:normal;overflow:hidden;text-overflow:ellipsis;-webkit-line-clamp: 2;-webkit-box-orient: vertical;display: -webkit-box;} .dr_mod4{background:#fff;padding:16px;width:473px;overflow:hidden;font-size:0px;} .dr_mod4 .big{display:inline-block;vertical-align:top;height:262px;width:465px;overflow:hidden;margin:4px;position:relative;} .dr_mod4 .big .title{display:block;width:100%;height:60px;line-height:60px;padding-top:13px;background:url(../images/20160811114357_498.png) center top repeat-x;position:absolute;bottom:0px;left:0px;text-align:center;} .dr_mod4 .big .title strong{display:block;width:80%;margin:0px 10%;height:60px;line-height:60px;font-size:24px;font-weight:bold;color:#fff;text-align:center;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;} .dr_mod4 .big img{display:block;height:262px;width:465px;transition:all ease 0.3s;} .dr_mod4 .big:hover img{transform:scale(1.02);} .dr_mod4 .small{display:inline-block;vertical-align:top;height:84px;width:150px;overflow:hidden;margin:4px;} .dr_mod4 .small:last-child{margin-right:0px;} .dr_mod4 .small img{display:block;height:84px;width:150px;transition:all ease 0.3s;} .dr_mod4 .small:hover img{transform:scale(1.03);} .dr_mod5{width:345px;background:#fff;margin:0px 10px;padding-bottom:8px;display:inline-block;vertical-align:top;} .dr_mod5 .title{height:60px;line-height:60px;font-size:16px;color:#333;padding-left:20px;border-bottom:1px solid #f5f5f5;} .dr_mod5itemlist{padding:8px 0px;} .dr_mod5item{height:50px;padding:8px 20px 8px 80px;position:relative;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;} .dr_mod5item .ava{height:50px;width:50px;border-radius:25px;position:absolute;left:20px;top:8px;} .dr_mod5item .name{height:25px;line-height:25px;color:#333;font-size:16px;display:block;width:70%;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;} .dr_mod5item .des{height:25px;line-height:25px;font-size:13px;color:#999;display:block;width:70%;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;} .dr_mod5item .tag{display:block;position:absolute;right:20px;top:21px;height:24px;border-radius:2px;padding:0px 8px;color:#fff;font-size:12px;line-height:24px;} .dr_mod5item .name:hover{color:#ff4c35;text-decoration:underline;} .dr_mod5item .tag1{background:#ff7c7c;} .dr_mod5item .tag2{background:#ff4233;} .dr_mod5item .tag3{background:#ffc533;} .dr_mod5item .tag4{background:#77bf2e;} .dr_mod5item .tag5{background:#39c45d;} .dr_mod5item .tag6{background:#33ddaf;} .dr_mod5item .tag7{background:#33d9fd;} .dr_mod5item .tag8{background:#3357b5;} .dr_mod5item .tag9{background:#6933ab;} .dr_mod5item .tag10{background:#b933be;} .dr_mod5item .tag11{background:#fa74dd;} .dr_mod5item .btn{display:block;position:absolute;right:20px;top:21px;height:24px;border-radius:2px;padding:0px 8px;color:#fff;font-size:12px;line-height:24px;background:#ff4c35;} .dr_mod5item .gzed{color:#999;background:#f8f8f8;} .dr_xdr{position:relative;width:300px;height:481px;display:inline-block;vertical-align:top;margin:0px 10px;background:#fff url(../images/20160824100248_224.png) center 40px no-repeat;} .dr_xdr p{padding:154px 40px 0px;font-size:14px;line-height:23px;color:#666;} .dr_xdr .btn{height:44px;width:160px;line-height:44px;color:#fff;font-size:18px;text-align:center;background:#ff4c35;display:block;margin:100px auto 0px;border-radius:2px;transition:all ease 0.3s;position:absolute;left:70px;bottom:70px;} .dr_xdr .btn:hover{background:#e90808;} .dr_mod6item{width:822px;position:relative;border-bottom:1px dashed #eee;padding:24px 40px 24px 168px;background:#fff;height:70px;margin:0px 10px;} .dr_mod6item:hover{background:#fdfdfd;} .dr_mod6item .img{display:block;height:70px;width:124px;position:absolute;left:24px;top:24px;border-radius:2px;} .dr_mod6item .img img{display:block;height:70px;width:124px;border-radius:2px;} .dr_mod6item .title{height:36px;padding-top:4px;line-height:36px;width:70%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;} .dr_mod6item .title .tag{height:24px;line-height:24px;padding:0px 8px;margin-top:6px;display:inline-block;vertical-align:top;color:#fff;border-radius:2px;margin-right:6px;} .dr_mod6item .title .t{font-size:18px;color:#333;line-height:36px;} .dr_mod6item .title .t:hover{color:#ff4c35;text-decoration:underline;} .dr_mod6item .title .tag1{background:#ff7c7c;} .dr_mod6item .title .tag2{background:#ff4233;} .dr_mod6item .title .tag3{background:#ffc533;} .dr_mod6item .title .tag4{background:#77bf2e;} .dr_mod6item .title .tag5{background:#39c45d;} .dr_mod6item .title .tag6{background:#33ddaf;} .dr_mod6item .title .tag7{background:#33d9fd;} .dr_mod6item .title .tag8{background:#3357b5;} .dr_mod6item .title .tag9{background:#6933ab;} .dr_mod6item .title .tag10{background:#b933be;} .dr_mod6item .title .tag11{background:#fa74dd;} .dr_mod6item .des{line-height:26px;height:26px;color:#999;font-size:13px;width:70%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;} .dr_mod6item .des strong{font-weight:bold;color:#333;} .dr_mod6item .btn{display:block;transition:all ease 0.3s;border-radius:2px;height:36px;width:86px;color:#fff;text-align:center;line-height:36px;font-size:14px;position:absolute;right:40px;top:41px;} .dr_mod6item .btn1{background:#ff4c35;} .dr_mod6item .btn1:hover{background:#e90808;} .dr_mod6item .btn2{background:#92d96b;} .dr_mod6item .btn3{background:#aaaaaa;} .dr_mod6item .btn4{background:#dddddd;} .dr_mod6item .jltip{height:24px;line-height:24px;padding-left:24px;background:url(../images/20160811144358_913.png) 0px 0px no-repeat;position:absolute;right:140px;top:47px;color:#ffce0f;font-weight:bold;font-size:15px;} .dr_mod6_more{display:block;margin:0px 10px;height:60px;line-height:60px;text-align:center;color:#333;background:#fff;font-size:15px;} .dr_mod6_more:hover{color:#ff4c35;background:#fdfdfd;} .dr_mod6item .pphz{position:absolute;left:0px;top:0px;height:65px;width:65px;background:url(../images/20160824102654_986.png) 0px 0px no-repeat;} .dr_pageitem{width:1030px;height:40px;clear:both;margin:0px auto 0px;text-align:center;padding:20px 0px;font-size:0px;} .dr_pageitem ul{clear:both;} .dr_pageitem li{display:inline-block;vertical-align:top;*display:inline;*zoom:1;height:40px;text-align:center;background:#fff;line-height:40px;margin-right:10px ;color:#666;list-style: none;} .dr_pageitem li a{ display:inline-block;vertical-align:top;*display:inline;*zoom:1;padding:0px 16px;height:40px;text-align:center;background:#fff;line-height:40px; color:#666;list-style: none;} .dr_pageitem li a:hover{background:#ff4c35;color:#fff;} .dr_pageitem li a.current{background:#ff4c35;color:#fff;} .dr_path{height:60px;line-height:60px;width:1030px;margin:0px 10px;} .dr_path a{font-size:15px;color:#333;} .dr_path a:hover{color:#ff4c35;text-decoration:underline;} .dr_path span{font-size:15px;color:#333;} .dr_mod7{width:950px;margin:0px 10px;background:#fff;height:180px;padding:40px;border-bottom:1px dashed #eee;position:relative;} .dr_mod7 .img{height:180px;width:320px;float:left;border-radius:4px;} .dr_mod7 .dr_mod7info{height:180px;width:610px;padding-left:20px;float:left;} .dr_mod7 .dr_mod7info .t{margin-top:10px;height:24px;line-height:24px;color:#333;font-size:0px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;} .dr_mod7 .dr_mod7info .t .tag{height:24px;display:inline-block;vertical-align:top;padding:0px 8px;font-size:13px;color:#fff;border-radius:2px;} .dr_mod7 .dr_mod7info .t h1{display:inline-block;vertical-align:top;font-size:18px;font-weight:bold;padding-left:10px;text-overflow:ellipsis;white-space:nowrap;} .dr_mod7 .dr_mod7info .info1{height:24px;line-height:24px;margin-top:15px;font-size:15px;} .dr_mod7 .dr_mod7info .info1 strong{display:inline-block;vertical-align:top;font-weight:bold;padding-left:24px;background:url(../images/20160811144358_913.png) 0px 0px no-repeat;color:#ffce0f;padding-right:20px;} .dr_mod7 .dr_mod7info .info1 span{display:inline-block;vertical-align:top;padding-right:20px;} .dr_mod7 .dr_mod7info .info1 span.b{font-weight:bold;} .dr_mod7 .dr_mod7info .info2{height:24px;line-height:24px;margin-top:13px;font-size:13px;color:#999;} .dr_mod7 .dr_mod7info .info2 strong{font-weight:bold;color:#333;} .dr_mod7 .getmissionbtn{height:44px;line-height:44px;color:#fff;font-size:15px;width:106px;text-align:center;display:block;border-radius:4px;margin-top:15px;} .dr_mod7 .getmissionbtn_s1{background:#ff4c35;} .dr_mod7 .getmissionbtn_s1:hover{background:#e90808;} .dr_mod7 .getmissionbtn_s2{background:#92d96b;} .dr_mod7 .getmissionbtn_s3{background:#aaaaaa;} .dr_mod7 .getmissionbtn_s4{background:#dddddd;} .dr_mod7_pphz{height:91px;width:91px;background:url(../images/20160824102843_376.png) center no-repeat;position:absolute;left:0px;top:0px;} .dr_mod8{width:1030px;margin:0px 10px;background:#fff;padding:0px 0px 40px;} .dr_mission_para{padding:0px 100px;} .dr_mission_para p{color:#666;font-size:15px;line-height:24px;} .dr_mission_para p strong{font-weight:bold;color:#333;} .dr_mission_para p img{display:block;margin:10px 0px;} .dr_mod8 .getmissionbtn{width:144px;height:60px;line-height:60px;background:#ff4c35;color:#fff;font-size:24px;text-align:center;border-radius:4px;margin:40px auto 40px;display:block;transition:all ease 0.3s;} .dr_mod8 .getmissionbtn_s1{background:#ff4c35;} .dr_mod8 .getmissionbtn_s1:hover{background:#e90808;} .dr_mod8 .getmissionbtn_s2{background:#92d96b;} .dr_mod8 .getmissionbtn_s3{background:#aaaaaa;} .dr_mod8 .getmissionbtn_s4{background:#dddddd;} .dr_mod9{width:840px;margin:0px 10px;background:#fff;padding:60px 95px 20px;font-size:0px;} .dr_mod9item{height:150px;width:100px;margin:0px 10px;display:inline-block;vertical-align:top;transition:all ease 0.3s;position:relative;top:0px;} .dr_mod9item:hover{top:-3px;} .dr_mod9item img{display:block;height:100px;width:100px;border-radius:50px;} .dr_mod9item strong{line-height:36px;height:36px;color:#333;font-size:16px;text-align:center;display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;} .dr_mod9item:hover strong{color:#ff4c35;} .dr_getmission_box{height:100%;width:100%;background:#000;background:rgba(0,0,0,0.6);position:fixed;left:0px;top:0px;z-index:6000;display:none;} .dr_getmission_box_c{height:430px;width:800px;background:#fff;box-shadow:0px 0px 40px rgba(0,0,0,0.6);position:fixed;left:50%;top:50%;margin:-215px 0px 0px -400px;border-radius:2px;} .dr_getmission_box_c .topbar{height:60px;line-height:60px;font-size:22px;color:#333;text-align:center;border-bottom:1px dashed #eee;} .dr_getmission_box_c .info{padding:0px 40px;} .dr_getmission_box_c .info strong{font-size:18px;line-height:32px;display:block;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;margin-top:20px;} .dr_getmission_box_c .info span{color:#ff4c35;font-size:14px;line-height:24px;display:inline-block;vertical-align:top;padding-right:14px;} .dr_getmission_box_c .addrbox{width:72%;position:absolute;left:14%;bottom:0px;height:270px;font-size:0px;} .dr_getmission_box_c .addrbox .t{height:60px;line-height:60px;color:#333;text-align:center;display:block;font-weight:bold;font-size:15px;border-top:1px dashed #eee;} .dr_getmission_box_c .addrbox .addrinputw{height:32px;margin-bottom:10px;width:50%;display:inline-block;vertical-align:top;} .dr_getmission_box_c .addrbox .addrinputw span{width:80px;text-align:right;display:inline-block;vertical-align:top;font-size:13px;color:#666;text-align:right;line-height:32px;} .dr_getmission_box_c .addrbox .addrinputw span em{color:#ff4c35;} .dr_getmission_box_c .addrbox .addrinputw input{height:22px;line-height:22px;color:#333;font-size:15px;padding:4px;border:1px solid #ddd;border-radius:2px;width:180px;} .dr_getmission_box_c .addrbox .addrinputw_l{width:100%;} .dr_getmission_box_c .addrbox .addrinputw_l input{width:468px;} .dr_getmission_box_c .addrbox .addrsubmitw{width:100%;height:32px;line-height:32px;text-align:center;margin-top:14px;} .dr_getmission_box_c .addrbox .addrsubmitw .exit{height:30px;line-height:30px;border:1px solid #ddd;background:#f5f5f5;color:#666;font-size:15px;text-align:center;width:80px;display:inline-block;vertical-align:top;border-radius:2px;margin:0px 6px;} .dr_getmission_box_c .addrbox .addrsubmitw .exit:hover{background:#eee;} .dr_getmission_box_c .addrbox .addrsubmitw .submit{height:30px;line-height:30px;border:1px solid #e90808;background:#ff4c35;color:#fff;font-size:15px;text-align:center;width:80px;display:inline-block;vertical-align:top;border-radius:2px;margin:0px 6px;} .dr_getmission_box_c .addrbox .addrsubmitw .submit:hover{background:#e90808;} .dr_con_left{width:710px;margin:40px 10px 0px;display:inline-block;vertical-align:top;} .dr_mod10{width:100%;background:#fff;padding-bottom:1px;} .dr_mod10_tw{border-bottom:1px dashed #eee;padding:32px 40px 22px;} .dr_mod10_tw h1{font-size:21px;font-weight:bold;line-height:32px;text-align:center;color:#333;} .dr_mod10_tw .info{line-height:32px;font-size:14px;color:#999;text-align:center;display:block;} .dr_con_maincontxt{padding:40px 60px;} .dr_con_maincontxt p{font-size:15px;line-height:26px;color:#333;} .dr_con_maincontxt p img{display:block;margin:16px auto;max-width:590px;} .dr_con_maincontxt p strong{font-weight:bold;} .dr_con_maincontxt p a{color:#4a63d0;text-decoration:underline;} .dr_con_maincontxt p a:hover{color:#ff4c35;} .drcon_mzsm{width:588px;margin:40px auto;border:1px solid #eee;} .drcon_mzsm p{padding:20px 30px;font-size:15px;color:#999;line-height:23px;} .drcon_mzsm p strong{color:#333;} .drcon_mzsm p .red{color:#ff4c35;display:inline-block;vertical-align:top;padding-top:10px;} .dr_con_zanbox{width:588px;padding:40px 0px;border:1px dashed #eee;margin:0px auto 60px;} .dr_con_zanbox .zanbtn{height:64px;width:64px;line-height:64px;border-radius:32px;color:#fff;font-size:24px;text-align:center;background:#ff4c35;display:block;margin:0px auto;position:relative;} .dr_con_zanbox .zanbtn:hover{background:#e90808;} .dr_con_zanbox .zanbtn .yz{position:absolute;height:56px;width:56px;line-height:56px;color:#fff;background:#ff4c35;left:4px;top:4px;border-radius:28px;font-size:16px;display:none;} .dr_con_zanbox .zanbtned:hover .yz{display:block;} .dr_con_zanbox .zannumw{line-height:28px;height:28px;width:100%;text-align:center;color:#999;display:block;padding-top:6px;} .dr_con_zanbox .dr_con_sharebox{height:28px;width:92px;padding-left:6px;vertical-align:top;margin:0px auto;} .dr_con_zanbox .zanerlist{height:44px;width:432px;font-size:0px;text-align:center;overflow:hidden;margin:10px auto 0px;} .dr_con_zanbox .zanerlist a{display:inline-block;vertical-align:top;height:44px;width:44px;margin:0px 5px;border-radius:22px;overflow:hidden;} .dr_con_zanbox .zanerlist a img{display:block;height:44px;width:44px;border-radius:22px;} .showadd1{font-size:24px;position:absolute;width:64px;height:64px;line-height:64px;left:0px;top:0px;opacity:0;transition:all ease 1s;text-align:center;color:#ff4c35;} .showadd1.step1{top:-56px;opacity:1;transition:all ease 1s;} .showadd1.step2{top:-112px;opacity:0;transition:all ease 1s;} .postwz_mzsm{width:908px;margin:40px auto;border:1px solid #eee;} .postwz_mzsm p{padding:20px 30px;font-size:13px;color:#999;line-height:22px;} .postwz_mzsm p strong{color:#333;} .postwz_mzsm p .red{color:#ff4c35;display:inline-block;vertical-align:top;padding-top:10px;} .dr_con_right{width:300px;display:inline-block;vertical-align:top;margin:40px 10px 0px;} .dr_mod11{width:300px;margin:0px auto;background:#fff;padding-bottom:40px;} .dr_mod11 .ava{display:block;height:150px;width:150px;position:relative;padding-top:40px;margin:0px auto 0px;} .dr_mod11 .ava img{display:block;height:150px;width:150px;border-radius:75px;} .dr_mod11 .dricon{display:block;right:5px;bottom:5px;height:32px;width:32px;position:absolute;background:url(../images/20160812140555_974.png) center no-repeat;} .dr_mod11 .aun{width:220px;text-align:center;white-space: nowrap;overflow:hidden;text-overflow:ellipsis;display:block;height:36px;font-size:21px;color:#333;text-align:center;line-height:36px;margin:6px auto 0px;} .dr_mod11 .aun:hover{color:#ff4c35;} .dr_mod11 .sign{width:220px;padding:4px 0px;display:block;margin:0px auto;text-align:center;color:#999;font-size:13px;line-height:18px;} .dr_mod11 .info1{width:300px;border-bottom:1px dashed #eee;height:70px;margin-top:10px;font-size:0px;} .dr_mod11 .info1 .item{width:149px;display:inline-block;vertical-align:top;text-align:center;height:70px;} .dr_mod11 .info1 .item strong{color:#ff4c35;font-size:24px;line-height:34px;display:block;} .dr_mod11 .info1 .item span{color:#999;font-size:12px;line-height:22px;display:block;} .dr_mod11 .info1 .item:first-child{border-right:1px dashed #eee;} .dr_mod11 .info2{padding:32px 60px 0px;} .dr_mod11 .info2 p{font-size:13px;line-height:24px;color:#999;} .dr_mod11 .gzbtn{display:block;height:32px;width:90px;text-align:center;font-size:14px;color:#fff;border-radius:4px;background:#ff4c35;line-height:32px;margin:20px auto 0px;} .dr_mod11 .gzbtn:hover{background:#e90808;} .dr_mod11 .gzbtned{background:#eee;color:#666;} .dr_mod11 .gzbtned:hover{background:#eee;} .dr_mod12{width:990px;background:#fff;height:310px;padding: 20px;margin:40px 10px 0px;position:relative;font-size:0px;} .dr_mod12 .topimg{height:310px;width:551px;display:inline-block;vertical-align:top;} .dr_mod12 .infow{height:310px;width:399px;padding-left:20px;display:inline-block;vertical-align:top;} .dr_mod12 .infow h1{display:inline-block;vertical-align:top;line-height:22px;line-height:32px;color:#333;font-size:22px;padding:5px 0px;} .dr_mod12 .infow .tag{height:30px;padding:0px 10px;border-radius:2px;font-size:16px;line-height:30px;color:#fff;display:inline-block;vertical-align:top;margin-top:10px;} .dr_mod12 .infow .info{padding-top:15px;} .dr_mod12 .infow .info p{font-size:15px;line-height:24px;color:#666;} .dr_mod12 .infow .morebtn{display:inline-block;vertical-align:top;padding:0px 14px;height:40px;line-height:40px;border-radius:2px;color:#fff;font-size:15px;background:#ff4c35;margin-top:15px;} .dr_mod12 .infow .morebtn:hover{background:#e90808;} .dr_mod12 .pphz{position:absolute;left:0px;top:0px;background:url(../images/20160824103108_208.png) center no-repeat;height:119px;width:119px;} .xqw{width:1050px;margin:0px auto;border-top:1px dashed #eee;display:none;} .dr_xqw_slideUpbtn{width:1030px;margin:0px 10px;height:60px;text-align:center;cursor:pointer;font-size:15px;color:#333;line-height:60px;background:#fff;border-top:1px dashed #eee;} .dr_xqw_slideUpbtn:hover{color:#ff4c35;} .dr_mod13{width:990px;background:#fff;padding: 40px 0px 40px 40px;margin:0px auto 0px;position:relative;font-size:0px;} .dr_mod13_item{width:316px;height:140px;position:relative;display:inline-block;vertical-align:top;} .dr_mod13_item a{display:block;height:100px;width:186px;padding:20px 0px 20px 130px;position:relative;transition:all ease 0.5s;background:#fff;} .dr_mod13_item a:hover{background:#f5f5f5;} .dr_mod13_item a img{display:block;position:absolute;left:20px;top:20px;height:100px;width:100px;border-radius:50px;} .dr_mod13_item a .aun{font-size:16px;color:#333;line-height:26px;display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-top:12px;} .dr_mod13_item a span{font-size:14px;color:#999;line-height:24px;display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;} .dr_mod13_more{height:60px;line-height:60px;width:1030px;background:#fff;margin:0px auto;border-top:1px dashed #eee;} .dr_mod13_more a{display:block;line-height:60px;font-size:15px;color:#333;width:100%;height:60px;text-align:center;} .dr_mod13_more a:hover{color:#ff4c35;background:#fdfdfd;} .forediter{width:588px;border:1px solid #eee;margin:40px auto;padding:0px 0px;} .forediter .t{height:60px;line-height:60px;color:#333;text-align:center;font-size:15px;font-weight:bold;} .forediter .w{padding:0px 24px;line-height:24px;font-size:15px;color:#666;} .forediter .w p{font-size:14px;} .forediter .w .text{height:22px;line-height:22px;width:400px;padding:6px;border:1px solid #eee;border-radius:4px;margin-top:4px;display:inline-block;vertical-align:top;color:#333;font-size:14px;} .forediter .w .submit{height:36px;line-height:36px;width:70px;border-radius:4px;margin-top:4px;display:inline-block;vertical-align:top;color:#fff;background:#ff4c35;border:0px;font-size:14px;cursor:pointer;} .forediter .btns{margin-top:24px;border-top:1px solid #eee;text-align:center;padding:20px 0px;font-size:0px;} .forediter .btns a{display: inline-block;vertical-align:top;margin:0px 10px;height:44px;padding:0px 20px;font-size:15px;color:#fff;line-height:44px;border-radius:4px;transition:all ease 0.3s;position:relative;top:0px;} .forediter .btns a.blue{background:#77bf2e;} .forediter .btns a.red{background:#ff4c35;} .forediter .btns a.grey{background:#aaa;} .forediter .btns a:hover{top:-3px;} .postwz_w{width:910px;background:#fff;margin:0px 10px;padding:60px;} .postwz_w .row{width:700px;font-size:0px;margin:0px auto 16px;} .postwz_w .row .lw{width:100px;text-align:right;font-size:15px;color:#333;line-height:40px;display:inline-block;vertical-align:top;} .postwz_w .row .rw{width:600px;display:inline-block;vertical-align:top;} .postwz_w .row .rw .titletext{font-size:14px;color:#333;height:22px;line-height:22px;padding:8px;border:1px solid #ddd;border-radius:2px;width:400px;} .postwz_w .row .uploadfilebtn{color:#fff;height:40px;width:144px;background:#ff4c35;border-radius:2px;line-height:40px;text-align:center;font-size:15px;position:relative;overflow:hidden;} .postwz_w .row .uploadfilebtn:hover{background:#e90808;} .postwz_w .row .uploadfilebtn input{display:block;height:40px;line-height:40px;font-size:40px;opacity:0;top:0px;right:0px;position:absolute;cursor:pointer;} .postwz_w .row .error{line-height:40px;padding-top:16px;font-size:15px;color:#ff4c35;display:none;} .postwz_w .row .btnsw{width:100%;height:40px;text-align:center;padding-top:40px;border-top:1px dashed #ddd;margin-top:40px;} .postwz_w .row .btnsw a{color:#fff;background:#ff4c35;text-align:center;display:inline-block;vertical-align:top;margin:0px 10px;padding:0px 24px;height:40px;line-height:40px;font-size:15px;} .postwz_w .row .btnsw a:hover{background:#e90808;} .dr_mod14w{width:100%;} .dr_mod14{width:942px;height:90px;padding:24px;display:block;border-bottom:1px dashed #ddd;} .dr_mod14 .img{height:90px;width:160px;border-radius:2px;display:block;float:left;} .dr_mod14 .img img{height:90px;width:160px;border-radius:2px;display:block;} .dr_mod14 .info{float:left;height:90px;position:relative;width:768px;padding-left:14px;} .dr_mod14 .info .rwn{height:24px;line-height:24px;font-size:16px;color:#333;padding-top:6px;display:inline-block;vertical-align:top;} .dr_mod14 .info .rwn:hover{color:#ff4c35;text-decoration:underline;} .dr_mod14 .info .rwtype{line-height:24px;font-size:13px;color:#999;display:inline-block;vertical-align:top;padding-top:2px;} .dr_mod14 .info .rwstate{line-height:24px;display:inline-block;vertical-align:top;font-size:13px;} .dr_mod14 .info .s_black{color:#333;} .dr_mod14 .info .s_red{color:#ff4c35;} .dr_mod14 .info .s_green{color:#77bf2e;} .dr_mod14 .info .lastedittime{font-size:13px;color:#999;position:absolute;display:block;height:24px;line-height:24px;text-align:right;right:0px;top:6px;} .dr_mod14 .info .gobtn{height:40px;border-radius:2px; background:#ff4c35;color:#fff;line-height:40px;padding:0px 14px;font-size:15px;position:absolute;right:0px;bottom:6px;} .dr_mod14 .info .gobtn:hover{background:#e90808;} .dr_mod15{width:942px;height:135px;padding:24px;display:block;border-bottom:1px dashed #ddd;} .dr_mod15 .img{height:135px;width:240px;border-radius:2px;display:block;float:left;} .dr_mod15 .img img{height:135px;width:240px;border-radius:2px;display:block;} .dr_mod15 .info{float:left;height:135px;position:relative;width:688px;padding-left:14px;} .dr_mod15 .info .rwn{height:24px;line-height:24px;font-size:18px;color:#333;padding-top:6px;display:inline-block;vertical-align:top;} .dr_mod15 .info .rwn:hover{color:#ff4c35;text-decoration:underline;} .dr_mod15 .info .i{font-size:12px;color:#999;line-height:22px;height:22px;padding-top:6px;} .dr_mod15 .info .i img{display:inline-block;vertical-align:top;margin-right:2px;} .dr_mod15 .info .des{font-size:14px;color:#666;padding:5px 0px 0px;margin-bottom:5px;line-height:22px;height:66px;white-space:normal;overflow:hidden;text-overflow:ellipsis;-webkit-line-clamp: 3;-webkit-box-orient: vertical;display: -webkit-box;} .dr_mod15 .info .lastedittime{font-size:13px;color:#999;position:absolute;display:block;height:24px;line-height:24px;text-align:right;right:0px;top:6px;} .postpl_ww{width:710px;margin:0px auto;padding-bottom:40px;background:#fff;padding-top:40px;} .postpl_w{height:120px;margin:0px auto;padding:0px 40px 0px 40px;} .postpl_w a{display:block;height:80px;width:80px;float:left;border-radius:8px;overflow:hidden;} .postpl_w a img{display:block;height:80px;width:80px;} .postplform{height:120px;float:left;padding-left:10px;position:relative;} .postplform textarea{line-height:22px;background:#eee;color:#333;padding:6px 10px;overflow:auto;height:68px;width:518px;border:0px;border-radius:8px;overflow:hidden;font-size:14px;} .postplform input{position:absolute;right:0px;bottom:0px;height:32px;width:66px;background:#ff4c35;color:#fff;text-align:center;font-size:14px;border:0px;} .postplform input:hover{background:#e90808;cursor:pointer;} .plitem{width:628px;padding:20px 40px 0px;margin:0px auto;} .plitem .img{display:block;height:80px;width:80px;border-radius:8px;overflow:hidden;float:left;} .plitem .img img{display:block;height:80px;width:80px;} .plitem .plcon{width:518px;padding-left:10px;float:left;position:relative;} .plitem .plcon .name{font-size:12px;color:#ff4c35;font-weight:bold;line-height:18px;} .plitem .plcon p{font-size:14px;color:#333;line-height:22px;padding:6px 0px;} .plitem .plcon .time{line-height:18px;color:#999;} .plcon a.re{position:absolute;right:0px;color:#ff4c35;} .plcon a.re:hover{text-decoration:underline;} .comscoms ul li div.c1{float:left;margin-left:10px;} .comscoms{padding:10px 20px 0px 20px;background:#eee;margin-bottom:20px;clear:both;margin-left:90px;border-radius:10px;margin-top:10px;margin-right:20px;position:relative;top:10px;} .comscoms ul{} .comscoms ul li{border-bottom:1px solid #c9c9c9;padding:10px 0px 0px 46px;position:relative;} .comscoms ul li.hided{display:none;} .comscoms ul li div.c1 p.p2{font-size:12px;color:#666;line-height:20px;padding-bottom:4px;} .comscoms ul li div.c1 p.p2 a{color:#ff4c35;padding-right:2px;font-size: 12px;} .comscoms ul li div.c1 p.p2 a:hover{text-decoration:underline;} .comscoms ul li div.c1 p.p2 a.v_small{height:20px;} .comscoms ul li a.avatar1{height:36px;width:36px;float:left;margin-bottom:10px;position:absolute;left:0px;top:10px;} .comscoms ul li a.avatar1 img{display:block;height:36px;width:36px;} .morepls{height:32px;float:left;color:#999;display:block;margin-top:10px;line-height:32px;} .morepls a{color:#ff4c35;} .morepls a:hover{text-decoration:underline;} .pagebtns{height:32px;float:left;color:#999;display:block;padding-top:8px;} .pagebtns a{color:#ff4c35;padding:0px 3px;display:inline-block;vertical-align:top;*display:inline;*zoom:1;height:32px;line-height:32px;} .pagebtns a.current{color:#333;font-size:12px;font-weight:bold;padding:0px 3px;display:inline-block;vertical-align:top;*display:inline;*zoom:1;height:32px;line-height:32px;} .pagebtns a:hover{text-decoration:underline;} .pagebtns a.current{text-decoration: none;} .saybtn{height:32px;width:100px;background:#ff4c35;border:1px solid #ff4c35;display:block;float:right;line-height:32px;color:#fff;text-align:center;margin:10px 0px 20px} .saybtn:hover{background:#ff4c35;} .saybtn_ed{background:#eee;border:1px solid #ddd;color:#888;} .saybtn_ed:hover{background:#c9c9c9;} .comscoms ul li span.a{color:#ff4c35;line-height:18px;} .re_form{float:right;width:478px;height:150px;position:relative;top:-10px;display:none;} .re_form textarea{height:70px;width:448px;padding:14px;border:1px solid #ddd;background:#fff;font-size:14px;color:#333;} .re_form input{position:absolute;right:0px;bottom:10px;height:30px;width:80px;color:#fff;font-size:12px;text-align:center;background:#ff4c35;border:1px solid #ff4c35;line-height:30px;} .re_form input:hover{background:#e90808;cursor:pointer;} .comscoms li div.info{position:relative;height:40px;line-height:40px;color:#999;} .comscoms li div.info span a{color:#ff4c35;padding:0px 3px;} .comscoms li div.info span a:hover{text-decoration:underline;} .comscoms div.info a.re{color:#999;position:absolute;right:0px;top:0px;line-height:40px;display:inline-block;vertical-align:top;*display:inline;*zoom:1;} .comscoms div.info a.re:hover{color:#ff4c35;text-decoration:underline;} .comscoms div.info1{position:relative;height:36px;line-height:30px;color:#999;} .comscoms div.info1 span a{color:#ff4c35;padding:0px 3px;} .comscoms div.info1 span a:hover{text-decoration:underline;} .postpl_ww_forw1030{width:1030px;} .postpl_ww_forw1030 .postplform textarea{width:838px;} .postpl_ww_forw1030 .plitem{width:948px;} .postpl_ww_forw1030 .plitem .plcon{width:838px;} .postpl_ww_forw1030 .re_form{width:798px;} .postpl_ww_forw1030 .re_form textarea{width:768px;} /*CutPage*/ .nav_zuopin_8{width:710px;height:40px;clear:both;margin:0px auto 0px;text-align:center;padding:40px 0px;} .nav_zuopin_8 ul{clear:both;} .nav_zuopin_8 li{display:inline-block;vertical-align:top;*display:inline;*zoom:1;height:40px;text-align:center;background:#fff;line-height:40px;margin-right:10px ;color:#666;list-style: none;} .nav_zuopin_8 li a{ display:inline-block;vertical-align:top;*display:inline;*zoom:1;padding:0px 16px;height:40px;text-align:center;background:#f5f5f5;line-height:40px; color:#666;list-style: none;} .nav_zuopin_8 li a:hover{background:#ff4c35;color:#fff;} .nav_zuopin_8 li span{ display:inline-block;vertical-align:top;*display:inline;*zoom:1;padding:0px 16px;height:40px;text-align:center;background:#ff4c35;line-height:40px; color:#fff;list-style: none;} .mt30{margin-top:30px;} .mt60{margin-top:60px;} .pt0{padding-top:0px;} .w1050{width:1050px;margin:0px auto;font-size:0px;} .mt-20{margin-top:-20px;} .w505{width:505px;margin:0px 10px;display:inline-block;vertical-align:top;} .hidd1 { width: 0!important; height: 0!important; opacity: 0; visibility: hidd1en!important; display: none!important;} .hidd{opacity: 0!important;filter: alpha(opacity=0)!important;width: 0!important;height: 0!important;transition: opacity .3s;visibility: hidden;margin: 0!important;padding: 0!important;} .drtag1{background:#ff7c7c;} .drtag2{background:#ff4233;} .drtag3{background:#ffc533;} .drtag4{background:#77bf2e;} .drtag5{background:#39c45d;} .drtag6{background:#33ddaf;} .drtag7{background:#33d9fd;} .drtag8{background:#3357b5;} .drtag9{background:#6933ab;} .drtag10{background:#b933be;} .drtag11{background:#fa74dd;}
{ "content_hash": "e80181915b992bc2ad18e50592c3c471", "timestamp": "", "source": "github", "line_count": 550, "max_line_length": 253, "avg_line_length": 63.99818181818182, "alnum_prop": 0.7790846330861673, "repo_name": "IceIceWZ/www.iceicewz.cn", "id": "807c74dab37927c9eaf3b62d68bb74e967369486", "size": "35213", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/static/index/css/dr2016.css", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "46548" }, { "name": "ApacheConf", "bytes": "242" }, { "name": "Batchfile", "bytes": "261" }, { "name": "CSS", "bytes": "1371534" }, { "name": "HTML", "bytes": "455939" }, { "name": "JavaScript", "bytes": "4176839" }, { "name": "PHP", "bytes": "1154237" }, { "name": "PLpgSQL", "bytes": "3807" }, { "name": "Shell", "bytes": "248" }, { "name": "Smarty", "bytes": "35785" } ], "symlink_target": "" }
package com.meltmedia.jgroups.aws; import com.amazonaws.services.ec2.model.Tag; import org.junit.Test; import java.util.List; import static com.meltmedia.jgroups.aws.Mocks.ec2Mock; import static org.junit.Assert.*; public class TagUtilsTest { private static InstanceIdentity instanceIdentity = new InstanceIdentity( "zone", "1.2.3.4", "instance_id", "instance_type", "image_id", "architecture", "region"); @Test public void canHandleNullTagString() { final TagsUtils tagsUtils = new TagsUtils(ec2Mock(), instanceIdentity, null); assertFalse(tagsUtils.getAwsTagNames().isPresent()); } @Test public void canHandleEmptyTagString() { final TagsUtils tagsUtils = new TagsUtils(ec2Mock(), instanceIdentity, ""); assertFalse(tagsUtils.getAwsTagNames().isPresent()); } @Test public void willParseConfiguredTags() { final Tag instanceTag1 = new Tag("tag1", "value1"); final Tag instanceTag2 = new Tag("tag2", "value2"); final TagsUtils tagsUtils = new TagsUtils(ec2Mock(instanceTag1, instanceTag2), instanceIdentity, "tag1, tag2").validateTags(); assertTrue(tagsUtils.getAwsTagNames().isPresent()); tagsUtils.getAwsTagNames().ifPresent(tags -> { assertEquals(2, tags.size()); assertArrayEquals(new String[]{"tag1", "tag2"}, tags.toArray()); }); } @Test public void canGetInstanceTags() { final Tag instanceTag1 = new Tag("instanceTag1", "value1"); final Tag instanceTag2 = new Tag("instanceTag2", "value2"); final TagsUtils tagsUtils = new TagsUtils(ec2Mock(instanceTag1, instanceTag2), instanceIdentity, null).validateTags(); final List<Tag> tags = tagsUtils.getInstanceTags(); assertEquals(2, tags.size()); Tag tag1 = tags.get(0); Tag tag2 = tags.get(1); assertEquals("instanceTag1", tag1.getKey()); assertEquals("value1", tag1.getValue()); assertEquals("instanceTag2", tag2.getKey()); assertEquals("value2", tag2.getValue()); } @Test(expected = IllegalStateException.class) public void missingInstanceTagsShouldThrowException() { final Tag instanceTag1 = new Tag("tag1", "value1"); final Tag instanceTag2 = new Tag("tag2", "value2"); new TagsUtils(ec2Mock(instanceTag1, instanceTag2), instanceIdentity, "tag1, tag2, tag3").validateTags(); } }
{ "content_hash": "943b5d64032b0d8e0aa1b6254e98987d", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 130, "avg_line_length": 32.859154929577464, "alnum_prop": 0.6982426060865838, "repo_name": "meltmedia/jgroups-aws", "id": "21bcf597ce31a4a3006fc4bbda9237d17b44bf54", "size": "2333", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "src/test/java/com/meltmedia/jgroups/aws/TagUtilsTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "43321" } ], "symlink_target": "" }
<?php echo form_open(uri_string(), 'class="crud"') ?> <div class="exams-form"> <div class="one_full"> <section class="title"> <h4>Exam Information</h4> </section> <section class="item"> <label> <span>Name:</span> <?php echo form_input('name', '') ?> </label> <label> <span>Version:</span> <?php echo form_input('version', '1.0') ?> </label> <label> <span>Description:</span> <?php echo form_input('description', '') ?> </label> </section> </div> <div class="one_full"> <section class="title"> <h4>Question 1</h4> </section> <section class="item"> <label> <span>Text:</span> <?php echo form_textarea('query1_text', '') ?> </label> <label> <span>Option 1:</span> <?php echo form_textarea('query1_option[]', '1.0') ?> <span class="exams-controls"> <input type="checkbox" name="query1_answer[]" value="correct" title="This is a correct answer." /> <button type="submit" name="query1_deleteoption[]" value="1" class="button actions" title="Delete this option.">-</button> </span> </label> <label> <span>Option 2:</span> <?php echo form_textarea('query1_option[]', '') ?> <span class="exams-controls"> <input type="checkbox" name="query1_answer[]" value="correct" title="This is a correct answer." class="correct-answer" /> <button type="submit" name="query1_deleteoption[]" value="2" class="button actions" title="Delete this option.">-</button> </span> </label> <label> <span>Option 3:</span> <?php echo form_textarea('query1_option[]', '') ?> <span class="exams-controls"> <input type="checkbox" name="query1_answer[]" value="correct" title="This is a correct answer." class="correct-answer" /> <button type="submit" name="query1_deleteoption[]" value="3" class="button actions" title="Delete this option.">-</button> </span> </label> <label> <span>Option 4:</span> <?php echo form_textarea('query1_option[]', '') ?> <span class="exams-controls"> <input type="checkbox" name="query1_answer[]" value="correct" title="This is a correct answer." class="correct-answer" /> <button type="submit" name="query1_addoption" value="true" class="button actions" title="Add an option below this one.">+</button> </span> </label> </section> <section> <label> <button type="submit" class="button" name="addquery" value="2" title="Add a query below this one.">+</button> </label> </section> </div> <div class="one_full"> <section> <label> <button type="submit" class="btn blue">Save</button> <button type="submit" class="btn red" name="delete" value="delete">Delete</button> <button type="submit" class="btn gray" name="cancel" value="cancel">Cancel</button> </label> </section> </div> </div> <?php echo form_close() ?>
{ "content_hash": "a225733018d3355aac4e824a7042e36e", "timestamp": "", "source": "github", "line_count": 84, "max_line_length": 135, "avg_line_length": 33.976190476190474, "alnum_prop": 0.6163279607568325, "repo_name": "KingCountySAR/KCSARA_Exams", "id": "e525c365ca9999c0b03aa17119152719b3164c09", "size": "2854", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "views/admin/create.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1045" }, { "name": "PHP", "bytes": "72499" } ], "symlink_target": "" }
classdef TestRunDisplay < TestRunMonitor %TestRunDisplay Print test suite execution results. % TestRunDisplay is a subclass of TestRunMonitor. If a TestRunDisplay % object is passed to the run method of a TestComponent, such as a % TestSuite or a TestCase, it will print information to the Command % Window (or specified file handle) as the test run proceeds. % % TestRunDisplay methods: % testComponentStarted - Update Command Window display % testComponentFinished - Update Command Window display % testCaseFailure - Log test failure information % testCaseError - Log test error information % % TestRunDisplay properties: % TestCaseCount - Number of test cases executed % Faults - Struct array of test fault info % % See also TestRunLogger, TestRunMonitor, TestSuite % Steven L. Eddins % Copyright 2008-2010 The MathWorks, Inc. properties (SetAccess = private) %TestCaseCount - Number of test cases executed TestCaseCount %Faults - Struct array of test fault info % Faults is a struct array with these fields: % Type - either 'failure' or 'error' % TestCase - the TestCase object that suffered the fault % Exception - the MException thrown when the fault occurred Faults = struct('Type', {}, 'TestCase', {}, 'Exception', {}); end properties (SetAccess = private, GetAccess = private) %InitialTic - Out of tic at beginning of test run InitialTic %InitialComponent First test component executed % InitialComponent is set to the first test component executed in the % test run. This component is saved so that the end of the test run % can be identified. InitialComponent = [] end properties (Access = protected) %FileHandle - Handle used by fprintf for displaying results. % Default value of 1 displays to Command Window. FileHandle = 1 end methods function self = TestRunDisplay(output) if nargin > 0 if ischar(output) self.FileHandle = fopen(output, 'w'); if self.FileHandle < 0 error('xunit:TestRunDisplay:FileOpenError', ... 'Could not open file "%s" for writing.', ... filename); end else self.FileHandle = output; end end end function testComponentStarted(self, component) %testComponentStarted Update Command Window display % If the InitialComponent property is not yet set, % obj.testComponentStarted(component) sets the property and calls % obj.testRunStarted(component). if isempty(self.InitialComponent) self.InitialComponent = component; self.testRunStarted(component); end end function testComponentFinished(self, component, did_pass) %testComponentFinished Update Command Window display % If component is a TestCase object, then % obj.testComponentFinished(component, did_pass) prints pass/fail % information to the Command Window. % % If component is the InitialComponent, then % obj.testRunFinished(did_pass) is called. if isa(component, 'TestCase') self.TestCaseCount = self.TestCaseCount + 1; if did_pass fprintf(self.FileHandle, '.'); else fprintf(self.FileHandle, 'F'); end line_length = 20; if mod(self.TestCaseCount, line_length) == 0 fprintf(self.FileHandle, '\n'); end end if isequal(component, self.InitialComponent) self.testRunFinished(did_pass); end end function testCaseFailure(self, test_case, failure_exception) %testCaseFailure Log test failure information % obj.testCaseFailure(test_case, failure_exception) logs the test % case failure information. self.logFault('failure', test_case, ... failure_exception); end function testCaseError(self, test_case, error_exception) %testCaseError Log test error information % obj.testCaseError(test_case, error_exception) logs the test % case error information. self.logFault('error', test_case, ... error_exception); end end methods (Access = protected) function testRunStarted(self, component) %testRunStarted Update Command Window display % obj.testRunStarted(component) displays information about the test % run to the Command Window. self.InitialTic = tic; self.TestCaseCount = 0; num_cases = component.numTestCases(); if num_cases == 1 str = 'case'; else str = 'cases'; end fprintf(self.FileHandle, 'Starting test run with %d test %s.\n', ... num_cases, str); end function testRunFinished(self, did_pass) %testRunFinished Update Command Window display % obj.testRunFinished(component) displays information about the test % run results, including any test failures, to the Command Window. if did_pass result = 'PASSED'; else result = 'FAILED'; end fprintf(self.FileHandle, '\n%s in %.3f seconds.\n', result, toc(self.InitialTic)); self.displayFaults(); end function logFault(self, type, test_case, exception) %logFault Log test fault information % obj.logFault(type, test_case, exception) logs test fault % information. type is either 'failure' or 'error'. test_case is a % TestCase object. exception is an MException object. self.Faults(end + 1).Type = type; self.Faults(end).TestCase = test_case; self.Faults(end).Exception = exception; end function displayFaults(self) %displayFaults Display test fault info to Command Window % obj.displayFaults() displays a summary of each test failure and % test error to the command window. for k = 1:numel(self.Faults) faultData = self.Faults(k); if strcmp(faultData.Type, 'failure') str = 'Failure'; else str = 'Error'; end fprintf(self.FileHandle, '\n===== Test Case %s =====\nLocation: %s\nName: %s\n\n', str, ... faultData.TestCase.Location, faultData.TestCase.Name); displayStack(filterStack(faultData.Exception.stack), ... self.FileHandle); fprintf(self.FileHandle, '\n%s\n', faultData.Exception.message); fprintf(self.FileHandle, '\n'); end end end end function displayStack(stack, file_handle) %displayStack Display stack trace from MException instance % displayStack(stack) prints information about an exception stack to the % command window. for k = 1:numel(stack) filename = stack(k).file; linenumber = stack(k).line; href = sprintf('matlab: opentoline(''%s'',%d)', filename, linenumber); fprintf(file_handle, '%s at <a href="%s">line %d</a>\n', filename, href, linenumber); end end function new_stack = filterStack(stack) %filterStack Remove unmeaningful stack trace calls % new_stack = filterStack(stack) removes from the input stack trace calls % that are framework functions and methods that are not likely to be % meaningful to the user. % Testing stack traces follow this common pattern: % % 1. The first function call in the trace is often one of the assert functions % in the framework directory. This is useful to see. % % 2. The next function calls are in the user-written test functions/methods and % the user-written code under test. These calls are useful to see. % % 3. The final set of function calls are methods in the various framework % classes. There are usually several of these calls, which clutter up the % stack display without being that useful. % % The pattern above suggests the following stack filtering strategy: Once the % stack trace has left the framework directory, do not follow the stack trace back % into the framework directory. mtest_directory = fileparts(which('runtests')); last_keeper = numel(stack); have_left_mtest_directory = false; for k = 1:numel(stack) directory = fileparts(stack(k).file); if have_left_mtest_directory if strcmp(directory, mtest_directory) % Stack trace has reentered mtest directory. last_keeper = k - 1; break; end else if ~strcmp(directory, mtest_directory) have_left_mtest_directory = true; end end end new_stack = stack(1:last_keeper); end
{ "content_hash": "5676f8f435e9c6ceeb16bd2b6bcdc6dd", "timestamp": "", "source": "github", "line_count": 258, "max_line_length": 111, "avg_line_length": 37.87596899224806, "alnum_prop": 0.5788988948014736, "repo_name": "Heathckliff/cantera", "id": "57ae200c754860ca858fa9802df141e9c056cab1", "size": "9772", "binary": false, "copies": "14", "ref": "refs/heads/master", "path": "ext/matlab_xunit/TestRunDisplay.m", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "1935303" }, { "name": "C++", "bytes": "6751664" }, { "name": "CSS", "bytes": "2167" }, { "name": "FORTRAN", "bytes": "1175454" }, { "name": "Groff", "bytes": "2843" }, { "name": "HTML", "bytes": "17002" }, { "name": "M", "bytes": "980" }, { "name": "Matlab", "bytes": "284988" }, { "name": "Python", "bytes": "1055361" }, { "name": "Shell", "bytes": "2662" } ], "symlink_target": "" }
// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "../../include/pdfwindow/PDFWindow.h" #include "../../include/pdfwindow/PWL_Wnd.h" #include "../../include/pdfwindow/PWL_ListCtrl.h" #include "../../include/pdfwindow/PWL_IconList.h" #include "../../include/pdfwindow/PWL_Utils.h" #include "../../include/pdfwindow/PWL_ScrollBar.h" #include "../../include/pdfwindow/PWL_Label.h" #define PWL_IconList_ITEM_ICON_LEFTMARGIN 10.0f #define PWL_IconList_ITEM_WIDTH 20.0f #define PWL_IconList_ITEM_HEIGHT 20.0f #define PWL_IconList_ITEM_SPACE 4.0f /* ------------------ CPWL_IconList_Item ------------------- */ CPWL_IconList_Item::CPWL_IconList_Item() : m_nIconIndex(-1), m_pData(NULL), m_bSelected(FALSE), m_pText(NULL) {} CPWL_IconList_Item::~CPWL_IconList_Item() {} CFX_ByteString CPWL_IconList_Item::GetClassName() const { return "CPWL_IconList_Item"; } FX_FLOAT CPWL_IconList_Item::GetItemHeight(FX_FLOAT fLimitWidth) { return PWL_IconList_ITEM_HEIGHT; } void CPWL_IconList_Item::DrawThisAppearance(CFX_RenderDevice* pDevice, CPDF_Matrix* pUser2Device) { CPDF_Rect rcClient = GetClientRect(); if (m_bSelected) { if (IsEnabled()) { CPWL_Utils::DrawFillRect( pDevice, pUser2Device, rcClient, CPWL_Utils::PWLColorToFXColor(PWL_DEFAULT_SELBACKCOLOR, GetTransparency())); } else { CPWL_Utils::DrawFillRect( pDevice, pUser2Device, rcClient, CPWL_Utils::PWLColorToFXColor(PWL_DEFAULT_LIGHTGRAYCOLOR, GetTransparency())); } } CPDF_Rect rcIcon = rcClient; rcIcon.left += PWL_IconList_ITEM_ICON_LEFTMARGIN; rcIcon.right = rcIcon.left + PWL_IconList_ITEM_WIDTH; CPWL_Utils::DrawIconAppStream(pDevice, pUser2Device, m_nIconIndex, rcIcon, m_crIcon, m_pText->GetTextColor(), GetTransparency()); } void CPWL_IconList_Item::SetSelect(FX_BOOL bSelected) { m_bSelected = bSelected; if (bSelected) m_pText->SetTextColor(PWL_DEFAULT_WHITECOLOR); else m_pText->SetTextColor(PWL_DEFAULT_BLACKCOLOR); } FX_BOOL CPWL_IconList_Item::IsSelected() const { return m_bSelected; } void CPWL_IconList_Item::CreateChildWnd(const PWL_CREATEPARAM& cp) { m_pText = new CPWL_Label; PWL_CREATEPARAM lcp = cp; lcp.pParentWnd = this; lcp.dwFlags = PWS_CHILD | PWS_VISIBLE | PES_LEFT | PES_CENTER; lcp.sTextColor = PWL_DEFAULT_BLACKCOLOR; lcp.fFontSize = 12; m_pText->Create(lcp); } void CPWL_IconList_Item::SetData(void* pData) { m_pData = pData; } void CPWL_IconList_Item::SetIcon(int32_t nIconIndex) { m_nIconIndex = nIconIndex; } void CPWL_IconList_Item::SetText(const CFX_WideString& str) { m_pText->SetText(str.c_str()); } CFX_WideString CPWL_IconList_Item::GetText() const { return m_pText->GetText(); } void CPWL_IconList_Item::RePosChildWnd() { CPDF_Rect rcClient = GetClientRect(); rcClient.left += (PWL_IconList_ITEM_ICON_LEFTMARGIN + PWL_IconList_ITEM_WIDTH + PWL_IconList_ITEM_ICON_LEFTMARGIN); m_pText->Move(rcClient, TRUE, FALSE); } void CPWL_IconList_Item::SetIconFillColor(const CPWL_Color& color) { m_crIcon = color; } void CPWL_IconList_Item::OnEnabled() { if (m_bSelected) m_pText->SetTextColor(PWL_DEFAULT_WHITECOLOR); else m_pText->SetTextColor(PWL_DEFAULT_BLACKCOLOR); InvalidateRect(); } void CPWL_IconList_Item::OnDisabled() { m_pText->SetTextColor(PWL_DEFAULT_HEAVYGRAYCOLOR); InvalidateRect(); } /* ----------------- CPWL_IconList_Content ----------------- */ CPWL_IconList_Content::CPWL_IconList_Content(int32_t nListCount) : m_nSelectIndex(-1), m_pNotify(NULL), m_bEnableNotify(TRUE), m_bMouseDown(FALSE), m_nListCount(nListCount) {} CPWL_IconList_Content::~CPWL_IconList_Content() {} void CPWL_IconList_Content::CreateChildWnd(const PWL_CREATEPARAM& cp) { for (int32_t i = 0; i < m_nListCount; i++) { CPWL_IconList_Item* pNewItem = new CPWL_IconList_Item(); PWL_CREATEPARAM icp = cp; icp.pParentWnd = this; icp.dwFlags = PWS_CHILD | PWS_VISIBLE | PWS_NOREFRESHCLIP; pNewItem->Create(icp); } SetItemSpace(PWL_IconList_ITEM_SPACE); ResetContent(0); if (CPWL_Wnd* pParent = GetParentWindow()) { CPDF_Rect rcScroll = GetScrollArea(); GetScrollPos(); PWL_SCROLL_INFO sInfo; sInfo.fContentMin = rcScroll.bottom; sInfo.fContentMax = rcScroll.top; sInfo.fPlateWidth = GetClientRect().Height(); sInfo.fSmallStep = 13.0f; sInfo.fBigStep = sInfo.fPlateWidth; pParent->OnNotify(this, PNM_SETSCROLLINFO, SBT_VSCROLL, (intptr_t)&sInfo); } } FX_BOOL CPWL_IconList_Content::OnLButtonDown(const CPDF_Point& point, FX_DWORD nFlag) { SetFocus(); SetCapture(); m_bMouseDown = TRUE; int32_t nItemIndex = FindItemIndex(point); SetSelect(nItemIndex); ScrollToItem(nItemIndex); return TRUE; } FX_BOOL CPWL_IconList_Content::OnLButtonUp(const CPDF_Point& point, FX_DWORD nFlag) { m_bMouseDown = FALSE; ReleaseCapture(); return TRUE; } FX_BOOL CPWL_IconList_Content::OnMouseMove(const CPDF_Point& point, FX_DWORD nFlag) { if (m_bMouseDown) { int32_t nItemIndex = FindItemIndex(point); SetSelect(nItemIndex); ScrollToItem(nItemIndex); } return TRUE; } FX_BOOL CPWL_IconList_Content::OnKeyDown(FX_WORD nChar, FX_DWORD nFlag) { switch (nChar) { case FWL_VKEY_Up: if (m_nSelectIndex > 0) { int32_t nItemIndex = m_nSelectIndex - 1; SetSelect(nItemIndex); ScrollToItem(nItemIndex); } return TRUE; case FWL_VKEY_Down: if (m_nSelectIndex < m_nListCount - 1) { int32_t nItemIndex = m_nSelectIndex + 1; SetSelect(nItemIndex); ScrollToItem(nItemIndex); } return TRUE; } return FALSE; } int32_t CPWL_IconList_Content::FindItemIndex(const CPDF_Point& point) { int32_t nIndex = 0; for (int32_t i = 0, sz = m_aChildren.GetSize(); i < sz; i++) { if (CPWL_Wnd* pChild = m_aChildren.GetAt(i)) { CPDF_Rect rcWnd = pChild->ChildToParent(pChild->GetWindowRect()); if (point.y < rcWnd.top) { nIndex = i; } } } return nIndex; } void CPWL_IconList_Content::ScrollToItem(int32_t nItemIndex) { CPDF_Rect rcClient = GetClientRect(); if (CPWL_IconList_Item* pItem = GetListItem(nItemIndex)) { CPDF_Rect rcOrigin = pItem->GetWindowRect(); CPDF_Rect rcWnd = pItem->ChildToParent(rcOrigin); if (!(rcWnd.bottom > rcClient.bottom && rcWnd.top < rcClient.top)) { CPDF_Point ptScroll = GetScrollPos(); if (rcWnd.top > rcClient.top) { ptScroll.y = rcOrigin.top; } else if (rcWnd.bottom < rcClient.bottom) { ptScroll.y = rcOrigin.bottom + rcClient.Height(); } SetScrollPos(ptScroll); ResetFace(); InvalidateRect(); if (CPWL_Wnd* pParent = GetParentWindow()) { pParent->OnNotify(this, PNM_SETSCROLLPOS, SBT_VSCROLL, (intptr_t)&ptScroll.y); } } } } void CPWL_IconList_Content::SetSelect(int32_t nIndex) { if (m_nSelectIndex != nIndex) { SelectItem(m_nSelectIndex, FALSE); SelectItem(nIndex, TRUE); m_nSelectIndex = nIndex; if (IPWL_IconList_Notify* pNotify = GetNotify()) pNotify->OnNoteListSelChanged(nIndex); } } int32_t CPWL_IconList_Content::GetSelect() const { return m_nSelectIndex; } IPWL_IconList_Notify* CPWL_IconList_Content::GetNotify() const { if (m_bEnableNotify) return m_pNotify; return NULL; } void CPWL_IconList_Content::SetNotify(IPWL_IconList_Notify* pNotify) { m_pNotify = pNotify; } void CPWL_IconList_Content::EnableNotify(FX_BOOL bNotify) { m_bEnableNotify = bNotify; } void CPWL_IconList_Content::SelectItem(int32_t nItemIndex, FX_BOOL bSelect) { if (CPWL_IconList_Item* pItem = GetListItem(nItemIndex)) { pItem->SetSelect(bSelect); pItem->InvalidateRect(); } } CPWL_IconList_Item* CPWL_IconList_Content::GetListItem( int32_t nItemIndex) const { if (nItemIndex >= 0 && nItemIndex < m_aChildren.GetSize()) { if (CPWL_Wnd* pChild = m_aChildren.GetAt(nItemIndex)) { if (pChild->GetClassName() == "CPWL_IconList_Item") { return (CPWL_IconList_Item*)pChild; } } } return NULL; } void CPWL_IconList_Content::SetListData(int32_t nItemIndex, void* pData) { if (CPWL_IconList_Item* pItem = GetListItem(nItemIndex)) pItem->SetData(pData); } void CPWL_IconList_Content::SetListIcon(int32_t nItemIndex, int32_t nIconIndex) { if (CPWL_IconList_Item* pItem = GetListItem(nItemIndex)) pItem->SetIcon(nIconIndex); } void CPWL_IconList_Content::SetListString(int32_t nItemIndex, const CFX_WideString& str) { if (CPWL_IconList_Item* pItem = GetListItem(nItemIndex)) pItem->SetText(str); } CFX_WideString CPWL_IconList_Content::GetListString(int32_t nItemIndex) const { if (CPWL_IconList_Item* pItem = GetListItem(nItemIndex)) return pItem->GetText(); return L""; } void CPWL_IconList_Content::SetIconFillColor(const CPWL_Color& color) { for (int32_t i = 0, sz = m_aChildren.GetSize(); i < sz; i++) { if (CPWL_Wnd* pChild = m_aChildren.GetAt(i)) { if (pChild->GetClassName() == "CPWL_IconList_Item") { CPWL_IconList_Item* pItem = (CPWL_IconList_Item*)pChild; pItem->SetIconFillColor(color); pItem->InvalidateRect(); } } } } /* -------------------- CPWL_IconList --------------------- */ CPWL_IconList::CPWL_IconList(int32_t nListCount) : m_pListContent(NULL), m_nListCount(nListCount) {} CPWL_IconList::~CPWL_IconList() {} void CPWL_IconList::RePosChildWnd() { CPWL_Wnd::RePosChildWnd(); if (m_pListContent) m_pListContent->Move(GetClientRect(), TRUE, FALSE); } void CPWL_IconList::CreateChildWnd(const PWL_CREATEPARAM& cp) { m_pListContent = new CPWL_IconList_Content(m_nListCount); PWL_CREATEPARAM ccp = cp; ccp.pParentWnd = this; ccp.dwFlags = PWS_CHILD | PWS_VISIBLE; m_pListContent->Create(ccp); } void CPWL_IconList::OnCreated() { if (CPWL_ScrollBar* pScrollBar = GetVScrollBar()) { pScrollBar->RemoveFlag(PWS_AUTOTRANSPARENT); pScrollBar->SetTransparency(255); pScrollBar->SetNotifyForever(TRUE); } } void CPWL_IconList::OnNotify(CPWL_Wnd* pWnd, FX_DWORD msg, intptr_t wParam, intptr_t lParam) { CPWL_Wnd::OnNotify(pWnd, msg, wParam, lParam); if (wParam == SBT_VSCROLL) { switch (msg) { case PNM_SETSCROLLINFO: if (PWL_SCROLL_INFO* pInfo = (PWL_SCROLL_INFO*)lParam) { if (CPWL_ScrollBar* pScrollBar = GetVScrollBar()) { if (pInfo->fContentMax - pInfo->fContentMin > pInfo->fPlateWidth) { if (!pScrollBar->IsVisible()) { pScrollBar->SetVisible(TRUE); RePosChildWnd(); } else { } } else { if (pScrollBar->IsVisible()) { pScrollBar->SetVisible(FALSE); RePosChildWnd(); } if (m_pListContent) m_pListContent->SetScrollPos(CPDF_Point(0.0f, 0.0f)); } pScrollBar->OnNotify(pWnd, PNM_SETSCROLLINFO, wParam, lParam); } } return; case PNM_SCROLLWINDOW: if (m_pListContent) { m_pListContent->SetScrollPos(CPDF_Point(0.0f, *(FX_FLOAT*)lParam)); m_pListContent->ResetFace(); m_pListContent->InvalidateRect(NULL); } return; case PNM_SETSCROLLPOS: if (CPWL_ScrollBar* pScrollBar = GetVScrollBar()) pScrollBar->OnNotify(pWnd, PNM_SETSCROLLPOS, wParam, lParam); return; } } } void CPWL_IconList::SetSelect(int32_t nIndex) { m_pListContent->SetSelect(nIndex); } void CPWL_IconList::SetTopItem(int32_t nIndex) { m_pListContent->ScrollToItem(nIndex); } int32_t CPWL_IconList::GetSelect() const { return m_pListContent->GetSelect(); } void CPWL_IconList::SetNotify(IPWL_IconList_Notify* pNotify) { m_pListContent->SetNotify(pNotify); } void CPWL_IconList::EnableNotify(FX_BOOL bNotify) { m_pListContent->EnableNotify(bNotify); } void CPWL_IconList::SetListData(int32_t nItemIndex, void* pData) { m_pListContent->SetListData(nItemIndex, pData); } void CPWL_IconList::SetListIcon(int32_t nItemIndex, int32_t nIconIndex) { m_pListContent->SetListIcon(nItemIndex, nIconIndex); } void CPWL_IconList::SetListString(int32_t nItemIndex, const CFX_WideString& str) { m_pListContent->SetListString(nItemIndex, str); } CFX_WideString CPWL_IconList::GetListString(int32_t nItemIndex) const { return m_pListContent->GetListString(nItemIndex); } void CPWL_IconList::SetIconFillColor(const CPWL_Color& color) { m_pListContent->SetIconFillColor(color); } FX_BOOL CPWL_IconList::OnMouseWheel(short zDelta, const CPDF_Point& point, FX_DWORD nFlag) { CPDF_Point ptScroll = m_pListContent->GetScrollPos(); CPDF_Rect rcScroll = m_pListContent->GetScrollArea(); CPDF_Rect rcContents = m_pListContent->GetClientRect(); if (rcScroll.top - rcScroll.bottom > rcContents.Height()) { CPDF_Point ptNew = ptScroll; if (zDelta > 0) ptNew.y += 30; else ptNew.y -= 30; if (ptNew.y > rcScroll.top) ptNew.y = rcScroll.top; if (ptNew.y < rcScroll.bottom + rcContents.Height()) ptNew.y = rcScroll.bottom + rcContents.Height(); if (ptNew.y < rcScroll.bottom) ptNew.y = rcScroll.bottom; if (ptNew.y != ptScroll.y) { m_pListContent->SetScrollPos(ptNew); m_pListContent->ResetFace(); m_pListContent->InvalidateRect(NULL); if (CPWL_ScrollBar* pScrollBar = GetVScrollBar()) pScrollBar->OnNotify(this, PNM_SETSCROLLPOS, SBT_VSCROLL, (intptr_t)&ptNew.y); return TRUE; } } return FALSE; }
{ "content_hash": "632eb9460558e53b936e45135ede38cd", "timestamp": "", "source": "github", "line_count": 505, "max_line_length": 80, "avg_line_length": 28.601980198019803, "alnum_prop": 0.6381888673497647, "repo_name": "azunite/libpdfium", "id": "24d2dad5fa9c6b3f5ee6cc7ac96232fac88b162a", "size": "14444", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "fpdfsdk/src/pdfwindow/PWL_IconList.cpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "4924778" }, { "name": "C++", "bytes": "9778619" }, { "name": "Python", "bytes": "61427" }, { "name": "Shell", "bytes": "545" } ], "symlink_target": "" }
package net.liftweb.util /** * A simple Read-through cache. * * An example of using it with a ProtoUser subclass: * * object UserCache extends KeyedCache[Long, User](100, Full(0.75f), * (id: Long) => User.find(By(User.id, id))) * * @param size the size of the cache * @param loadFactor the optional Load Factor * @param cons A function that will take a value of type K and return a Box[T] * populated into the cache if the return value is Full. * * @author Steve Jenson (stevej@pobox.com) */ class KeyedCache[K, T](size: Int, loadFactor: Box[Float], cons: K => Box[T]) { val cache = new LRU[K, T](size, loadFactor) /** * Evict a value from the cache. */ def remove(key: K) = cache.remove(key) /** * Update the cache yourself with KeyedCache(1) = "hello" */ def update(key: K, value: T) = cache.update(key, value) /** * If the cache contains a value mapped to {@code key} then return it, * otherwise run cons and add that value to the cache and return it. */ def apply(key: K): Box[T] = if (cache.contains(key)) { Full(cache(key)) } else { cons(key) match { case f@Full(v) => cache.update(key, v); f case _ => Empty } } }
{ "content_hash": "1bd133d6ac60b0046950520c7853b05e", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 78, "avg_line_length": 26.282608695652176, "alnum_prop": 0.6311000827129859, "repo_name": "beni55/liftweb", "id": "5d2342f40b333e650a99a181824cc6a9a23e17f4", "size": "1811", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lift-util/src/main/scala/net/liftweb/util/KeyedCache.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "13098" }, { "name": "CSS", "bytes": "67047" }, { "name": "HTML", "bytes": "108437" }, { "name": "JavaScript", "bytes": "299266" }, { "name": "Scala", "bytes": "1479897" }, { "name": "Shell", "bytes": "10389" } ], "symlink_target": "" }
Created by Melinda Morang, Esri Copyright 2018 Esri 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. ## What this tool does The Display GTFS in ArcGIS toolbox allows you to add GTFS transit stops and route shapes to ArcMap or ArcGIS Pro. The [Display GTFS Stops](#Stops) tool makes a feature class of stops using information from the GTFS stops.txt file. The [Display GTFS Route Shapes](#Shapes) tool converts the information from the GTFS routes.txt and shapes.txt files into an ArcGIS feature class, allowing you to view your transit lines on a map. The output will contain one line feature for each unique shape in your GTFS data. The attributes for each line contain all the information about the routes represented by the shape. ## Software requirements - ArcGIS 10.1 or higher with a Desktop Basic (ArcView) license, or ArcGIS Pro. *This toolbox is deprecated in ArcGIS Pro 2.2 and higher. To convert your GTFS stops and shapes to feature classes in ArcGIS Pro 2.2 and higher, please use the [GTFS Stops To Features](http://pro.arcgis.com/en/pro-app/tool-reference/conversion/gtfs-stops-to-features.htm) and [GTFS Shapes To Features](http://pro.arcgis.com/en/pro-app/tool-reference/conversion/gtfs-shapes-to-features.htm) tools in the Conversion Tools toolbox.* ## Data requirements - A valid GTFS dataset. To use the Display GTFS Route Shapes tool, your GTFS dataset must include the optional shapes.txt file. ## Getting started - Download the tool and save it anywhere on your computer. - Unzip the file you downloaded. The unzipped package contains a .tbx toolbox file, a folder of python scripts needed to run the toolbox, and a copy of this user's guide. - No installation is necessary. You can run the tool from ArcCatalog, ArcMap, or ArcGIS Pro. In any of those products, just navigate to the folder containing the .tbx file, and it should show up as a toolbox with tools you can run. You can also add the tool to ArcToolbox to make it easier to find later. - *Warning: If you wish to move the toolbox to a different location on your computer, make sure you move the entire package (the .tbx file, the scripts folder, and the user's guide) together so that the toolbox does not become disconnected from the scripts.* ## <a name="Stops"></a>Running *Display GTFS Stops* ![Screenshot of Display GTFS Stops dialog](./images/Screenshot_DisplayGTFSStops_Dialog.png) ### Inputs - **GTFS stops.txt file**: The stops.txt file you wish to display in the map - **Output GTFS stops feature class**: The feature class version of your GTFS stops that will be created. *Note: a file geodatabase feature class is recommended over a shapefile because shapefiles will truncate the longer field names to 10 characters.* ### Outputs - **[Your designated output feature class]**: This feature class will be an exact copy of your stops.txt file and will display the stop locations on the map. ## <a name="Shapes"></a>Running *Display GTFS Route Shapes* ![Screenshot of tool dialog](./images/Screenshot_DisplayGTFSRouteShapes_Dialog.png) ### Inputs - **GTFS directory**: The *folder* containing your (unzipped) GTFS .txt files. Your GTFS data folder must contain these files: trips.txt, routes.txt, and shapes.txt. - **Output feature class**: The output feature class that will contain the GTFS route shapes. ### Outputs - **[Your designated output feature class]**: The output feature class contains all the information from the GTFS routes.txt file as well as the shape_id. Please review the [GTFS Reference](https://github.com/google/transit/blob/master/gtfs/spec/en/reference.md) if you need help understanding these fields. If your GTFS dataset contains route_color information, route colors are given in the original hexadecimal format as well as an RGB triplet that can more easily be used as reference when choosing symbology in ArcGIS (see below). ## Tips for viewing output in the map ### Displaying shapes with the correct colors If your GTFS dataset contains route_color information and you want to view these colors in the map, you can do the following: #### In ArcMap 1. In the symbology tab of the layer properties, select Categories->Unique Values. 2. Choose route_color_formatted as the Value Field. Click Add All Values. 3. For each route color that appears, double click the line symbol next to it. 4. When the Symbol Selector appears, choose More Colors from the Color drop-down. 5. Flip the drop-down to RGB. Enter the RGB values from the route_color_RGB field into the R, G, and B boxes. For example, if the RGB color triplet was (198, 12, 48), modify the color selector to look like the picture here: ![Screenshot of ArcMap RGB symbology picker](./images/Screenshot_RGB_ArcMap.png) #### In ArcGIS Pro In ArcGIS Pro 1.2 or later, the output layer should automatically display using the colors specified in the route_color GTFS field defined in routes.txt. This is done using [attribute-driven symbology](http://pro.arcgis.com/en/pro-app/help/mapping/symbols-and-styles/attribute-driven-symbology.htm). The route shape display color is defined in the route_color_formatted field in the data. You can manually set the route shape colors as follows: 1. Open the Symbology pane to format your layer's symbology. 2. Choose Unique Values in the Symbology drop-down selector. 3. Choose route_color_formatted as the Value field. 4. For each route color, click on the symbol so that the "Format Line Symbol" part of the Symbology pane appears. 5. Click on Properties toward the top of this page of the pane. 6. In the drop-down color pallet, select "Color Properties". 7. When the Color Editor appears, make sure "Color Model" is set to HEX, and then enter the appropriate hexadecimal color code for your line. Note: If you plan to publish your layer to ArcGIS Online, you should manually set the symbology because attribute-driven symbology will not work. ### Rearranging the drawing order of your transit shapes If you want to rearrange the draw order of your different transit shapes, do the following: #### In ArcMap - In the symbology tab, click the Advanced button on the bottom right. - Select Symbol Levels. A dialog box appears. - Check the box for "Draw this layer using the symbol levels specified below." - Rearrange your symbols however you wish. The ones at the top will be drawn on top of the ones at the bottom. #### In ArcGIS Pro Coming soon... ## Questions or problems? Search for answers and post questions in the [Esri Community forums](https://community.esri.com/t5/public-transit-questions/bd-p/public-transit-questions).
{ "content_hash": "ad525e9672f61943daecaaef10d649d1", "timestamp": "", "source": "github", "line_count": 91, "max_line_length": 536, "avg_line_length": 78.74725274725274, "alnum_prop": 0.7652804912084845, "repo_name": "Esri/public-transit-tools", "id": "bc92f94681d0fbdae21233bfdd7e1422811a9736", "size": "7205", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "deprecated-tools/display-GTFS-in-ArcGIS/UsersGuide.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "110390" }, { "name": "NSIS", "bytes": "15505" }, { "name": "Python", "bytes": "990598" } ], "symlink_target": "" }
package org.apache.camel.component.aws.ddbstream; import com.amazonaws.ClientConfiguration; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.AWSCredentialsProvider; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicAWSCredentials; import com.amazonaws.regions.Regions; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBStreams; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBStreamsClientBuilder; import com.amazonaws.services.dynamodbv2.model.Record; import org.apache.camel.Consumer; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.Producer; import org.apache.camel.spi.UriEndpoint; import org.apache.camel.spi.UriParam; import org.apache.camel.support.ScheduledPollEndpoint; import org.apache.camel.util.ObjectHelper; /** * The aws-ddbstream component is used for working with Amazon DynamoDB Streams. */ @UriEndpoint(firstVersion = "2.17.0", scheme = "aws-ddbstream", title = "AWS DynamoDB Streams", consumerOnly = true, syntax = "aws-ddbstream:tableName", label = "cloud,messaging,streams") public class DdbStreamEndpoint extends ScheduledPollEndpoint { @UriParam DdbStreamConfiguration configuration; private AmazonDynamoDBStreams ddbStreamClient; public DdbStreamEndpoint(String uri, DdbStreamConfiguration configuration, DdbStreamComponent component) { super(uri, component); this.configuration = configuration; } @Override public Producer createProducer() throws Exception { throw new UnsupportedOperationException("Not supported yet."); } @Override public Consumer createConsumer(Processor processor) throws Exception { DdbStreamConsumer consumer = new DdbStreamConsumer(this, processor); consumer.setSchedulerProperties(consumer.getEndpoint().getSchedulerProperties()); configureConsumer(consumer); return consumer; } Exchange createExchange(Record record) { Exchange ex = super.createExchange(); ex.getIn().setBody(record, Record.class); return ex; } @Override public void doStart() throws Exception { super.doStart(); ddbStreamClient = configuration.getAmazonDynamoDbStreamsClient() != null ? configuration.getAmazonDynamoDbStreamsClient() : createDdbStreamClient(); } @Override public void doStop() throws Exception { if (ObjectHelper.isEmpty(configuration.getAmazonDynamoDbStreamsClient())) { if (ddbStreamClient != null) { ddbStreamClient.shutdown(); } } super.doStop(); } public DdbStreamConfiguration getConfiguration() { return configuration; } public AmazonDynamoDBStreams getClient() { return ddbStreamClient; } public String getSequenceNumber() { switch (configuration.getIteratorType()) { case AFTER_SEQUENCE_NUMBER: case AT_SEQUENCE_NUMBER: if (null == configuration.getSequenceNumberProvider()) { throw new IllegalStateException("sequenceNumberProvider must be" + " provided, either as an implementation of" + " SequenceNumberProvider or a literal String."); } else { return configuration.getSequenceNumberProvider().getSequenceNumber(); } default: return ""; } } AmazonDynamoDBStreams createDdbStreamClient() { AmazonDynamoDBStreams client = null; ClientConfiguration clientConfiguration = null; AmazonDynamoDBStreamsClientBuilder clientBuilder = null; boolean isClientConfigFound = false; if (ObjectHelper.isNotEmpty(configuration.getProxyHost()) && ObjectHelper.isNotEmpty(configuration.getProxyPort())) { clientConfiguration = new ClientConfiguration(); clientConfiguration.setProxyHost(configuration.getProxyHost()); clientConfiguration.setProxyPort(configuration.getProxyPort()); isClientConfigFound = true; } if (configuration.getAccessKey() != null && configuration.getSecretKey() != null) { AWSCredentials credentials = new BasicAWSCredentials(configuration.getAccessKey(), configuration.getSecretKey()); AWSCredentialsProvider credentialsProvider = new AWSStaticCredentialsProvider(credentials); if (isClientConfigFound) { clientBuilder = AmazonDynamoDBStreamsClientBuilder.standard().withClientConfiguration(clientConfiguration).withCredentials(credentialsProvider); } else { clientBuilder = AmazonDynamoDBStreamsClientBuilder.standard().withCredentials(credentialsProvider); } } else { if (isClientConfigFound) { clientBuilder = AmazonDynamoDBStreamsClientBuilder.standard(); } else { clientBuilder = AmazonDynamoDBStreamsClientBuilder.standard().withClientConfiguration(clientConfiguration); } } if (ObjectHelper.isNotEmpty(configuration.getRegion())) { clientBuilder = clientBuilder.withRegion(Regions.valueOf(configuration.getRegion())); } client = clientBuilder.build(); return client; } @Override public String toString() { return "DdbStreamEndpoint{" + "tableName=" + configuration.getTableName() + ", amazonDynamoDbStreamsClient=[redacted], maxResultsPerRequest=" + configuration.getMaxResultsPerRequest() + ", iteratorType=" + configuration.getIteratorType() + ", sequenceNumberProvider=" + configuration.getSequenceNumberProvider() + ", uri=" + getEndpointUri() + '}'; } }
{ "content_hash": "fa0eb26c5681cc098298ea2b3fb59ea7", "timestamp": "", "source": "github", "line_count": 145, "max_line_length": 160, "avg_line_length": 40.83448275862069, "alnum_prop": 0.682317176152677, "repo_name": "zregvart/camel", "id": "82e9a27d5f5ba80f5799d305ff050ab1996433a3", "size": "6723", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "components/camel-aws-ddb/src/main/java/org/apache/camel/component/aws/ddbstream/DdbStreamEndpoint.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Apex", "bytes": "6521" }, { "name": "Batchfile", "bytes": "2353" }, { "name": "CSS", "bytes": "5472" }, { "name": "Elm", "bytes": "10852" }, { "name": "FreeMarker", "bytes": "8015" }, { "name": "Groovy", "bytes": "20938" }, { "name": "HTML", "bytes": "914791" }, { "name": "Java", "bytes": "90321137" }, { "name": "JavaScript", "bytes": "101298" }, { "name": "RobotFramework", "bytes": "8461" }, { "name": "Shell", "bytes": "11165" }, { "name": "TSQL", "bytes": "28835" }, { "name": "Tcl", "bytes": "4974" }, { "name": "Thrift", "bytes": "6979" }, { "name": "XQuery", "bytes": "546" }, { "name": "XSLT", "bytes": "280849" } ], "symlink_target": "" }
require 'spec_helper' describe CommitRange do let(:sha_from) { 'f3f85602' } let(:sha_to) { 'e86e1013' } let(:range) { described_class.new("#{sha_from}...#{sha_to}") } let(:range2) { described_class.new("#{sha_from}..#{sha_to}") } it 'raises ArgumentError when given an invalid range string' do expect { described_class.new("Foo") }.to raise_error end describe '#to_s' do it 'is correct for three-dot syntax' do expect(range.to_s).to eq "#{sha_from[0..7]}...#{sha_to[0..7]}" end it 'is correct for two-dot syntax' do expect(range2.to_s).to eq "#{sha_from[0..7]}..#{sha_to[0..7]}" end end describe '#reference_title' do it 'returns the correct String for three-dot ranges' do expect(range.reference_title).to eq "Commits #{sha_from} through #{sha_to}" end it 'returns the correct String for two-dot ranges' do expect(range2.reference_title).to eq "Commits #{sha_from}^ through #{sha_to}" end end describe '#to_param' do it 'includes the correct keys' do expect(range.to_param.keys).to eq %i(from to) end it 'includes the correct values for a three-dot range' do expect(range.to_param).to eq({from: sha_from, to: sha_to}) end it 'includes the correct values for a two-dot range' do expect(range2.to_param).to eq({from: sha_from + '^', to: sha_to}) end end describe '#exclude_start?' do it 'is false for three-dot ranges' do expect(range.exclude_start?).to eq false end it 'is true for two-dot ranges' do expect(range2.exclude_start?).to eq true end end describe '#valid_commits?' do context 'without a project' do it 'returns nil' do expect(range.valid_commits?).to be_nil end end it 'accepts an optional project argument' do project1 = double('project1').as_null_object project2 = double('project2').as_null_object # project1 gets assigned through the accessor, but ignored when not given # as an argument to `valid_commits?` expect(project1).not_to receive(:present?) range.project = project1 # project2 gets passed to `valid_commits?` expect(project2).to receive(:present?).and_return(false) range.valid_commits?(project2) end context 'with a project' do let(:project) { double('project', repository: double('repository')) } context 'with a valid repo' do before do expect(project).to receive(:valid_repo?).and_return(true) range.project = project end it 'is false when `sha_from` is invalid' do expect(project.repository).to receive(:commit).with(sha_from).and_return(false) expect(project.repository).not_to receive(:commit).with(sha_to) expect(range).not_to be_valid_commits end it 'is false when `sha_to` is invalid' do expect(project.repository).to receive(:commit).with(sha_from).and_return(true) expect(project.repository).to receive(:commit).with(sha_to).and_return(false) expect(range).not_to be_valid_commits end it 'is true when both `sha_from` and `sha_to` are valid' do expect(project.repository).to receive(:commit).with(sha_from).and_return(true) expect(project.repository).to receive(:commit).with(sha_to).and_return(true) expect(range).to be_valid_commits end end context 'without a valid repo' do before do expect(project).to receive(:valid_repo?).and_return(false) range.project = project end it 'returns false' do expect(range).not_to be_valid_commits end end end end end
{ "content_hash": "af57a4b63f1bbf052717f1a46a6587f2", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 89, "avg_line_length": 31.208333333333332, "alnum_prop": 0.6285714285714286, "repo_name": "rhels/gitlabhq", "id": "31ee3e99cad6eccbecb79e94406571944ffcf6b0", "size": "3745", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "spec/models/commit_range_spec.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "111558" }, { "name": "CoffeeScript", "bytes": "120944" }, { "name": "Cucumber", "bytes": "119436" }, { "name": "HTML", "bytes": "433885" }, { "name": "JavaScript", "bytes": "29632" }, { "name": "Ruby", "bytes": "2272533" }, { "name": "Shell", "bytes": "13494" } ], "symlink_target": "" }
class OpenGLRenderTarget : public RenderTarget { public: OpenGLRenderTarget(int x, int y, int width, int height, Graphics::MULTISAMPLE_TYPE multiSampleType = Graphics::MULTISAMPLE_TYPE::MULTISAMPLE_0X); virtual ~OpenGLRenderTarget() {destroy();} virtual void enable(); virtual void disable(); virtual void bind(unsigned int textureUnit = 0); virtual void unbind(); // ILLEGAL: void blitResolveFrameBufferIntoFrameBuffer(OpenGLRenderTarget *rt); void blitFrameBufferIntoFrameBuffer(OpenGLRenderTarget *rt); inline unsigned int getFrameBuffer() const {return m_iFrameBuffer;} inline unsigned int getRenderTexture() const {return m_iRenderTexture;} inline unsigned int getResolveFrameBuffer() const {return m_iResolveFrameBuffer;} inline unsigned int getResolveTexture() const {return m_iResolveTexture;} private: virtual void init(); virtual void initAsync(); virtual void destroy(); unsigned int m_iFrameBuffer; unsigned int m_iRenderTexture; unsigned int m_iDepthBuffer; unsigned int m_iResolveFrameBuffer; unsigned int m_iResolveTexture; int m_iFrameBufferBackup; unsigned int m_iTextureUnitBackup; int m_iViewportBackup[4]; }; #endif #endif
{ "content_hash": "a4632d1fca17b39a68beee6961f2c7a1", "timestamp": "", "source": "github", "line_count": 39, "max_line_length": 146, "avg_line_length": 30.128205128205128, "alnum_prop": 0.7880851063829787, "repo_name": "McKay42/McEngine", "id": "29e70c930189be9f8bc12bc39cb8d5bfe5845e25", "size": "1605", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "McEngine/src/Engine/Renderer/OpenGLRenderTarget.h", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "12023" }, { "name": "C", "bytes": "8567787" }, { "name": "C#", "bytes": "628349" }, { "name": "C++", "bytes": "8967564" }, { "name": "CMake", "bytes": "46447" }, { "name": "Lua", "bytes": "24873" }, { "name": "Makefile", "bytes": "37122" }, { "name": "Objective-C", "bytes": "9060" }, { "name": "Objective-C++", "bytes": "15899" }, { "name": "Python", "bytes": "26615" }, { "name": "Shell", "bytes": "8467" } ], "symlink_target": "" }
package org.optaplanner.examples.common.swingui; import java.awt.Desktop; import java.awt.event.ActionEvent; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import javax.swing.AbstractAction; import javax.swing.JOptionPane; public class OpenBrowserAction extends AbstractAction { private final URI uri; public OpenBrowserAction(String title, String urlString) { super(title); try { uri = new URI(urlString); } catch (URISyntaxException e) { throw new IllegalStateException("Failed creating URI for urlString (" + urlString + ").", e); } } @Override public void actionPerformed(ActionEvent event) { Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; if (desktop == null || !desktop.isSupported(Desktop.Action.BROWSE)) { JOptionPane.showMessageDialog(null, "Cannot open a browser automatically." + "\nPlease open this url manually:\n" + uri.toString(), "Cannot open browser", JOptionPane.INFORMATION_MESSAGE); return; } try { desktop.browse(uri); } catch (IOException e) { throw new IllegalStateException("Failed showing uri (" + uri + ") in browser.", e); } } }
{ "content_hash": "a360e93f3c082c241968491ef6cb2cc6", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 105, "avg_line_length": 32.11904761904762, "alnum_prop": 0.6397331356560415, "repo_name": "oskopek/optaplanner", "id": "bee6bf4fb23feb78a11d4fc06e228efb09de5347", "size": "1969", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "optaplanner-examples/src/main/java/org/optaplanner/examples/common/swingui/OpenBrowserAction.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": "6969940" }, { "name": "JavaScript", "bytes": "215434" }, { "name": "Shell", "bytes": "1548" } ], "symlink_target": "" }
Most routers out there implement the routing mechanism to decide which view to render. But we know that with technologies like React, the state is what dictates what to render. Also, with a unidirectional data flow like `redux`, we can allow to go back and forth our state via steps, which are triggered via actions. With all this into account, we can build a router that just renders the url with a function that only depends on the state, and that emit changes whenever the url changes from outside. Thus, we can have the url be one more component in our tree rendered with React: ```js <Location render={renderUrlFromState} onChange={transitionToUrl} /> ``` ## Url as a function of the state A Url in an app is a representation of the state. As such, it can be written as a function of the state, just like with any other UI component. ``` url = renderUrl(state) ``` We can define a `renderUrl` function that whenever the state changes, gets called, and returns the app url at that particular state. Then we can grab that result and set it as the location in our browser, using the history API. With this approach, you can now model your entire render tree as a function of the state, and decide which component to render based on that state, and nothing else. This is unlike other router approaches that determine what to render depending on the url. Modeling the urls as a byproduct of the state gives us all the benefits of still having a single source of truth in our app. Time travel, interaction serialization, and all that goodness. So any manipulation to the state will recreate exactly the same UI and same url. So now, by representing the urls as a function of the state, we have solved the first problem, but in the world of the web we need links, and we interact with urls in the address bar. ## Links Links need to point to a specific url, so that the html can be crawlable, accessible and all the stuff that the web expects. But with this approach, we don't need to manually specify the url for the link, since, as we said, the url can be obtained from the state. How can we avoid setting the url to a link? By just specifying a callback on the Link when it's followed (via a click for example), and that callback dispatching some action to our app that will trigger a state change, we can call that callback in a fake context to simulate the next step after that action is executed, in order to get that next state and run the `renderUrl` function with that. If the callback has no side-effects, that is, it simply calls an action, and makes no calls to the database, we can safely do that simulation and get the url for the link. ```js <Link onFollow={() => dispatch({type: 'SELECT_CONTACT', contactId: 1})}> {this.props.contact.name} </Link> ``` ## Initial route and history Now coming from the outside, whenever a route is triggered, either via a click to the previous or next buttons in the browser, or via a direct input of a url, we need to dispatch a change to the state to get to that state. For that we can just use any route matching library that we know, and define which action to return based on the particular url. We then dispatch that action returned and then the app will render based on the state after that action, rendering the url as well (which should be the same as the one that triggered the action). ```js import Router from 'routes'; const router = Router(); router.addRoute('/contacts/new', () => ({type: 'ADDING_NEW_CONTACT'})); router.addRoute('/contacts/:id', params => ({type: 'SELECT_CONTACT', contactId: params.id})); router.addRoute('/contacts', () => ({type: 'SHOW_CONTACTS'})); ... function transitionTo(url) { const route = router.match(url); return route.fn(route.params); } <Location render={renderUrl} onChange={url => dispatch(transitionTo(url))} /> ```
{ "content_hash": "ad71bae16a9bf63c417982a150ed0d9d", "timestamp": "", "source": "github", "line_count": 66, "max_line_length": 351, "avg_line_length": 58.22727272727273, "alnum_prop": 0.7582617746552173, "repo_name": "leoasis/state-router", "id": "bd8d9d7bc1c2fa92ca321e5689bd788006ec3982", "size": "3856", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "142" }, { "name": "JavaScript", "bytes": "9885" } ], "symlink_target": "" }
using System; using QuantConnect.Data; using QuantConnect.Data.UniverseSelection; using QuantConnect.Interfaces; using QuantConnect.Packets; namespace QuantConnect.Lean.Engine.DataFeeds { /// <summary> /// Specifies data channel settings /// </summary> public class DataChannelProvider : IDataChannelProvider { /// <summary> /// Initializes the instance with an algorithm node packet /// </summary> /// <param name="packet">Algorithm node packet</param> public virtual void Initialize(AlgorithmNodePacket packet) { } /// <summary> /// True if this subscription request should be streamed /// </summary> public virtual bool ShouldStreamSubscription(SubscriptionDataConfig config) { return IsStreamingType(config) || !config.IsCustomData && config.Type != typeof(CoarseFundamental); } /// <summary> /// Returns true if the data type for the given subscription configuration supports streaming /// </summary> protected static bool IsStreamingType(SubscriptionDataConfig configuration) { var dataTypeInstance = configuration.Type.GetBaseDataInstance(); return dataTypeInstance.GetSource(configuration, DateTime.UtcNow, true) .TransportMedium == SubscriptionTransportMedium.Streaming; } } }
{ "content_hash": "997f0a87632d2c5b978f41f6be407d3b", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 111, "avg_line_length": 33.95238095238095, "alnum_prop": 0.6584852734922861, "repo_name": "AlexCatarino/Lean", "id": "09d5a87bd09dfcbaa9fdb0deb35ab682e3a02ea6", "size": "2130", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "Engine/DataFeeds/DataChannelProvider.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "411" }, { "name": "C#", "bytes": "20991395" }, { "name": "CSS", "bytes": "10299" }, { "name": "Dockerfile", "bytes": "1397" }, { "name": "HTML", "bytes": "15699" }, { "name": "Jupyter Notebook", "bytes": "32227" }, { "name": "Python", "bytes": "1341050" }, { "name": "Shell", "bytes": "4135" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in Mycotaxon 92: 34 (2005) #### Original name Kochmania Piatek ### Remarks null
{ "content_hash": "485666196381703122be732d119a340e", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 23, "avg_line_length": 10.76923076923077, "alnum_prop": 0.7, "repo_name": "mdoering/backbone", "id": "2dd7a6d875b11e9f6116d10c714b32dffe3b2e06", "size": "178", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Ustilaginomycetes/Urocystidiales/Glomosporiaceae/Kochmania/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" #include "irc.h" #include "chainparams.h" #include "db.h" #include "net.h" #include "main.h" #include "addrman.h" #include "ui_interface.h" #include "darksend.h" #include "wallet.h" #ifdef WIN32 #include <string.h> #endif #ifdef USE_UPNP #include <miniupnpc/miniwget.h> #include <miniupnpc/miniupnpc.h> #include <miniupnpc/upnpcommands.h> #include <miniupnpc/upnperrors.h> #endif // Dump addresses to peers.dat every 15 minutes (900s) #define DUMP_ADDRESSES_INTERVAL 900 using namespace std; using namespace boost; static const int MAX_OUTBOUND_CONNECTIONS = 32; bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false); struct LocalServiceInfo { int nScore; int nPort; }; // // Global state variables // bool fDiscover = true; uint64_t nLocalServices = NODE_NETWORK; static CCriticalSection cs_mapLocalHost; static map<CNetAddr, LocalServiceInfo> mapLocalHost; static bool vfReachable[NET_MAX] = {}; static bool vfLimited[NET_MAX] = {}; static CNode* pnodeLocalHost = NULL; static CNode* pnodeSync = NULL; uint64_t nLocalHostNonce = 0; static std::vector<SOCKET> vhListenSocket; CAddrMan addrman; vector<CNode*> vNodes; CCriticalSection cs_vNodes; map<CInv, CDataStream> mapRelay; deque<pair<int64_t, CInv> > vRelayExpiration; CCriticalSection cs_mapRelay; map<CInv, int64_t> mapAlreadyAskedFor; static deque<string> vOneShots; CCriticalSection cs_vOneShots; set<CNetAddr> setservAddNodeAddresses; CCriticalSection cs_setservAddNodeAddresses; vector<std::string> vAddedNodes; CCriticalSection cs_vAddedNodes; NodeId nLastNodeId = 0; CCriticalSection cs_nLastNodeId; static CSemaphore *semOutbound = NULL; // Signals for message handling static CNodeSignals g_signals; CNodeSignals& GetNodeSignals() { return g_signals; } void AddOneShot(string strDest) { LOCK(cs_vOneShots); vOneShots.push_back(strDest); } unsigned short GetListenPort() { return (unsigned short)(GetArg("-port", Params().GetDefaultPort())); } // find 'best' local address for a particular peer bool GetLocal(CService& addr, const CNetAddr *paddrPeer) { if (fNoListen) return false; int nBestScore = -1; int nBestReachability = -1; { LOCK(cs_mapLocalHost); for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) { int nScore = (*it).second.nScore; int nReachability = (*it).first.GetReachabilityFrom(paddrPeer); if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) { addr = CService((*it).first, (*it).second.nPort); nBestReachability = nReachability; nBestScore = nScore; } } } return nBestScore >= 0; } // get best local address for a particular peer as a CAddress // Otherwise, return the unroutable 0.0.0.0 but filled in with // the normal parameters, since the IP may be changed to a useful // one by discovery. CAddress GetLocalAddress(const CNetAddr *paddrPeer) { CAddress ret(CService("0.0.0.0",GetListenPort()),0); CService addr; if (GetLocal(addr, paddrPeer)) { ret = CAddress(addr); } ret.nServices = nLocalServices; ret.nTime = GetAdjustedTime(); return ret; } bool RecvLine(SOCKET hSocket, string& strLine) { strLine = ""; while (!ShutdownRequested()) { char c; int nBytes = recv(hSocket, &c, 1, MSG_DONTWAIT); if(ShutdownRequested()) return false; if (nBytes > 0) { if (c == '\n') continue; if (c == '\r') return true; strLine += c; if (strLine.size() >= 9000) return true; } else if (nBytes <= 0) { boost::this_thread::interruption_point(); if (nBytes < 0) { int nErr = WSAGetLastError(); if (nErr == WSAEMSGSIZE) continue; if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS) { MilliSleep(10); continue; } } if (!strLine.empty()) return true; if (nBytes == 0) { // socket closed LogPrint("net", "socket closed\n"); return false; } else { // socket error int nErr = WSAGetLastError(); LogPrint("net", "recv failed: %d\n", nErr); return false; } } } return false; } int GetnScore(const CService& addr) { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == LOCAL_NONE) return 0; return mapLocalHost[addr].nScore; } // Is our peer's addrLocal potentially useful as an external IP source? bool IsPeerAddrLocalGood(CNode *pnode) { return fDiscover && pnode->addr.IsRoutable() && pnode->addrLocal.IsRoutable() && !IsLimited(pnode->addrLocal.GetNetwork()); } // pushes our own address to a peer void AdvertizeLocal(CNode *pnode) { if (!fNoListen && pnode->fSuccessfullyConnected) { CAddress addrLocal = GetLocalAddress(&pnode->addr); // If discovery is enabled, sometimes give our peer the address it // tells us that it sees us as in case it has a better idea of our // address than we do. if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() || GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8:2) == 0)) { addrLocal.SetIP(pnode->addrLocal); } if (addrLocal.IsRoutable()) { pnode->PushAddress(addrLocal); } } } void SetReachable(enum Network net, bool fFlag) { LOCK(cs_mapLocalHost); vfReachable[net] = fFlag; if (net == NET_IPV6 && fFlag) vfReachable[NET_IPV4] = true; } // learn a new local address bool AddLocal(const CService& addr, int nScore) { if (!addr.IsRoutable()) return false; if (!fDiscover && nScore < LOCAL_MANUAL) return false; if (IsLimited(addr)) return false; LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore); { LOCK(cs_mapLocalHost); bool fAlready = mapLocalHost.count(addr) > 0; LocalServiceInfo &info = mapLocalHost[addr]; if (!fAlready || nScore >= info.nScore) { info.nScore = nScore + (fAlready ? 1 : 0); info.nPort = addr.GetPort(); } SetReachable(addr.GetNetwork()); } return true; } bool AddLocal(const CNetAddr &addr, int nScore) { return AddLocal(CService(addr, GetListenPort()), nScore); } /** Make a particular network entirely off-limits (no automatic connects to it) */ void SetLimited(enum Network net, bool fLimited) { if (net == NET_UNROUTABLE) return; LOCK(cs_mapLocalHost); vfLimited[net] = fLimited; } bool IsLimited(enum Network net) { LOCK(cs_mapLocalHost); return vfLimited[net]; } bool IsLimited(const CNetAddr &addr) { return IsLimited(addr.GetNetwork()); } /** vote for a local address */ bool SeenLocal(const CService& addr) { { LOCK(cs_mapLocalHost); if (mapLocalHost.count(addr) == 0) return false; mapLocalHost[addr].nScore++; } return true; } /** check whether a given address is potentially local */ bool IsLocal(const CService& addr) { LOCK(cs_mapLocalHost); return mapLocalHost.count(addr) > 0; } /** check whether a given address is in a network we can probably connect to */ bool IsReachable(const CNetAddr& addr) { LOCK(cs_mapLocalHost); enum Network net = addr.GetNetwork(); return vfReachable[net] && !vfLimited[net]; } void AddressCurrentlyConnected(const CService& addr) { addrman.Connected(addr); } uint64_t CNode::nTotalBytesRecv = 0; uint64_t CNode::nTotalBytesSent = 0; CCriticalSection CNode::cs_totalBytesRecv; CCriticalSection CNode::cs_totalBytesSent; CNode* FindNode(const CNetAddr& ip) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if ((CNetAddr)pnode->addr == ip) return (pnode); } return NULL; } CNode* FindNode(const std::string& addrName) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->addrName == addrName) return (pnode); return NULL; } CNode* FindNode(const CService& addr) { { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if ((CService)pnode->addr == addr) return (pnode); } return NULL; } CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool darkSendMaster) { if (pszDest == NULL) { if (IsLocal(addrConnect)) return NULL; // Look for an existing connection CNode* pnode = FindNode((CService)addrConnect); if (pnode) { if(darkSendMaster) pnode->fDarkSendMaster = true; pnode->AddRef(); return pnode; } } /// debug print LogPrint("net", "trying connection %s lastseen=%.1fhrs\n", pszDest ? pszDest : addrConnect.ToString(), pszDest ? 0 : (double)(GetAdjustedTime() - addrConnect.nTime)/3600.0); // Connect SOCKET hSocket; bool proxyConnectionFailed = false; if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) : ConnectSocket(addrConnect, hSocket, nConnectTimeout, &proxyConnectionFailed)) { addrman.Attempt(addrConnect); LogPrint("net", "connected %s\n", pszDest ? pszDest : addrConnect.ToString()); // Set to non-blocking #ifdef WIN32 u_long nOne = 1; if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) LogPrintf("ConnectSocket() : ioctlsocket non-blocking setting failed, error %d\n", WSAGetLastError()); #else if (fcntl(hSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) LogPrintf("ConnectSocket() : fcntl non-blocking setting failed, error %d\n", errno); #endif // Add node CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } pnode->nTimeConnected = GetTime(); return pnode; } else if (!proxyConnectionFailed) { // If connecting to the node failed, and failure is not caused by a problem connecting to // the proxy, mark this as an attempt. addrman.Attempt(addrConnect); } return NULL; } void CNode::CloseSocketDisconnect() { fDisconnect = true; if (hSocket != INVALID_SOCKET) { LogPrint("net", "disconnecting node %s\n", addrName); closesocket(hSocket); hSocket = INVALID_SOCKET; } // in case this fails, we'll empty the recv buffer when the CNode is deleted TRY_LOCK(cs_vRecvMsg, lockRecv); if (lockRecv) vRecvMsg.clear(); // if this was the sync node, we'll need a new one if (this == pnodeSync) pnodeSync = NULL; } void CNode::PushVersion() { /// when NTP implemented, change to just nTime = GetAdjustedTime() int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime()); CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0",0))); CAddress addrMe = GetLocalAddress(&addr); RAND_bytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce)); LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), addr.ToString()); PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe, nLocalHostNonce, FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, std::vector<string>()), nBestHeight); } std::map<CNetAddr, int64_t> CNode::setBanned; CCriticalSection CNode::cs_setBanned; void CNode::ClearBanned() { setBanned.clear(); } bool CNode::IsBanned(CNetAddr ip) { bool fResult = false; { LOCK(cs_setBanned); std::map<CNetAddr, int64_t>::iterator i = setBanned.find(ip); if (i != setBanned.end()) { int64_t t = (*i).second; if (GetTime() < t) fResult = true; } } return fResult; } bool CNode::Misbehaving(int howmuch) { if (addr.IsLocal()) { LogPrintf("Warning: Local node %s misbehaving (delta: %d)!\n", addrName, howmuch); return false; } nMisbehavior += howmuch; if (nMisbehavior >= GetArg("-banscore", 100)) { int64_t banTime = GetTime()+GetArg("-bantime", 60*60*24); // Default 24-hour ban LogPrintf("Misbehaving: %s (%d -> %d) DISCONNECTING\n", addr.ToString(), nMisbehavior-howmuch, nMisbehavior); { LOCK(cs_setBanned); if (setBanned[addr] < banTime) setBanned[addr] = banTime; } CloseSocketDisconnect(); return true; } else LogPrintf("Misbehaving: %s (%d -> %d)\n", addr.ToString(), nMisbehavior-howmuch, nMisbehavior); return false; } #undef X #define X(name) stats.name = name void CNode::copyStats(CNodeStats &stats) { stats.nodeid = this->GetId(); X(nServices); X(nLastSend); X(nLastRecv); X(nTimeConnected); X(addrName); X(nVersion); X(cleanSubVer); X(strSubVer); X(fInbound); X(nStartingHeight); X(nMisbehavior); X(nSendBytes); X(nRecvBytes); stats.fSyncNode = (this == pnodeSync); // It is common for nodes with good ping times to suddenly become lagged, // due to a new block arriving or other large transfer. // Merely reporting pingtime might fool the caller into thinking the node was still responsive, // since pingtime does not update until the ping is complete, which might take a while. // So, if a ping is taking an unusually long time in flight, // the caller can immediately detect that this is happening. int64_t nPingUsecWait = 0; if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) { nPingUsecWait = GetTimeMicros() - nPingUsecStart; } // Raw ping time is in microseconds, but show it to user as whole seconds (Bitcoin users should be well used to small numbers with many decimal places by now :) stats.dPingTime = (((double)nPingUsecTime) / 1e6); stats.dPingWait = (((double)nPingUsecWait) / 1e6); // Leave string empty if addrLocal invalid (not filled in yet) stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : ""; } #undef X // requires LOCK(cs_vRecvMsg) bool CNode::ReceiveMsgBytes(const char *pch, unsigned int nBytes) { while (nBytes > 0) { // get current incomplete message, or create a new one if (vRecvMsg.empty() || vRecvMsg.back().complete()) vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion)); CNetMessage& msg = vRecvMsg.back(); // absorb network data int handled; if (!msg.in_data) handled = msg.readHeader(pch, nBytes); else handled = msg.readData(pch, nBytes); if (handled < 0) return false; pch += handled; nBytes -= handled; if (msg.complete()) msg.nTime = GetTimeMicros(); } return true; } int CNetMessage::readHeader(const char *pch, unsigned int nBytes) { // copy data to temporary parsing buffer unsigned int nRemaining = 24 - nHdrPos; unsigned int nCopy = std::min(nRemaining, nBytes); memcpy(&hdrbuf[nHdrPos], pch, nCopy); nHdrPos += nCopy; // if header incomplete, exit if (nHdrPos < 24) return nCopy; // deserialize to CMessageHeader try { hdrbuf >> hdr; } catch (std::exception &e) { return -1; } // reject messages larger than MAX_SIZE if (hdr.nMessageSize > MAX_SIZE) return -1; // switch state to reading message data in_data = true; return nCopy; } int CNetMessage::readData(const char *pch, unsigned int nBytes) { unsigned int nRemaining = hdr.nMessageSize - nDataPos; unsigned int nCopy = std::min(nRemaining, nBytes); if (vRecv.size() < nDataPos + nCopy) { // Allocate up to 256 KiB ahead, but never more than the total message size. vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024)); } memcpy(&vRecv[nDataPos], pch, nCopy); nDataPos += nCopy; return nCopy; } // requires LOCK(cs_vSend) void SocketSendData(CNode *pnode) { std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin(); while (it != pnode->vSendMsg.end()) { const CSerializeData &data = *it; assert(data.size() > pnode->nSendOffset); int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT); if (nBytes > 0) { pnode->nLastSend = GetTime(); pnode->nSendBytes += nBytes; pnode->nSendOffset += nBytes; pnode->RecordBytesSent(nBytes); if (pnode->nSendOffset == data.size()) { pnode->nSendOffset = 0; pnode->nSendSize -= data.size(); it++; } else { // could not send full message; stop sending more break; } } else { if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { LogPrintf("socket send error %d\n", nErr); pnode->CloseSocketDisconnect(); } } // couldn't send anything at all break; } } if (it == pnode->vSendMsg.end()) { assert(pnode->nSendOffset == 0); assert(pnode->nSendSize == 0); } pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it); } static list<CNode*> vNodesDisconnected; void ThreadSocketHandler() { unsigned int nPrevNodeCount = 0; while (true) { // // Disconnect nodes // { LOCK(cs_vNodes); // Disconnect unused nodes vector<CNode*> vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (pnode->fDisconnect || (pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty())) { // remove from vNodes vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end()); // release outbound grant (if any) pnode->grantOutbound.Release(); // close socket and cleanup pnode->CloseSocketDisconnect(); // hold in disconnected pool until all refs are released if (pnode->fNetworkNode || pnode->fInbound) pnode->Release(); vNodesDisconnected.push_back(pnode); } } } { // Delete disconnected nodes list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected; BOOST_FOREACH(CNode* pnode, vNodesDisconnectedCopy) { // wait until threads are done using it if (pnode->GetRefCount() <= 0) { bool fDelete = false; { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { TRY_LOCK(pnode->cs_inventory, lockInv); if (lockInv) fDelete = true; } } } if (fDelete) { vNodesDisconnected.remove(pnode); delete pnode; } } } } if(vNodes.size() != nPrevNodeCount) { nPrevNodeCount = vNodes.size(); uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount); } // // Find which sockets have data to receive // struct timeval timeout; timeout.tv_sec = 0; timeout.tv_usec = 50000; // frequency to poll pnode->vSend fd_set fdsetRecv; fd_set fdsetSend; fd_set fdsetError; FD_ZERO(&fdsetRecv); FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); SOCKET hSocketMax = 0; bool have_fds = false; BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) { FD_SET(hListenSocket, &fdsetRecv); hSocketMax = max(hSocketMax, hListenSocket); have_fds = true; } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (pnode->hSocket == INVALID_SOCKET) continue; { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) { // do not read, if draining write queue if (!pnode->vSendMsg.empty()) FD_SET(pnode->hSocket, &fdsetSend); else FD_SET(pnode->hSocket, &fdsetRecv); FD_SET(pnode->hSocket, &fdsetError); hSocketMax = max(hSocketMax, pnode->hSocket); have_fds = true; } } } } int nSelect = select(have_fds ? hSocketMax + 1 : 0, &fdsetRecv, &fdsetSend, &fdsetError, &timeout); boost::this_thread::interruption_point(); if (nSelect == SOCKET_ERROR) { if (have_fds) { int nErr = WSAGetLastError(); LogPrintf("socket select error %d\n", nErr); for (unsigned int i = 0; i <= hSocketMax; i++) FD_SET(i, &fdsetRecv); } FD_ZERO(&fdsetSend); FD_ZERO(&fdsetError); MilliSleep(timeout.tv_usec/1000); } // // Accept new connections // BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) if (hListenSocket != INVALID_SOCKET && FD_ISSET(hListenSocket, &fdsetRecv)) { struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); SOCKET hSocket = accept(hListenSocket, (struct sockaddr*)&sockaddr, &len); CAddress addr; int nInbound = 0; if (hSocket != INVALID_SOCKET) if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr)) LogPrintf("Warning: Unknown socket family\n"); { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->fInbound) nInbound++; } if (hSocket == INVALID_SOCKET) { int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK) LogPrintf("socket error accept failed: %d\n", nErr); } else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS) { closesocket(hSocket); } else if (CNode::IsBanned(addr)) { LogPrintf("connection from %s dropped (banned)\n", addr.ToString()); closesocket(hSocket); } else { LogPrint("net", "accepted connection %s\n", addr.ToString()); CNode* pnode = new CNode(hSocket, addr, "", true); pnode->AddRef(); { LOCK(cs_vNodes); vNodes.push_back(pnode); } } } // // Service each socket // vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->AddRef(); } BOOST_FOREACH(CNode* pnode, vNodesCopy) { boost::this_thread::interruption_point(); // // Receive // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { if (pnode->GetTotalRecvSize() > ReceiveFloodSize()) { if (!pnode->fDisconnect) LogPrintf("socket recv flood control disconnect (%u bytes)\n", pnode->GetTotalRecvSize()); pnode->CloseSocketDisconnect(); } else { // typical socket buffer is 8K-64K char pchBuf[0x10000]; int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT); if (nBytes > 0) { if (!pnode->ReceiveMsgBytes(pchBuf, nBytes)) pnode->CloseSocketDisconnect(); pnode->nLastRecv = GetTime(); pnode->nRecvBytes += nBytes; pnode->RecordBytesRecv(nBytes); } else if (nBytes == 0) { // socket closed gracefully if (!pnode->fDisconnect) LogPrint("net", "socket closed\n"); pnode->CloseSocketDisconnect(); } else if (nBytes < 0) { // error int nErr = WSAGetLastError(); if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) { if (!pnode->fDisconnect) LogPrintf("socket recv error %d\n", nErr); pnode->CloseSocketDisconnect(); } } } } } // // Send // if (pnode->hSocket == INVALID_SOCKET) continue; if (FD_ISSET(pnode->hSocket, &fdsetSend)) { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) SocketSendData(pnode); } // // Inactivity checking // int64_t nTime = GetTime(); if (nTime - pnode->nTimeConnected > 60) { if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) { LogPrint("net", "socket no message in first 60 seconds, %d %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0); pnode->fDisconnect = true; } else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL) { LogPrintf("socket sending timeout: %ds\n", nTime - pnode->nLastSend); pnode->fDisconnect = true; } else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90*60)) { LogPrintf("socket receive timeout: %ds\n", nTime - pnode->nLastRecv); pnode->fDisconnect = true; } else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros()) { LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart)); pnode->fDisconnect = true; } } } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } } } #ifdef USE_UPNP void ThreadMapPort() { std::string port = strprintf("%u", GetListenPort()); const char * multicastif = 0; const char * minissdpdpath = 0; struct UPNPDev * devlist = 0; char lanaddr[64]; #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0); #else /* miniupnpc 1.6 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error); #endif struct UPNPUrls urls; struct IGDdatas data; int r; r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)); if (r == 1) { if (fDiscover) { char externalIPAddress[40]; r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress); if(r != UPNPCOMMAND_SUCCESS) LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r); else { if(externalIPAddress[0]) { LogPrintf("UPnP: ExternalIPAddress = %s\n", externalIPAddress); AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP); } else LogPrintf("UPnP: GetExternalIPAddress failed.\n"); } } string strDesc = "8Bit " + FormatFullVersion(); try { while (!ShutdownRequested()) { boost::this_thread::interruption_point(); #ifndef UPNPDISCOVER_SUCCESS /* miniupnpc 1.5 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0); #else /* miniupnpc 1.6 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0"); #endif if(r!=UPNPCOMMAND_SUCCESS) LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", port, port, lanaddr, r, strupnperror(r)); else LogPrintf("UPnP Port Mapping successful.\n");; MilliSleep(20*60*1000); // Refresh every 20 minutes } } catch (boost::thread_interrupted) { r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0); LogPrintf("UPNP_DeletePortMapping() returned : %d\n", r); freeUPNPDevlist(devlist); devlist = 0; FreeUPNPUrls(&urls); throw; } } else { LogPrintf("No valid UPnP IGDs found\n"); freeUPNPDevlist(devlist); devlist = 0; if (r != 0) FreeUPNPUrls(&urls); } } void MapPort(bool fUseUPnP) { static boost::thread* upnp_thread = NULL; if (fUseUPnP) { if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; } upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort)); } else if (upnp_thread) { upnp_thread->interrupt(); upnp_thread->join(); delete upnp_thread; upnp_thread = NULL; } } #else void MapPort(bool) { // Intentionally left blank. } #endif void ThreadDNSAddressSeed() { // goal: only query DNS seeds if address need is acute if ((addrman.size() > 0) && (!GetBoolArg("-forcednsseed", false))) { MilliSleep(11 * 1000); LOCK(cs_vNodes); if (vNodes.size() >= 2) { LogPrintf("P2P peers available. Skipped DNS seeding.\n"); return; } } const vector<CDNSSeedData> &vSeeds = Params().DNSSeeds(); int found = 0; LogPrintf("Loading addresses from DNS seeds (could take a while)\n"); BOOST_FOREACH(const CDNSSeedData &seed, vSeeds) { if (HaveNameProxy()) { AddOneShot(seed.host); } else { vector<CNetAddr> vIPs; vector<CAddress> vAdd; if (LookupHost(seed.host.c_str(), vIPs)) { BOOST_FOREACH(CNetAddr& ip, vIPs) { int nOneDay = 24*3600; CAddress addr = CAddress(CService(ip, Params().GetDefaultPort())); addr.nTime = GetTime() - 3*nOneDay - GetRand(4*nOneDay); // use a random age between 3 and 7 days old vAdd.push_back(addr); found++; } } addrman.Add(vAdd, CNetAddr(seed.name, true)); } } LogPrintf("%d addresses found from DNS seeds\n", found); } void DumpAddresses() { int64_t nStart = GetTimeMillis(); CAddrDB adb; adb.Write(addrman); LogPrint("net", "Flushed %d addresses to peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart); } void static ProcessOneShot() { string strDest; { LOCK(cs_vOneShots); if (vOneShots.empty()) return; strDest = vOneShots.front(); vOneShots.pop_front(); } CAddress addr; CSemaphoreGrant grant(*semOutbound, true); if (grant) { if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true)) AddOneShot(strDest); } } void ThreadOpenConnections() { // Connect to specific addresses if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { for (int64_t nLoop = 0;; nLoop++) { ProcessOneShot(); BOOST_FOREACH(string strAddr, mapMultiArgs["-connect"]) { CAddress addr; OpenNetworkConnection(addr, NULL, strAddr.c_str()); for (int i = 0; i < 10 && i < nLoop; i++) { MilliSleep(500); } } MilliSleep(500); } } // Initiate network connections int64_t nStart = GetTime(); while (true) { ProcessOneShot(); MilliSleep(500); CSemaphoreGrant grant(*semOutbound); boost::this_thread::interruption_point(); // Add seed nodes if DNS seeds are all down (an infrastructure attack?). if (addrman.size() == 0 && (GetTime() - nStart > 60)) { static bool done = false; if (!done) { LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n"); addrman.Add(Params().FixedSeeds(), CNetAddr("127.0.0.1")); done = true; } } // // Choose an address to connect to based on most recently seen // CAddress addrConnect; // Only connect out to one peer per network group (/16 for IPv4). // Do this here so we don't have to critsect vNodes inside mapAddresses critsect. int nOutbound = 0; set<vector<unsigned char> > setConnected; { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if (!pnode->fInbound) { setConnected.insert(pnode->addr.GetGroup()); nOutbound++; } } } int64_t nANow = GetAdjustedTime(); int nTries = 0; while (true) { // use an nUnkBias between 10 (no outgoing connections) and 90 (8 outgoing connections) CAddress addr = addrman.Select(10 + min(nOutbound,8)*10); // if we selected an invalid address, restart if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr)) break; // If we didn't find an appropriate destination after trying 100 addresses fetched from addrman, // stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates // already-connected network ranges, ...) before trying new addrman addresses. nTries++; if (nTries > 100) break; if (IsLimited(addr)) continue; // only consider very recently tried nodes after 30 failed attempts if (nANow - addr.nLastTry < 600 && nTries < 30) continue; // do not allow non-default ports, unless after 50 invalid addresses selected already if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50) continue; addrConnect = addr; break; } if (addrConnect.IsValid()) OpenNetworkConnection(addrConnect, &grant); } } void ThreadOpenAddedConnections() { { LOCK(cs_vAddedNodes); vAddedNodes = mapMultiArgs["-addnode"]; } if (HaveNameProxy()) { while(true) { list<string> lAddresses(0); { LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) lAddresses.push_back(strAddNode); } BOOST_FOREACH(string& strAddNode, lAddresses) { CAddress addr; CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(addr, &grant, strAddNode.c_str()); MilliSleep(500); } MilliSleep(120000); // Retry every 2 minutes } } for (unsigned int i = 0; true; i++) { list<string> lAddresses(0); { LOCK(cs_vAddedNodes); BOOST_FOREACH(string& strAddNode, vAddedNodes) lAddresses.push_back(strAddNode); } list<vector<CService> > lservAddressesToAdd(0); BOOST_FOREACH(string& strAddNode, lAddresses) { vector<CService> vservNode(0); if(Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0)) { lservAddressesToAdd.push_back(vservNode); { LOCK(cs_setservAddNodeAddresses); BOOST_FOREACH(CService& serv, vservNode) setservAddNodeAddresses.insert(serv); } } } // Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry // (keeping in mind that addnode entries can have many IPs if fNameLookup) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++) BOOST_FOREACH(CService& addrNode, *(it)) if (pnode->addr == addrNode) { it = lservAddressesToAdd.erase(it); it--; break; } } BOOST_FOREACH(vector<CService>& vserv, lservAddressesToAdd) { CSemaphoreGrant grant(*semOutbound); OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant); MilliSleep(500); } MilliSleep(120000); // Retry every 2 minutes } } // if successful, this moves the passed grant to the constructed node bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound, const char *strDest, bool fOneShot) { // // Initiate outbound network connection // boost::this_thread::interruption_point(); if (!strDest) if (IsLocal(addrConnect) || FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) || FindNode(addrConnect.ToStringIPPort().c_str())) return false; if (strDest && FindNode(strDest)) return false; CNode* pnode = ConnectNode(addrConnect, strDest); boost::this_thread::interruption_point(); if (!pnode) return false; if (grantOutbound) grantOutbound->MoveTo(pnode->grantOutbound); pnode->fNetworkNode = true; if (fOneShot) pnode->fOneShot = true; return true; } // for now, use a very simple selection metric: the node from which we received // most recently static int64_t NodeSyncScore(const CNode *pnode) { return pnode->nLastRecv; } void static StartSync(const vector<CNode*> &vNodes) { CNode *pnodeNewSync = NULL; int64_t nBestScore = 0; // fImporting and fReindex are accessed out of cs_main here, but only // as an optimization - they are checked again in SendMessages. if (fImporting || fReindex) return; // Iterate over all nodes BOOST_FOREACH(CNode* pnode, vNodes) { // check preconditions for allowing a sync if (!pnode->fClient && !pnode->fOneShot && !pnode->fDisconnect && pnode->fSuccessfullyConnected && (pnode->nStartingHeight > (nBestHeight - 144)) && (pnode->nVersion < NOBLKS_VERSION_START || pnode->nVersion >= NOBLKS_VERSION_END)) { // if ok, compare node's score with the best so far int64_t nScore = NodeSyncScore(pnode); if (pnodeNewSync == NULL || nScore > nBestScore) { pnodeNewSync = pnode; nBestScore = nScore; } } } // if a new sync candidate was found, start sync! if (pnodeNewSync) { pnodeNewSync->fStartSync = true; pnodeSync = pnodeNewSync; } } void ThreadMessageHandler() { SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL); while (true) { bool fHaveSyncNode = false; vector<CNode*> vNodesCopy; { LOCK(cs_vNodes); vNodesCopy = vNodes; BOOST_FOREACH(CNode* pnode, vNodesCopy) { pnode->AddRef(); if (pnode == pnodeSync) fHaveSyncNode = true; } } if (!fHaveSyncNode) StartSync(vNodesCopy); // Poll the connected nodes for messages CNode* pnodeTrickle = NULL; if (!vNodesCopy.empty()) pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())]; bool fSleep = true; BOOST_FOREACH(CNode* pnode, vNodesCopy) { if (pnode->fDisconnect) continue; // Receive messages { TRY_LOCK(pnode->cs_vRecvMsg, lockRecv); if (lockRecv) { if (!g_signals.ProcessMessages(pnode)) pnode->CloseSocketDisconnect(); if (pnode->nSendSize < SendBufferSize()) { if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete())) { fSleep = false; } } } } boost::this_thread::interruption_point(); // Send messages { TRY_LOCK(pnode->cs_vSend, lockSend); if (lockSend) g_signals.SendMessages(pnode, pnode == pnodeTrickle); } boost::this_thread::interruption_point(); } { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodesCopy) pnode->Release(); } if (fSleep) MilliSleep(100); } } bool BindListenPort(const CService &addrBind, string& strError) { strError = ""; int nOne = 1; #ifdef WIN32 // Initialize Windows Sockets WSADATA wsadata; int ret = WSAStartup(MAKEWORD(2,2), &wsadata); if (ret != NO_ERROR) { strError = strprintf("Error: TCP/IP socket library failed to start (WSAStartup returned error %d)", ret); LogPrintf("%s\n", strError); return false; } #endif // Create socket for listening for incoming connections struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { strError = strprintf("Error: bind address family for %s not supported", addrBind.ToString()); LogPrintf("%s\n", strError); return false; } SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP); if (hListenSocket == INVALID_SOCKET) { strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %d)", WSAGetLastError()); LogPrintf("%s\n", strError); return false; } #ifdef SO_NOSIGPIPE // Different way of disabling SIGPIPE on BSD setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int)); #endif #ifndef WIN32 // Allow binding if the port is still in TIME_WAIT state after // the program was closed and restarted. Not an issue on windows. setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int)); #endif #ifdef WIN32 // Set to non-blocking, incoming connections will also inherit this if (ioctlsocket(hListenSocket, FIONBIO, (u_long*)&nOne) == SOCKET_ERROR) #else if (fcntl(hListenSocket, F_SETFL, O_NONBLOCK) == SOCKET_ERROR) #endif { strError = strprintf("Error: Couldn't set properties on socket for incoming connections (error %d)", WSAGetLastError()); LogPrintf("%s\n", strError); return false; } // some systems don't have IPV6_V6ONLY but are always v6only; others do have the option // and enable it by default or not. Try to enable it, if possible. if (addrBind.IsIPv6()) { #ifdef IPV6_V6ONLY #ifdef WIN32 setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int)); #else setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int)); #endif #endif #ifdef WIN32 int nProtLevel = 10 /* PROTECTION_LEVEL_UNRESTRICTED */; int nParameterId = 23 /* IPV6_PROTECTION_LEVEl */; // this call is allowed to fail setsockopt(hListenSocket, IPPROTO_IPV6, nParameterId, (const char*)&nProtLevel, sizeof(int)); #endif } if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); if (nErr == WSAEADDRINUSE) strError = strprintf(_("Unable to bind to %s on this computer. 8Bit is probably already running."), addrBind.ToString()); else strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %d, %s)"), addrBind.ToString(), nErr, strerror(nErr)); LogPrintf("%s\n", strError); return false; } LogPrintf("Bound to %s\n", addrBind.ToString()); // Listen for incoming connections if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) { strError = strprintf("Error: Listening for incoming connections failed (listen returned error %d)", WSAGetLastError()); LogPrintf("%s\n", strError); return false; } vhListenSocket.push_back(hListenSocket); if (addrBind.IsRoutable() && fDiscover) AddLocal(addrBind, LOCAL_BIND); return true; } void static Discover(boost::thread_group& threadGroup) { if (!fDiscover) return; #ifdef WIN32 // Get local host IP char pszHostName[1000] = ""; if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) { vector<CNetAddr> vaddr; if (LookupHost(pszHostName, vaddr)) { BOOST_FOREACH (const CNetAddr &addr, vaddr) { AddLocal(addr, LOCAL_IF); } } } #else // Get local host ip struct ifaddrs* myaddrs; if (getifaddrs(&myaddrs) == 0) { for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) { if (ifa->ifa_addr == NULL) continue; if ((ifa->ifa_flags & IFF_UP) == 0) continue; if (strcmp(ifa->ifa_name, "lo") == 0) continue; if (strcmp(ifa->ifa_name, "lo0") == 0) continue; if (ifa->ifa_addr->sa_family == AF_INET) { struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr); CNetAddr addr(s4->sin_addr); if (AddLocal(addr, LOCAL_IF)) LogPrintf("IPv4 %s: %s\n", ifa->ifa_name, addr.ToString()); } else if (ifa->ifa_addr->sa_family == AF_INET6) { struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr); CNetAddr addr(s6->sin6_addr); if (AddLocal(addr, LOCAL_IF)) LogPrintf("IPv6 %s: %s\n", ifa->ifa_name, addr.ToString()); } } freeifaddrs(myaddrs); } #endif } void StartNode(boost::thread_group& threadGroup) { if (semOutbound == NULL) { // initialize semaphore int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125)); semOutbound = new CSemaphore(nMaxOutbound); } if (pnodeLocalHost == NULL) pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices)); Discover(threadGroup); // // Start threads // if (!GetBoolArg("-dnsseed", true)) LogPrintf("DNS seeding disabled\n"); else threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dnsseed", &ThreadDNSAddressSeed)); #ifdef USE_UPNP // Map ports with UPnP MapPort(GetBoolArg("-upnp", USE_UPNP)); #endif // Get addresses from IRC and advertise ours threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "irc", &ThreadIRCSeed)); // Send and receive from sockets, accept connections threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler)); // Initiate outbound connections from -addnode threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections)); // Initiate outbound connections threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections)); // Process messages threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler)); // Dump network addresses threadGroup.create_thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, DUMP_ADDRESSES_INTERVAL * 1000)); } bool StopNode() { LogPrintf("StopNode()\n"); MapPort(false); mempool.AddTransactionsUpdated(1); if (semOutbound) for (int i=0; i<MAX_OUTBOUND_CONNECTIONS; i++) semOutbound->post(); DumpAddresses(); return true; } class CNetCleanup { public: CNetCleanup() { } ~CNetCleanup() { // Close sockets BOOST_FOREACH(CNode* pnode, vNodes) if (pnode->hSocket != INVALID_SOCKET) closesocket(pnode->hSocket); BOOST_FOREACH(SOCKET hListenSocket, vhListenSocket) if (hListenSocket != INVALID_SOCKET) if (closesocket(hListenSocket) == SOCKET_ERROR) LogPrintf("closesocket(hListenSocket) failed with error %d\n", WSAGetLastError()); #ifdef WIN32 // Shutdown Windows Sockets WSACleanup(); #endif } } instance_of_cnetcleanup; void RelayTransaction(const CTransaction& tx, const uint256& hash) { CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(10000); ss << tx; RelayTransaction(tx, hash, ss); } void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss) { CInv inv(MSG_TX, hash); { LOCK(cs_mapRelay); // Expire old relay messages while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime()) { mapRelay.erase(vRelayExpiration.front().second); vRelayExpiration.pop_front(); } // Save original serialized message so newer versions are preserved mapRelay.insert(std::make_pair(inv, ss)); vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv)); } RelayInventory(inv); } void RelayTransactionLockReq(const CTransaction& tx, const uint256& hash, bool relayToAll) { CInv inv(MSG_TXLOCK_REQUEST, tx.GetHash()); //broadcast the new lock LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if(!relayToAll && !pnode->fRelayTxes) continue; pnode->PushMessage("txlreq", tx); } } void RelayDarkSendFinalTransaction(const int sessionID, const CTransaction& txNew) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { pnode->PushMessage("dsf", sessionID, txNew); } } void RelayDarkSendIn(const std::vector<CTxIn>& in, const int64_t& nAmount, const CTransaction& txCollateral, const std::vector<CTxOut>& out) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if((CNetAddr)darkSendPool.submittedToMasternode != (CNetAddr)pnode->addr) continue; LogPrintf("RelayDarkSendIn - found master, relaying message - %s \n", pnode->addr.ToString().c_str()); pnode->PushMessage("dsi", in, nAmount, txCollateral, out); } } void RelayDarkSendStatus(const int sessionID, const int newState, const int newEntriesCount, const int newAccepted, const std::string error) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { pnode->PushMessage("dssu", sessionID, newState, newEntriesCount, newAccepted, error); } } void RelayDarkSendElectionEntry(const CTxIn vin, const CService addr, const std::vector<unsigned char> vchSig, const int64_t nNow, const CPubKey pubkey, const CPubKey pubkey2, const int count, const int current, const int64_t lastUpdated, const int protocolVersion) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if(!pnode->fRelayTxes) continue; pnode->PushMessage("dsee", vin, addr, vchSig, nNow, pubkey, pubkey2, count, current, lastUpdated, protocolVersion); } } void SendDarkSendElectionEntry(const CTxIn vin, const CService addr, const std::vector<unsigned char> vchSig, const int64_t nNow, const CPubKey pubkey, const CPubKey pubkey2, const int count, const int current, const int64_t lastUpdated, const int protocolVersion) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { pnode->PushMessage("dsee", vin, addr, vchSig, nNow, pubkey, pubkey2, count, current, lastUpdated, protocolVersion); } } void RelayDarkSendElectionEntryPing(const CTxIn vin, const std::vector<unsigned char> vchSig, const int64_t nNow, const bool stop) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { if(!pnode->fRelayTxes) continue; pnode->PushMessage("dseep", vin, vchSig, nNow, stop); } } void SendDarkSendElectionEntryPing(const CTxIn vin, const std::vector<unsigned char> vchSig, const int64_t nNow, const bool stop) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { pnode->PushMessage("dseep", vin, vchSig, nNow, stop); } } void RelayDarkSendCompletedTransaction(const int sessionID, const bool error, const std::string errorMessage) { LOCK(cs_vNodes); BOOST_FOREACH(CNode* pnode, vNodes) { pnode->PushMessage("dsc", sessionID, error, errorMessage); } } void CNode::RecordBytesRecv(uint64_t bytes) { LOCK(cs_totalBytesRecv); nTotalBytesRecv += bytes; } void CNode::RecordBytesSent(uint64_t bytes) { LOCK(cs_totalBytesSent); nTotalBytesSent += bytes; } uint64_t CNode::GetTotalBytesRecv() { LOCK(cs_totalBytesRecv); return nTotalBytesRecv; } uint64_t CNode::GetTotalBytesSent() { LOCK(cs_totalBytesSent); return nTotalBytesSent; } // // CAddrDB // CAddrDB::CAddrDB() { pathAddr = GetDataDir() / "peers.dat"; } bool CAddrDB::Write(const CAddrMan& addr) { // Generate random temporary filename unsigned short randv = 0; RAND_bytes((unsigned char *)&randv, sizeof(randv)); std::string tmpfn = strprintf("peers.dat.%04x", randv); // serialize addresses, checksum data up to that point, then append csum CDataStream ssPeers(SER_DISK, CLIENT_VERSION); ssPeers << FLATDATA(Params().MessageStart()); ssPeers << addr; uint256 hash = Hash(ssPeers.begin(), ssPeers.end()); ssPeers << hash; // open temp output file, and associate with CAutoFile boost::filesystem::path pathTmp = GetDataDir() / tmpfn; FILE *file = fopen(pathTmp.string().c_str(), "wb"); CAutoFile fileout = CAutoFile(file, SER_DISK, CLIENT_VERSION); if (!fileout) return error("CAddrman::Write() : open failed"); // Write and commit header, data try { fileout << ssPeers; } catch (std::exception &e) { return error("CAddrman::Write() : I/O error"); } FileCommit(fileout); fileout.fclose(); // replace existing peers.dat, if any, with new peers.dat.XXXX if (!RenameOver(pathTmp, pathAddr)) return error("CAddrman::Write() : Rename-into-place failed"); return true; } bool CAddrDB::Read(CAddrMan& addr) { // open input file, and associate with CAutoFile FILE *file = fopen(pathAddr.string().c_str(), "rb"); CAutoFile filein = CAutoFile(file, SER_DISK, CLIENT_VERSION); if (!filein) return error("CAddrman::Read() : open failed"); // use file size to size memory buffer int fileSize = boost::filesystem::file_size(pathAddr); int dataSize = fileSize - sizeof(uint256); // Don't try to resize to a negative number if file is small if ( dataSize < 0 ) dataSize = 0; vector<unsigned char> vchData; vchData.resize(dataSize); uint256 hashIn; // read data and checksum from file try { filein.read((char *)&vchData[0], dataSize); filein >> hashIn; } catch (std::exception &e) { return error("CAddrman::Read() 2 : I/O error or stream data corrupted"); } filein.fclose(); CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION); // verify stored checksum matches input data uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end()); if (hashIn != hashTmp) return error("CAddrman::Read() : checksum mismatch; data corrupted"); unsigned char pchMsgTmp[4]; try { // de-serialize file header (network specific magic number) and .. ssPeers >> FLATDATA(pchMsgTmp); // ... verify the network matches ours if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp))) return error("CAddrman::Read() : invalid network magic number"); // de-serialize address data into one CAddrMan object ssPeers >> addr; } catch (std::exception &e) { return error("CAddrman::Read() : I/O error or stream data corrupted"); } return true; }
{ "content_hash": "c99898e09590926ce9b4d685655d1501", "timestamp": "", "source": "github", "line_count": 1979, "max_line_length": 265, "avg_line_length": 30.54522486104093, "alnum_prop": 0.5646081821039223, "repo_name": "8bit-dev/8bit", "id": "6599fdbc629e7e9bd5d421e547d0025df298ebd6", "size": "60449", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/net.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "51312" }, { "name": "C", "bytes": "38295" }, { "name": "C++", "bytes": "3111936" }, { "name": "CSS", "bytes": "1127" }, { "name": "HTML", "bytes": "50620" }, { "name": "Makefile", "bytes": "11728" }, { "name": "NSIS", "bytes": "5914" }, { "name": "Objective-C", "bytes": "858" }, { "name": "Objective-C++", "bytes": "3517" }, { "name": "Python", "bytes": "54355" }, { "name": "QMake", "bytes": "15303" }, { "name": "Shell", "bytes": "8509" } ], "symlink_target": "" }
package com.alipay.zxingdemo.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.view.View; import com.alipay.zxingdemo.QrCodeCaptureManager; import com.alipay.zxingdemo.R; import com.journeyapps.barcodescanner.BarcodeResult; import com.journeyapps.barcodescanner.CompoundBarcodeView; public abstract class BaseQRCodeScanActivity extends AppCompatActivity { public static final String EXTRA_SCAN_CONTENT = "extra_scan_content"; protected CompoundBarcodeView mBarcodeView; protected QrCodeCaptureManager mCapture; protected boolean mIsTorchOn = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); setContentView(getContentLayoutResId()); findViewById(R.id.switch_torch).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mIsTorchOn) { mBarcodeView.setTorchOff(); } else { mBarcodeView.setTorchOn(); } mIsTorchOn = !mIsTorchOn; } }); mBarcodeView = findViewById(R.id.bar_code_view); mCapture = new QrCodeCaptureManager(this, mBarcodeView, mScanListener); mCapture.initializeFromIntent(getIntent(), savedInstanceState); mCapture.decode(); mBarcodeView.setStatusText(null); setResult(Activity.RESULT_CANCELED); } @LayoutRes protected abstract int getContentLayoutResId(); private QrCodeCaptureManager.OnScanListener mScanListener = new QrCodeCaptureManager.OnScanListener() { @Override public void onResult(BarcodeResult result) { Intent data = new Intent(); data.putExtra(EXTRA_SCAN_CONTENT, result.getText()); setResult(Activity.RESULT_OK, data); finish(); } }; @Override protected void onResume() { super.onResume(); mCapture.onResume(); } @Override protected void onPause() { super.onPause(); mCapture.onPause(); } @Override protected void onDestroy() { super.onDestroy(); mCapture.onDestroy(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mCapture.onSaveInstanceState(outState); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { return mBarcodeView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event); } }
{ "content_hash": "8b3ea52514d9cf80e8b33968f2e43e41", "timestamp": "", "source": "github", "line_count": 99, "max_line_length": 87, "avg_line_length": 29.171717171717173, "alnum_prop": 0.6461218836565097, "repo_name": "arnozhang/android-zxing-demo", "id": "ac6cba48261fa26849b55030c2faa87ab08559f4", "size": "3543", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "sources/app/src/main/java/com/alipay/zxingdemo/activity/BaseQRCodeScanActivity.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "14721" } ], "symlink_target": "" }
```sh bower install silverhold-radio ```
{ "content_hash": "de4430addca7633aa82e4266d3440234", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 30, "avg_line_length": 13.666666666666666, "alnum_prop": 0.7073170731707317, "repo_name": "LoicGoyet/custom-radio", "id": "a05c904aba42bf600a8f775875df4e062c642d43", "size": "74", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "12480" }, { "name": "HTML", "bytes": "13468" } ], "symlink_target": "" }
package com.tierzero.stacksonstacks.core; import java.io.File; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.Configuration; public class ConfigHandler { private static Configuration config; private static final String CATEGORY_NAME_APPEARANCE = "Appearance"; public static String defaultTextureName; public static boolean useIngotBlockTexture; private static final String CATEGORY_NAME_DEBUG = "Debug"; public static boolean printOnRegistration; public static void initConfig(File suggestedConfigurationFile) { config = new Configuration(suggestedConfigurationFile); loadConfig(); } private static void loadConfig() { config.load(); String[] validTextureNames = { "sos:default_ingot_texture" }; config.addCustomCategoryComment(CATEGORY_NAME_APPEARANCE, "Change how the ingots look"); defaultTextureName = config.getString("Ingot Texture", CATEGORY_NAME_APPEARANCE, "sos:default_ingot_texture", "The texture that ingots use to render(Textures belonging to other mods require that mod to work!)", validTextureNames); useIngotBlockTexture = config.getBoolean("useIngotBlockTexture", CATEGORY_NAME_APPEARANCE, true, "Use the texture of the block version of the ingot if one exists (ex: gold ingot uses gold block texture)"); config.addCustomCategoryComment(CATEGORY_NAME_DEBUG, "Enables some debug features of the mod, should not be used!"); printOnRegistration = config.getBoolean("printOnRegistration", CATEGORY_NAME_DEBUG, false, "Causes a text containing the registered item's type and name to print when it is registered"); config.save(); } }
{ "content_hash": "f9b8aef4e82c43ade57152767f1ed24d", "timestamp": "", "source": "github", "line_count": 37, "max_line_length": 238, "avg_line_length": 46.729729729729726, "alnum_prop": 0.7484094852515906, "repo_name": "primetoxinz/StacksOnStacks", "id": "aa7f9474eaa4c05aa50bebfea05d852d405f7215", "size": "1729", "binary": false, "copies": "1", "ref": "refs/heads/1.11", "path": "src/main/java/com/tierzero/stacksonstacks/core/ConfigHandler.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "44442" } ], "symlink_target": "" }
namespace Nop.Core.Domain.Catalog { /// <summary> /// Represents a product specification attribute /// </summary> public partial class ProductSpecificationAttribute : BaseEntity { /// <summary> /// Gets or sets the product identifier /// </summary> public virtual int ProductId { get; set; } /// <summary> /// Gets or sets the specification attribute identifier /// </summary> public virtual int SpecificationAttributeOptionId { get; set; } /// <summary> /// Gets or sets whether the attribute can be filtered by /// </summary> public virtual bool AllowFiltering { get; set; } /// <summary> /// Gets or sets whether the attrbiute will be shown on the product page /// </summary> public virtual bool ShowOnProductPage { get; set; } /// <summary> /// Gets or sets the display order /// </summary> public virtual int DisplayOrder { get; set; } /// <summary> /// Gets or sets the product /// </summary> public virtual Product Product { get; set; } /// <summary> /// Gets or sets the specification attribute option /// </summary> public virtual SpecificationAttributeOption SpecificationAttributeOption { get; set; } } }
{ "content_hash": "0f7bc6af51f1f7a422bef00264b7c9dd", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 94, "avg_line_length": 31.86046511627907, "alnum_prop": 0.5846715328467154, "repo_name": "lewischeng-ms/WebApi", "id": "d0ee32c45c8b0040c7066879ee9fd74bb4a0dc44", "size": "1370", "binary": false, "copies": "8", "ref": "refs/heads/OData60", "path": "OData/test/E2ETest/WebStack.QA.Test.OData/Common/Models/NopCommerce/Domain/Catalog/ProductSpecificationAttribute.cs", "mode": "33188", "license": "mit", "language": [ { "name": "1C Enterprise", "bytes": "185749" }, { "name": "ASP", "bytes": "119" }, { "name": "Batchfile", "bytes": "2842" }, { "name": "C#", "bytes": "14865821" }, { "name": "JavaScript", "bytes": "7493" }, { "name": "PowerShell", "bytes": "382" } ], "symlink_target": "" }
const__ char* __bea_callspec__ BeaEngineVersion(void) { return "5.3"; } const__ char* __bea_callspec__ BeaEngineRevision(void) { return "0"; }
{ "content_hash": "418a8e15fd3f3bef3b1a3738473461a8", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 56, "avg_line_length": 20.857142857142858, "alnum_prop": 0.6575342465753424, "repo_name": "0vercl0k/rp", "id": "b359b7b800191bcb02a2a0067d076785b1f2098d", "size": "934", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/third_party/beaengine/src/Includes/BeaEngineVersion.c", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "116" }, { "name": "C", "bytes": "1214" }, { "name": "C++", "bytes": "107056" }, { "name": "CMake", "bytes": "1327" }, { "name": "Shell", "bytes": "118" } ], "symlink_target": "" }
let templates = { get(name) { let url = `src/templates/${name}.html`; return requester.get(url); } };
{ "content_hash": "f6f4c0fd39a973132bf17b7cdb603c1a", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 47, "avg_line_length": 20.833333333333332, "alnum_prop": 0.528, "repo_name": "WorkenWithLopaten/MovieDatabaseServer", "id": "6300e840555563da267529c29b827f03ac0e57bd", "size": "125", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "TheMovies/src/js/templateLoader.js", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "100" }, { "name": "C#", "bytes": "339202" }, { "name": "CSS", "bytes": "2311" }, { "name": "HTML", "bytes": "9811" }, { "name": "JavaScript", "bytes": "9398" } ], "symlink_target": "" }
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>windows::basic_object_handle::native_handle</title> <link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.78.1"> <link rel="home" href="../../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../windows__basic_object_handle.html" title="windows::basic_object_handle"> <link rel="prev" href="native.html" title="windows::basic_object_handle::native"> <link rel="next" href="native_handle_type.html" title="windows::basic_object_handle::native_handle_type"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td> <td align="center"><a href="../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="native.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../windows__basic_object_handle.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="native_handle_type.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="boost_asio.reference.windows__basic_object_handle.native_handle"></a><a class="link" href="native_handle.html" title="windows::basic_object_handle::native_handle">windows::basic_object_handle::native_handle</a> </h4></div></div></div> <p> <span class="emphasis"><em>Inherited from windows::basic_handle.</em></span> </p> <p> <a class="indexterm" name="idp184105248"></a> Get the native handle representation. </p> <pre class="programlisting"><span class="identifier">native_handle_type</span> <span class="identifier">native_handle</span><span class="special">();</span> </pre> <p> This function may be used to obtain the underlying representation of the handle. This is intended to allow access to native handle functionality that is not otherwise provided. </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2015 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="native.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../windows__basic_object_handle.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="native_handle_type.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{ "content_hash": "54514875f9fc32489bc1121bcba848a6", "timestamp": "", "source": "github", "line_count": 58, "max_line_length": 450, "avg_line_length": 63.758620689655174, "alnum_prop": 0.6373715521903732, "repo_name": "Franky666/programmiersprachen-raytracer", "id": "6894f1993b41e7b8c824446a8ff106761f524b8a", "size": "3698", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "external/boost_1_59_0/doc/html/boost_asio/reference/windows__basic_object_handle/native_handle.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "905071" }, { "name": "C++", "bytes": "46207" }, { "name": "CMake", "bytes": "4419" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>V8 API Reference Guide for node.js v0.12.2: Class Members</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v0.12.2 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li class="current"><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <div id="navrow3" class="tabs2"> <ul class="tablist"> <li class="current"><a href="functions.html"><span>All</span></a></li> <li><a href="functions_func.html"><span>Functions</span></a></li> <li><a href="functions_vars.html"><span>Variables</span></a></li> <li><a href="functions_type.html"><span>Typedefs</span></a></li> <li><a href="functions_enum.html"><span>Enumerations</span></a></li> </ul> </div> <div id="navrow4" class="tabs3"> <ul class="tablist"> <li><a href="functions.html#index_a"><span>a</span></a></li> <li><a href="functions_b.html#index_b"><span>b</span></a></li> <li><a href="functions_c.html#index_c"><span>c</span></a></li> <li><a href="functions_d.html#index_d"><span>d</span></a></li> <li><a href="functions_e.html#index_e"><span>e</span></a></li> <li><a href="functions_f.html#index_f"><span>f</span></a></li> <li><a href="functions_g.html#index_g"><span>g</span></a></li> <li><a href="functions_h.html#index_h"><span>h</span></a></li> <li><a href="functions_i.html#index_i"><span>i</span></a></li> <li><a href="functions_j.html#index_j"><span>j</span></a></li> <li><a href="functions_k.html#index_k"><span>k</span></a></li> <li><a href="functions_l.html#index_l"><span>l</span></a></li> <li class="current"><a href="functions_m.html#index_m"><span>m</span></a></li> <li><a href="functions_n.html#index_n"><span>n</span></a></li> <li><a href="functions_o.html#index_o"><span>o</span></a></li> <li><a href="functions_p.html#index_p"><span>p</span></a></li> <li><a href="functions_r.html#index_r"><span>r</span></a></li> <li><a href="functions_s.html#index_s"><span>s</span></a></li> <li><a href="functions_t.html#index_t"><span>t</span></a></li> <li><a href="functions_u.html#index_u"><span>u</span></a></li> <li><a href="functions_v.html#index_v"><span>v</span></a></li> <li><a href="functions_w.html#index_w"><span>w</span></a></li> <li><a href="functions_~.html#index_~"><span>~</span></a></li> </ul> </div> </div><!-- top --> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="contents"> <div class="textblock">Here is a list of all documented class members with links to the class documentation for each member:</div> <h3><a class="anchor" id="index_m"></a>- m -</h3><ul> <li>MakeExternal() : <a class="el" href="classv8_1_1_string.html#a5efd1eba40c1fa8a6aae2c4a175a63be">v8::String</a> </li> <li>MarkAsUndetectable() : <a class="el" href="classv8_1_1_object_template.html#a7e40ef313b44c2ad336c73051523b4f8">v8::ObjectTemplate</a> </li> <li>MarkIndependent() : <a class="el" href="classv8_1_1_persistent_base.html#aed12b0a54bc5ade1fb44e3bdb3a1fe74">v8::PersistentBase&lt; T &gt;</a> </li> <li>MarkPartiallyDependent() : <a class="el" href="classv8_1_1_persistent_base.html#a4a876d30dda0dfb812e82bb240e4686e">v8::PersistentBase&lt; T &gt;</a> </li> <li>Message() : <a class="el" href="classv8_1_1_try_catch.html#a2811e500fbb906ee505895a3d94fc66f">v8::TryCatch</a> </li> <li>MessageHandler : <a class="el" href="classv8_1_1_debug.html#a526826b857bd3e3efa184e12bcebc694">v8::Debug</a> </li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Aug 11 2015 23:46:23 for V8 API Reference Guide for node.js v0.12.2 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
{ "content_hash": "1fb0dbe7e67c0b584db2a913c6cf9886", "timestamp": "", "source": "github", "line_count": 153, "max_line_length": 154, "avg_line_length": 46.24183006535948, "alnum_prop": 0.6333568904593639, "repo_name": "v8-dox/v8-dox.github.io", "id": "ce06c778a0df9dc8afb2b9d8031040185a1cb25a", "size": "7075", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "2fc5eeb/html/functions_m.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
""" .. py:currentmodule:: __init__ :synopsis: Init for the package. .. moduleauthor:: Hendrix Demers <hendrix.demers@mail.mcgill.ca> Init for the package. """ ############################################################################### # Copyright 2007 Hendrix Demers # # 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. ############################################################################### # Standard library modules. # Third party modules. # Local modules. # Project modules. # Globals and constants variables.
{ "content_hash": "3a0c5234e47411646667dc4f8eee2ef2", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 79, "avg_line_length": 30.264705882352942, "alnum_prop": 0.6277939747327502, "repo_name": "drix00/microanalysis_file_format", "id": "39a1c38adcde014e7223139bc25599a60b273c7d", "size": "1076", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "pySpectrumFileFormat/OxfordInstruments/INCA/__init__.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "2367" }, { "name": "PLSQL", "bytes": "129" }, { "name": "Python", "bytes": "235002" } ], "symlink_target": "" }
import { authSecret } from '../common/constants' if ( process.env.NODE_ENV === 'production' && !process.env.hasOwnProperty('JWT_SECRET') ) { // eslint-disable-next-line no-console console.warn( 'In production mode you must specify jwt secret key in JWT_SECRET environment variable' ) } export default process.env.JWT_SECRET || authSecret
{ "content_hash": "86bdb07e481e94314af264a29fbd2749", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 91, "avg_line_length": 32, "alnum_prop": 0.7159090909090909, "repo_name": "reimagined/resolve", "id": "dbe8ff9a476fe40da987888f4032b5a71669a967", "size": "352", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "examples/js/personal-data/auth/jwt-secret.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "11199" }, { "name": "JavaScript", "bytes": "724085" }, { "name": "TypeScript", "bytes": "2067323" }, { "name": "Vue", "bytes": "2902" } ], "symlink_target": "" }
namespace arangodb { struct FlushSubscription; namespace iresearch { struct MaintenanceState; class IResearchFeature; class IResearchView; class IResearchLink; //////////////////////////////////////////////////////////////////////////////// /// @brief IResarchLink handle to use with asynchronous tasks //////////////////////////////////////////////////////////////////////////////// class AsyncLinkHandle { public: explicit AsyncLinkHandle(IResearchLink* link); ~AsyncLinkHandle(); bool empty() const { return _link.empty(); } auto lock() { return _link.lock(); } auto try_lock() noexcept { return _link.try_lock(); } bool terminationRequested() const noexcept { return _asyncTerminate.load(); } private: friend class IResearchLink; AsyncLinkHandle(AsyncLinkHandle const&) = delete; AsyncLinkHandle(AsyncLinkHandle&&) = delete; AsyncLinkHandle& operator=(AsyncLinkHandle const&) = delete; AsyncLinkHandle& operator=(AsyncLinkHandle&&) = delete; void reset(); AsyncValue<IResearchLink> _link; std::atomic<bool> _asyncTerminate{false}; // trigger termination of long-running async jobs }; // AsyncLinkHandle //////////////////////////////////////////////////////////////////////////////// /// @brief common base class for functionality required to link an ArangoDB /// LogicalCollection with an IResearchView //////////////////////////////////////////////////////////////////////////////// class IResearchLink { public: using AsyncLinkPtr = std::shared_ptr<AsyncLinkHandle>; using InitCallback = std::function<irs::directory_attributes()>; ////////////////////////////////////////////////////////////////////////////// /// @brief a snapshot representation of the data-store /// locked to prevent data store deallocation ////////////////////////////////////////////////////////////////////////////// class Snapshot { public: Snapshot() = default; Snapshot(AsyncValue<IResearchLink>::Value&& lock, irs::directory_reader&& reader) noexcept : _lock(std::move(lock)), _reader(std::move(reader)) { TRI_ASSERT(_lock.ownsLock()); } Snapshot(Snapshot&& rhs) noexcept : _lock(std::move(rhs._lock)), _reader(std::move(rhs._reader)) { TRI_ASSERT(_lock.ownsLock()); } Snapshot& operator=(Snapshot&& rhs) noexcept { if (this != &rhs) { _lock = std::move(rhs._lock); _reader = std::move(rhs._reader); } TRI_ASSERT(_lock.ownsLock()); return *this; } operator irs::directory_reader const&() const noexcept { return _reader; } private: AsyncValue<IResearchLink>::Value _lock; // lock preventing data store dealocation irs::directory_reader _reader; }; virtual ~IResearchLink(); //////////////////////////////////////////////////////////////////////////////// /// @brief does this IResearch Link reference the supplied view //////////////////////////////////////////////////////////////////////////////// bool operator==(LogicalView const& view) const noexcept; bool operator!=(LogicalView const& view) const noexcept { return !(*this == view); } //////////////////////////////////////////////////////////////////////////////// /// @brief does this iResearch Link match the meta definition //////////////////////////////////////////////////////////////////////////////// bool operator==(IResearchLinkMeta const& meta) const noexcept; bool operator!=(IResearchLinkMeta const& meta) const noexcept { return !(*this == meta); } void afterTruncate(TRI_voc_tick_t tick, transaction::Methods* trx); // arangodb::Index override bool canBeDropped() const { // valid for a link to be dropped from an ArangoSearch view return true; }; ////////////////////////////////////////////////////////////////////////////// /// @return the associated collection /// @note arangodb::Index override ////////////////////////////////////////////////////////////////////////////// LogicalCollection& collection() const noexcept { return _collection; } ////////////////////////////////////////////////////////////////////////////// /// @brief mark the current data store state as the latest valid state /// @param wait even if other thread is committing ////////////////////////////////////////////////////////////////////////////// Result commit(bool wait = true); //////////////////////////////////////////////////////////////////////////////// /// @brief called when the iResearch Link is dropped /// @note arangodb::Index override //////////////////////////////////////////////////////////////////////////////// Result drop(); bool hasSelectivityEstimate() const; // arangodb::Index override ////////////////////////////////////////////////////////////////////////////// /// @brief the identifier for this link ////////////////////////////////////////////////////////////////////////////// IndexId id() const noexcept { return _id; } //////////////////////////////////////////////////////////////////////////////// /// @brief insert an ArangoDB document into an iResearch View using '_meta' params /// @note arangodb::Index override //////////////////////////////////////////////////////////////////////////////// Result insert(transaction::Methods& trx, LocalDocumentId const& documentId, velocypack::Slice const doc); bool isHidden() const; // arangodb::Index override bool isSorted() const; // arangodb::Index override //////////////////////////////////////////////////////////////////////////////// /// @brief called when the iResearch Link is loaded into memory /// @note arangodb::Index override //////////////////////////////////////////////////////////////////////////////// void load(); //////////////////////////////////////////////////////////////////////////////// /// @brief index comparator, used by the coordinator to detect if the specified /// definition is the same as this link /// @note arangodb::Index override //////////////////////////////////////////////////////////////////////////////// bool matchesDefinition(velocypack::Slice const& slice) const; //////////////////////////////////////////////////////////////////////////////// /// @brief amount of memory in bytes occupied by this iResearch Link /// @note arangodb::Index override //////////////////////////////////////////////////////////////////////////////// void toVelocyPackStats(VPackBuilder& builder) const; ////////////////////////////////////////////////////////////////////////////// /// @brief fill and return a jSON description of a IResearchLink object /// elements are appended to an existing object ////////////////////////////////////////////////////////////////////////////// Result properties(velocypack::Builder& builder, bool forPersistence) const; ////////////////////////////////////////////////////////////////////////////// /// @brief update runtine data processing properties (not persisted) /// @return success ////////////////////////////////////////////////////////////////////////////// Result properties(IResearchViewMeta const& meta); //////////////////////////////////////////////////////////////////////////////// /// @brief remove an ArangoDB document from an iResearch View /// @note arangodb::Index override //////////////////////////////////////////////////////////////////////////////// Result remove(transaction::Methods& trx, LocalDocumentId const& documentId, velocypack::Slice const doc); /////////////////////////////////////////////////////////////////////////////// /// @brief 'this' for the lifetime of the link data-store /// for use with asynchronous calls, e.g. callbacks, view /////////////////////////////////////////////////////////////////////////////// AsyncLinkPtr self() const { return _asyncSelf; } ////////////////////////////////////////////////////////////////////////////// /// @return pointer to an index reader containing the data store current /// record snapshot /// (nullptr == no data store snapshot availabe, e.g. error) ////////////////////////////////////////////////////////////////////////////// Snapshot snapshot() const; //////////////////////////////////////////////////////////////////////////////// /// @brief ArangoSearch Link index type enum value /// @note arangodb::Index override //////////////////////////////////////////////////////////////////////////////// Index::IndexType type() const; //////////////////////////////////////////////////////////////////////////////// /// @brief ArangoSearch Link index type string value /// @note arangodb::Index override //////////////////////////////////////////////////////////////////////////////// char const* typeName() const; //////////////////////////////////////////////////////////////////////////////// /// @brief called when the iResearch Link is unloaded from memory /// @note arangodb::Index override //////////////////////////////////////////////////////////////////////////////// Result unload(); //////////////////////////////////////////////////////////////////////////////// /// @brief lookup referenced analyzer //////////////////////////////////////////////////////////////////////////////// AnalyzerPool::ptr findAnalyzer(AnalyzerPool const& analyzer) const; //////////////////////////////////////////////////////////////////////////////// /// @brief initialize from the specified definition used in make(...) /// @return success //////////////////////////////////////////////////////////////////////////////// Result init(velocypack::Slice const& definition, InitCallback const& initCallback = {}); //////////////////////////////////////////////////////////////////////////////// /// @return arangosearch internal format identifier //////////////////////////////////////////////////////////////////////////////// std::string_view format() const noexcept; //////////////////////////////////////////////////////////////////////////////// /// @brief get stored values //////////////////////////////////////////////////////////////////////////////// IResearchViewStoredValues const& storedValues() const noexcept; /// @brief sets the _collectionName in Link meta. Used in cluster only to store /// linked collection name (as shard name differs from the cluster-wide collection name) /// @param name collectioName to set. Should match existing value of the _collectionName /// if it is not empty. /// @return true if name not existed in link before and was actually set by this call, /// false otherwise bool setCollectionName(irs::string_ref name) noexcept; protected: ////////////////////////////////////////////////////////////////////////////// /// @brief index stats ////////////////////////////////////////////////////////////////////////////// struct Stats { size_t docsCount{}; // total number of documents size_t liveDocsCount{}; // number of live documents size_t numBufferedDocs{}; // number of buffered docs size_t indexSize{}; // size of the index in bytes size_t numSegments{}; // number of segments size_t numFiles{}; // number of files }; protected: //////////////////////////////////////////////////////////////////////////////// /// @brief construct an uninitialized IResearch link, must call init(...) /// after //////////////////////////////////////////////////////////////////////////////// IResearchLink(IndexId iid, LogicalCollection& collection); //////////////////////////////////////////////////////////////////////////////// /// @brief link was created during recovery //////////////////////////////////////////////////////////////////////////////// bool createdInRecovery() const noexcept { return _createdInRecovery; } //////////////////////////////////////////////////////////////////////////////// /// @brief get index stats for current snapshot //////////////////////////////////////////////////////////////////////////////// Stats stats() const; private: friend struct CommitTask; friend struct ConsolidationTask; ////////////////////////////////////////////////////////////////////////////// /// @brief detailed commit result ////////////////////////////////////////////////////////////////////////////// enum class CommitResult { //////////////////////////////////////////////////////////////////////////// /// @brief undefined state //////////////////////////////////////////////////////////////////////////// UNDEFINED = 0, //////////////////////////////////////////////////////////////////////////// /// @brief no changes were made //////////////////////////////////////////////////////////////////////////// NO_CHANGES, //////////////////////////////////////////////////////////////////////////// /// @brief another commit is in progress //////////////////////////////////////////////////////////////////////////// IN_PROGRESS, //////////////////////////////////////////////////////////////////////////// /// @brief commit is done //////////////////////////////////////////////////////////////////////////// DONE }; // CommitResult ////////////////////////////////////////////////////////////////////////////// /// @brief the underlying iresearch data store ////////////////////////////////////////////////////////////////////////////// struct DataStore { IResearchViewMeta _meta; // runtime meta for a data store (not persisted) irs::directory::ptr _directory; basics::ReadWriteLock _mutex; // for use with member '_meta' irs::utf8_path _path; irs::directory_reader _reader; irs::index_writer::ptr _writer; TRI_voc_tick_t _recoveryTick{ 0 }; // the tick at which data store was recovered std::atomic<bool> _inRecovery{ false }; // data store is in recovery operator bool() const noexcept { return _directory && _writer; } void resetDataStore() noexcept { // reset all underlying readers to release file handles _reader.reset(); _writer.reset(); _directory.reset(); } }; ////////////////////////////////////////////////////////////////////////////// /// @brief run filesystem cleanup on the data store /// @note assumes that '_asyncSelf' is read-locked (for use with async tasks) ////////////////////////////////////////////////////////////////////////////// Result cleanupUnsafe(); ////////////////////////////////////////////////////////////////////////////// /// @brief mark the current data store state as the latest valid state /// @param wait even if other thread is committing /// @note assumes that '_asyncSelf' is read-locked (for use with async tasks) ////////////////////////////////////////////////////////////////////////////// Result commitUnsafe(bool wait, CommitResult* code); ////////////////////////////////////////////////////////////////////////////// /// @brief run segment consolidation on the data store /// @note assumes that '_asyncSelf' is read-locked (for use with async tasks) ////////////////////////////////////////////////////////////////////////////// Result consolidateUnsafe( IResearchViewMeta::ConsolidationPolicy const& policy, irs::merge_writer::flush_progress_t const& progress, bool& emptyConsolidation); ////////////////////////////////////////////////////////////////////////////// /// @brief initialize the data store with a new or from an existing directory ////////////////////////////////////////////////////////////////////////////// Result initDataStore( InitCallback const& initCallback, uint32_t version, bool sorted, std::vector<IResearchViewStoredValues::StoredColumn> const& storedColumns, irs::type_info::type_id primarySortCompression); ////////////////////////////////////////////////////////////////////////////// /// @brief schedule a commit job ////////////////////////////////////////////////////////////////////////////// void scheduleCommit(std::chrono::milliseconds delay); ////////////////////////////////////////////////////////////////////////////// /// @brief schedule a consolidation job ////////////////////////////////////////////////////////////////////////////// void scheduleConsolidation(std::chrono::milliseconds delay); StorageEngine* _engine; VPackComparer _comparer; IResearchFeature* _asyncFeature; // the feature where async jobs were registered (nullptr == no jobs registered) AsyncLinkPtr _asyncSelf; // 'this' for the lifetime of the link (for use with asynchronous calls) LogicalCollection& _collection; // the linked collection DataStore _dataStore; // the iresearch data store, protected by _asyncSelf->mutex() std::shared_ptr<FlushSubscription> _flushSubscription; std::shared_ptr<MaintenanceState> _maintenanceState; IndexId const _id; // the index identifier TRI_voc_tick_t _lastCommittedTick; // protected by _commitMutex IResearchLinkMeta const _meta; // how this collection should be indexed (read-only, set via init()) std::mutex _commitMutex; // prevents data store sequential commits std::function<void(transaction::Methods& trx, transaction::Status status)> _trxCallback; // for insert(...)/remove(...) std::string const _viewGuid; // the identifier of the desired view (read-only, set via init()) bool _createdInRecovery; // link was created based on recovery marker }; // IResearchLink irs::utf8_path getPersistedPath(DatabasePathFeature const& dbPathFeature, iresearch::IResearchLink const& link); } // namespace iresearch } // namespace arangodb
{ "content_hash": "ced0d0f4257befd28a1aa33f9d3cd3ee", "timestamp": "", "source": "github", "line_count": 389, "max_line_length": 121, "avg_line_length": 46.12596401028278, "alnum_prop": 0.43693919634397815, "repo_name": "graetzer/arangodb", "id": "aec5870547999ff7f8dbbdce5b8675c6a69c91a3", "size": "19388", "binary": false, "copies": "1", "ref": "refs/heads/devel", "path": "arangod/IResearch/IResearchLink.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "89079" }, { "name": "Assembly", "bytes": "391227" }, { "name": "Awk", "bytes": "4272" }, { "name": "Batchfile", "bytes": "63025" }, { "name": "C", "bytes": "7952921" }, { "name": "C#", "bytes": "96431" }, { "name": "C++", "bytes": "274543069" }, { "name": "CMake", "bytes": "646773" }, { "name": "CSS", "bytes": "1054160" }, { "name": "Cuda", "bytes": "52444" }, { "name": "DIGITAL Command Language", "bytes": "259402" }, { "name": "Emacs Lisp", "bytes": "14637" }, { "name": "Fortran", "bytes": "1856" }, { "name": "Groovy", "bytes": "131" }, { "name": "HTML", "bytes": "2215528" }, { "name": "Java", "bytes": "922156" }, { "name": "JavaScript", "bytes": "53300241" }, { "name": "LLVM", "bytes": "24129" }, { "name": "Lex", "bytes": "1231" }, { "name": "Lua", "bytes": "17899" }, { "name": "M4", "bytes": "575204" }, { "name": "Makefile", "bytes": "492694" }, { "name": "Max", "bytes": "36857" }, { "name": "Module Management System", "bytes": "1545" }, { "name": "NSIS", "bytes": "28404" }, { "name": "Objective-C", "bytes": "18435" }, { "name": "Objective-C++", "bytes": "2503" }, { "name": "PHP", "bytes": "107274" }, { "name": "Pascal", "bytes": "150599" }, { "name": "Perl", "bytes": "564374" }, { "name": "Perl6", "bytes": "9918" }, { "name": "Python", "bytes": "4527647" }, { "name": "QMake", "bytes": "16692" }, { "name": "R", "bytes": "5123" }, { "name": "Rebol", "bytes": "354" }, { "name": "Roff", "bytes": "1007604" }, { "name": "Ruby", "bytes": "929950" }, { "name": "SAS", "bytes": "1847" }, { "name": "Scheme", "bytes": "10604" }, { "name": "Shell", "bytes": "424800" }, { "name": "Swift", "bytes": "116" }, { "name": "Tcl", "bytes": "1172" }, { "name": "TeX", "bytes": "32117" }, { "name": "Visual Basic", "bytes": "11568" }, { "name": "XSLT", "bytes": "551977" }, { "name": "Yacc", "bytes": "53072" } ], "symlink_target": "" }
'use strict'; angular.module("DivinElegy.pages.index", []) .controller("IndexController", ['$scope', function($scope) { $scope.simpleVariable = 'hello'; }]);
{ "content_hash": "a50c3f802e5cb2d616011d49b0300d45", "timestamp": "", "source": "github", "line_count": 8, "max_line_length": 58, "avg_line_length": 20.375, "alnum_prop": 0.6687116564417178, "repo_name": "DivinElegy/roll.divinelegy", "id": "97f6cda90b469f971589e801eb903014dbe55a6d", "size": "163", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/pages/index/index.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "25676" }, { "name": "HTML", "bytes": "40421" }, { "name": "JavaScript", "bytes": "60178" } ], "symlink_target": "" }
<?php /** */ class PluginDmLockTable extends myDoctrineTable { /** * @return array usernames of current active users on the same page */ public function getLocks(array $data) { $locks = dmDb::pdo( sprintf( 'SELECT DISTINCT a.user_name FROM %s a WHERE a.user_id != ? AND a.module = ? AND a.action = ? AND a.record_id = ? AND a.time > ? ORDER BY a.user_name ASC', $this->getTableName() ), array($data['user_id'], $data['module'], $data['action'], $data['record_id'], $_SERVER['REQUEST_TIME'] - sfConfig::get('dm_locks_timeout', 10)) )->fetchAll(PDO::FETCH_NUM); return $this->toUsernames($locks); } /** * @return array usernames of current active users */ public function getUserNames() { $locks = dmDb::pdo( sprintf('SELECT DISTINCT a.user_name FROM %s a WHERE a.time > ? ORDER BY a.user_name ASC', $this->getTableName()), array($_SERVER['REQUEST_TIME'] - sfConfig::get('dm_locks_timeout', 10)) )->fetchAll(PDO::FETCH_NUM); return $this->toUsernames($locks); } protected function toUsernames(array $locks) { $usernames = array(); foreach($locks as $lock) { $usernames[] = $lock[0]; } return $usernames; } /** * When a user displays a page */ public function update(array $data) { $lock = $this->findOneByData($data); if(!$lock) { $lock = $this->create($data)->saveGet(); } else { $lock->merge($data)->save(); } $this->removeOldLocks(); } /** * When receiving an ajax ping */ public function ping(array $data) { $lock = $this->findOneByData($data); if($lock = $this->findOneByData($data)) { $lock->merge($data)->save(); } $this->removeOldLocks(); } public function removeOldLocks() { dmDb::pdo( sprintf('DELETE FROM %s WHERE time < ?', $this->getTableName()), array($_SERVER['REQUEST_TIME'] - 10*sfConfig::get('dm_locks_timeout', 10)) ); } public function findOneByData(array $data) { return $this->createQuery('a') ->where('a.user_id = ?', $data['user_id']) ->andWhere('a.module = ?', $data['module']) ->andWhere('a.action = ?', $data['action']) ->andWhere('a.record_id = ?', $data['record_id']) ->fetchRecord(); } }
{ "content_hash": "7e37829d2a9a02a55dbce83e9a07d0bb", "timestamp": "", "source": "github", "line_count": 98, "max_line_length": 163, "avg_line_length": 23.612244897959183, "alnum_prop": 0.5773552290406223, "repo_name": "carechimba/diem", "id": "aef1f33428db28a063097d168533b7d29974d9b3", "size": "2314", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "dmCorePlugin/lib/model/doctrine/PluginDmLockTable.class.php", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "1447883" }, { "name": "PHP", "bytes": "6562230" }, { "name": "Shell", "bytes": "5570" } ], "symlink_target": "" }
# -*- coding: utf-8 -*- import base64 import json import os import os.path import shutil import sys import tarfile import tempfile import pytest import six try: from ssl import OP_NO_SSLv3, OP_NO_SSLv2, OP_NO_TLSv1 except ImportError: OP_NO_SSLv2 = 0x1000000 OP_NO_SSLv3 = 0x2000000 OP_NO_TLSv1 = 0x4000000 from docker.client import Client from docker.constants import DEFAULT_DOCKER_API_VERSION from docker.errors import DockerException, InvalidVersion from docker.ssladapter import ssladapter from docker.utils import ( parse_repository_tag, parse_host, convert_filters, kwargs_from_env, create_host_config, Ulimit, LogConfig, parse_bytes, parse_env_file, exclude_paths, convert_volume_binds, decode_json_header, tar, split_command, create_ipam_config, create_ipam_pool, parse_devices, ) from docker.utils.utils import create_endpoint_config from docker.utils.ports import build_port_bindings, split_port from .. import base from ..helpers import make_tree TEST_CERT_DIR = os.path.join( os.path.dirname(__file__), 'testdata/certs', ) class HostConfigTest(base.BaseTestCase): def test_create_host_config_no_options(self): config = create_host_config(version='1.19') self.assertFalse('NetworkMode' in config) def test_create_host_config_no_options_newer_api_version(self): config = create_host_config(version='1.20') self.assertEqual(config['NetworkMode'], 'default') def test_create_host_config_invalid_cpu_cfs_types(self): with pytest.raises(TypeError): create_host_config(version='1.20', cpu_quota='0') with pytest.raises(TypeError): create_host_config(version='1.20', cpu_period='0') with pytest.raises(TypeError): create_host_config(version='1.20', cpu_quota=23.11) with pytest.raises(TypeError): create_host_config(version='1.20', cpu_period=1999.0) def test_create_host_config_with_cpu_quota(self): config = create_host_config(version='1.20', cpu_quota=1999) self.assertEqual(config.get('CpuQuota'), 1999) def test_create_host_config_with_cpu_period(self): config = create_host_config(version='1.20', cpu_period=1999) self.assertEqual(config.get('CpuPeriod'), 1999) def test_create_host_config_with_shm_size(self): config = create_host_config(version='1.22', shm_size=67108864) self.assertEqual(config.get('ShmSize'), 67108864) def test_create_host_config_with_shm_size_in_mb(self): config = create_host_config(version='1.22', shm_size='64M') self.assertEqual(config.get('ShmSize'), 67108864) def test_create_host_config_with_oom_kill_disable(self): config = create_host_config(version='1.20', oom_kill_disable=True) self.assertEqual(config.get('OomKillDisable'), True) self.assertRaises( InvalidVersion, lambda: create_host_config(version='1.18.3', oom_kill_disable=True)) def test_create_endpoint_config_with_aliases(self): config = create_endpoint_config(version='1.22', aliases=['foo', 'bar']) assert config == {'Aliases': ['foo', 'bar']} with pytest.raises(InvalidVersion): create_endpoint_config(version='1.21', aliases=['foo', 'bar']) class UlimitTest(base.BaseTestCase): def test_create_host_config_dict_ulimit(self): ulimit_dct = {'name': 'nofile', 'soft': 8096} config = create_host_config( ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION ) self.assertIn('Ulimits', config) self.assertEqual(len(config['Ulimits']), 1) ulimit_obj = config['Ulimits'][0] self.assertTrue(isinstance(ulimit_obj, Ulimit)) self.assertEqual(ulimit_obj.name, ulimit_dct['name']) self.assertEqual(ulimit_obj.soft, ulimit_dct['soft']) self.assertEqual(ulimit_obj['Soft'], ulimit_obj.soft) def test_create_host_config_dict_ulimit_capitals(self): ulimit_dct = {'Name': 'nofile', 'Soft': 8096, 'Hard': 8096 * 4} config = create_host_config( ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION ) self.assertIn('Ulimits', config) self.assertEqual(len(config['Ulimits']), 1) ulimit_obj = config['Ulimits'][0] self.assertTrue(isinstance(ulimit_obj, Ulimit)) self.assertEqual(ulimit_obj.name, ulimit_dct['Name']) self.assertEqual(ulimit_obj.soft, ulimit_dct['Soft']) self.assertEqual(ulimit_obj.hard, ulimit_dct['Hard']) self.assertEqual(ulimit_obj['Soft'], ulimit_obj.soft) def test_create_host_config_obj_ulimit(self): ulimit_dct = Ulimit(name='nofile', soft=8096) config = create_host_config( ulimits=[ulimit_dct], version=DEFAULT_DOCKER_API_VERSION ) self.assertIn('Ulimits', config) self.assertEqual(len(config['Ulimits']), 1) ulimit_obj = config['Ulimits'][0] self.assertTrue(isinstance(ulimit_obj, Ulimit)) self.assertEqual(ulimit_obj, ulimit_dct) def test_ulimit_invalid_type(self): self.assertRaises(ValueError, lambda: Ulimit(name=None)) self.assertRaises(ValueError, lambda: Ulimit(name='hello', soft='123')) self.assertRaises(ValueError, lambda: Ulimit(name='hello', hard='456')) class LogConfigTest(base.BaseTestCase): def test_create_host_config_dict_logconfig(self): dct = {'type': LogConfig.types.SYSLOG, 'config': {'key1': 'val1'}} config = create_host_config( version=DEFAULT_DOCKER_API_VERSION, log_config=dct ) self.assertIn('LogConfig', config) self.assertTrue(isinstance(config['LogConfig'], LogConfig)) self.assertEqual(dct['type'], config['LogConfig'].type) def test_create_host_config_obj_logconfig(self): obj = LogConfig(type=LogConfig.types.SYSLOG, config={'key1': 'val1'}) config = create_host_config( version=DEFAULT_DOCKER_API_VERSION, log_config=obj ) self.assertIn('LogConfig', config) self.assertTrue(isinstance(config['LogConfig'], LogConfig)) self.assertEqual(obj, config['LogConfig']) def test_logconfig_invalid_config_type(self): with pytest.raises(ValueError): LogConfig(type=LogConfig.types.JSON, config='helloworld') class KwargsFromEnvTest(base.BaseTestCase): def setUp(self): self.os_environ = os.environ.copy() def tearDown(self): os.environ = self.os_environ def test_kwargs_from_env_empty(self): os.environ.update(DOCKER_HOST='', DOCKER_CERT_PATH='') os.environ.pop('DOCKER_TLS_VERIFY', None) kwargs = kwargs_from_env() self.assertEqual(None, kwargs.get('base_url')) self.assertEqual(None, kwargs.get('tls')) def test_kwargs_from_env_tls(self): os.environ.update(DOCKER_HOST='tcp://192.168.59.103:2376', DOCKER_CERT_PATH=TEST_CERT_DIR, DOCKER_TLS_VERIFY='1') kwargs = kwargs_from_env(assert_hostname=False) self.assertEqual('https://192.168.59.103:2376', kwargs['base_url']) self.assertTrue('ca.pem' in kwargs['tls'].ca_cert) self.assertTrue('cert.pem' in kwargs['tls'].cert[0]) self.assertTrue('key.pem' in kwargs['tls'].cert[1]) self.assertEqual(False, kwargs['tls'].assert_hostname) self.assertTrue(kwargs['tls'].verify) try: client = Client(**kwargs) self.assertEqual(kwargs['base_url'], client.base_url) self.assertEqual(kwargs['tls'].ca_cert, client.verify) self.assertEqual(kwargs['tls'].cert, client.cert) except TypeError as e: self.fail(e) def test_kwargs_from_env_tls_verify_false(self): os.environ.update(DOCKER_HOST='tcp://192.168.59.103:2376', DOCKER_CERT_PATH=TEST_CERT_DIR, DOCKER_TLS_VERIFY='') kwargs = kwargs_from_env(assert_hostname=True) self.assertEqual('https://192.168.59.103:2376', kwargs['base_url']) self.assertTrue('ca.pem' in kwargs['tls'].ca_cert) self.assertTrue('cert.pem' in kwargs['tls'].cert[0]) self.assertTrue('key.pem' in kwargs['tls'].cert[1]) self.assertEqual(True, kwargs['tls'].assert_hostname) self.assertEqual(False, kwargs['tls'].verify) try: client = Client(**kwargs) self.assertEqual(kwargs['base_url'], client.base_url) self.assertEqual(kwargs['tls'].cert, client.cert) self.assertFalse(kwargs['tls'].verify) except TypeError as e: self.fail(e) def test_kwargs_from_env_tls_verify_false_no_cert(self): temp_dir = tempfile.mkdtemp() cert_dir = os.path.join(temp_dir, '.docker') shutil.copytree(TEST_CERT_DIR, cert_dir) os.environ.update(DOCKER_HOST='tcp://192.168.59.103:2376', HOME=temp_dir, DOCKER_TLS_VERIFY='') os.environ.pop('DOCKER_CERT_PATH', None) kwargs = kwargs_from_env(assert_hostname=True) self.assertEqual('https://192.168.59.103:2376', kwargs['base_url']) self.assertTrue('ca.pem' in kwargs['tls'].ca_cert) self.assertTrue('cert.pem' in kwargs['tls'].cert[0]) self.assertTrue('key.pem' in kwargs['tls'].cert[1]) self.assertEqual(True, kwargs['tls'].assert_hostname) self.assertEqual(False, kwargs['tls'].verify) try: client = Client(**kwargs) self.assertEqual(kwargs['base_url'], client.base_url) self.assertEqual(kwargs['tls'].cert, client.cert) self.assertFalse(kwargs['tls'].verify) except TypeError as e: self.fail(e) def test_kwargs_from_env_no_cert_path(self): try: temp_dir = tempfile.mkdtemp() cert_dir = os.path.join(temp_dir, '.docker') shutil.copytree(TEST_CERT_DIR, cert_dir) os.environ.update(HOME=temp_dir, DOCKER_CERT_PATH='', DOCKER_TLS_VERIFY='1') kwargs = kwargs_from_env() self.assertTrue(kwargs['tls'].verify) self.assertIn(cert_dir, kwargs['tls'].ca_cert) self.assertIn(cert_dir, kwargs['tls'].cert[0]) self.assertIn(cert_dir, kwargs['tls'].cert[1]) finally: if temp_dir: shutil.rmtree(temp_dir) class ConverVolumeBindsTest(base.BaseTestCase): def test_convert_volume_binds_empty(self): self.assertEqual(convert_volume_binds({}), []) self.assertEqual(convert_volume_binds([]), []) def test_convert_volume_binds_list(self): data = ['/a:/a:ro', '/b:/c:z'] self.assertEqual(convert_volume_binds(data), data) def test_convert_volume_binds_complete(self): data = { '/mnt/vol1': { 'bind': '/data', 'mode': 'ro' } } self.assertEqual(convert_volume_binds(data), ['/mnt/vol1:/data:ro']) def test_convert_volume_binds_compact(self): data = { '/mnt/vol1': '/data' } self.assertEqual(convert_volume_binds(data), ['/mnt/vol1:/data:rw']) def test_convert_volume_binds_no_mode(self): data = { '/mnt/vol1': { 'bind': '/data' } } self.assertEqual(convert_volume_binds(data), ['/mnt/vol1:/data:rw']) def test_convert_volume_binds_unicode_bytes_input(self): if six.PY2: expected = [unicode('/mnt/지연:/unicode/박:rw', 'utf-8')] data = { '/mnt/지연': { 'bind': '/unicode/박', 'mode': 'rw' } } self.assertEqual( convert_volume_binds(data), expected ) else: expected = ['/mnt/지연:/unicode/박:rw'] data = { bytes('/mnt/지연', 'utf-8'): { 'bind': bytes('/unicode/박', 'utf-8'), 'mode': 'rw' } } self.assertEqual( convert_volume_binds(data), expected ) def test_convert_volume_binds_unicode_unicode_input(self): if six.PY2: expected = [unicode('/mnt/지연:/unicode/박:rw', 'utf-8')] data = { unicode('/mnt/지연', 'utf-8'): { 'bind': unicode('/unicode/박', 'utf-8'), 'mode': 'rw' } } self.assertEqual( convert_volume_binds(data), expected ) else: expected = ['/mnt/지연:/unicode/박:rw'] data = { '/mnt/지연': { 'bind': '/unicode/박', 'mode': 'rw' } } self.assertEqual( convert_volume_binds(data), expected ) class ParseEnvFileTest(base.BaseTestCase): def generate_tempfile(self, file_content=None): """ Generates a temporary file for tests with the content of 'file_content' and returns the filename. Don't forget to unlink the file with os.unlink() after. """ local_tempfile = tempfile.NamedTemporaryFile(delete=False) local_tempfile.write(file_content.encode('UTF-8')) local_tempfile.close() return local_tempfile.name def test_parse_env_file_proper(self): env_file = self.generate_tempfile( file_content='USER=jdoe\nPASS=secret') get_parse_env_file = parse_env_file(env_file) self.assertEqual(get_parse_env_file, {'USER': 'jdoe', 'PASS': 'secret'}) os.unlink(env_file) def test_parse_env_file_commented_line(self): env_file = self.generate_tempfile( file_content='USER=jdoe\n#PASS=secret') get_parse_env_file = parse_env_file((env_file)) self.assertEqual(get_parse_env_file, {'USER': 'jdoe'}) os.unlink(env_file) def test_parse_env_file_invalid_line(self): env_file = self.generate_tempfile( file_content='USER jdoe') self.assertRaises( DockerException, parse_env_file, env_file) os.unlink(env_file) class ParseHostTest(base.BaseTestCase): def test_parse_host(self): invalid_hosts = [ '0.0.0.0', 'tcp://', 'udp://127.0.0.1', 'udp://127.0.0.1:2375', ] valid_hosts = { '0.0.0.1:5555': 'http://0.0.0.1:5555', ':6666': 'http://127.0.0.1:6666', 'tcp://:7777': 'http://127.0.0.1:7777', 'http://:7777': 'http://127.0.0.1:7777', 'https://kokia.jp:2375': 'https://kokia.jp:2375', 'unix:///var/run/docker.sock': 'http+unix:///var/run/docker.sock', 'unix://': 'http+unix://var/run/docker.sock', 'somehost.net:80/service/swarm': ( 'http://somehost.net:80/service/swarm' ), } for host in invalid_hosts: with pytest.raises(DockerException): parse_host(host, None) for host, expected in valid_hosts.items(): self.assertEqual(parse_host(host, None), expected, msg=host) def test_parse_host_empty_value(self): unix_socket = 'http+unix://var/run/docker.sock' tcp_port = 'http://127.0.0.1:2375' for val in [None, '']: for platform in ['darwin', 'linux2', None]: assert parse_host(val, platform) == unix_socket assert parse_host(val, 'win32') == tcp_port def test_parse_host_tls(self): host_value = 'myhost.docker.net:3348' expected_result = 'https://myhost.docker.net:3348' self.assertEqual(parse_host(host_value, None, True), expected_result) class ParseRepositoryTagTest(base.BaseTestCase): sha = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' def test_index_image_no_tag(self): self.assertEqual( parse_repository_tag("root"), ("root", None) ) def test_index_image_tag(self): self.assertEqual( parse_repository_tag("root:tag"), ("root", "tag") ) def test_index_user_image_no_tag(self): self.assertEqual( parse_repository_tag("user/repo"), ("user/repo", None) ) def test_index_user_image_tag(self): self.assertEqual( parse_repository_tag("user/repo:tag"), ("user/repo", "tag") ) def test_private_reg_image_no_tag(self): self.assertEqual( parse_repository_tag("url:5000/repo"), ("url:5000/repo", None) ) def test_private_reg_image_tag(self): self.assertEqual( parse_repository_tag("url:5000/repo:tag"), ("url:5000/repo", "tag") ) def test_index_image_sha(self): self.assertEqual( parse_repository_tag("root@sha256:{0}".format(self.sha)), ("root", "sha256:{0}".format(self.sha)) ) def test_private_reg_image_sha(self): self.assertEqual( parse_repository_tag("url:5000/repo@sha256:{0}".format(self.sha)), ("url:5000/repo", "sha256:{0}".format(self.sha)) ) class ParseDeviceTest(base.BaseTestCase): def test_dict(self): devices = parse_devices([{ 'PathOnHost': '/dev/sda1', 'PathInContainer': '/dev/mnt1', 'CgroupPermissions': 'r' }]) self.assertEqual(devices[0], { 'PathOnHost': '/dev/sda1', 'PathInContainer': '/dev/mnt1', 'CgroupPermissions': 'r' }) def test_partial_string_definition(self): devices = parse_devices(['/dev/sda1']) self.assertEqual(devices[0], { 'PathOnHost': '/dev/sda1', 'PathInContainer': '/dev/sda1', 'CgroupPermissions': 'rwm' }) def test_permissionless_string_definition(self): devices = parse_devices(['/dev/sda1:/dev/mnt1']) self.assertEqual(devices[0], { 'PathOnHost': '/dev/sda1', 'PathInContainer': '/dev/mnt1', 'CgroupPermissions': 'rwm' }) def test_full_string_definition(self): devices = parse_devices(['/dev/sda1:/dev/mnt1:r']) self.assertEqual(devices[0], { 'PathOnHost': '/dev/sda1', 'PathInContainer': '/dev/mnt1', 'CgroupPermissions': 'r' }) def test_hybrid_list(self): devices = parse_devices([ '/dev/sda1:/dev/mnt1:rw', { 'PathOnHost': '/dev/sda2', 'PathInContainer': '/dev/mnt2', 'CgroupPermissions': 'r' } ]) self.assertEqual(devices[0], { 'PathOnHost': '/dev/sda1', 'PathInContainer': '/dev/mnt1', 'CgroupPermissions': 'rw' }) self.assertEqual(devices[1], { 'PathOnHost': '/dev/sda2', 'PathInContainer': '/dev/mnt2', 'CgroupPermissions': 'r' }) class ParseBytesTest(base.BaseTestCase): def test_parse_bytes_valid(self): self.assertEqual(parse_bytes("512MB"), 536870912) self.assertEqual(parse_bytes("512M"), 536870912) self.assertEqual(parse_bytes("512m"), 536870912) def test_parse_bytes_invalid(self): self.assertRaises(DockerException, parse_bytes, "512MK") self.assertRaises(DockerException, parse_bytes, "512L") self.assertRaises(DockerException, parse_bytes, "127.0.0.1K") def test_parse_bytes_float(self): self.assertRaises(DockerException, parse_bytes, "1.5k") def test_parse_bytes_maxint(self): self.assertEqual( parse_bytes("{0}k".format(sys.maxsize)), sys.maxsize * 1024 ) class UtilsTest(base.BaseTestCase): longMessage = True def test_convert_filters(self): tests = [ ({'dangling': True}, '{"dangling": ["true"]}'), ({'dangling': "true"}, '{"dangling": ["true"]}'), ({'exited': 0}, '{"exited": [0]}'), ({'exited': [0, 1]}, '{"exited": [0, 1]}'), ] for filters, expected in tests: self.assertEqual(convert_filters(filters), expected) def test_decode_json_header(self): obj = {'a': 'b', 'c': 1} data = None if six.PY3: data = base64.urlsafe_b64encode(bytes(json.dumps(obj), 'utf-8')) else: data = base64.urlsafe_b64encode(json.dumps(obj)) decoded_data = decode_json_header(data) self.assertEqual(obj, decoded_data) def test_create_ipam_config(self): ipam_pool = create_ipam_pool(subnet='192.168.52.0/24', gateway='192.168.52.254') ipam_config = create_ipam_config(pool_configs=[ipam_pool]) self.assertEqual(ipam_config, { 'Driver': 'default', 'Config': [{ 'Subnet': '192.168.52.0/24', 'Gateway': '192.168.52.254', 'AuxiliaryAddresses': None, 'IPRange': None, }] }) class SplitCommandTest(base.BaseTestCase): def test_split_command_with_unicode(self): if six.PY2: self.assertEqual( split_command(unicode('echo μμ', 'utf-8')), ['echo', 'μμ'] ) else: self.assertEqual(split_command('echo μμ'), ['echo', 'μμ']) @pytest.mark.skipif(six.PY3, reason="shlex doesn't support bytes in py3") def test_split_command_with_bytes(self): self.assertEqual(split_command('echo μμ'), ['echo', 'μμ']) class PortsTest(base.BaseTestCase): def test_split_port_with_host_ip(self): internal_port, external_port = split_port("127.0.0.1:1000:2000") self.assertEqual(internal_port, ["2000"]) self.assertEqual(external_port, [("127.0.0.1", "1000")]) def test_split_port_with_protocol(self): internal_port, external_port = split_port("127.0.0.1:1000:2000/udp") self.assertEqual(internal_port, ["2000/udp"]) self.assertEqual(external_port, [("127.0.0.1", "1000")]) def test_split_port_with_host_ip_no_port(self): internal_port, external_port = split_port("127.0.0.1::2000") self.assertEqual(internal_port, ["2000"]) self.assertEqual(external_port, [("127.0.0.1", None)]) def test_split_port_range_with_host_ip_no_port(self): internal_port, external_port = split_port("127.0.0.1::2000-2001") self.assertEqual(internal_port, ["2000", "2001"]) self.assertEqual(external_port, [("127.0.0.1", None), ("127.0.0.1", None)]) def test_split_port_with_host_port(self): internal_port, external_port = split_port("1000:2000") self.assertEqual(internal_port, ["2000"]) self.assertEqual(external_port, ["1000"]) def test_split_port_range_with_host_port(self): internal_port, external_port = split_port("1000-1001:2000-2001") self.assertEqual(internal_port, ["2000", "2001"]) self.assertEqual(external_port, ["1000", "1001"]) def test_split_port_no_host_port(self): internal_port, external_port = split_port("2000") self.assertEqual(internal_port, ["2000"]) self.assertEqual(external_port, None) def test_split_port_range_no_host_port(self): internal_port, external_port = split_port("2000-2001") self.assertEqual(internal_port, ["2000", "2001"]) self.assertEqual(external_port, None) def test_split_port_range_with_protocol(self): internal_port, external_port = split_port( "127.0.0.1:1000-1001:2000-2001/udp") self.assertEqual(internal_port, ["2000/udp", "2001/udp"]) self.assertEqual(external_port, [("127.0.0.1", "1000"), ("127.0.0.1", "1001")]) def test_split_port_invalid(self): self.assertRaises(ValueError, lambda: split_port("0.0.0.0:1000:2000:tcp")) def test_non_matching_length_port_ranges(self): self.assertRaises( ValueError, lambda: split_port("0.0.0.0:1000-1010:2000-2002/tcp") ) def test_port_and_range_invalid(self): self.assertRaises(ValueError, lambda: split_port("0.0.0.0:1000:2000-2002/tcp")) def test_port_only_with_colon(self): self.assertRaises(ValueError, lambda: split_port(":80")) def test_host_only_with_colon(self): self.assertRaises(ValueError, lambda: split_port("localhost:")) def test_build_port_bindings_with_one_port(self): port_bindings = build_port_bindings(["127.0.0.1:1000:1000"]) self.assertEqual(port_bindings["1000"], [("127.0.0.1", "1000")]) def test_build_port_bindings_with_matching_internal_ports(self): port_bindings = build_port_bindings( ["127.0.0.1:1000:1000", "127.0.0.1:2000:1000"]) self.assertEqual(port_bindings["1000"], [("127.0.0.1", "1000"), ("127.0.0.1", "2000")]) def test_build_port_bindings_with_nonmatching_internal_ports(self): port_bindings = build_port_bindings( ["127.0.0.1:1000:1000", "127.0.0.1:2000:2000"]) self.assertEqual(port_bindings["1000"], [("127.0.0.1", "1000")]) self.assertEqual(port_bindings["2000"], [("127.0.0.1", "2000")]) def test_build_port_bindings_with_port_range(self): port_bindings = build_port_bindings(["127.0.0.1:1000-1001:1000-1001"]) self.assertEqual(port_bindings["1000"], [("127.0.0.1", "1000")]) self.assertEqual(port_bindings["1001"], [("127.0.0.1", "1001")]) def test_build_port_bindings_with_matching_internal_port_ranges(self): port_bindings = build_port_bindings( ["127.0.0.1:1000-1001:1000-1001", "127.0.0.1:2000-2001:1000-1001"]) self.assertEqual(port_bindings["1000"], [("127.0.0.1", "1000"), ("127.0.0.1", "2000")]) self.assertEqual(port_bindings["1001"], [("127.0.0.1", "1001"), ("127.0.0.1", "2001")]) def test_build_port_bindings_with_nonmatching_internal_port_ranges(self): port_bindings = build_port_bindings( ["127.0.0.1:1000:1000", "127.0.0.1:2000:2000"]) self.assertEqual(port_bindings["1000"], [("127.0.0.1", "1000")]) self.assertEqual(port_bindings["2000"], [("127.0.0.1", "2000")]) class ExcludePathsTest(base.BaseTestCase): dirs = [ 'foo', 'foo/bar', 'bar', ] files = [ 'Dockerfile', 'Dockerfile.alt', '.dockerignore', 'a.py', 'a.go', 'b.py', 'cde.py', 'foo/a.py', 'foo/b.py', 'foo/bar/a.py', 'bar/a.py', 'foo/Dockerfile3', ] all_paths = set(dirs + files) def setUp(self): self.base = make_tree(self.dirs, self.files) def tearDown(self): shutil.rmtree(self.base) def exclude(self, patterns, dockerfile=None): return set(exclude_paths(self.base, patterns, dockerfile=dockerfile)) def test_no_excludes(self): assert self.exclude(['']) == self.all_paths def test_no_dupes(self): paths = exclude_paths(self.base, ['!a.py']) assert sorted(paths) == sorted(set(paths)) def test_wildcard_exclude(self): assert self.exclude(['*']) == set(['Dockerfile', '.dockerignore']) def test_exclude_dockerfile_dockerignore(self): """ Even if the .dockerignore file explicitly says to exclude Dockerfile and/or .dockerignore, don't exclude them from the actual tar file. """ assert self.exclude(['Dockerfile', '.dockerignore']) == self.all_paths def test_exclude_custom_dockerfile(self): """ If we're using a custom Dockerfile, make sure that's not excluded. """ assert self.exclude(['*'], dockerfile='Dockerfile.alt') == \ set(['Dockerfile.alt', '.dockerignore']) assert self.exclude(['*'], dockerfile='foo/Dockerfile3') == \ set(['foo/Dockerfile3', '.dockerignore']) def test_exclude_dockerfile_child(self): includes = self.exclude(['foo/'], dockerfile='foo/Dockerfile3') assert 'foo/Dockerfile3' in includes assert 'foo/a.py' not in includes def test_single_filename(self): assert self.exclude(['a.py']) == self.all_paths - set(['a.py']) # As odd as it sounds, a filename pattern with a trailing slash on the # end *will* result in that file being excluded. def test_single_filename_trailing_slash(self): assert self.exclude(['a.py/']) == self.all_paths - set(['a.py']) def test_wildcard_filename_start(self): assert self.exclude(['*.py']) == self.all_paths - set([ 'a.py', 'b.py', 'cde.py', ]) def test_wildcard_with_exception(self): assert self.exclude(['*.py', '!b.py']) == self.all_paths - set([ 'a.py', 'cde.py', ]) def test_wildcard_with_wildcard_exception(self): assert self.exclude(['*.*', '!*.go']) == self.all_paths - set([ 'a.py', 'b.py', 'cde.py', 'Dockerfile.alt', ]) def test_wildcard_filename_end(self): assert self.exclude(['a.*']) == self.all_paths - set(['a.py', 'a.go']) def test_question_mark(self): assert self.exclude(['?.py']) == self.all_paths - set(['a.py', 'b.py']) def test_single_subdir_single_filename(self): assert self.exclude(['foo/a.py']) == self.all_paths - set(['foo/a.py']) def test_single_subdir_wildcard_filename(self): assert self.exclude(['foo/*.py']) == self.all_paths - set([ 'foo/a.py', 'foo/b.py', ]) def test_wildcard_subdir_single_filename(self): assert self.exclude(['*/a.py']) == self.all_paths - set([ 'foo/a.py', 'bar/a.py', ]) def test_wildcard_subdir_wildcard_filename(self): assert self.exclude(['*/*.py']) == self.all_paths - set([ 'foo/a.py', 'foo/b.py', 'bar/a.py', ]) def test_directory(self): assert self.exclude(['foo']) == self.all_paths - set([ 'foo', 'foo/a.py', 'foo/b.py', 'foo/bar', 'foo/bar/a.py', 'foo/Dockerfile3' ]) def test_directory_with_trailing_slash(self): assert self.exclude(['foo']) == self.all_paths - set([ 'foo', 'foo/a.py', 'foo/b.py', 'foo/bar', 'foo/bar/a.py', 'foo/Dockerfile3' ]) def test_directory_with_single_exception(self): assert self.exclude(['foo', '!foo/bar/a.py']) == self.all_paths - set([ 'foo/a.py', 'foo/b.py', 'foo', 'foo/bar', 'foo/Dockerfile3' ]) def test_directory_with_subdir_exception(self): assert self.exclude(['foo', '!foo/bar']) == self.all_paths - set([ 'foo/a.py', 'foo/b.py', 'foo', 'foo/Dockerfile3' ]) def test_directory_with_wildcard_exception(self): assert self.exclude(['foo', '!foo/*.py']) == self.all_paths - set([ 'foo/bar', 'foo/bar/a.py', 'foo', 'foo/Dockerfile3' ]) def test_subdirectory(self): assert self.exclude(['foo/bar']) == self.all_paths - set([ 'foo/bar', 'foo/bar/a.py', ]) class TarTest(base.Cleanup, base.BaseTestCase): def test_tar_with_excludes(self): dirs = [ 'foo', 'foo/bar', 'bar', ] files = [ 'Dockerfile', 'Dockerfile.alt', '.dockerignore', 'a.py', 'a.go', 'b.py', 'cde.py', 'foo/a.py', 'foo/b.py', 'foo/bar/a.py', 'bar/a.py', ] exclude = [ '*.py', '!b.py', '!a.go', 'foo', 'Dockerfile*', '.dockerignore', ] expected_names = set([ 'Dockerfile', '.dockerignore', 'a.go', 'b.py', 'bar', 'bar/a.py', ]) base = make_tree(dirs, files) self.addCleanup(shutil.rmtree, base) with tar(base, exclude=exclude) as archive: tar_data = tarfile.open(fileobj=archive) assert sorted(tar_data.getnames()) == sorted(expected_names) def test_tar_with_empty_directory(self): base = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base) for d in ['foo', 'bar']: os.makedirs(os.path.join(base, d)) with tar(base) as archive: tar_data = tarfile.open(fileobj=archive) self.assertEqual(sorted(tar_data.getnames()), ['bar', 'foo']) def test_tar_with_file_symlinks(self): base = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base) with open(os.path.join(base, 'foo'), 'w') as f: f.write("content") os.makedirs(os.path.join(base, 'bar')) os.symlink('../foo', os.path.join(base, 'bar/foo')) with tar(base) as archive: tar_data = tarfile.open(fileobj=archive) self.assertEqual( sorted(tar_data.getnames()), ['bar', 'bar/foo', 'foo'] ) def test_tar_with_directory_symlinks(self): base = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, base) for d in ['foo', 'bar']: os.makedirs(os.path.join(base, d)) os.symlink('../foo', os.path.join(base, 'bar/foo')) with tar(base) as archive: tar_data = tarfile.open(fileobj=archive) self.assertEqual( sorted(tar_data.getnames()), ['bar', 'bar/foo', 'foo'] ) class SSLAdapterTest(base.BaseTestCase): def test_only_uses_tls(self): ssl_context = ssladapter.urllib3.util.ssl_.create_urllib3_context() assert ssl_context.options & OP_NO_SSLv3 assert ssl_context.options & OP_NO_SSLv2 assert not ssl_context.options & OP_NO_TLSv1
{ "content_hash": "a8d04d9f4001c1a7e5685db3daeb5e7e", "timestamp": "", "source": "github", "line_count": 956, "max_line_length": 79, "avg_line_length": 36.13284518828452, "alnum_prop": 0.5668876472802015, "repo_name": "mark-adams/docker-py", "id": "87796d11752aa87ed4de8b7629080ccffce8a6c0", "size": "34603", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tests/unit/utils_test.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Makefile", "bytes": "2227" }, { "name": "Python", "bytes": "353887" } ], "symlink_target": "" }
'use strict'; var scatterAttrs = require('../scatter/attributes'); var hovertemplateAttrs = require('../../plots/template_attributes').hovertemplateAttrs; var texttemplateAttrs = require('../../plots/template_attributes').texttemplateAttrs; var colorScaleAttrs = require('../../components/colorscale/attributes'); var fontAttrs = require('../../plots/font_attributes'); var constants = require('./constants'); var extendFlat = require('../../lib/extend').extendFlat; var textFontAttrs = fontAttrs({ editType: 'calc', arrayOk: true, colorEditType: 'style', description: '' }); var scatterMarkerAttrs = scatterAttrs.marker; var scatterMarkerLineAttrs = scatterMarkerAttrs.line; var markerLineWidth = extendFlat({}, scatterMarkerLineAttrs.width, { dflt: 0 }); var markerLine = extendFlat({ width: markerLineWidth, editType: 'calc' }, colorScaleAttrs('marker.line')); var marker = extendFlat({ line: markerLine, editType: 'calc' }, colorScaleAttrs('marker'), { opacity: { valType: 'number', arrayOk: true, dflt: 1, min: 0, max: 1, role: 'style', editType: 'style', description: 'Sets the opacity of the bars.' } }); module.exports = { x: scatterAttrs.x, x0: scatterAttrs.x0, dx: scatterAttrs.dx, y: scatterAttrs.y, y0: scatterAttrs.y0, dy: scatterAttrs.dy, xperiod: scatterAttrs.xperiod, yperiod: scatterAttrs.yperiod, xperiod0: scatterAttrs.xperiod0, yperiod0: scatterAttrs.yperiod0, xperiodalignment: scatterAttrs.xperiodalignment, yperiodalignment: scatterAttrs.yperiodalignment, text: scatterAttrs.text, texttemplate: texttemplateAttrs({editType: 'plot'}, { keys: constants.eventDataKeys }), hovertext: scatterAttrs.hovertext, hovertemplate: hovertemplateAttrs({}, { keys: constants.eventDataKeys }), textposition: { valType: 'enumerated', role: 'info', values: ['inside', 'outside', 'auto', 'none'], dflt: 'none', arrayOk: true, editType: 'calc', description: [ 'Specifies the location of the `text`.', '*inside* positions `text` inside, next to the bar end', '(rotated and scaled if needed).', '*outside* positions `text` outside, next to the bar end', '(scaled if needed), unless there is another bar stacked on', 'this one, then the text gets pushed inside.', '*auto* tries to position `text` inside the bar, but if', 'the bar is too small and no bar is stacked on this one', 'the text is moved outside.' ].join(' ') }, insidetextanchor: { valType: 'enumerated', values: ['end', 'middle', 'start'], dflt: 'end', role: 'info', editType: 'plot', description: [ 'Determines if texts are kept at center or start/end points in `textposition` *inside* mode.' ].join(' ') }, textangle: { valType: 'angle', dflt: 'auto', role: 'info', editType: 'plot', description: [ 'Sets the angle of the tick labels with respect to the bar.', 'For example, a `tickangle` of -90 draws the tick labels', 'vertically. With *auto* the texts may automatically be', 'rotated to fit with the maximum size in bars.' ].join(' ') }, textfont: extendFlat({}, textFontAttrs, { description: 'Sets the font used for `text`.' }), insidetextfont: extendFlat({}, textFontAttrs, { description: 'Sets the font used for `text` lying inside the bar.' }), outsidetextfont: extendFlat({}, textFontAttrs, { description: 'Sets the font used for `text` lying outside the bar.' }), constraintext: { valType: 'enumerated', values: ['inside', 'outside', 'both', 'none'], role: 'info', dflt: 'both', editType: 'calc', description: [ 'Constrain the size of text inside or outside a bar to be no', 'larger than the bar itself.' ].join(' ') }, cliponaxis: extendFlat({}, scatterAttrs.cliponaxis, { description: [ 'Determines whether the text nodes', 'are clipped about the subplot axes.', 'To show the text nodes above axis lines and tick labels,', 'make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*.' ].join(' ') }), orientation: { valType: 'enumerated', role: 'info', values: ['v', 'h'], editType: 'calc+clearAxisTypes', description: [ 'Sets the orientation of the bars.', 'With *v* (*h*), the value of the each bar spans', 'along the vertical (horizontal).' ].join(' ') }, base: { valType: 'any', dflt: null, arrayOk: true, role: 'info', editType: 'calc', description: [ 'Sets where the bar base is drawn (in position axis units).', 'In *stack* or *relative* barmode,', 'traces that set *base* will be excluded', 'and drawn in *overlay* mode instead.' ].join(' ') }, offset: { valType: 'number', dflt: null, arrayOk: true, role: 'info', editType: 'calc', description: [ 'Shifts the position where the bar is drawn', '(in position axis units).', 'In *group* barmode,', 'traces that set *offset* will be excluded', 'and drawn in *overlay* mode instead.' ].join(' ') }, width: { valType: 'number', dflt: null, min: 0, arrayOk: true, role: 'info', editType: 'calc', description: [ 'Sets the bar width (in position axis units).' ].join(' ') }, marker: marker, offsetgroup: { valType: 'string', role: 'info', dflt: '', editType: 'calc', description: [ 'Set several traces linked to the same position axis', 'or matching axes to the same', 'offsetgroup where bars of the same position coordinate will line up.' ].join(' ') }, alignmentgroup: { valType: 'string', role: 'info', dflt: '', editType: 'calc', description: [ 'Set several traces linked to the same position axis', 'or matching axes to the same', 'alignmentgroup. This controls whether bars compute their positional', 'range dependently or independently.' ].join(' ') }, selected: { marker: { opacity: scatterAttrs.selected.marker.opacity, color: scatterAttrs.selected.marker.color, editType: 'style' }, textfont: scatterAttrs.selected.textfont, editType: 'style' }, unselected: { marker: { opacity: scatterAttrs.unselected.marker.opacity, color: scatterAttrs.unselected.marker.color, editType: 'style' }, textfont: scatterAttrs.unselected.textfont, editType: 'style' }, r: scatterAttrs.r, t: scatterAttrs.t, _deprecated: { bardir: { valType: 'enumerated', role: 'info', editType: 'calc', values: ['v', 'h'], description: 'Renamed to `orientation`.' } } };
{ "content_hash": "8e1a6726f92313e22f0907df92bbf6ab", "timestamp": "", "source": "github", "line_count": 259, "max_line_length": 105, "avg_line_length": 29.455598455598455, "alnum_prop": 0.5586577533097391, "repo_name": "aburato/plotly.js", "id": "fd7572d7eef437a1926edc2353b956aee51f20a8", "size": "7820", "binary": false, "copies": "1", "ref": "refs/heads/ion-build-1.56", "path": "src/traces/bar/attributes.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "9607" }, { "name": "HTML", "bytes": "2358" }, { "name": "JavaScript", "bytes": "3137736" } ], "symlink_target": "" }
using System.Threading.Tasks; namespace Ma.CustomMapper.Abstract { /// <summary>Asynchronous mapper interface with only Target type.</summary> /// <typeparam name="TTarget">Type of target</typeparam> public interface IAsyncMapper<TTarget> : IMapperBase where TTarget : class { /// <summary>Map source object from type of source to TTarget type asynchronously</summary> /// <param name="source">Source to map</param> /// <param name="mapChildEntities">Also Map child entities in this source</param> /// <returns>Task to get mapped object of TTarget type</returns> Task<TTarget> MapAsync(object source, bool mapChildEntities); } /// <summary> /// Interface which custom mappers must implement /// in order to be able to map object from one type /// to other asynchronously. /// </summary> /// <typeparam name="TSource">Thpe of source.</typeparam> /// <typeparam name="TTarget">Type of target.</typeparam> public interface IAsyncMapper<TSource, TTarget> : IAsyncMapper<TTarget> where TSource : class where TTarget : class { } }
{ "content_hash": "a7c3c53922e3c30d23eb921bdb96bf96", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 95, "avg_line_length": 37.793103448275865, "alnum_prop": 0.7025547445255474, "repo_name": "MammadovAdil/CustomMapper", "id": "2b176f2beb3d815b0c6a56bb54ce33ec099d5606", "size": "1098", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Ma.CustomMapper/Abstract/IAsyncMapper.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "19823" } ], "symlink_target": "" }
package org.kie.workbench.common.screens.datamodeller.client.widgets.editor; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import javax.enterprise.context.Dependent; import javax.inject.Inject; import com.google.gwt.cell.client.FieldUpdater; import com.google.gwt.cell.client.TextCell; import com.google.gwt.core.client.GWT; import com.google.gwt.dom.client.Style; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.cellview.client.Column; import com.google.gwt.user.cellview.client.ColumnSortEvent; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; import com.google.gwt.view.client.ListDataProvider; import com.google.gwt.view.client.SelectionChangeEvent; import com.google.gwt.view.client.SingleSelectionModel; import org.gwtbootstrap3.client.ui.Button; import org.gwtbootstrap3.client.ui.constants.ButtonSize; import org.gwtbootstrap3.client.ui.constants.ButtonType; import org.gwtbootstrap3.client.ui.constants.IconType; import org.gwtbootstrap3.client.ui.gwt.ButtonCell; import org.kie.workbench.common.screens.datamodeller.client.resources.i18n.Constants; import org.kie.workbench.common.screens.datamodeller.client.resources.images.ImagesResources; import org.kie.workbench.common.screens.datamodeller.client.util.AnnotationValueHandler; import org.kie.workbench.common.screens.datamodeller.client.widgets.refactoring.ShowUsagesPopup; import org.kie.workbench.common.screens.datamodeller.model.maindomain.MainDomainAnnotations; import org.kie.workbench.common.services.datamodeller.core.ObjectProperty; import org.uberfire.backend.vfs.Path; import org.uberfire.ext.widgets.common.client.common.BusyPopup; import org.uberfire.ext.widgets.common.client.common.popups.YesNoCancelPopup; import org.uberfire.ext.widgets.common.client.tables.SimpleTable; import org.uberfire.mvp.Command; @Dependent public class DataObjectBrowserViewImpl extends Composite implements DataObjectBrowserView { interface DataObjectBrowserViewImplUIBinder extends UiBinder<Widget, DataObjectBrowserViewImpl> { } enum ColumnId { NAME_COLUMN, LABEL_COLUMN, TYPE_COLUMN } private static DataObjectBrowserViewImplUIBinder uiBinder = GWT.create( DataObjectBrowserViewImplUIBinder.class ); private final ButtonCell deleteCell = new ButtonCell( IconType.TRASH, ButtonType.DANGER, ButtonSize.SMALL ); @UiField Button objectButton; @UiField Button newPropertyButton; @UiField( provided = true ) SimpleTable<ObjectProperty> propertiesTable = new BrowserSimpleTable<ObjectProperty>( 1000 ); Map<Column<?,?>, ColumnId> columnIds = new HashMap<Column<?, ?>, ColumnId>( ); ListDataProvider<ObjectProperty> dataProvider; private Presenter presenter; private boolean readonly = true; private int tableHeight = 480; @Inject public DataObjectBrowserViewImpl() { initWidget( uiBinder.createAndBindUi( this ) ); } @PostConstruct protected void init() { newPropertyButton.setIcon( IconType.PLUS ); newPropertyButton.addClickHandler( new ClickHandler() { @Override public void onClick( ClickEvent event ) { presenter.onNewProperty(); } } ); objectButton.addClickHandler( new ClickHandler() { @Override public void onClick( ClickEvent event ) { presenter.onSelectCurrentDataObject(); } } ); //Init properties table propertiesTable.setEmptyTableCaption( Constants.INSTANCE.objectBrowser_emptyTable() ); propertiesTable.setcolumnPickerButtonVisibe( false ); propertiesTable.setToolBarVisible( false ); setTableHeight( tableHeight ); addPropertyNameColumn(); addPropertyLabelColumn(); addPropertyTypeBrowseColumn(); addPropertyTypeColumn(); addRemoveRowColumn(); addSortHandler(); //Init the selection model SingleSelectionModel<ObjectProperty> selectionModel = new SingleSelectionModel<ObjectProperty>(); propertiesTable.setSelectionModel( selectionModel ); selectionModel.addSelectionChangeHandler( new SelectionChangeEvent.Handler() { @Override public void onSelectionChange( SelectionChangeEvent event ) { ObjectProperty selectedProperty = ( ( SingleSelectionModel<ObjectProperty> ) propertiesTable.getSelectionModel() ).getSelectedObject(); presenter.onSelectProperty( selectedProperty ); } } ); setReadonly( true ); } @Override public void init( Presenter presenter ) { this.presenter = presenter; } @Override public void setDataProvider( ListDataProvider<ObjectProperty> dataProvider ) { if ( !dataProvider.getDataDisplays().contains( propertiesTable ) ) { dataProvider.addDataDisplay( propertiesTable ); } this.dataProvider = dataProvider; } public void setObjectSelectorLabel( String label, String title ) { objectButton.setText( label ); objectButton.setTitle( title ); } public void setReadonly( boolean readonly ) { this.readonly = readonly; enableNewPropertyAction( !readonly ); enableDeleteRowAction( !readonly ); } public void enableNewPropertyAction( boolean enable ) { newPropertyButton.setEnabled( enable ); } @Override public void enableDeleteRowAction( boolean enable ) { deleteCell.setEnabled( enable ); } @Override public void redrawRow( int row ) { //ideally we should have a method redrawRow( row ); propertiesTable.redraw(); } @Override public void redrawTable() { propertiesTable.redraw(); } @Override public ObjectProperty getSelectedRow() { return ( ( SingleSelectionModel<ObjectProperty> ) propertiesTable.getSelectionModel() ).getSelectedObject(); } @Override public void setSelectedRow( ObjectProperty objectProperty, boolean select ) { ( ( SingleSelectionModel<ObjectProperty> ) propertiesTable.getSelectionModel() ).setSelected( objectProperty, select ); } @Override public void setTableHeight( int height ) { this.tableHeight = height; propertiesTable.setHeight( tableHeight + "px" ); } @Override public int getTableHeight() { return tableHeight; } private void addPropertyNameColumn() { Column<ObjectProperty, String> column = new Column<ObjectProperty, String>( new TextCell() ) { @Override public String getValue( ObjectProperty objectProperty ) { if ( objectProperty.getName() != null ) { return objectProperty.getName(); } else { return ""; } } }; column.setSortable( true ); propertiesTable.addColumn( column, Constants.INSTANCE.objectBrowser_columnName() ); propertiesTable.setColumnWidth( column, 25, Style.Unit.PCT ); columnIds.put( column, ColumnId.NAME_COLUMN ); } private void addPropertyLabelColumn() { Column<ObjectProperty, String> column = new Column<ObjectProperty, String>( new TextCell() ) { @Override public String getValue( ObjectProperty objectProperty ) { if ( objectProperty.getName() != null ) { return AnnotationValueHandler.getStringValue( objectProperty, MainDomainAnnotations.LABEL_ANNOTATION, MainDomainAnnotations.VALUE_PARAM ); } else { return ""; } } }; column.setSortable( true ); propertiesTable.addColumn( column, Constants.INSTANCE.objectBrowser_columnLabel() ); propertiesTable.setColumnWidth( column, 25, Style.Unit.PCT ); columnIds.put( column, ColumnId.LABEL_COLUMN ); } private void addPropertyTypeBrowseColumn() { ClickableImageResourceCell typeImageCell = new ClickableImageResourceCell( true, 20 ); final Column<ObjectProperty, ImageResource> column = new Column<ObjectProperty, ImageResource>( typeImageCell ) { @Override public ImageResource getValue( final ObjectProperty property ) { if ( presenter != null && presenter.isSelectablePropertyType( property ) ) { return ImagesResources.INSTANCE.BrowseObject(); } else { return null; } } }; column.setFieldUpdater( new FieldUpdater<ObjectProperty, ImageResource>() { public void update( final int index, final ObjectProperty property, final ImageResource value ) { presenter.onSelectPropertyType( property ); } } ); propertiesTable.addColumn( column, " " ); propertiesTable.setColumnWidth( column, 38, Style.Unit.PX ); } private void addPropertyTypeColumn() { Column<ObjectProperty, String> column = new Column<ObjectProperty, String>( new TextCell() ) { @Override public String getValue( ObjectProperty objectProperty ) { if ( objectProperty.getName() != null && presenter != null ) { return presenter.getPropertyTypeDisplayValue( objectProperty ); } else { return ""; } } }; column.setSortable( true ); propertiesTable.addColumn( column, Constants.INSTANCE.objectBrowser_columnType() ); propertiesTable.setColumnWidth( column, 35, Style.Unit.PCT ); columnIds.put( column, ColumnId.TYPE_COLUMN ); } private void addRemoveRowColumn() { Column<ObjectProperty, String> column = new Column<ObjectProperty, String>( new ButtonCell( IconType.TRASH, ButtonType.DANGER, ButtonSize.SMALL ) ) { @Override public String getValue( ObjectProperty objectProperty ) { return Constants.INSTANCE.objectBrowser_action_delete(); } }; column.setFieldUpdater( new FieldUpdater<ObjectProperty, String>() { @Override public void update( int index, ObjectProperty objectProperty, String value ) { if ( !readonly ) { presenter.onDeleteProperty( objectProperty, index ); } } } ); propertiesTable.addColumn( column, "" ); propertiesTable.setColumnWidth( column, calculateButtonSize( Constants.INSTANCE.objectBrowser_action_delete() ), Style.Unit.PX ); } private void addSortHandler() { propertiesTable.addColumnSortHandler( new ColumnSortEvent.Handler() { @Override public void onColumnSort( ColumnSortEvent event ) { Column<?, ?> column = event.getColumn(); ColumnId columnId; if ( ( columnId = columnIds.get( column ) ) != null ) { switch ( columnId ) { case NAME_COLUMN: presenter.onSortByName( event.isSortAscending() ); break; case LABEL_COLUMN: presenter.onSortByLabel( event.isSortAscending() ); break; case TYPE_COLUMN: presenter.onSortByType( event.isSortAscending() ); } } } } ); } @Override public void showBusyIndicator( String message ) { BusyPopup.showMessage( message ); } @Override public void hideBusyIndicator() { BusyPopup.close(); } @Override public void showYesNoCancelPopup( final String title, final String content, final Command yesCommand, final String yesButtonText, final ButtonType yesButtonType, final Command noCommand, final String noButtonText, final ButtonType noButtonType, final Command cancelCommand, final String cancelButtonText, final ButtonType cancelButtonType ) { YesNoCancelPopup yesNoCancelPopup = YesNoCancelPopup.newYesNoCancelPopup( title, content, yesCommand, yesButtonText, yesButtonType, noCommand, noButtonText, noButtonType, cancelCommand, cancelButtonText, cancelButtonType ); yesNoCancelPopup.setClosable( false ); yesNoCancelPopup.show(); } @Override public void showUsagesPopupForDeletion( final String message, final List<Path> usedByFiles, final Command yesCommand, final Command cancelCommand ) { ShowUsagesPopup showUsagesPopup = ShowUsagesPopup.newUsagesPopupForDeletion( message, usedByFiles, yesCommand, cancelCommand ); showUsagesPopup.setClosable( false ); showUsagesPopup.show(); } private int calculateButtonSize( String buttonLabel ) { return 11 * buttonLabel.length() + 12 + 4; } private class BrowserSimpleTable<T> extends SimpleTable<T> { public BrowserSimpleTable( int pageSize ) { super(); dataGrid.setPageSize( pageSize ); } } }
{ "content_hash": "7a7defc7c2bfc6c88014c5fe7f26e98e", "timestamp": "", "source": "github", "line_count": 397, "max_line_length": 157, "avg_line_length": 35.30982367758186, "alnum_prop": 0.6417463261520902, "repo_name": "scandihealth/kie-wb-common", "id": "f48f7b1eaee1a3fc7fcb52502e564681048bba17", "size": "14639", "binary": false, "copies": "1", "ref": "refs/heads/6.5.0.csc", "path": "kie-wb-common-screens/kie-wb-common-data-modeller/kie-wb-common-data-modeller-client/src/main/java/org/kie/workbench/common/screens/datamodeller/client/widgets/editor/DataObjectBrowserViewImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "18581" }, { "name": "GAP", "bytes": "86275" }, { "name": "HTML", "bytes": "31605" }, { "name": "Java", "bytes": "8589867" } ], "symlink_target": "" }
package gov.samhsa.consent2share.infrastructure.eventlistener; import gov.samhsa.acs.audit.AuditService; import gov.samhsa.consent2share.domain.SecurityEvent; /** * The listener interface for receiving securityEvent events. The class that is * interested in processing a securityEvent event implements this interface, and * the object created with that class is registered with a component using the * component's <code>addSecurityEventListener<code> method. When * the securityEvent event occurs, that object's appropriate * method is invoked. * * @see SecurityEventEvent */ public abstract class SecurityEventListener extends EventListener { /** The audit service. */ protected AuditService auditService; /** * Instantiates a new security event listener. * * @param eventService * the event service * @param auditService * the audit service */ public SecurityEventListener(EventService eventService, AuditService auditService) { super(eventService); this.auditService = auditService; } /* * (non-Javadoc) * * @see * gov.samhsa.consent2share.infrastructure.eventlistener.EventListener#handle * (java.lang.Object) */ @Override public void handle(Object event) { audit((SecurityEvent) event); } /** * Audit. * * @param event * the event */ public abstract void audit(SecurityEvent event); }
{ "content_hash": "6240e35d794f3b98d109d4195d59a4b0", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 80, "avg_line_length": 25.833333333333332, "alnum_prop": 0.72831541218638, "repo_name": "OBHITA/Consent2Share", "id": "f8540962c1cc4d59b659f05cba2eb6478723199d", "size": "1395", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DS4P/consent2share/infrastructure/src/main/java/gov/samhsa/consent2share/infrastructure/eventlistener/SecurityEventListener.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "491834" }, { "name": "HTML", "bytes": "2415468" }, { "name": "Java", "bytes": "8076505" }, { "name": "JavaScript", "bytes": "659769" }, { "name": "Ruby", "bytes": "1504" }, { "name": "XSLT", "bytes": "341926" } ], "symlink_target": "" }
package redis // import "github.com/gopkg/database/redigo/redis"
{ "content_hash": "e7c88b044d96b85132fd247540447a18", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 64, "avg_line_length": 65, "alnum_prop": 0.7846153846153846, "repo_name": "gopkg/database", "id": "0d7f47ce918608a74771cb9c806bf638865e0a2e", "size": "6294", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "redigo/redis/doc.go", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "8004139" }, { "name": "C++", "bytes": "366162" }, { "name": "Go", "bytes": "2570108" }, { "name": "JavaScript", "bytes": "7407" }, { "name": "Makefile", "bytes": "802" }, { "name": "Objective-C", "bytes": "3062" }, { "name": "Shell", "bytes": "1424" } ], "symlink_target": "" }
package models import ( "github.com/bboozzoo/q3stats/store" "github.com/jinzhu/gorm" "log" ) type GlobalStats struct { // total number of frags/kills Frags uint // total number of suicides Suicides uint // total number of matches Matches uint // total number of unique maps Maps uint // number of rockets launched RocketsLaunched uint // players Players uint } // obtain kills/suicidees/deaths counts func getKillSuicideDeathCount(db *gorm.DB) (uint, uint, uint) { var result = struct { Kills uint Deaths uint Suicides uint }{} db.Model(&PlayerMatchStat{}). Select("sum(kills) as kills, sum(deaths) as deaths, sum(suicides)as suicides"). Scan(&result) log.Printf("kills: %u deaths: %u suicides: %u", result.Kills, result.Deaths, result.Suicides) return result.Kills, result.Deaths, result.Suicides } func getUniqueMapsCount(db *gorm.DB) uint { var result = struct { Maps uint }{} db.Raw("select count(map) as maps from (select distinct map from matches)"). Scan(&result) log.Printf("unique maps: %u", result.Maps) return result.Maps } func getUniquePlayersCount(db *gorm.DB) uint { var count uint db.Model(&Alias{}).Count(&count) log.Printf("unique players: %u", count) return count } func getRocketsLaunchedCount(db *gorm.DB) uint { var result = struct { Launched uint }{} db.Model(&WeaponStat{}). Where(&WeaponStat{Type: RocketLauncher}). Select("sum(shots) as launched"). Scan(&result) log.Printf("launched rockets: %u", result.Launched) return result.Launched } func getMatchCount(db *gorm.DB) uint { var count uint db.Model(&Match{}).Count(&count) return count } func GetGlobalStats(store store.DB) GlobalStats { db := store.Conn() gs := GlobalStats{} gs.Matches = getMatchCount(db) k, _, s := getKillSuicideDeathCount(db) gs.Frags = k gs.Suicides = s gs.Players = getUniquePlayersCount(db) gs.Maps = getUniqueMapsCount(db) gs.RocketsLaunched = getRocketsLaunchedCount(db) return gs }
{ "content_hash": "0d632ed291fb2f952a82167e5ac68d6f", "timestamp": "", "source": "github", "line_count": 93, "max_line_length": 81, "avg_line_length": 21.311827956989248, "alnum_prop": 0.7129162462159435, "repo_name": "bboozzoo/q3stats", "id": "ac808a94a1835433de91cd19b6846b7ad2a5a07f", "size": "3118", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "models/global.go", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "136" }, { "name": "Go", "bytes": "129207" }, { "name": "JavaScript", "bytes": "42186" }, { "name": "Makefile", "bytes": "1247" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <!-- 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. --> <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"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>${groupId}</groupId> <artifactId>${rootArtifactId}</artifactId> <version>${version}</version> <relativePath>../pom.xml</relativePath> </parent> <name>File Manager (Apache OODT)</name> <artifactId>${rootArtifactId}-${artifactId}</artifactId> <packaging>jar</packaging> <profiles> <profile> <id>default</id> <activation> <activeByDefault>true</activeByDefault> </activation> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>2.2-beta-2</version> <configuration> <descriptors> <descriptor>src/main/assembly/assembly.xml</descriptor> </descriptors> </configuration> <executions> <execution> <id>dist-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> <profile> <id>fm-solr-catalog</id> <activation/> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>2.2-beta-2</version> <configuration> <descriptors> <descriptor>src/main/assembly/assembly.fm-solr-catalog.xml</descriptor> </descriptors> </configuration> <executions> <execution> <id>dist-assembly</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </profile> </profiles> <dependencies> <dependency> <groupId>${groupId}</groupId> <artifactId>${rootArtifactId}-extensions</artifactId> <version>${project.parent.version}</version> <type>jar</type> <scope>runtime</scope> <exclusions> <exclusion> <groupId>org.apache.oodt</groupId> <artifactId>cas-filemgr</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.oodt</groupId> <artifactId>cas-filemgr</artifactId> <version>${oodt.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.2</version> <scope>test</scope> </dependency> </dependencies> </project>
{ "content_hash": "0c2c75db1f412b678c422bce2bfef9e6", "timestamp": "", "source": "github", "line_count": 116, "max_line_length": 99, "avg_line_length": 36.62931034482759, "alnum_prop": 0.5358907978347847, "repo_name": "Cyan3/oodt", "id": "d0216db29ef59bc2c10baa53a02381b297cdf580", "size": "4249", "binary": false, "copies": "4", "ref": "refs/heads/trunk", "path": "mvn/archetypes/radix/src/main/resources/archetype-resources/filemgr/pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "2030" }, { "name": "C++", "bytes": "22622" }, { "name": "CSS", "bytes": "130561" }, { "name": "HTML", "bytes": "105622" }, { "name": "Java", "bytes": "7497995" }, { "name": "JavaScript", "bytes": "189227" }, { "name": "Makefile", "bytes": "1135" }, { "name": "PHP", "bytes": "432498" }, { "name": "PLSQL", "bytes": "3736" }, { "name": "Perl", "bytes": "4459" }, { "name": "Python", "bytes": "131018" }, { "name": "Ruby", "bytes": "4884" }, { "name": "Scala", "bytes": "1015" }, { "name": "Shell", "bytes": "108646" }, { "name": "TeX", "bytes": "862979" }, { "name": "XSLT", "bytes": "28584" } ], "symlink_target": "" }
Lokaverkefni vsh
{ "content_hash": "7100ad5267a7ce6c60c1fa6a8b4a53c3", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 16, "avg_line_length": 17, "alnum_prop": 0.8823529411764706, "repo_name": "AtliOskarsson/Vsh2_Hopverkefni", "id": "4f1a891ae3ed2ad031d424bdcb073c9fe1aef3df", "size": "36", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8957" }, { "name": "HTML", "bytes": "4779" } ], "symlink_target": "" }
<!doctype html> <html> <head> <title>Licenses</title> <meta charset="utf-8"> <style type="text/css"> h1 { font-size: 15pt; } a, pre { font-size: 10pt; } ul, li { padding: 0; list-style-type: none; } </style> </head> <body> <p>This app uses the following components:</p> <ul> <li><a href="#sp">Spectaculum</a></li> <li><a href="#sp-flowabs">Spectaculum-Effect-FlowAbs</a></li> <li><a href="#mpx">MediaPlayer-Extended</a></li> <li><a href="#exo">ExoPlayer</a></li> <li><a href="#flowabs">FlowAbs</a></li> <li><a href="#qrmarker">QrMarker-ComputerVision</a></li> </ul> <a name="sp"></a> <h1>Spectaculum</h1> <pre> Spectaculum and all of its modules except Spectaculum-Effect-FlowAbs (see next license) are licensed as follows: Copyright 2016 Mario Guggenberger &lt;mg@protyposis.net&gt; 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. </pre> <a name="sp-flowabs"></a> <h1>Spectaculum-Effect-FlowAbs</h1> <pre> Copyright (c) 2014 Mario Guggenberger &lt;mg@protyposis.net&gt; This file is part of Spectaculum-Effect-FlowAbs. Spectaculum-Effect-FlowAbs 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. Spectaculum-Effect-FlowAbs 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 Spectaculum-Effect-FlowAbs. If not, see &lt;http://www.gnu.org/licenses/&gt;. </pre> <a name="mpx"></a> <h1>MediaPlayer-Extended</h1> <pre> Copyright 2014 Mario Guggenberger &lt;mg@protyposis.net&gt; 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. </pre> <a name="exo"></a> <h1>ExoPlayer</h1> <pre> Copyright (C) 2014 The Android Open Source Project 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. </pre> <a name="flowabs"></a> <h1>FlowAbs</h1> <pre> The FlowAbs shaders have been copied, without modification, from flowabs at https://code.google.com/p/flowabs/, distributed under the following license: by Jan Eric Kyprianidis &lt;www.kyprianidis.com&gt; Copyright (C) 2008-2011 Computer Graphics Systems Group at the Hasso-Plattner-Institut, Potsdam, Germany &lt;www.hpi3d.de&gt; This program 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. This program 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. </pre> <a name="qrmarker"></a> <h1>QrMarker-ComputerVision</h1> <pre> The QrMarker shaders have been copied, without modification, from QrMarker-ComputerVision at https://github.com/thHube/QrMarker-ComputerVision, distributed under the following license: Copyright (c) 2011, Alberto Franco All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Alberto Franco nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ALBERTO FRANCO BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. </pre> </body> </html>
{ "content_hash": "5ae585d6a513525819ef2f0e13108e17", "timestamp": "", "source": "github", "line_count": 161, "max_line_length": 91, "avg_line_length": 39.86335403726708, "alnum_prop": 0.729354939233406, "repo_name": "protyposis/Spectaculum", "id": "0fbbb70df4f59a3fa6652d8564389082b3852a03", "size": "6418", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Spectaculum-Demo/src/main/assets/licenses.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "598" }, { "name": "GLSL", "bytes": "43877" }, { "name": "HTML", "bytes": "6418" }, { "name": "Java", "bytes": "381813" } ], "symlink_target": "" }
require_relative '../../test_helper' require_relative 'flow_test_helper' require "smart_answer_flows/childcare-costs-for-tax-credits" class ChildcareCostsForTaxCreditsTest < ActiveSupport::TestCase include FlowTestHelper setup do setup_for_testing_flow SmartAnswer::ChildcareCostsForTaxCreditsFlow end context "answering Q1" do context "answering with yes" do setup do add_response :yes end should "take you to Q3 if you answer yes" do assert_current_node :have_costs_changed? end context "answering Q3" do should "take you to outcome if you answer no" do add_response :no assert_current_node :no_change end should "take you to how_often_pay_2 if you answer yes" do add_response :yes assert_current_node :how_often_pay_2? end context "answering Q5" do setup do add_response :yes end should "be Q5" do assert_current_node :how_often_pay_2? end should "take you to weekly costs for weekly answer" do add_response :weekly_same_amount assert_current_node :new_weekly_costs? end should "take you to how_much_12_months_2 if you answer with weekly diff amount" do add_response :weekly_diff_amount assert_current_node :how_much_52_weeks_2? end should "take you to the new_monthly_cost if you say monthly_same_amount" do add_response :monthly_same_amount assert_current_node :new_monthly_cost? end should "take you to 52 weeks question if you answer with monthly diff" do add_response :monthly_diff_amount assert_current_node :how_much_12_months_2? end end #Q5 end #Q3 end context "answering with no" do setup do add_response :no end should "take you to Q2 if you answer no" do assert_current_node :how_often_use_childcare? end context "answering Q2" do should "take you to how_often_pay_1 if you answer less than year" do add_response :regularly_less_than_year assert_current_node :how_often_pay_1? end should "take you to pay_same_each_time if you answer more than year" do add_response :regularly_more_than_year assert_current_node :pay_same_each_time? end should "take you to outcome if you answer only_short_while" do add_response :only_short_while assert_current_node :call_helpline_detailed end context "answering Q11" do setup do add_response :regularly_more_than_year #Q2 add_response :yes #Q11 end should "be on Q12 if you answer yes to Q11" do assert_current_node :how_often_pay_providers? end context "answering Q12" do setup do add_response :other end should "take user to helpline outcome" do assert_current_node :call_helpline_plain end end end context "answering Q4" do setup do add_response :regularly_less_than_year end should "take you to round_up_weekly outcome if you answer weekly_same_amount" do add_response :weekly_same_amount assert_current_node :round_up_weekly end should "take you to how_much_12_months if you answer with other" do add_response :other assert_current_node :how_much_12_months_1? end context "answering Q7" do setup do add_response :weekly_diff_amount end should "calculate the weekly cost and take user to outcome" do add_response 52 assert_current_node :weekly_costs_are_x assert_state_variable :weekly_cost, 1 end end #Q7 context "answering Q6" do setup do add_response :other # answer Q4 add_response 52 # answer Q6 end should "take you to weekly costs outcome" do assert_current_node :weekly_costs_are_x end should "calculate the weekly cost" do assert_state_variable :weekly_cost, 1 end end #Q6 end #Q4 end #Q2 end end #Q1 context "calculating weekly costs" do context "through Question 10" do setup do add_response :no #Q1 add_response :regularly_more_than_year #Q2 add_response :yes #Q11 add_response :every_month #Q12 end should "calculate the weekly cost" do add_response 4 #Q10 assert_state_variable :weekly_cost, 1 assert_current_node :weekly_costs_are_x end end context "through Question 13" do setup do add_response :no #Q1 add_response :regularly_more_than_year #Q2 add_response :yes #Q11 add_response :fortnightly #Q12 end should "ask you how much you pay fortnightly" do add_response 10 # Answer Q13 assert_state_variable :weekly_cost, 5 assert_current_node :weekly_costs_are_x end end # Q13 context "through Question 14" do setup do add_response :no #Q1 add_response :regularly_more_than_year #Q2 add_response :yes #Q11 add_response :every_4_weeks #Q12 end should "calculate the weekly cost" do add_response 20 #Q14 assert_state_variable :weekly_cost, 5 assert_current_node :weekly_costs_are_x end end # Q14 context "through Question 15" do setup do add_response :no #Q1 add_response :regularly_more_than_year #Q2 add_response :yes #Q11 add_response :yearly #Q12 end should "calculate the weekly cost" do add_response 52 #Q14 assert_state_variable :weekly_cost, 1 assert_current_node :weekly_costs_are_x end end # Q15 end # questions that lead to weekly-costs outcome context "questions that calculate the difference in costs" do context "Through Question 18" do setup do add_response :yes #Q1 add_response :yes #Q3 add_response :weekly_diff_amount #Q5 end should "be at Q8" do assert_current_node :how_much_52_weeks_2? end should "be at Q18" do add_response 52 #Q8 assert_current_node :old_weekly_amount_1? end should "calculate weekly_cost from Q8" do add_response 52 #Q8 assert_state_variable :weekly_cost, 1 end should "calculate diff after answering Q18" do add_response 52 # Q8 add_response 2 # Q18 assert_state_variable :old_weekly_cost, 2 assert_state_variable :weekly_difference, -1 assert_state_variable :weekly_difference_abs, 1 assert_state_variable :cost_change_4_weeks, false assert_current_node :cost_changed end end # Q18 end # questions that calculate cost difference context "going through Question 17" do setup do add_response :yes #Q1 add_response :yes #Q3 add_response :weekly_same_amount #Q5 end should "be at Q17" do assert_current_node :new_weekly_costs? end should "take user to not paying output if they answer 0" do add_response 0 assert_current_node :no_longer_paying end should "take user to Q20 if they give an answer" do add_response 1 assert_state_variable :new_weekly_costs, 1 assert_current_node :old_weekly_amount_2? end context "answering Q20" do setup do add_response 1 # Q17 add_response 11 # Q20 end should "calculate the old costs based on user answer" do assert_state_variable :old_weekly_costs, 11 assert_state_variable :weekly_difference, -10 assert_state_variable :weekly_difference_abs, 10 assert_state_variable :ten_or_more, true assert_state_variable :cost_change_4_weeks, true assert_current_node :cost_changed end should "show correct phrases" do assert_state_variable :title_change_text, "decreased" end end # Q20 end # Q17 context "going through Q19" do setup do add_response :yes #Q1 add_response :yes #Q3 add_response :monthly_same_amount #Q5 end should "be at Q19" do assert_current_node :new_monthly_cost? end should "take user to not paying output if they answer 0" do add_response 0 assert_current_node :no_longer_paying end should "take the user to Q21 if they give an answer" do add_response 4 assert_state_variable :new_weekly_costs, 1 assert_current_node :old_weekly_amount_3? end context "answering Q21" do setup do add_response 4 # Q19 add_response 10 end should "calculate old costs and difference" do assert_state_variable :old_weekly_costs, 10 assert_state_variable :weekly_difference, -9 assert_state_variable :ten_or_more, false assert_state_variable :title_change_text, "decreased" assert_state_variable :cost_change_4_weeks, false assert_current_node :cost_changed end end end context "answering Q16" do setup do add_response :no #Q1 add_response :regularly_more_than_year #Q2 add_response :no #Q11 end should "be on Q16" do assert_current_node :how_much_spent_last_12_months? end should "take user to weekly outcome" do add_response 52 assert_state_variable :weekly_cost, 1 assert_current_node :weekly_costs_are_x end end end
{ "content_hash": "6e2689ff163fd41e294b630c447c917c", "timestamp": "", "source": "github", "line_count": 350, "max_line_length": 92, "avg_line_length": 28.52, "alnum_prop": 0.6051893408134642, "repo_name": "stwalsh/smart-answers", "id": "5b8eac2377110498291fcc62719e2c1714fb7e40", "size": "9982", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "test/integration/smart_answer_flows/childcare_costs_for_tax_credits_test.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "8386" }, { "name": "HTML", "bytes": "2948544" }, { "name": "JavaScript", "bytes": "8814" }, { "name": "Ruby", "bytes": "1939196" }, { "name": "Shell", "bytes": "3673" } ], "symlink_target": "" }
/* * 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. */ /* * This code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.cloudsearch.v1.model; /** * Annotation metadata for YouTube artifact. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Search API. For a detailed explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class AppsDynamiteYoutubeMetadata extends com.google.api.client.json.GenericJson { /** * YouTube resource ID of the artifact. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.String id; /** * If this field is set to true, server should still contact external backends to get metadata for * search but clients should not render this chip. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Boolean shouldNotRender; /** * YouTube query parameter for timestamp. YouTube specific flag that allows users to embed time * token when sharing a link. This property contains parsed time token in seconds. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.lang.Integer startTime; /** * YouTube resource ID of the artifact. * @return value or {@code null} for none */ public java.lang.String getId() { return id; } /** * YouTube resource ID of the artifact. * @param id id or {@code null} for none */ public AppsDynamiteYoutubeMetadata setId(java.lang.String id) { this.id = id; return this; } /** * If this field is set to true, server should still contact external backends to get metadata for * search but clients should not render this chip. * @return value or {@code null} for none */ public java.lang.Boolean getShouldNotRender() { return shouldNotRender; } /** * If this field is set to true, server should still contact external backends to get metadata for * search but clients should not render this chip. * @param shouldNotRender shouldNotRender or {@code null} for none */ public AppsDynamiteYoutubeMetadata setShouldNotRender(java.lang.Boolean shouldNotRender) { this.shouldNotRender = shouldNotRender; return this; } /** * YouTube query parameter for timestamp. YouTube specific flag that allows users to embed time * token when sharing a link. This property contains parsed time token in seconds. * @return value or {@code null} for none */ public java.lang.Integer getStartTime() { return startTime; } /** * YouTube query parameter for timestamp. YouTube specific flag that allows users to embed time * token when sharing a link. This property contains parsed time token in seconds. * @param startTime startTime or {@code null} for none */ public AppsDynamiteYoutubeMetadata setStartTime(java.lang.Integer startTime) { this.startTime = startTime; return this; } @Override public AppsDynamiteYoutubeMetadata set(String fieldName, Object value) { return (AppsDynamiteYoutubeMetadata) super.set(fieldName, value); } @Override public AppsDynamiteYoutubeMetadata clone() { return (AppsDynamiteYoutubeMetadata) super.clone(); } }
{ "content_hash": "d6c4f0264826ef98026a2cc86889bfa8", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 182, "avg_line_length": 34.18333333333333, "alnum_prop": 0.7218430034129693, "repo_name": "googleapis/google-api-java-client-services", "id": "5aa4e0e4fd01ab39832daa655f5f0d0594a8a49b", "size": "4102", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "clients/google-api-services-cloudsearch/v1/2.0.0/com/google/api/services/cloudsearch/v1/model/AppsDynamiteYoutubeMetadata.java", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
var path = require('path'); var fileLoader = require('file-loader'); var querystring = require('querystring'); var AssetPathPlugin = require('./AssetPathPlugin'); const types = {jpg: 'jpeg', svg: 'svg+xml'}; const typeExpr = /\.(?:(png|gif|jpe?g|svg)|(woff2?|eot|ttf|otf))$/i; module.exports = function (content) { this.cacheable && this.cacheable(); var limit = 0; var inline = false; var options = this.options; var mimetype = mimeTypes(path.extname(this.resourcePath)); if (this.resourceQuery) { var query = querystring.parse(this.resourceQuery.substr(1)); inline = query.__inline !== undefined; } if (inline && !AssetPathPlugin.IMAGE_EXT_REG.test(this.resourcePath)) { return 'module.exports = ' + JSON.stringify(content.toString()); } if (options.dataUrlLimit && mimetype && AssetPathPlugin.IMAGE_EXT_REG.test(this.resourcePath)) { switch (typeof options.dataUrlLimit) { case 'boolean': limit = Number.MAX_VALUE; break; case 'number': limit = options.dataUrlLimit; break; default : this.emitError('unknown dataUrlLimit value `' + options.dataUrlLimit + '`'); } if (limit > content.length || inline) { return 'module.exports = ' + JSON.stringify('data:' + mimetype + ';base64,' + content.toString('base64')); } } return fileLoader.apply(this, arguments); }; function mimeTypes (ext) { if (typeExpr.test(ext)) { return !RegExp.$1 ? `application/octet-stream` : `image/${types[RegExp.$1] || RegExp.$1}`; } } module.exports.raw = true; module.exports.mimeTypes = mimeTypes;
{ "content_hash": "826f2a37ebe129ca6aeaf5d19e95ef14", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 84, "avg_line_length": 28.68421052631579, "alnum_prop": 0.6403669724770642, "repo_name": "dante1977/easepack", "id": "5d5bd555b8afa3bf0c643f99cce0dc165875b4b4", "size": "1635", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/plugins/urlLoader.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "158" }, { "name": "CSS", "bytes": "2972" }, { "name": "HTML", "bytes": "3647" }, { "name": "JavaScript", "bytes": "161242" }, { "name": "Shell", "bytes": "287" }, { "name": "Vue", "bytes": "5973" } ], "symlink_target": "" }
goog.require('goog.Uri'); goog.require('goog.dom'); goog.require('goog.events'); goog.require('goog.math.Coordinate'); goog.require('goog.math.Size'); goog.require('goog.string'); goog.require('goog.userAgent'); goog.require('webdriver.Key'); goog.require('webdriver.WebElement'); goog.require('webdriver.asserts'); goog.require('webdriver.factory'); goog.require('webdriver.jsunit'); window.IS_FF_3 = navigator.userAgent.search(/Firefox\/3\.\d+/) > -1; (function() { goog.global.whereIs = function(file) { return window.location.protocol + '//' + window.location.host + '/common/' + file; }; var testWindow; goog.global.openTestWindow = function(opt_url) { var url = opt_url || ''; testWindow = window.open(url, 'test_window'); testWindow.moveTo(window.screenLeft, window.screenTop); testWindow.resizeTo(window.outerWidth, window.outerHeight); }; goog.global.closeTestWindow = function() { if (testWindow) { testWindow.close(); } }; goog.global.switchToTestWindow = function(driver) { driver.switchToWindow('test_window'); }; goog.global.TEST_PAGE = { simpleTestPage: whereIs('simpleTest.html'), xhtmlTestPage: whereIs('xhtmlTest.html'), formPage: whereIs('formPage.html'), metaRedirectPage: whereIs('meta-redirect.html'), redirectPage: whereIs('redirect'), javascriptEnhancedForm: whereIs('javascriptEnhancedForm.html'), javascriptPage: whereIs('javascriptPage.html'), framesetPage: whereIs('frameset.html'), iframePage: whereIs('iframes.html'), dragAndDropPage: whereIs('dragAndDropTest.html'), chinesePage: whereIs('cn-test.html'), nestedPage: whereIs('nestedElements.html'), textPage: whereIs('plain.txt'), richtextPage: whereIs('rich_text.html'), resultPage: whereIs('resultPage.html') }; })();
{ "content_hash": "5e4f5351056135d335aee098478a5337", "timestamp": "", "source": "github", "line_count": 61, "max_line_length": 68, "avg_line_length": 30.19672131147541, "alnum_prop": 0.6905537459283387, "repo_name": "akiellor/selenium", "id": "ddb7ce2368a3f8f91b229bca890accbd605af4aa", "size": "1842", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "javascript/webdriver-jsapi/test/testbase.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "22777" }, { "name": "C", "bytes": "13787069" }, { "name": "C#", "bytes": "1592944" }, { "name": "C++", "bytes": "39839762" }, { "name": "Java", "bytes": "5948691" }, { "name": "JavaScript", "bytes": "15038006" }, { "name": "Objective-C", "bytes": "331601" }, { "name": "Python", "bytes": "544265" }, { "name": "Ruby", "bytes": "557579" }, { "name": "Shell", "bytes": "21701" } ], "symlink_target": "" }
import { LoadingBlocker } from '../../../components/common/loadingBlocker'; import React from 'react'; import LoadingIndicator from '../../../components/common/loadingIndicator'; import { shallow } from 'enzyme'; import ReactTestUtils from 'react-addons-test-utils'; const shallowRenderer = ReactTestUtils.createRenderer(); it('renders loading indicator when loading', () => { const component = shallow( <LoadingBlocker isLoading={ true } block={ true }> <p className='test-child'>children</p> </LoadingBlocker> ); expect(component.find(LoadingIndicator).length).toBe(1); }); it('matches snapshot when loading', () => { const tree = shallowRenderer.render( <LoadingBlocker isLoading={ true }> <p className='test-child'>children</p> </LoadingBlocker> ); expect(tree).toMatchSnapshot(); }); it('renders children when not loading', () => { const component = shallow( <LoadingBlocker isLoading={ false }> <p className='test-child'>children</p> </LoadingBlocker> ); expect(component.find('.test-child').length).toBe(1); }); it('matches snapshot when not loading', () => { const tree = shallowRenderer.render( <LoadingBlocker isLoading={ false }> <p className='test-child'>children</p> </LoadingBlocker> ); expect(tree).toMatchSnapshot(); });
{ "content_hash": "a1b56e0d279908fc6c3c437ee774f747", "timestamp": "", "source": "github", "line_count": 44, "max_line_length": 75, "avg_line_length": 30.068181818181817, "alnum_prop": 0.6780045351473923, "repo_name": "joejknowles/Open-Up", "id": "58338674fcd05296647914016419626f69018fcc", "size": "1323", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/src/__tests__/__tests__components/common/loadingBlocker.test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "4735" }, { "name": "CoffeeScript", "bytes": "211" }, { "name": "HTML", "bytes": "6671" }, { "name": "JavaScript", "bytes": "55820" }, { "name": "Ruby", "bytes": "45798" } ], "symlink_target": "" }
import numpy as np import matplotlib.pyplot as plt from directionFinder_backend.correlator import Correlator import scipy.signal from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes from mpl_toolkits.axes_grid1.inset_locator import mark_inset if __name__ == '__main__': c = Correlator() c.fetch_time_domain_snapshot(force=True) time_domain_padding = 10 fs = 800e6 upsample_factor = 100 a_idx = 0 b_idx = 1 a = np.concatenate( (np.zeros(time_domain_padding), c.time_domain_signals[a_idx], np.zeros(time_domain_padding))) a_time = np.linspace(-(time_domain_padding/fs), (len(a)-time_domain_padding)/fs, len(a), endpoint=False) b = c.time_domain_signals[b_idx] b_time = np.linspace(0, len(b)/fs, len(b), endpoint=False) correlation = np.correlate(a, b, mode='valid') correlation_time = np.linspace(a_time[0] - b_time[0], a_time[-1] - b_time[-1], len(correlation), endpoint=True) correlation_upped, correlation_time_upped = scipy.signal.resample( correlation, len(correlation)*upsample_factor, t = correlation_time) # normalise correlation_upped /= max(correlation) correlation /= max(correlation) correlation_time *= 1e9 correlation_time_upped *= 1e9 fig = plt.figure() ax1 = fig.gca() ax1.plot(correlation_time_upped, correlation_upped, color='b', linewidth=2, label="Upsampled") ax1.plot(correlation_time, correlation, color='r', linewidth=2, marker='.', markersize=15, label="Raw") xy_before = (correlation_time[np.argmax(correlation)-1], correlation[np.argmax(correlation)-1]) ax1.annotate('higher', xy=xy_before, xytext=(0.2, 0.4), textcoords='axes fraction', arrowprops=dict(facecolor='black', shrink=0.09, width=2), horizontalalignment='right', verticalalignment='top',) xy_after = (correlation_time[np.argmax(correlation)+1], correlation[np.argmax(correlation)+1]) ax1.annotate('lower', xy=xy_after, xytext=(0.6, 0.3), textcoords='axes fraction', arrowprops=dict(facecolor='black', shrink=0.09, width=2), horizontalalignment='right', verticalalignment='top',) axins = zoomed_inset_axes(ax1, 9, loc=1) axins.plot(correlation_time_upped, correlation_upped, color='b', marker='.', linewidth=2, label="Upsampled") axins.plot(correlation_time, correlation, color='r', linewidth=2, marker='.', markersize=15, label="Raw") axins.set_xlim(-3.2, -2.2) axins.set_ylim(0.97, 1.05) axins.xaxis.set_ticks(np.arange(-3.4, -1.9, 0.4)) #plt.xticks(visible=False) plt.yticks(visible=False) mark_inset(ax1, axins, loc1=2, loc2=3, fc='none', ec='0.5') ax1.set_title("Comparison of raw time domain cross correlation with upsampled version") ax1.set_xlabel("Time shift (ns)") ax1.set_ylabel("Cross correlation value (normalised)") ax1.legend(loc=2) plt.show()
{ "content_hash": "c80b50b5e3ea01424cfb835f640b2c02", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 112, "avg_line_length": 43.17333333333333, "alnum_prop": 0.6065472513897467, "repo_name": "jgowans/correlation_plotter", "id": "5a0011f2e3058d2f6f22a732704f80aa208ca483", "size": "3261", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "time_domain_cross_upsampled.py", "mode": "33261", "license": "mit", "language": [ { "name": "Python", "bytes": "83593" } ], "symlink_target": "" }
from __future__ import division, print_function , unicode_literals, absolute_import import os, sys, subprocess crow_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) eigen_cflags = "" try: has_pkg_eigen = subprocess.call(["pkg-config","--exists","eigen3"]) == 0 except: has_pkg_eigen = False if has_pkg_eigen: eigen_cflags = subprocess.check_output(["pkg-config","eigen3","--cflags"]) libmesh_eigen = os.path.abspath(os.path.join(crow_dir,os.pardir,"moose","libmesh","contrib","eigen","eigen")) if os.path.exists(libmesh_eigen): eigen_cflags = "-I"+libmesh_eigen if os.path.exists(os.path.join(crow_dir,"contrib","include","Eigen")): eigen_cflags = "" print(eigen_cflags)
{ "content_hash": "5fbbb3420fc6a45b29e42a08857a4893", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 109, "avg_line_length": 27.23076923076923, "alnum_prop": 0.6949152542372882, "repo_name": "joshua-cogliati-inl/raven", "id": "86779741a78857a3581a50e6664461c19c447f29", "size": "726", "binary": false, "copies": "2", "ref": "refs/heads/devel", "path": "scripts/find_eigen.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "1556080" }, { "name": "Batchfile", "bytes": "1095" }, { "name": "C", "bytes": "148504" }, { "name": "C++", "bytes": "48279546" }, { "name": "CMake", "bytes": "9998" }, { "name": "Jupyter Notebook", "bytes": "84202" }, { "name": "MATLAB", "bytes": "202335" }, { "name": "Makefile", "bytes": "2399" }, { "name": "Perl", "bytes": "1297" }, { "name": "Python", "bytes": "6952659" }, { "name": "R", "bytes": "67" }, { "name": "SWIG", "bytes": "8574" }, { "name": "Shell", "bytes": "124279" }, { "name": "TeX", "bytes": "479725" } ], "symlink_target": "" }
<?php $header_title = isset($header_title) ? $header_title : ''; $active_modul = isset($active_modul) ? $active_modul : 'none'; $detail = isset($detail) ? $detail : FALSE; ?> <div class="row"> <div class="col-md-12"> <form enctype="multipart/form-data" method="POST" class="form-horizontal"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Formulir <strong><?php echo $header_title; ?></strong></h3> </div> <div class="panel-body"> <p><?php echo load_partial("back_end/shared/attention_message"); ?></p> </div> <div class="panel-body"> <div class="form-group"> <label class="col-md-3 col-xs-12 control-label">Nama Agama *</label> <div class="col-md-6 col-xs-12"> <div class="input-group"> <input type="text" name="nama_agama" class="form-control" value="<?php echo $detail ? $detail->nama_agama : ""; ?>"> </div> <span class="help-block">Isikan sesuai dengan nama agama.</span> </div> </div> </div> <div class="panel-footer"> <button type="submit" class="btn-primary btn pull-right">Submit</button> <a href="<?php echo base_url("back_end/".$active_modul."/index"); ?>" class="btn-default btn">Batal / Kembali</a> </div> </div> </form> </div> </div>
{ "content_hash": "542bad9a4c381f0fe37cb3bb93ca1a05", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 148, "avg_line_length": 46.36842105263158, "alnum_prop": 0.4477866061293984, "repo_name": "lahirwisada/2016madfrct", "id": "f5c10deeef4e70be26b24c45fe6c8bed020386f9", "size": "1762", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "application/views/back_end/mssatuan/detail.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2503080" }, { "name": "HTML", "bytes": "194692" }, { "name": "JavaScript", "bytes": "3006985" }, { "name": "PHP", "bytes": "991990" }, { "name": "Ruby", "bytes": "578" }, { "name": "Shell", "bytes": "26" } ], "symlink_target": "" }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE // TODO actually recognize syntax of TypeScript constructs (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("javascript", function(config, parserConfig) { var indentUnit = config.indentUnit; var statementIndent = parserConfig.statementIndent; var jsonldMode = parserConfig.jsonld; var jsonMode = parserConfig.json || jsonldMode; var isTS = parserConfig.typescript; // Tokenizer var keywords = function(){ function kw(type) {return {type: type, style: "keyword"};} var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"); var operator = kw("operator"), atom = {type: "atom", style: "atom"}; var jsKeywords = { "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, "return": C, "break": C, "continue": C, "new": C, "delete": C, "throw": C, "debugger": C, "var": kw("var"), "const": kw("var"), "let": kw("var"), "function": kw("function"), "catch": kw("catch"), "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), "in": operator, "typeof": operator, "instanceof": operator, "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom, "this": kw("this"), "module": kw("module"), "class": kw("class"), "super": kw("atom"), "yield": C, "export": kw("export"), "import": kw("import"), "extends": C }; // Extend the 'normal' keywords with the TypeScript language extensions if (isTS) { var type = {type: "variable", style: "variable-3"}; var tsKeywords = { // object-like things "interface": kw("interface"), "extends": kw("extends"), "constructor": kw("constructor"), // scope modifiers "public": kw("public"), "private": kw("private"), "protected": kw("protected"), "static": kw("static"), // types "string": type, "number": type, "bool": type, "any": type }; for (var attr in tsKeywords) { jsKeywords[attr] = tsKeywords[attr]; } } return jsKeywords; }(); var isOperatorChar = /[+\-*&%=<>!?|~^]/; var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; function readRegexp(stream) { var escaped = false, next, inSet = false; while ((next = stream.next()) != null) { if (!escaped) { if (next == "/" && !inSet) return; if (next == "[") inSet = true; else if (inSet && next == "]") inSet = false; } escaped = !escaped && next == "\\"; } } // Used as scratch variables to communicate multiple values without // consing up tons of objects. var type, content; function ret(tp, style, cont) { type = tp; content = cont; return style; } function tokenBase(stream, state) { var ch = stream.next(); if (ch == '"' || ch == "'") { state.tokenize = tokenString(ch); return state.tokenize(stream, state); } else if (ch == "." && stream.match(/^\d+(?:[eE][+\-]?\d+)?/)) { return ret("number", "number"); } else if (ch == "." && stream.match("..")) { return ret("spread", "meta"); } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { return ret(ch); } else if (ch == "=" && stream.eat(">")) { return ret("=>", "operator"); } else if (ch == "0" && stream.eat(/x/i)) { stream.eatWhile(/[\da-f]/i); return ret("number", "number"); } else if (/\d/.test(ch)) { stream.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/); return ret("number", "number"); } else if (ch == "/") { if (stream.eat("*")) { state.tokenize = tokenComment; return tokenComment(stream, state); } else if (stream.eat("/")) { stream.skipToEnd(); return ret("comment", "comment"); } else if (state.lastType == "operator" || state.lastType == "keyword c" || state.lastType == "sof" || /^[\[{}\(,;:]$/.test(state.lastType)) { readRegexp(stream); stream.eatWhile(/[gimy]/); // 'y' is "sticky" option in Mozilla return ret("regexp", "string-2"); } else { stream.eatWhile(isOperatorChar); return ret("operator", "operator", stream.current()); } } else if (ch == "`") { state.tokenize = tokenQuasi; return tokenQuasi(stream, state); } else if (ch == "#") { stream.skipToEnd(); return ret("error", "error"); } else if (isOperatorChar.test(ch)) { stream.eatWhile(isOperatorChar); return ret("operator", "operator", stream.current()); } else { stream.eatWhile(/[\w\$_]/); var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word]; return (known && state.lastType != ".") ? ret(known.type, known.style, word) : ret("variable", "variable", word); } } function tokenString(quote) { return function(stream, state) { var escaped = false, next; if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){ state.tokenize = tokenBase; return ret("jsonld-keyword", "meta"); } while ((next = stream.next()) != null) { if (next == quote && !escaped) break; escaped = !escaped && next == "\\"; } if (!escaped) state.tokenize = tokenBase; return ret("string", "string"); }; } function tokenComment(stream, state) { var maybeEnd = false, ch; while (ch = stream.next()) { if (ch == "/" && maybeEnd) { state.tokenize = tokenBase; break; } maybeEnd = (ch == "*"); } return ret("comment", "comment"); } function tokenQuasi(stream, state) { var escaped = false, next; while ((next = stream.next()) != null) { if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { state.tokenize = tokenBase; break; } escaped = !escaped && next == "\\"; } return ret("quasi", "string-2", stream.current()); } var brackets = "([{}])"; // This is a crude lookahead trick to try and notice that we're // parsing the argument patterns for a fat-arrow function before we // actually hit the arrow token. It only works if the arrow is on // the same line as the arguments and there's no strange noise // (comments) in between. Fallback is to only notice when we hit the // arrow, and not declare the arguments as locals for the arrow // body. function findFatArrow(stream, state) { if (state.fatArrowAt) state.fatArrowAt = null; var arrow = stream.string.indexOf("=>", stream.start); if (arrow < 0) return; var depth = 0, sawSomething = false; for (var pos = arrow - 1; pos >= 0; --pos) { var ch = stream.string.charAt(pos); var bracket = brackets.indexOf(ch); if (bracket >= 0 && bracket < 3) { if (!depth) { ++pos; break; } if (--depth == 0) break; } else if (bracket >= 3 && bracket < 6) { ++depth; } else if (/[$\w]/.test(ch)) { sawSomething = true; } else if (sawSomething && !depth) { ++pos; break; } } if (sawSomething && !depth) state.fatArrowAt = pos; } // Parser var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true}; function JSLexical(indented, column, type, align, prev, info) { this.indented = indented; this.column = column; this.type = type; this.prev = prev; this.info = info; if (align != null) this.align = align; } function inScope(state, varname) { for (var v = state.localVars; v; v = v.next) if (v.name == varname) return true; for (var cx = state.context; cx; cx = cx.prev) { for (var v = cx.vars; v; v = v.next) if (v.name == varname) return true; } } function parseJS(state, style, type, content, stream) { var cc = state.cc; // Communicate our context to the combinators. // (Less wasteful than consing up a hundred closures on every call.) cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style; if (!state.lexical.hasOwnProperty("align")) state.lexical.align = true; while(true) { var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; if (combinator(type, content)) { while(cc.length && cc[cc.length - 1].lex) cc.pop()(); if (cx.marked) return cx.marked; if (type == "variable" && inScope(state, content)) return "variable-2"; return style; } } } // Combinator utils var cx = {state: null, column: null, marked: null, cc: null}; function pass() { for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); } function cont() { pass.apply(null, arguments); return true; } function register(varname) { function inList(list) { for (var v = list; v; v = v.next) if (v.name == varname) return true; return false; } var state = cx.state; if (state.context) { cx.marked = "def"; if (inList(state.localVars)) return; state.localVars = {name: varname, next: state.localVars}; } else { if (inList(state.globalVars)) return; if (parserConfig.globalVars) state.globalVars = {name: varname, next: state.globalVars}; } } // Combinators var defaultVars = {name: "this", next: {name: "arguments"}}; function pushcontext() { cx.state.context = {prev: cx.state.context, vars: cx.state.localVars}; cx.state.localVars = defaultVars; } function popcontext() { cx.state.localVars = cx.state.context.vars; cx.state.context = cx.state.context.prev; } function pushlex(type, info) { var result = function() { var state = cx.state, indent = state.indented; if (state.lexical.type == "stat") indent = state.lexical.indented; state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); }; result.lex = true; return result; } function poplex() { var state = cx.state; if (state.lexical.prev) { if (state.lexical.type == ")") state.indented = state.lexical.indented; state.lexical = state.lexical.prev; } } poplex.lex = true; function expect(wanted) { function exp(type) { if (type == wanted) return cont(); else if (wanted == ";") return pass(); else return cont(exp); }; return exp; } function statement(type, value) { if (type == "var") return cont(pushlex("vardef", value.length), vardef, expect(";"), poplex); if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex); if (type == "keyword b") return cont(pushlex("form"), statement, poplex); if (type == "{") return cont(pushlex("}"), block, poplex); if (type == ";") return cont(); if (type == "if") { if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) cx.state.cc.pop()(); return cont(pushlex("form"), expression, statement, poplex, maybeelse); } if (type == "function") return cont(functiondef); if (type == "for") return cont(pushlex("form"), forspec, statement, poplex); if (type == "variable") return cont(pushlex("stat"), maybelabel); if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"), block, poplex, poplex); if (type == "case") return cont(expression, expect(":")); if (type == "default") return cont(expect(":")); if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"), statement, poplex, popcontext); if (type == "module") return cont(pushlex("form"), pushcontext, afterModule, popcontext, poplex); if (type == "class") return cont(pushlex("form"), className, poplex); if (type == "export") return cont(pushlex("form"), afterExport, poplex); if (type == "import") return cont(pushlex("form"), afterImport, poplex); return pass(pushlex("stat"), expression, expect(";"), poplex); } function expression(type) { return expressionInner(type, false); } function expressionNoComma(type) { return expressionInner(type, true); } function expressionInner(type, noComma) { if (cx.state.fatArrowAt == cx.stream.start) { var body = noComma ? arrowBodyNoComma : arrowBody; if (type == "(") return cont(pushcontext, pushlex(")"), commasep(pattern, ")"), poplex, expect("=>"), body, popcontext); else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); } var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); if (type == "function") return cont(functiondef, maybeop); if (type == "keyword c") return cont(noComma ? maybeexpressionNoComma : maybeexpression); if (type == "(") return cont(pushlex(")"), maybeexpression, comprehension, expect(")"), poplex, maybeop); if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); if (type == "{") return contCommasep(objprop, "}", null, maybeop); if (type == "quasi") { return pass(quasi, maybeop); } return cont(); } function maybeexpression(type) { if (type.match(/[;\}\)\],]/)) return pass(); return pass(expression); } function maybeexpressionNoComma(type) { if (type.match(/[;\}\)\],]/)) return pass(); return pass(expressionNoComma); } function maybeoperatorComma(type, value) { if (type == ",") return cont(expression); return maybeoperatorNoComma(type, value, false); } function maybeoperatorNoComma(type, value, noComma) { var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; var expr = noComma == false ? expression : expressionNoComma; if (value == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); if (type == "operator") { if (/\+\+|--/.test(value)) return cont(me); if (value == "?") return cont(expression, expect(":"), expr); return cont(expr); } if (type == "quasi") { return pass(quasi, me); } if (type == ";") return; if (type == "(") return contCommasep(expressionNoComma, ")", "call", me); if (type == ".") return cont(property, me); if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); } function quasi(type, value) { if (type != "quasi") return pass(); if (value.slice(value.length - 2) != "${") return cont(quasi); return cont(expression, continueQuasi); } function continueQuasi(type) { if (type == "}") { cx.marked = "string-2"; cx.state.tokenize = tokenQuasi; return cont(quasi); } } function arrowBody(type) { findFatArrow(cx.stream, cx.state); if (type == "{") return pass(statement); return pass(expression); } function arrowBodyNoComma(type) { findFatArrow(cx.stream, cx.state); if (type == "{") return pass(statement); return pass(expressionNoComma); } function maybelabel(type) { if (type == ":") return cont(poplex, statement); return pass(maybeoperatorComma, expect(";"), poplex); } function property(type) { if (type == "variable") {cx.marked = "property"; return cont();} } function objprop(type, value) { if (type == "variable" || cx.style == "keyword") { cx.marked = "property"; if (value == "get" || value == "set") return cont(getterSetter); return cont(afterprop); } else if (type == "number" || type == "string") { cx.marked = jsonldMode ? "property" : (cx.style + " property"); return cont(afterprop); } else if (type == "jsonld-keyword") { return cont(afterprop); } else if (type == "[") { return cont(expression, expect("]"), afterprop); } } function getterSetter(type) { if (type != "variable") return pass(afterprop); cx.marked = "property"; return cont(functiondef); } function afterprop(type) { if (type == ":") return cont(expressionNoComma); if (type == "(") return pass(functiondef); } function commasep(what, end) { function proceed(type) { if (type == ",") { var lex = cx.state.lexical; if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; return cont(what, proceed); } if (type == end) return cont(); return cont(expect(end)); } return function(type) { if (type == end) return cont(); return pass(what, proceed); }; } function contCommasep(what, end, info) { for (var i = 3; i < arguments.length; i++) cx.cc.push(arguments[i]); return cont(pushlex(end, info), commasep(what, end), poplex); } function block(type) { if (type == "}") return cont(); return pass(statement, block); } function maybetype(type) { if (isTS && type == ":") return cont(typedef); } function typedef(type) { if (type == "variable"){cx.marked = "variable-3"; return cont();} } function vardef() { return pass(pattern, maybetype, maybeAssign, vardefCont); } function pattern(type, value) { if (type == "variable") { register(value); return cont(); } if (type == "[") return contCommasep(pattern, "]"); if (type == "{") return contCommasep(proppattern, "}"); } function proppattern(type, value) { if (type == "variable" && !cx.stream.match(/^\s*:/, false)) { register(value); return cont(maybeAssign); } if (type == "variable") cx.marked = "property"; return cont(expect(":"), pattern, maybeAssign); } function maybeAssign(_type, value) { if (value == "=") return cont(expressionNoComma); } function vardefCont(type) { if (type == ",") return cont(vardef); } function maybeelse(type, value) { if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); } function forspec(type) { if (type == "(") return cont(pushlex(")"), forspec1, expect(")"), poplex); } function forspec1(type) { if (type == "var") return cont(vardef, expect(";"), forspec2); if (type == ";") return cont(forspec2); if (type == "variable") return cont(formaybeinof); return pass(expression, expect(";"), forspec2); } function formaybeinof(_type, value) { if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } return cont(maybeoperatorComma, forspec2); } function forspec2(type, value) { if (type == ";") return cont(forspec3); if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression); } return pass(expression, expect(";"), forspec3); } function forspec3(type) { if (type != ")") cont(expression); } function functiondef(type, value) { if (value == "*") {cx.marked = "keyword"; return cont(functiondef);} if (type == "variable") {register(value); return cont(functiondef);} if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, statement, popcontext); } function funarg(type) { if (type == "spread") return cont(funarg); return pass(pattern, maybetype); } function className(type, value) { if (type == "variable") {register(value); return cont(classNameAfter);} } function classNameAfter(type, value) { if (value == "extends") return cont(expression, classNameAfter); if (type == "{") return cont(pushlex("}"), classBody, poplex); } function classBody(type, value) { if (type == "variable" || cx.style == "keyword") { cx.marked = "property"; if (value == "get" || value == "set") return cont(classGetterSetter, functiondef, classBody); return cont(functiondef, classBody); } if (value == "*") { cx.marked = "keyword"; return cont(classBody); } if (type == ";") return cont(classBody); if (type == "}") return cont(); } function classGetterSetter(type) { if (type != "variable") return pass(); cx.marked = "property"; return cont(); } function afterModule(type, value) { if (type == "string") return cont(statement); if (type == "variable") { register(value); return cont(maybeFrom); } } function afterExport(_type, value) { if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); } if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); } return pass(statement); } function afterImport(type) { if (type == "string") return cont(); return pass(importSpec, maybeFrom); } function importSpec(type, value) { if (type == "{") return contCommasep(importSpec, "}"); if (type == "variable") register(value); return cont(); } function maybeFrom(_type, value) { if (value == "from") { cx.marked = "keyword"; return cont(expression); } } function arrayLiteral(type) { if (type == "]") return cont(); return pass(expressionNoComma, maybeArrayComprehension); } function maybeArrayComprehension(type) { if (type == "for") return pass(comprehension, expect("]")); if (type == ",") return cont(commasep(expressionNoComma, "]")); return pass(commasep(expressionNoComma, "]")); } function comprehension(type) { if (type == "for") return cont(forspec, comprehension); if (type == "if") return cont(expression, comprehension); } // Interface return { startState: function(basecolumn) { var state = { tokenize: tokenBase, lastType: "sof", cc: [], lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), localVars: parserConfig.localVars, context: parserConfig.localVars && {vars: parserConfig.localVars}, indented: 0 }; if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") state.globalVars = parserConfig.globalVars; return state; }, token: function(stream, state) { if (stream.sol()) { if (!state.lexical.hasOwnProperty("align")) state.lexical.align = false; state.indented = stream.indentation(); findFatArrow(stream, state); } if (state.tokenize != tokenComment && stream.eatSpace()) return null; var style = state.tokenize(stream, state); if (type == "comment") return style; state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; return parseJS(state, style, type, content, stream); }, indent: function(state, textAfter) { if (state.tokenize == tokenComment) return CodeMirror.Pass; if (state.tokenize != tokenBase) return 0; var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical; // Kludge to prevent 'maybelse' from blocking lexical scope pops if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { var c = state.cc[i]; if (c == poplex) lexical = lexical.prev; else if (c != maybeelse) break; } if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev; if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") lexical = lexical.prev; var type = lexical.type, closing = firstChar == type; if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info + 1 : 0); else if (type == "form" && firstChar == "{") return lexical.indented; else if (type == "form") return lexical.indented + indentUnit; else if (type == "stat") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? statementIndent || indentUnit : 0); else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); else if (lexical.align) return lexical.column + (closing ? 0 : 1); else return lexical.indented + (closing ? 0 : indentUnit); }, electricChars: ":{}", blockCommentStart: jsonMode ? null : "/*", blockCommentEnd: jsonMode ? null : "*/", lineComment: jsonMode ? null : "//", fold: "brace", helperType: jsonMode ? "json" : "javascript", jsonldMode: jsonldMode, jsonMode: jsonMode }; }); CodeMirror.registerHelper("wordChars", "javascript", /[\\w$]/); CodeMirror.defineMIME("text/javascript", "javascript"); CodeMirror.defineMIME("text/ecmascript", "javascript"); CodeMirror.defineMIME("application/javascript", "javascript"); CodeMirror.defineMIME("application/ecmascript", "javascript"); CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true}); CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true}); CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); });
{ "content_hash": "ddd999d81634d8aedda9fbfa14c42aa1", "timestamp": "", "source": "github", "line_count": 682, "max_line_length": 139, "avg_line_length": 37.84310850439883, "alnum_prop": 0.5940175907629122, "repo_name": "GitYiheng/reinforcement_learning_test", "id": "4cabbe8682ee09e528cd8db4641d511fa7564351", "size": "25809", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "test01_cartpendulum/pydy-resources/js/external/codemirror/javascript-mode.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "14810" }, { "name": "HTML", "bytes": "15405" }, { "name": "JavaScript", "bytes": "51050" }, { "name": "Jupyter Notebook", "bytes": "3492256" }, { "name": "Python", "bytes": "1033931" }, { "name": "Shell", "bytes": "3108" } ], "symlink_target": "" }
class CreateBottles < ActiveRecord::Migration def change create_table :bottles do |t| t.string :name t.string :varietal t.timestamps end end end
{ "content_hash": "a09d56566e6fb20f61ef840690d60808", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 45, "avg_line_length": 17.6, "alnum_prop": 0.6534090909090909, "repo_name": "robmathews/search_steriods", "id": "93a8d2eab92e2782f162a46d1a933d2edac56019", "size": "176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/dummy/db/migrate/20130629161005_create_bottles.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "71409" } ], "symlink_target": "" }
using System.Text.Json; using Azure.Core; namespace Azure.Search.Documents.Indexes.Models { public partial class TagScoringFunction : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); writer.WritePropertyName("tag"); writer.WriteObjectValue(Parameters); writer.WritePropertyName("type"); writer.WriteStringValue(Type); writer.WritePropertyName("fieldName"); writer.WriteStringValue(FieldName); writer.WritePropertyName("boost"); writer.WriteNumberValue(Boost); if (Optional.IsDefined(Interpolation)) { writer.WritePropertyName("interpolation"); writer.WriteStringValue(Interpolation.Value.ToSerialString()); } writer.WriteEndObject(); } internal static TagScoringFunction DeserializeTagScoringFunction(JsonElement element) { TagScoringParameters tag = default; string type = default; string fieldName = default; double boost = default; Optional<ScoringFunctionInterpolation> interpolation = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("tag")) { tag = TagScoringParameters.DeserializeTagScoringParameters(property.Value); continue; } if (property.NameEquals("type")) { type = property.Value.GetString(); continue; } if (property.NameEquals("fieldName")) { fieldName = property.Value.GetString(); continue; } if (property.NameEquals("boost")) { boost = property.Value.GetDouble(); continue; } if (property.NameEquals("interpolation")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } interpolation = property.Value.GetString().ToScoringFunctionInterpolation(); continue; } } return new TagScoringFunction(type, fieldName, boost, Optional.ToNullable(interpolation), tag); } } }
{ "content_hash": "4b6f44a0f65c6b294d1665e048af0556", "timestamp": "", "source": "github", "line_count": 70, "max_line_length": 107, "avg_line_length": 37.785714285714285, "alnum_prop": 0.5274102079395085, "repo_name": "AsrOneSdk/azure-sdk-for-net", "id": "a5cdb75661e5c717c609ae65ca7edcd9125d60c4", "size": "2783", "binary": false, "copies": "7", "ref": "refs/heads/psSdkJson6Current", "path": "sdk/search/Azure.Search.Documents/src/Generated/Models/TagScoringFunction.Serialization.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "15473" }, { "name": "Bicep", "bytes": "13438" }, { "name": "C#", "bytes": "72203239" }, { "name": "CSS", "bytes": "6089" }, { "name": "Dockerfile", "bytes": "5652" }, { "name": "HTML", "bytes": "6169271" }, { "name": "JavaScript", "bytes": "16012" }, { "name": "PowerShell", "bytes": "649218" }, { "name": "Shell", "bytes": "31287" }, { "name": "Smarty", "bytes": "11135" } ], "symlink_target": "" }
module Wombat module Wundler module Package class Joey attr_reader :name, :version, :dependencies attr_accessor :options def initialize(name, version, options = {}) @name = name raise ArgumentError, 'Invalid version string' unless version.match?(/\A(?:[0-9]+\.)*[0-9]+\z/) @version = version @options = options @dependencies = [] build end def build attach_dependencies end def to_s "#{name} (#{version})" end private def attach_dependencies attach_dependencies_from_path attach_dependencies_from_options end def attach_dependencies_from_path return unless options[:path] config = YAML.load_file(File.join(options[:path], 'joey', 'config.yml')) @dependencies += Array(config['dependencies']).map do |dep| Package::Dependency.new(dep['name'], dep['version']) end end def attach_dependencies_from_options dependencies = options.delete(:dependencies) return unless dependencies.is_a?(Hash) dependencies.each_pair do |name, version_string| @dependencies.push(Package::Dependency.new(name, version_string)) end end end end end end
{ "content_hash": "d35fd8b8060451d18ae154c39d5f88ea", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 104, "avg_line_length": 27.62, "alnum_prop": 0.5655322230267922, "repo_name": "wombatapp/wombat.gem", "id": "4ac92d7f08fc5aeff90390e101679aa81d012d1c", "size": "1412", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/wombat/wundler/package/joey.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "138187" } ], "symlink_target": "" }
<!DOCTYPE html> <!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]--> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CRUDlex\SimpleFilesystemFileProcessor &mdash; CRUDlex 0.11.0 documentation</title> <link rel="stylesheet" href="../_static/css/theme.css" type="text/css" /> <link rel="top" title="CRUDlex 0.11.0 documentation" href="../index.html"/> <link rel="up" title="CRUDlex\FileProcessorInterface" href="FileProcessorInterface.html"/> <link rel="next" title="CRUDlex\ManyValidator" href="ManyValidator.html"/> <link rel="prev" title="CRUDlex\FileProcessorInterface" href="FileProcessorInterface.html"/> <script src="../_static/js/modernizr.min.js"></script> </head> <body class="wy-body-for-nav" role="document"> <div class="wy-grid-for-nav"> <nav data-toggle="wy-nav-shift" class="wy-nav-side"> <div class="wy-side-scroll"> <div class="wy-side-nav-search"> <a href="../index.html" class="icon icon-home"> CRUDlex </a> <div class="version"> 0.11.0 </div> <div role="search"> <form id="rtd-search-form" class="wy-form" action="../search.html" method="get"> <input type="text" name="q" placeholder="Search docs" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> </div> <div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation"> <p class="caption"><span class="caption-text">Manual</span></p> <ul> <li class="toctree-l1"><a class="reference internal" href="../manual/introduction.html">Introduction</a></li> <li class="toctree-l1"><a class="reference internal" href="../manual/setup.html">Setup</a></li> <li class="toctree-l1"><a class="reference internal" href="../manual/datastructures.html">Data Structure Definition</a></li> <li class="toctree-l1"><a class="reference internal" href="../manual/datatypes.html">Data Types</a></li> <li class="toctree-l1"><a class="reference internal" href="../manual/constraints.html">Constraints</a></li> <li class="toctree-l1"><a class="reference internal" href="../manual/layouts.html">Overriding Layouts</a></li> <li class="toctree-l1"><a class="reference internal" href="../manual/templates.html">Overriding Templates</a></li> <li class="toctree-l1"><a class="reference internal" href="../manual/events.html">Events</a></li> <li class="toctree-l1"><a class="reference internal" href="../manual/definitionvalidation.html">Definition Validation</a></li> <li class="toctree-l1"><a class="reference internal" href="../manual/extendedfeatures.html">Extended Features</a></li> <li class="toctree-l1"><a class="reference internal" href="../manual/addons.html">Addons</a></li> <li class="toctree-l1"><a class="reference internal" href="../manual/crudyamlreference.html">CRUD YAML Reference</a></li> </ul> <p class="caption"><span class="caption-text">API</span></p> <ul class="current"> <li class="toctree-l1"><a class="reference internal" href="AbstractData.html">CRUDlex\AbstractData</a></li> <li class="toctree-l1"><a class="reference internal" href="ControllerProvider.html">CRUDlex\ControllerProvider</a></li> <li class="toctree-l1"><a class="reference internal" href="DataFactoryInterface.html">CRUDlex\DataFactoryInterface</a></li> <li class="toctree-l1"><a class="reference internal" href="Entity.html">CRUDlex\Entity</a></li> <li class="toctree-l1"><a class="reference internal" href="EntityDefinition.html">CRUDlex\EntityDefinition</a></li> <li class="toctree-l1"><a class="reference internal" href="EntityDefinitionFactoryInterface.html">CRUDlex\EntityDefinitionFactoryInterface</a></li> <li class="toctree-l1"><a class="reference internal" href="EntityDefinitionValidatorInterface.html">CRUDlex\EntityDefinitionValidatorInterface</a></li> <li class="toctree-l1"><a class="reference internal" href="EntityValidator.html">CRUDlex\EntityValidator</a></li> <li class="toctree-l1 current"><a class="reference internal" href="FileProcessorInterface.html">CRUDlex\FileProcessorInterface</a><ul class="current"> <li class="toctree-l2 current"><a class="current reference internal" href="">CRUDlex\SimpleFilesystemFileProcessor</a></li> </ul> </li> <li class="toctree-l1"><a class="reference internal" href="ManyValidator.html">CRUDlex\ManyValidator</a></li> <li class="toctree-l1"><a class="reference internal" href="MimeTypes.html">CRUDlex\MimeTypes</a></li> <li class="toctree-l1"><a class="reference internal" href="ReferenceValidator.html">CRUDlex\ReferenceValidator</a></li> <li class="toctree-l1"><a class="reference internal" href="ServiceProvider.html">CRUDlex\ServiceProvider</a></li> <li class="toctree-l1"><a class="reference internal" href="StreamedFileResponse.html">CRUDlex\StreamedFileResponse</a></li> <li class="toctree-l1"><a class="reference internal" href="TwigExtensions.html">CRUDlex\TwigExtensions</a></li> <li class="toctree-l1"><a class="reference internal" href="UniqueValidator.html">CRUDlex\UniqueValidator</a></li> </ul> </div> </div> </nav> <section data-toggle="wy-nav-shift" class="wy-nav-content-wrap"> <nav class="wy-nav-top" role="navigation" aria-label="top navigation"> <i data-toggle="wy-nav-top" class="fa fa-bars"></i> <a href="../index.html">CRUDlex</a> </nav> <div class="wy-nav-content"> <div class="rst-content"> <div role="navigation" aria-label="breadcrumbs navigation"> <ul class="wy-breadcrumbs"> <li><a href="../index.html">Docs</a> &raquo;</li> <li><a href="FileProcessorInterface.html">CRUDlex\FileProcessorInterface</a> &raquo;</li> <li>CRUDlex\SimpleFilesystemFileProcessor</li> <li class="wy-breadcrumbs-aside"> <a href="../_sources/api/SimpleFilesystemFileProcessor.txt" rel="nofollow"> View page source</a> </li> </ul> <hr/> </div> <div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article"> <div itemprop="articleBody"> <div class="section" id="crudlex-simplefilesystemfileprocessor"> <h1>CRUDlex\SimpleFilesystemFileProcessor<a class="headerlink" href="#crudlex-simplefilesystemfileprocessor" title="Permalink to this headline">¶</a></h1> <dl class="class"> <dt id="SimpleFilesystemFileProcessor"> <em class="property">class </em><code class="descname">SimpleFilesystemFileProcessor</code><a class="headerlink" href="#SimpleFilesystemFileProcessor" title="Permalink to this definition">¶</a></dt> <dd><p>An implementation of the <a class="reference external" href="mailto:{&#37;&#52;&#48;see">{<span>&#64;</span>see</a> FileProcessorInterface} simply using the file system.</p> <dl class="attr"> <dt id="SimpleFilesystemFileProcessor::$basePath"> <em class="property">property </em><code class="descname">basePath</code><a class="headerlink" href="#SimpleFilesystemFileProcessor::$basePath" title="Permalink to this definition">¶</a></dt> <dd><p>protected</p> <p>Holds the base path where all files will be stored into subfolders.</p> </dd></dl> <dl class="method"> <dt id="SimpleFilesystemFileProcessor::getPath"> <code class="descname">getPath</code><span class="sig-paren">(</span><em>$entityName</em>, <em>Entity $entity</em>, <em>$field</em><span class="sig-paren">)</span><a class="headerlink" href="#SimpleFilesystemFileProcessor::getPath" title="Permalink to this definition">¶</a></dt> <dd><p>Constructs a file system path for the given parameters for storing the file of the file field.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first simple"> <li><strong>$entityName</strong> (<em>string</em>) &#8211; the entity name</li> <li><strong>$entity</strong> (<a class="reference internal" href="Entity.html#Entity" title="Entity"><em>Entity</em></a>) &#8211; the entity</li> <li><strong>$field</strong> (<em>string</em>) &#8211; the file field in the entity</li> </ul> </td> </tr> <tr class="field-even field"><th class="field-name">Returns:</th><td class="field-body"><p class="first last">string the constructed path for storing the file of the file field</p> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="SimpleFilesystemFileProcessor::__construct"> <code class="descname">__construct</code><span class="sig-paren">(</span><em>$basePath = ''</em><span class="sig-paren">)</span><a class="headerlink" href="#SimpleFilesystemFileProcessor::__construct" title="Permalink to this definition">¶</a></dt> <dd><p>Constructor.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>$basePath</strong> (<em>string</em>) &#8211; the base path where all files will be stored into subfolders</li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="SimpleFilesystemFileProcessor::createFile"> <code class="descname">createFile</code><span class="sig-paren">(</span><em>Request $request</em>, <em>Entity $entity</em>, <em>$entityName</em>, <em>$field</em><span class="sig-paren">)</span><a class="headerlink" href="#SimpleFilesystemFileProcessor::createFile" title="Permalink to this definition">¶</a></dt> <dd><p><a class="reference external" href="mailto:{&#37;&#52;&#48;inheritdoc">{<span>&#64;</span>inheritdoc</a>}</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>$request</strong> (<em>Request</em>) &#8211; </li> <li><strong>$entity</strong> (<a class="reference internal" href="Entity.html#Entity" title="Entity"><em>Entity</em></a>) &#8211; </li> <li><strong>$entityName</strong> &#8211; </li> <li><strong>$field</strong> &#8211; </li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="SimpleFilesystemFileProcessor::updateFile"> <code class="descname">updateFile</code><span class="sig-paren">(</span><em>Request $request</em>, <em>Entity $entity</em>, <em>$entityName</em>, <em>$field</em><span class="sig-paren">)</span><a class="headerlink" href="#SimpleFilesystemFileProcessor::updateFile" title="Permalink to this definition">¶</a></dt> <dd><p><a class="reference external" href="mailto:{&#37;&#52;&#48;inheritdoc">{<span>&#64;</span>inheritdoc</a>} For now, this implementation is defensive and doesn&#8217;t delete ever.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>$request</strong> (<em>Request</em>) &#8211; </li> <li><strong>$entity</strong> (<a class="reference internal" href="Entity.html#Entity" title="Entity"><em>Entity</em></a>) &#8211; </li> <li><strong>$entityName</strong> &#8211; </li> <li><strong>$field</strong> &#8211; </li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="SimpleFilesystemFileProcessor::deleteFile"> <code class="descname">deleteFile</code><span class="sig-paren">(</span><em>Entity $entity</em>, <em>$entityName</em>, <em>$field</em><span class="sig-paren">)</span><a class="headerlink" href="#SimpleFilesystemFileProcessor::deleteFile" title="Permalink to this definition">¶</a></dt> <dd><p><a class="reference external" href="mailto:{&#37;&#52;&#48;inheritdoc">{<span>&#64;</span>inheritdoc</a>} For now, this implementation is defensive and doesn&#8217;t delete ever.</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>$entity</strong> (<a class="reference internal" href="Entity.html#Entity" title="Entity"><em>Entity</em></a>) &#8211; </li> <li><strong>$entityName</strong> &#8211; </li> <li><strong>$field</strong> &#8211; </li> </ul> </td> </tr> </tbody> </table> </dd></dl> <dl class="method"> <dt id="SimpleFilesystemFileProcessor::renderFile"> <code class="descname">renderFile</code><span class="sig-paren">(</span><em>Entity $entity</em>, <em>$entityName</em>, <em>$field</em><span class="sig-paren">)</span><a class="headerlink" href="#SimpleFilesystemFileProcessor::renderFile" title="Permalink to this definition">¶</a></dt> <dd><p><a class="reference external" href="mailto:{&#37;&#52;&#48;inheritdoc">{<span>&#64;</span>inheritdoc</a>}</p> <table class="docutils field-list" frame="void" rules="none"> <col class="field-name" /> <col class="field-body" /> <tbody valign="top"> <tr class="field-odd field"><th class="field-name">Parameters:</th><td class="field-body"><ul class="first last simple"> <li><strong>$entity</strong> (<a class="reference internal" href="Entity.html#Entity" title="Entity"><em>Entity</em></a>) &#8211; </li> <li><strong>$entityName</strong> &#8211; </li> <li><strong>$field</strong> &#8211; </li> </ul> </td> </tr> </tbody> </table> </dd></dl> </dd></dl> </div> </div> </div> <footer> <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation"> <a href="ManyValidator.html" class="btn btn-neutral float-right" title="CRUDlex\ManyValidator" accesskey="n">Next <span class="fa fa-arrow-circle-right"></span></a> <a href="FileProcessorInterface.html" class="btn btn-neutral" title="CRUDlex\FileProcessorInterface" accesskey="p"><span class="fa fa-arrow-circle-left"></span> Previous</a> </div> <hr/> <div role="contentinfo"> <p> &copy; Copyright 2017, Philip Lehmann-Böhm. </p> </div> Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/snide/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>. </footer> </div> </div> </section> </div> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT:'../', VERSION:'0.11.0', COLLAPSE_INDEX:false, FILE_SUFFIX:'.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/js/theme.js"></script> <script type="text/javascript"> jQuery(function () { SphinxRtdTheme.StickyNav.enable(); }); </script> </body> </html>
{ "content_hash": "16de5847284add9fb57bbc8593c261dd", "timestamp": "", "source": "github", "line_count": 371, "max_line_length": 312, "avg_line_length": 42.25876010781671, "alnum_prop": 0.6616915422885572, "repo_name": "philiplb/CRUDlex", "id": "480728196cbee80e8a6a9d9625041bcc02cde546", "size": "15690", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "docs/html/0.11.0/api/SimpleFilesystemFileProcessor.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "414" }, { "name": "HTML", "bytes": "52017" }, { "name": "PHP", "bytes": "250769" } ], "symlink_target": "" }
from octopus.core import app from service import dao from octopus.lib import dataobj class ContentLog(dataobj.DataObj, dao.ContentLogDAO): ''' { "id" : "<unique persistent account id>", "created_date" : "<date account created>", "last_updated" : "<date account last modified>", "user" : "<user that requested the content>", "notification": "<the notification the requested content is from>", "filename": ">the requested filename if any", "delivered_from" : "<one of store, proxy, notfound>", } ''' @property def user(self): return self._get_single("user", coerce=self._utf8_unicode()) @user.setter def user(self, user): self._set_single("user", user, coerce=self._utf8_unicode()) @property def notification(self): return self._get_single("notification", coerce=self._utf8_unicode()) @user.setter def notification(self, notification): self._set_single("notification", notification, coerce=self._utf8_unicode()) @property def filename(self): return self._get_single("filename", coerce=self._utf8_unicode()) @user.setter def filename(self, filename): self._set_single("filename", filename, coerce=self._utf8_unicode()) @property def delivered_from(self): return self._get_single("delivered_from", coerce=self._utf8_unicode()) @user.setter def delivered_from(self, delivered_from): self._set_single("delivered_from", delivered_from, coerce=self._utf8_unicode())
{ "content_hash": "b778b42f5313b9f441e4b361aadb980e", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 87, "avg_line_length": 32, "alnum_prop": 0.6403061224489796, "repo_name": "JiscPER/jper", "id": "a659421695ed3209acbfbc67d872174256c7258e", "size": "1569", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "service/models/contentlog.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "8416" }, { "name": "HTML", "bytes": "85910" }, { "name": "JavaScript", "bytes": "31030" }, { "name": "Python", "bytes": "489883" }, { "name": "Shell", "bytes": "6559" } ], "symlink_target": "" }
local ffi = require "ffi" local bit = require "bit" require "include.headers" local c = require "include.constants" local C = ffi.C -- for inet_pton etc, due to be replaced with Lua local types = {} local t, pt, s, ctypes = {}, {}, {}, {} -- types, pointer types and sizes tables types.t, types.pt, types.s, types.ctypes = t, pt, s, ctypes local mt = {} -- metatables local meth = {} -- use 64 bit stat type always local stattypename = "struct stat" if ffi.abi("32bit") then stattypename = "struct stat64" end -- makes code tidier local function istype(tp, x) if ffi.istype(tp, x) then return x else return false end end -- TODO cleanup this (what should provide this?) local signal_reasons_gen = {} local signal_reasons = {} for k, v in pairs(c.SI) do signal_reasons_gen[v] = k end signal_reasons[c.SIG.ILL] = {} for k, v in pairs(c.SIGILL) do signal_reasons[c.SIG.ILL][v] = k end signal_reasons[c.SIG.FPE] = {} for k, v in pairs(c.SIGFPE) do signal_reasons[c.SIG.FPE][v] = k end signal_reasons[c.SIG.SEGV] = {} for k, v in pairs(c.SIGSEGV) do signal_reasons[c.SIG.SEGV][v] = k end signal_reasons[c.SIG.BUS] = {} for k, v in pairs(c.SIGBUS) do signal_reasons[c.SIG.BUS][v] = k end signal_reasons[c.SIG.TRAP] = {} for k, v in pairs(c.SIGTRAP) do signal_reasons[c.SIG.TRAP][v] = k end signal_reasons[c.SIG.CHLD] = {} for k, v in pairs(c.SIGCLD) do signal_reasons[c.SIG.CHLD][v] = k end signal_reasons[c.SIG.POLL] = {} for k, v in pairs(c.SIGPOLL) do signal_reasons[c.SIG.POLL][v] = k end -- endian conversion -- TODO add tests eg for signs. local htonl, htons if ffi.abi("be") then -- nothing to do function htonl(b) return b end else function htonl(b) return bit.bswap(b) end function htons(b) return bit.rshift(bit.bswap(b), 16) end end local ntohl = htonl -- reverse is the same local ntohs = htons -- reverse is the same -- functions we use from man(3) local function strerror(errno) return ffi.string(ffi.C.strerror(errno)) end -- Lua type constructors corresponding to defined types -- basic types -- cast to pointer to a type. could generate for all types. local function ptt(tp) local ptp = ffi.typeof("$ *", tp) return function(x) return ffi.cast(ptp, x) end end local function addtype(name, tp, mt) if mt then t[name] = ffi.metatype(tp, mt) else t[name] = ffi.typeof(tp) end ctypes[tp] = t[name] pt[name] = ptt(t[name]) s[name] = ffi.sizeof(t[name]) end local metatype = addtype local addtypes = { char = "char", uchar = "unsigned char", int = "int", uint = "unsigned int", uint16 = "uint16_t", int32 = "int32_t", uint32 = "uint32_t", int64 = "int64_t", uint64 = "uint64_t", long = "long", ulong = "unsigned long", uintptr = "uintptr_t", size = "size_t", mode = "mode_t", dev = "dev_t", loff = "loff_t", pid = "pid_t", aio_context = "aio_context_t", sa_family = "sa_family_t", fdset = "fd_set", msghdr = "struct msghdr", cmsghdr = "struct cmsghdr", ucred = "struct ucred", sysinfo = "struct sysinfo", epoll_event = "struct epoll_event", nlmsghdr = "struct nlmsghdr", rtgenmsg = "struct rtgenmsg", rtmsg = "struct rtmsg", ifinfomsg = "struct ifinfomsg", ifaddrmsg = "struct ifaddrmsg", rtattr = "struct rtattr", rta_cacheinfo = "struct rta_cacheinfo", nlmsgerr = "struct nlmsgerr", timex = "struct timex", utsname = "struct utsname", fdb_entry = "struct fdb_entry", iocb = "struct iocb", sighandler = "sighandler_t", sigaction = "struct sigaction", clockid = "clockid_t", io_event = "struct io_event", seccomp_data = "struct seccomp_data", iovec = "struct iovec", rtnl_link_stats = "struct rtnl_link_stats", statfs = "struct statfs64", ifreq = "struct ifreq", dirent = "struct linux_dirent64", ifa_cacheinfo = "struct ifa_cacheinfo", flock = "struct flock64", mqattr = "struct mq_attr", } for k, v in pairs(addtypes) do addtype(k, v) end -- these ones not in table as not helpful with vararg or arrays t.inotify_event = ffi.typeof("struct inotify_event") t.epoll_events = ffi.typeof("struct epoll_event[?]") -- TODO add metatable, like pollfds t.io_events = ffi.typeof("struct io_event[?]") t.iocbs = ffi.typeof("struct iocb[?]") t.iocb_ptrs = ffi.typeof("struct iocb *[?]") t.string_array = ffi.typeof("const char *[?]") t.ints = ffi.typeof("int[?]") t.buffer = ffi.typeof("char[?]") t.int1 = ffi.typeof("int[1]") t.int64_1 = ffi.typeof("int64_t[1]") t.uint64_1 = ffi.typeof("uint64_t[1]") t.socklen1 = ffi.typeof("socklen_t[1]") t.off1 = ffi.typeof("off_t[1]") t.loff1 = ffi.typeof("loff_t[1]") t.uid1 = ffi.typeof("uid_t[1]") t.gid1 = ffi.typeof("gid_t[1]") t.int2 = ffi.typeof("int[2]") t.timespec2 = ffi.typeof("struct timespec[2]") -- still need pointers to these pt.inotify_event = ptt(t.inotify_event) -- types with metatypes -- fd type. This will be overridden by syscall as it adds methods -- so this is the minimal one necessary to provide the interface eg does not gc file -- TODO add tests once types is standalone --[[ mt.fd = { __index = { getfd = function(fd) return fd.fileno end, }, __new = function(tp, i) return istype(tp, i) or ffi.new(tp, i) end } metatype("fd", "struct {int fileno;}", mt.fd) ]] -- even simpler version, just pass numbers t.fd = function(fd) return tonumber(fd) end -- can replace with a different t.fd function local function getfd(fd) if type(fd) == "number" or ffi.istype(t.int, fd) then return fd end return fd:getfd() end metatype("error", "struct {int errno;}", { __tostring = function(e) return strerror(e.errno) end, __index = function(t, k) if k == 'sym' then return errsyms[t.errno] end if k == 'lsym' then return errsyms[t.errno]:sub(2):lower() end if c.E[k] then return c.E[k] == t.errno end local uk = c.E['E' .. k:upper()] if uk then return uk == t.errno end end, __new = function(tp, errno) if not errno then errno = ffi.errno() end return ffi.new(tp, errno) end }) -- cast socket address to actual type based on family local samap, samap2 = {}, {} meth.sockaddr = { index = { family = function(sa) return sa.sa_family end, } } metatype("sockaddr", "struct sockaddr", { __index = function(sa, k) if meth.sockaddr.index[k] then return meth.sockaddr.index[k](sa) end end, }) meth.sockaddr_storage = { index = { family = function(sa) return sa.ss_family end, }, newindex = { family = function(sa, v) sa.ss_family = c.AF[v] end, } } -- experiment, see if we can use this as generic type, to avoid allocations. metatype("sockaddr_storage", "struct sockaddr_storage", { __index = function(sa, k) if meth.sockaddr_storage.index[k] then return meth.sockaddr_storage.index[k](sa) end local st = samap2[sa.ss_family] if st then local cs = st(sa) return cs[k] end end, __newindex = function(sa, k, v) if meth.sockaddr_storage.newindex[k] then meth.sockaddr_storage.newindex[k](sa, v) return end local st = samap2[sa.ss_family] if st then local cs = st(sa) cs[k] = v end end, __new = function(tp, init) local ss = ffi.new(tp) local family if init and init.family then family = c.AF[init.family] end local st if family then st = samap2[family] ss.ss_family = family init.family = nil end if st then local cs = st(ss) for k, v in pairs(init) do cs[k] = v end end return ss end, }) meth.sockaddr_in = { index = { family = function(sa) return sa.sin_family end, port = function(sa) return ntohs(sa.sin_port) end, addr = function(sa) return sa.sin_addr end, }, newindex = { port = function(sa, v) sa.sin_port = htons(v) end } } metatype("sockaddr_in", "struct sockaddr_in", { __index = function(sa, k) if meth.sockaddr_in.index[k] then return meth.sockaddr_in.index[k](sa) end end, __newindex = function(sa, k, v) if meth.sockaddr_in.newindex[k] then meth.sockaddr_in.newindex[k](sa, v) end end, __new = function(tp, port, addr) -- TODO allow table init if not ffi.istype(t.in_addr, addr) then addr = t.in_addr(addr) if not addr then return end end return ffi.new(tp, c.AF.INET, htons(port or 0), addr) end }) meth.sockaddr_in6 = { index = { family = function(sa) return sa.sin6_family end, port = function(sa) return ntohs(sa.sin6_port) end, addr = function(sa) return sa.sin6_addr end, }, newindex = { port = function(sa, v) sa.sin6_port = htons(v) end } } metatype("sockaddr_in6", "struct sockaddr_in6", { __index = function(sa, k) if meth.sockaddr_in6.index[k] then return meth.sockaddr_in6.index[k](sa) end end, __newindex = function(sa, k, v) if meth.sockaddr_in6.newindex[k] then meth.sockaddr_in6.newindex[k](sa, v) end end, __new = function(tp, port, addr, flowinfo, scope_id) -- reordered initialisers. TODO allow table init if not ffi.istype(t.in6_addr, addr) then addr = t.in6_addr(addr) if not addr then return end end return ffi.new(tp, c.AF.INET6, htons(port or 0), flowinfo or 0, addr, scope_id or 0) end }) meth.sockaddr_un = { index = { family = function(sa) return sa.un_family end, }, } metatype("sockaddr_un", "struct sockaddr_un", { __index = function(sa, k) if meth.sockaddr_un.index[k] then return meth.sockaddr_un.index[k](sa) end end, __new = function(tp) return ffi.new(tp, c.AF.UNIX) end, }) -- this is a bit odd, but we actually use Lua metatables for sockaddr_un, and use t.sa to multiplex mt.sockaddr_un = { __index = function(un, k) local sa = un.addr if k == 'family' then return tonumber(sa.sun_family) end local namelen = un.addrlen - s.sun_family if namelen > 0 then if sa.sun_path[0] == 0 then if k == 'abstract' then return true end if k == 'name' then return ffi.string(rets.addr.sun_path, namelen) end -- should we also remove leading \0? else if k == 'name' then return ffi.string(rets.addr.sun_path) end end else if k == 'unnamed' then return true end end end } function t.sa(addr, addrlen) local family = addr.family if family == c.AF.UNIX then -- we return Lua metatable not metatype, as need length to decode local sa = t.sockaddr_un() ffi.copy(sa, addr, addrlen) return setmetatable({addr = sa, addrlen = addrlen}, mt.sockaddr_un) end return addr end local nlgroupmap = { -- map from netlink socket type to group names. Note there are two forms of name though, bits and shifts. [c.NETLINK.ROUTE] = c.RTMGRP, -- or RTNLGRP_ and shift not mask TODO make shiftflags function -- add rest of these -- [c.NETLINK.SELINUX] = c.SELNLGRP, } meth.sockaddr_nl = { index = { family = function(sa) return sa.nl_family end, pid = function(sa) return sa.nl_pid end, groups = function(sa) return sa.nl_groups end, }, newindex = { pid = function(sa, v) sa.nl_pid = v end, groups = function(sa, v) sa.nl_groups = v end, } } metatype("sockaddr_nl", "struct sockaddr_nl", { __index = function(sa, k) if meth.sockaddr_nl.index[k] then return meth.sockaddr_nl.index[k](sa) end end, __newindex = function(sa, k, v) if meth.sockaddr_nl.newindex[k] then meth.sockaddr_nl.newindex[k](sa, v) end end, __new = function(tp, pid, groups, nltype) if type(pid) == "table" then local tb = pid pid, groups, nltype = tb.nl_pid or tb.pid, tb.nl_groups or tb.groups, tb.type end if nltype and nlgroupmap[nltype] then groups = nlgroupmap[nltype][groups] end -- see note about shiftflags return ffi.new(tp, {nl_family = c.AF.NETLINK, nl_pid = pid, nl_groups = groups}) end, }) -- 64 to 32 bit conversions via unions TODO use meth not object? if ffi.abi("le") then mt.i6432 = { __index = { to32 = function(u) return u.i32[1], u.i32[0] end, } } else mt.i6432 = { __index = { to32 = function(u) return u.i32[0], u.i32[1] end, } } end t.i6432 = ffi.metatype("union {int64_t i64; int32_t i32[2];}", mt.i6432) t.u6432 = ffi.metatype("union {uint64_t i64; uint32_t i32[2];}", mt.i6432) -- Lua metatables where we cannot return an ffi type eg value is an array or integer or otherwise problematic -- TODO should we change to meth mt.device = { __index = { major = function(dev) local h, l = t.i6432(dev.dev):to32() return bit.bor(bit.band(bit.rshift(l, 8), 0xfff), bit.band(h, bit.bnot(0xfff))); end, minor = function(dev) local h, l = t.i6432(dev.dev):to32() return bit.bor(bit.band(l, 0xff), bit.band(bit.rshift(l, 12), bit.bnot(0xff))); end, device = function(dev) return tonumber(dev.dev) end, }, } t.device = function(major, minor) local dev = major if minor then dev = bit.bor(bit.band(minor, 0xff), bit.lshift(bit.band(major, 0xfff), 8), bit.lshift(bit.band(minor, bit.bnot(0xff)), 12)) + 0x100000000 * bit.band(major, bit.bnot(0xfff)) end return setmetatable({dev = t.dev(dev)}, mt.device) end meth.stat = { index = { dev = function(st) return t.device(st.st_dev) end, ino = function(st) return tonumber(st.st_ino) end, mode = function(st) return st.st_mode end, nlink = function(st) return st.st_nlink end, uid = function(st) return st.st_uid end, gid = function(st) return st.st_gid end, rdev = function(st) return tonumber(st.st_rdev) end, size = function(st) return tonumber(st.st_size) end, blksize = function(st) return tonumber(st.st_blksize) end, blocks = function(st) return tonumber(st.st_blocks) end, atime = function(st) return tonumber(st.st_atime) end, ctime = function(st) return tonumber(st.st_ctime) end, mtime = function(st) return tonumber(st.st_mtime) end, rdev = function(st) return t.device(st.st_rdev) end, isreg = function(st) return bit.band(st.st_mode, c.S.IFMT) == c.S.IFREG end, isdir = function(st) return bit.band(st.st_mode, c.S.IFMT) == c.S.IFDIR end, ischr = function(st) return bit.band(st.st_mode, c.S.IFMT) == c.S.IFCHR end, isblk = function(st) return bit.band(st.st_mode, c.S.IFMT) == c.S.IFBLK end, isfifo = function(st) return bit.band(st.st_mode, c.S.IFMT) == c.S.IFIFO end, islnk = function(st) return bit.band(st.st_mode, c.S.IFMT) == c.S.IFLNK end, issock = function(st) return bit.band(st.st_mode, c.S.IFMT) == c.S.IFSOCK end, } } metatype("stat", stattypename, { -- either struct stat on 64 bit or struct stat64 on 32 bit __index = function(st, k) if meth.stat.index[k] then return meth.stat.index[k](st) end end, }) meth.siginfo = { index = { si_pid = function(s) return s.sifields.kill.si_pid end, si_uid = function(s) return s.sifields.kill.si_uid end, si_timerid = function(s) return s.sifields.timer.si_tid end, si_overrun = function(s) return s.sifields.timer.si_overrun end, si_status = function(s) return s.sifields.sigchld.si_status end, si_utime = function(s) return s.sifields.sigchld.si_utime end, si_stime = function(s) return s.sifields.sigchld.si_stime end, si_value = function(s) return s.sifields.rt.si_sigval end, si_int = function(s) return s.sifields.rt.si_sigval.sival_int end, si_ptr = function(s) return s.sifields.rt.si_sigval.sival_ptr end, si_addr = function(s) return s.sifields.sigfault.si_addr end, si_band = function(s) return s.sifields.sigpoll.si_band end, si_fd = function(s) return s.sifields.sigpoll.si_fd end, }, newindex = { si_pid = function(s, v) s.sifields.kill.si_pid = v end, si_uid = function(s, v) s.sifields.kill.si_uid = v end, si_timerid = function(s, v) s.sifields.timer.si_tid = v end, si_overrun = function(s, v) s.sifields.timer.si_overrun = v end, si_status = function(s, v) s.sifields.sigchld.si_status = v end, si_utime = function(s, v) s.sifields.sigchld.si_utime = v end, si_stime = function(s, v) s.sifields.sigchld.si_stime = v end, si_value = function(s, v) s.sifields.rt.si_sigval = v end, si_int = function(s, v) s.sifields.rt.si_sigval.sival_int = v end, si_ptr = function(s, v) s.sifields.rt.si_sigval.sival_ptr = v end, si_addr = function(s, v) s.sifields.sigfault.si_addr = v end, si_band = function(s, v) s.sifields.sigpoll.si_band = v end, si_fd = function(s, v) s.sifields.sigpoll.si_fd = v end, } } metatype("siginfo", "struct siginfo", { __index = function(t, k) if meth.siginfo.index[k] then return meth.siginfo.index[k](t) end end, __newindex = function(t, k, v) if meth.siginfo.newindex[k] then meth.siginfo.newindex[k](t, v) end end, }) metatype("macaddr", "struct {uint8_t mac_addr[6];}", { __tostring = function(m) local hex = {} for i = 1, 6 do hex[i] = string.format("%02x", m.mac_addr[i - 1]) end return table.concat(hex, ":") end, __new = function(tp, str) local mac = ffi.new(tp) if str then for i = 1, 6 do local n = tonumber(str:sub(i * 3 - 2, i * 3 - 1), 16) -- TODO more checks on syntax mac.mac_addr[i - 1] = n end end return mac end, }) meth.timeval = { index = { time = function(tv) return tonumber(tv.tv_sec) + tonumber(tv.tv_usec) / 1000000 end, sec = function(tv) return tonumber(tv.tv_sec) end, usec = function(tv) return tonumber(tv.tv_usec) end, }, newindex = { time = function(tv, v) local i, f = math.modf(v) tv.tv_sec, tv.tv_usec = i, math.floor(f * 1000000) end, sec = function(tv, v) tv.tv_sec = v end, usec = function(tv, v) tv.tv_usec = v end, } } meth.rlimit = { index = { cur = function(r) return tonumber(r.rlim_cur) end, max = function(r) return tonumber(r.rlim_max) end, } } metatype("rlimit", "struct rlimit64", { __index = function(r, k) if meth.rlimit.index[k] then return meth.rlimit.index[k](r) end end, }) metatype("timeval", "struct timeval", { __index = function(tv, k) if meth.timeval.index[k] then return meth.timeval.index[k](tv) end end, __newindex = function(tv, k, v) if meth.timeval.newindex[k] then meth.timeval.newindex[k](tv, v) end end, __new = function(tp, v) if not v then v = {0, 0} end if type(v) ~= "number" then return ffi.new(tp, v) end local ts = ffi.new(tp) ts.time = v return ts end }) meth.timespec = { index = { time = function(tv) return tonumber(tv.tv_sec) + tonumber(tv.tv_nsec) / 1000000000 end, sec = function(tv) return tonumber(tv.tv_sec) end, nsec = function(tv) return tonumber(tv.tv_nsec) end, }, newindex = { time = function(tv, v) local i, f = math.modf(v) tv.tv_sec, tv.tv_nsec = i, math.floor(f * 1000000000) end, sec = function(tv, v) tv.tv_sec = v end, nsec = function(tv, v) tv.tv_nsec = v end, } } metatype("timespec", "struct timespec", { __index = function(tv, k) if meth.timespec.index[k] then return meth.timespec.index[k](tv) end end, __newindex = function(tv, k, v) if meth.timespec.newindex[k] then meth.timespec.newindex[k](tv, v) end end, __new = function(tp, v) if not v then v = {0, 0} end if type(v) ~= "number" then return ffi.new(tp, v) end local ts = ffi.new(tp) ts.time = v return ts end }) local function itnormal(v) if not v then v = {{0, 0}, {0, 0}} end if v.interval then v.it_interval = v.interval v.interval = nil end if v.value then v.it_value = v.value v.value = nil end if not v.it_interval then v.it_interval = v[1] v[1] = nil end if not v.it_value then v.it_value = v[2] v[2] = nil end return v end meth.itimerspec = { index = { interval = function(it) return it.it_interval end, value = function(it) return it.it_value end, } } metatype("itimerspec", "struct itimerspec", { __index = function(it, k) if meth.itimerspec.index[k] then return meth.itimerspec.index[k](it) end end, __new = function(tp, v) v = itnormal(v) v.it_interval = istype(t.timespec, v.it_interval) or t.timespec(v.it_interval) v.it_value = istype(t.timespec, v.it_value) or t.timespec(v.it_value) return ffi.new(tp, v) end }) metatype("itimerval", "struct itimerval", { __index = function(it, k) if meth.itimerspec.index[k] then return meth.itimerspec.index[k](it) end end, -- can use same meth __new = function(tp, v) v = itnormal(v) v.it_interval = istype(t.timeval, v.it_interval) or t.timeval(v.it_interval) v.it_value = istype(t.timeval, v.it_value) or t.timeval(v.it_value) return ffi.new(tp, v) end }) mt.iovecs = { __index = function(io, k) return io.iov[k - 1] end, __newindex = function(io, k, v) v = istype(t.iovec, v) or t.iovec(v) ffi.copy(io.iov[k - 1], v, s.iovec) end, __len = function(io) return io.count end, __new = function(tp, is) if type(is) == 'number' then return ffi.new(tp, is, is) end local count = #is local iov = ffi.new(tp, count, count) for n = 1, count do local i = is[n] if type(i) == 'string' then local buf = t.buffer(#i) ffi.copy(buf, i, #i) iov[n].iov_base = buf iov[n].iov_len = #i elseif type(i) == 'number' then iov[n].iov_base = t.buffer(i) iov[n].iov_len = i elseif ffi.istype(t.iovec, i) then ffi.copy(iov[n], i, s.iovec) elseif type(i) == 'cdata' then -- eg buffer or other structure iov[n].iov_base = i iov[n].iov_len = ffi.sizeof(i) else -- eg table iov[n] = i end end return iov end } t.iovecs = ffi.metatype("struct { int count; struct iovec iov[?];}", mt.iovecs) -- do not use metatype helper as variable size metatype("pollfd", "struct pollfd", { __index = function(t, k) if k == 'getfd' then return t.fd end -- TODO use meth return bit.band(t.revents, c.POLL[k]) ~= 0 end }) mt.pollfds = { __index = function(p, k) return p.pfd[k - 1] end, __newindex = function(p, k, v) v = istype(t.pollfd, v) or t.pollfd(v) ffi.copy(p.pfd[k - 1], v, s.pollfd) end, __len = function(p) return p.count end, __new = function(tp, ps) if type(ps) == 'number' then return ffi.new(tp, ps, ps) end local count = #ps local fds = ffi.new(tp, count, count) for n = 1, count do fds[n].fd = ps[n].fd:getfd() fds[n].events = c.POLL[ps[n].events] fds[n].revents = 0 end return fds end, } t.pollfds = ffi.metatype("struct {int count; struct pollfd pfd[?];}", mt.pollfds) meth.signalfd = { index = { signo = function(ss) return tonumber(ss.ssi_signo) end, code = function(ss) return tonumber(ss.ssi_code) end, pid = function(ss) return tonumber(ss.ssi_pid) end, uid = function(ss) return tonumber(ss.ssi_uid) end, fd = function(ss) return tonumber(ss.ssi_fd) end, tid = function(ss) return tonumber(ss.ssi_tid) end, band = function(ss) return tonumber(ss.ssi_band) end, overrun = function(ss) return tonumber(ss.ssi_overrun) end, trapno = function(ss) return tonumber(ss.ssi_trapno) end, status = function(ss) return tonumber(ss.ssi_status) end, int = function(ss) return tonumber(ss.ssi_int) end, ptr = function(ss) return ss.ss_ptr end, utime = function(ss) return tonumber(ss.ssi_utime) end, stime = function(ss) return tonumber(ss.ssi_stime) end, addr = function(ss) return ss.ss_addr end, }, } metatype("signalfd_siginfo", "struct signalfd_siginfo", { __index = function(ss, k) if ss.ssi_signo == c.SIG(k) then return true end local rname = signal_reasons_gen[ss.ssi_code] if not rname and signal_reasons[ss.ssi_signo] then rname = signal_reasons[ss.ssi_signo][ss.ssi_code] end if rname == k then return true end if rname == k:upper() then return true end -- TODO use some metatable to hide this? if meth.signalfd.index[k] then return meth.signalfd.index[k](ss) end end, }) mt.siginfos = { __index = function(ss, k) return ss.sfd[k - 1] end, __len = function(p) return p.count end, __new = function(tp, ss) return ffi.new(tp, ss, ss, ss * s.signalfd_siginfo) end, } t.siginfos = ffi.metatype("struct {int count, bytes; struct signalfd_siginfo sfd[?];}", mt.siginfos) local INET6_ADDRSTRLEN = 46 local function inet_ntop(af, src) af = c.AF[af] -- TODO do not need, in fact could split into two functions if no need to export. if af == c.AF.INET then local b = pt.uchar(src) return tonumber(b[0]) .. "." .. tonumber(b[1]) .. "." .. tonumber(b[2]) .. "." .. tonumber(b[3]) end local len = INET6_ADDRSTRLEN local dst = t.buffer(len) local ret = C.inet_ntop(af, src, dst, len) -- TODO replace with pure Lua if ret == nil then return nil, t.error() end return ffi.string(dst) end local function inet_pton(af, src, addr) af = c.AF[af] if not addr then addr = t.addrtype[af]() end local ret = C.inet_pton(af, src, addr) -- TODO redo in pure Lua if ret == -1 then return nil, t.error() end if ret == 0 then return nil end -- maybe return string return addr end -- TODO add generic address type that works out which to take? basically inet_name, except without netmask metatype("in_addr", "struct in_addr", { __tostring = function(a) return inet_ntop(c.AF.INET, a) end, __new = function(tp, s) local addr = ffi.new(tp) if s then addr = inet_pton(c.AF.INET, s, addr) end return addr end }) metatype("in6_addr", "struct in6_addr", { __tostring = function(a) return inet_ntop(c.AF.INET6, a) end, __new = function(tp, s) local addr = ffi.new(tp) if s then addr = inet_pton(c.AF.INET6, s, addr) end return addr end }) t.addrtype = { [c.AF.INET] = t.in_addr, [c.AF.INET6] = t.in6_addr, } -- signal set handlers TODO replace with metatypes, reuse code from stringflags local function sigismember(set, sig) local d = bit.rshift(sig - 1, 5) -- always 32 bits return bit.band(set.val[d], bit.lshift(1, (sig - 1) % 32)) ~= 0 end local function sigemptyset(set) for i = 0, s.sigset / 4 - 1 do if set.val[i] ~= 0 then return false end end return true end local function sigaddset(set, sig) set = t.sigset(set) local d = bit.rshift(sig - 1, 5) set.val[d] = bit.bor(set.val[d], bit.lshift(1, (sig - 1) % 32)) return set end local function sigdelset(set, sig) set = t.sigset(set) local d = bit.rshift(sig - 1, 5) set.val[d] = bit.band(set.val[d], bit.bnot(bit.lshift(1, (sig - 1) % 32))) return set end -- TODO remove duplication of split and trim as this should all be in constants, metatypes local function split(delimiter, text) if delimiter == "" then return {text} end if #text == 0 then return {} end local list = {} local pos = 1 while true do local first, last = text:find(delimiter, pos) if first then list[#list + 1] = text:sub(pos, first - 1) pos = last + 1 else list[#list + 1] = text:sub(pos) break end end return list end local function trim(s) -- TODO should replace underscore with space return (s:gsub("^%s*(.-)%s*$", "%1")) end local function sigaddsets(set, sigs) -- allow multiple if type(sigs) ~= "string" then return sigaddset(set, sigs) end set = t.sigset(set) local a = split(",", sigs) for i, v in ipairs(a) do local s = trim(v) local sig = c.SIG[s] if not sig then error("invalid signal: " .. v) end -- don't use this format if you don't want exceptions, better than silent ignore sigaddset(set, sig) end return set end local function sigdelsets(set, sigs) -- allow multiple if type(sigs) ~= "string" then return sigdelset(set, sigs) end set = t.sigset(set) local a = split(",", sigs) for i, v in ipairs(a) do local s = trim(v) local sig = c.SIG[s] if not sig then error("invalid signal: " .. v) end -- don't use this format if you don't want exceptions, better than silent ignore sigdelset(set, sig) end return set end metatype("sigset", "sigset_t", { __index = function(set, k) if k == 'add' then return sigaddsets end if k == 'del' then return sigdelsets end if k == 'isemptyset' then return sigemptyset(set) end local sig = c.SIG[k] if sig then return sigismember(set, sig) end end, __new = function(tp, str) if ffi.istype(tp, str) then return str end if not str then return ffi.new(tp) end local f = ffi.new(tp) local a = split(",", str) for i, v in ipairs(a) do local st = trim(v) local sig = c.SIG[st] if not sig then error("invalid signal: " .. v) end -- don't use this format if you don't want exceptions, better than silent ignore local d = bit.rshift(sig - 1, 5) -- always 32 bits f.val[d] = bit.bor(f.val[d], bit.lshift(1, (sig - 1) % 32)) end return f end, }) local voidp = ffi.typeof("void *") pt.void = function(x) return ffi.cast(voidp, x) end -- these are declared above samap = { [c.AF.UNIX] = t.sockaddr_un, [c.AF.INET] = t.sockaddr_in, [c.AF.INET6] = t.sockaddr_in6, [c.AF.NETLINK] = t.sockaddr_nl, } samap2 = { [c.AF.UNIX] = pt.sockaddr_un, [c.AF.INET] = pt.sockaddr_in, [c.AF.INET6] = pt.sockaddr_in6, [c.AF.NETLINK] = pt.sockaddr_nl, } -- slightly miscellaneous types, eg need to use Lua metatables -- TODO convert to use constants? note missing some macros eg WCOREDUMP(). Allow lower case. mt.wait = { __index = function(w, k) local WTERMSIG = bit.band(w.status, 0x7f) local EXITSTATUS = bit.rshift(bit.band(w.status, 0xff00), 8) local WIFEXITED = (WTERMSIG == 0) local tab = { WIFEXITED = WIFEXITED, WIFSTOPPED = bit.band(w.status, 0xff) == 0x7f, WIFSIGNALED = not WIFEXITED and bit.band(w.status, 0x7f) ~= 0x7f -- I think this is right????? TODO recheck, cleanup } if tab.WIFEXITED then tab.EXITSTATUS = EXITSTATUS end if tab.WIFSTOPPED then tab.WSTOPSIG = EXITSTATUS end if tab.WIFSIGNALED then tab.WTERMSIG = WTERMSIG end if tab[k] then return tab[k] end local uc = 'W' .. k:upper() if tab[uc] then return tab[uc] end end } -- cannot really use metatype here, as status is just an int, and we need to pass pid function t.wait(pid, status) return setmetatable({pid = pid, status = status}, mt.wait) end return types
{ "content_hash": "ac73eff1a525d12fc2d3f0ce576e3114", "timestamp": "", "source": "github", "line_count": 966, "max_line_length": 195, "avg_line_length": 31.21946169772257, "alnum_prop": 0.6382386099873997, "repo_name": "lukego/ljsyscall", "id": "7854460e1dba76a5d3ba54284b430f5d9ff6b7d5", "size": "30637", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/types.lua", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
package org.elasticsearch.action.support.broadcast; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.NoShardAvailableActionException; import org.elasticsearch.action.support.ActionFilters; import org.elasticsearch.action.support.TransportAction; import org.elasticsearch.action.support.TransportActions; import org.elasticsearch.cluster.ClusterService; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.block.ClusterBlockException; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.routing.GroupShardsIterator; import org.elasticsearch.cluster.routing.ShardIterator; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReferenceArray; /** * */ public abstract class TransportBroadcastOperationAction<Request extends BroadcastOperationRequest, Response extends BroadcastOperationResponse, ShardRequest extends BroadcastShardOperationRequest, ShardResponse extends BroadcastShardOperationResponse> extends TransportAction<Request, Response> { protected final ThreadPool threadPool; protected final ClusterService clusterService; protected final TransportService transportService; final String transportShardAction; final String executor; protected TransportBroadcastOperationAction(Settings settings, String actionName, ThreadPool threadPool, ClusterService clusterService, TransportService transportService, ActionFilters actionFilters) { super(settings, actionName, threadPool, actionFilters); this.clusterService = clusterService; this.transportService = transportService; this.threadPool = threadPool; this.transportShardAction = actionName + "/s"; this.executor = executor(); transportService.registerHandler(actionName, new TransportHandler()); transportService.registerHandler(transportShardAction, new ShardTransportHandler()); } @Override protected void doExecute(Request request, ActionListener<Response> listener) { new AsyncBroadcastAction(request, listener).start(); } protected abstract String executor(); protected abstract Request newRequest(); protected abstract Response newResponse(Request request, AtomicReferenceArray shardsResponses, ClusterState clusterState); protected abstract ShardRequest newShardRequest(); protected abstract ShardRequest newShardRequest(int numShards, ShardRouting shard, Request request); protected abstract ShardResponse newShardResponse(); protected abstract ShardResponse shardOperation(ShardRequest request) throws ElasticsearchException; /** * Determines the shards this operation will be executed on. The operation is executed once per shard iterator, typically * on the first shard in it. If the operation fails, it will be retried on the next shard in the iterator. */ protected abstract GroupShardsIterator shards(ClusterState clusterState, Request request, String[] concreteIndices); protected abstract ClusterBlockException checkGlobalBlock(ClusterState state, Request request); protected abstract ClusterBlockException checkRequestBlock(ClusterState state, Request request, String[] concreteIndices); class AsyncBroadcastAction { private final Request request; private final ActionListener<Response> listener; private final ClusterState clusterState; private final DiscoveryNodes nodes; private final GroupShardsIterator shardsIts; private final int expectedOps; private final AtomicInteger counterOps = new AtomicInteger(); private final AtomicReferenceArray shardsResponses; AsyncBroadcastAction(Request request, ActionListener<Response> listener) { this.request = request; this.listener = listener; clusterState = clusterService.state(); ClusterBlockException blockException = checkGlobalBlock(clusterState, request); if (blockException != null) { throw blockException; } // update to concrete indices String[] concreteIndices = clusterState.metaData().concreteIndices(request.indicesOptions(), request.indices()); blockException = checkRequestBlock(clusterState, request, concreteIndices); if (blockException != null) { throw blockException; } nodes = clusterState.nodes(); logger.trace("resolving shards based on cluster state version [{}]", clusterState.version()); shardsIts = shards(clusterState, request, concreteIndices); expectedOps = shardsIts.size(); shardsResponses = new AtomicReferenceArray<Object>(expectedOps); } public void start() { if (shardsIts.size() == 0) { // no shards try { listener.onResponse(newResponse(request, new AtomicReferenceArray(0), clusterState)); } catch (Throwable e) { listener.onFailure(e); } return; } request.beforeStart(); // count the local operations, and perform the non local ones int shardIndex = -1; for (final ShardIterator shardIt : shardsIts) { shardIndex++; final ShardRouting shard = shardIt.nextOrNull(); if (shard != null) { performOperation(shardIt, shard, shardIndex); } else { // really, no shards active in this group onOperation(null, shardIt, shardIndex, new NoShardAvailableActionException(shardIt.shardId())); } } } void performOperation(final ShardIterator shardIt, final ShardRouting shard, final int shardIndex) { if (shard == null) { // no more active shards... (we should not really get here, just safety) onOperation(null, shardIt, shardIndex, new NoShardAvailableActionException(shardIt.shardId())); } else { try { final ShardRequest shardRequest = newShardRequest(shardIt.size(), shard, request); if (shard.currentNodeId().equals(nodes.localNodeId())) { threadPool.executor(executor).execute(new Runnable() { @Override public void run() { try { onOperation(shard, shardIndex, shardOperation(shardRequest)); } catch (Throwable e) { onOperation(shard, shardIt, shardIndex, e); } } }); } else { DiscoveryNode node = nodes.get(shard.currentNodeId()); if (node == null) { // no node connected, act as failure onOperation(shard, shardIt, shardIndex, new NoShardAvailableActionException(shardIt.shardId())); } else { transportService.sendRequest(node, transportShardAction, shardRequest, new BaseTransportResponseHandler<ShardResponse>() { @Override public ShardResponse newInstance() { return newShardResponse(); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void handleResponse(ShardResponse response) { onOperation(shard, shardIndex, response); } @Override public void handleException(TransportException e) { onOperation(shard, shardIt, shardIndex, e); } }); } } } catch (Throwable e) { onOperation(shard, shardIt, shardIndex, e); } } } @SuppressWarnings({"unchecked"}) void onOperation(ShardRouting shard, int shardIndex, ShardResponse response) { shardsResponses.set(shardIndex, response); if (expectedOps == counterOps.incrementAndGet()) { finishHim(); } } @SuppressWarnings({"unchecked"}) void onOperation(@Nullable ShardRouting shard, final ShardIterator shardIt, int shardIndex, Throwable t) { // we set the shard failure always, even if its the first in the replication group, and the next one // will work (it will just override it...) setFailure(shardIt, shardIndex, t); ShardRouting nextShard = shardIt.nextOrNull(); if (nextShard != null) { if (t != null) { if (logger.isTraceEnabled()) { if (!TransportActions.isShardNotAvailableException(t)) { logger.trace("{}: failed to execute [{}]", t, shard != null ? shard.shortSummary() : shardIt.shardId(), request); } } } performOperation(shardIt, nextShard, shardIndex); } else { if (logger.isDebugEnabled()) { if (t != null) { if (!TransportActions.isShardNotAvailableException(t)) { logger.debug("{}: failed to executed [{}]", t, shard != null ? shard.shortSummary() : shardIt.shardId(), request); } } } if (expectedOps == counterOps.incrementAndGet()) { finishHim(); } } } void finishHim() { try { listener.onResponse(newResponse(request, shardsResponses, clusterState)); } catch (Throwable e) { listener.onFailure(e); } } void setFailure(ShardIterator shardIt, int shardIndex, Throwable t) { // we don't aggregate shard failures on non active shards (but do keep the header counts right) if (TransportActions.isShardNotAvailableException(t)) { return; } if (!(t instanceof BroadcastShardOperationFailedException)) { t = new BroadcastShardOperationFailedException(shardIt.shardId(), t); } Object response = shardsResponses.get(shardIndex); if (response == null) { // just override it and return shardsResponses.set(shardIndex, t); } if (!(response instanceof Throwable)) { // we should never really get here... return; } // the failure is already present, try and not override it with an exception that is less meaningless // for example, getting illegal shard state if (TransportActions.isReadOverrideException(t)) { shardsResponses.set(shardIndex, t); } } } class TransportHandler extends BaseTransportRequestHandler<Request> { @Override public Request newInstance() { return newRequest(); } @Override public String executor() { return ThreadPool.Names.SAME; } @Override public void messageReceived(Request request, final TransportChannel channel) throws Exception { // we just send back a response, no need to fork a listener request.listenerThreaded(false); execute(request, new ActionListener<Response>() { @Override public void onResponse(Response response) { try { channel.sendResponse(response); } catch (Throwable e) { onFailure(e); } } @Override public void onFailure(Throwable e) { try { channel.sendResponse(e); } catch (Exception e1) { logger.warn("Failed to send response", e1); } } }); } } class ShardTransportHandler extends BaseTransportRequestHandler<ShardRequest> { @Override public ShardRequest newInstance() { return newShardRequest(); } @Override public String executor() { return executor; } @Override public void messageReceived(final ShardRequest request, final TransportChannel channel) throws Exception { channel.sendResponse(shardOperation(request)); } } }
{ "content_hash": "bce29ce120cc48847ea735aeeb745c94", "timestamp": "", "source": "github", "line_count": 325, "max_line_length": 251, "avg_line_length": 42.356923076923074, "alnum_prop": 0.5862269359291007, "repo_name": "peschlowp/elasticsearch", "id": "d6c569353365b5317035eaa3576456111f68f117", "size": "14554", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/org/elasticsearch/action/support/broadcast/TransportBroadcastOperationAction.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "9" }, { "name": "Java", "bytes": "24768875" }, { "name": "Perl", "bytes": "5805" }, { "name": "Python", "bytes": "30533" }, { "name": "Ruby", "bytes": "31602" }, { "name": "Shell", "bytes": "28251" } ], "symlink_target": "" }
var RQCommon = require('./rq-common'); describe('LocalTreeTests', function () { var c; beforeEach(function () { c = new RQCommon(); }); it('testCacheInfoExists', function (done) { c.localTree.cacheInfoExists('/test', function (err, exists) { expect(err).toBeFalsy(); expect(exists).toBeFalsy(); c.addFile(c.localRawTree, '/.aem/test.json', function () { c.localTree.cacheInfoExists('/test', function (err, exists) { expect(err).toBeFalsy(); expect(exists).toBeTruthy(); done(); }); }); }); }); it('testGetInfoFilePath', function () { expect(c.localTree.getInfoFilePath('/test')).toEqual('/.aem/test.json'); }); describe('Downloading', function () { it('testIsDownloading', function () { expect(c.localTree.isDownloading('/testfile')).toBeFalsy(); c.localTree.setDownloading('/testfile', true); expect(c.localTree.isDownloading('/testfile')).toBeTruthy(); c.localTree.setDownloading('/testfile', false); expect(c.localTree.isDownloading('/testfile')).toBeFalsy(); }); it('testDownloadingMultiple', function () { c.localTree.setDownloading('/testfile', false); expect(c.localTree.isDownloading('/testfile')).toBeFalsy(); c.localTree.setDownloading('/testfile', true); expect(c.localTree.isDownloading('/testfile')).toBeTruthy(); }); it('testWaitDownload', function (done) { var waited = false; c.localTree.setDownloading('/testfile', true); c.localTree.waitOnDownload('/testfile', function (err) { expect(err).toBeFalsy(); expect(waited).toBeTruthy(); // it shouldn't wait a second time c.localTree.waitOnDownload('/testfile', function (err) { expect(err).toBeFalsy(); done(); }); }); setTimeout(function () { waited = true; c.localTree.setDownloading('/testfile', false); }, 500); }); it('testWaitDownloadNotDownloading', function (done) { c.localTree.waitOnDownload('/testfile', function (err) { expect(err).toBeFalsy(); done(); }); }); it('testDownload', function (done) { c.addFile(c.remoteTree, '/test', function () { c.expectLocalFileExist('/test', false, false, function () { c.localTree.download(c.remoteTree, '/test', function (err, file) { expect(err).toBeFalsy(); expect(file).toBeTruthy(); c.expectLocalFileExistExt('/test', true, true, false, done); }); }); }); }); }); describe('RefreshCacheInfo', function () { it('testRefreshCacheInfo', function (done) { c.addFile(c.remoteTree, '/test', function (remote) { c.localTree.createFile('/test', function (err, local) { expect(err).toBeFalsy(); var lastModified = local.lastModified(); var lastSynced = local.getLastSyncDate(); expect(lastModified).toBeTruthy(); expect(lastSynced).toBeTruthy(); expect(local.getDownloadedRemoteModifiedDate()).toBeFalsy(); expect(local.isCreatedLocally()).toBeTruthy(); setTimeout(function () { c.localTree.refreshCacheInfo('/test', remote, function (err) { expect(err).toBeFalsy(); c.localTree.open('/test', function (err, local) { expect(err).toBeFalsy(); expect(local.lastModified()).toEqual(local.lastModified()); expect(local.getLastSyncDate()).not.toEqual(lastSynced); expect(local.getDownloadedRemoteModifiedDate()).toEqual(remote.lastModified()); expect(local.isCreatedLocally()).toBeFalsy(); done(); }); }); }, 5); }); }); }); it('testRefreshCacheInfoAfterUpdate', function (done) { // verify that if a remote file is updated to a local version, the local modified date is still used c.addFile(c.remoteTree, '/test', function (remote) { c.localTree.download(c.remoteTree, '/test', function (err, local) { expect(err).toBeFalsy(); local.setLastModified(local.lastModified() + 10); var localModified = local.lastModified(); local.close(function (err) { expect(err).toBeFalsy(); remote.setLastModified(local.lastModified() + 10); remote.close(function (err) { expect(err).toBeFalsy(); c.localTree.refreshCacheInfo('/test', remote, function (err) { expect(err).toBeFalsy(); c.localTree.open('/test', function (err, local) { expect(err).toBeFalsy(); expect(local.lastModified()).toEqual(localModified); done(); }); }); }); }); }); }); }); it('testRefreshCacheInfoNoExist', function (done) { c.addFile(c.remoteTree, '/test', function (remote) { c.addFile(c.localRawTree, '/test', function () { c.localTree.refreshCacheInfo('/test', remote, function (err) { expect(err).toBeFalsy(); c.expectLocalFileExist('/test', true, false, done); }); }); }); }); }); describe('CreateFile', function () { it('testCreateFromSource', function (done) { c.addFile(c.remoteTree, '/test', function (remote) { c.addFile(c.localRawTree, '/test', function (file) { c.addFile(c.localRawTree, '/test2', function (file2) { c.localTree.createFromSource(file, remote, true, function (err, local) { expect(err).toBeFalsy(); expect(local).toBeTruthy(); expect(local.getDownloadedRemoteModifiedDate()).toEqual(remote.lastModified()); expect(local.isCreatedLocally()).toBeTruthy(); remote.setLastModified(12345); c.expectLocalFileExist('/test', true, true, function () { c.localTree.createFromSource(file, remote, false, function (err, local2) { expect(err).toBeFalsy(); expect(local2).toBeTruthy(); expect(local2.getDownloadedRemoteModifiedDate()).toEqual(local.getDownloadedRemoteModifiedDate()); expect(local2.isCreatedLocally()).toBeTruthy(); c.expectLocalFileExist('/test', true, true, function () { c.localTree.createFromSource(file2, remote, false, function (err, local3) { expect(err).toBeFalsy(); expect(local3).toBeTruthy(); expect(local3.getDownloadedRemoteModifiedDate()).toEqual(12345); expect(local3.isCreatedLocally()).toBeFalsy(); done(); }); }); }); }); }); }); }); }); }); it('testCreateFromSourceDir', function (done) { c.addDirectory(c.remoteTree, '/test', function (remote) { c.addDirectory(c.localRawTree, '/test', function (dir) { c.localTree.createFromSource(dir, remote, true, function (err, local) { expect(err).toBeFalsy(); expect(local).toBeTruthy(); expect(local.getDownloadedRemoteModifiedDate()).toBeFalsy(); expect(local.isCreatedLocally()).toBeFalsy(); c.expectLocalFileExistExt('/test', true, false, false, done); }); }); }); }); it('testCreateFromSourceTempFile', function (done) { c.addFile(c.remoteTree, '/.test', function (remote) { c.addFile(c.localRawTree, '/.test', function (file) { c.localTree.createFromSource(file, remote, true, function (err, local) { expect(err).toBeFalsy(); expect(local).toBeTruthy(); expect(local.getDownloadedRemoteModifiedDate()).toBeFalsy(); expect(local.isCreatedLocally()).toBeFalsy(); c.expectLocalFileExistExt('/.test', true, false, false, done); }); }); }); }); }); it('testExists', function (done) { c.localTree.exists('/test', function (err, exists) { expect(err).toBeFalsy(); expect(exists).toBeFalsy(); c.addFile(c.localTree, '/test', function () { c.localTree.exists('/test', function (err, exists) { expect(err).toBeFalsy(); expect(exists).toBeTruthy(); done(); }); }); }); }); describe('OpenTest', function () { it('testOpen', function (done) { c.localTree.createFile('/test', function (err) { expect(err).toBeFalsy(); c.localTree.open('/test', function (err, file) { expect(err).toBeFalsy(); expect(file).toBeTruthy(); c.expectLocalFileExistExt('/test', true, true, true, done); }); }); }); it('testOpenNoExist', function (done) { c.localTree.open('/test', function (err) { expect(err).toBeTruthy(); done(); }); }); it('testOpenNoWork', function (done) { c.addFile(c.localRawTree, '/test', function () { c.localTree.open('/test', function (err, file) { expect(err).toBeFalsy(); expect(file).toBeTruthy(); c.expectLocalFileExistExt('/test', true, true, false, done); }); }); }); }); describe('ListTest', function () { it('testList', function (done) { c.localTree.createFile('/test', function (err) { expect(err).toBeFalsy(); c.localTree.createFile('/test2', function (err) { expect(err).toBeFalsy(); c.localTree.list('/*', function (err, files) { expect(err).toBeFalsy(); expect(files.length).toEqual(2); expect(files[0].isCreatedLocally()).toBeTruthy(); expect(files[1].isCreatedLocally()).toBeTruthy(); expect(files[0].getPath()).not.toEqual(files[1].getPath()); done(); }); }); }); }); it('testListDangling', function (done) { c.addFile(c.localRawTree, '/test', function () { c.expectLocalFileExistExt('/test', true, false, false, function () { c.localTree.list('/*', function (err, files) { expect(err).toBeFalsy(); expect(files.length).toEqual(1); expect(files[0].isCreatedLocally()).toBeFalsy(); c.expectLocalFileExistExt('/test', true, true, false, done); }); }); }); }); it('testListMix', function (done) { c.addDirectory(c.localTree, '/test', function () { c.addFile(c.localTree, '/file', function () { c.addFile(c.localTree, '/.tempfile', function () { c.localTree.list('/*', function (err, files) { expect(err).toBeFalsy(); expect(files.length).toEqual(3); expect(files[0].isCreatedLocally()).toBeFalsy(); expect(files[1].isCreatedLocally()).toBeFalsy(); expect(files[2].isCreatedLocally()).toBeFalsy(); expect(files[0].getPath()).not.toEqual(files[1].getPath()); expect(files[0].getPath()).not.toEqual(files[2].getPath()); expect(files[1].getPath()).not.toEqual(files[2].getPath()); c.expectLocalFileExistExt('/test', true, false, false, function () { c.expectLocalFileExistExt('/file', true, true, false, function () { c.expectLocalFileExistExt('/.tempfile', true, false, false, done); }); }); }); }); }); }); }); it('testListOneItem', function (done) { var validateItem = function (name, workExist, cb) { c.localTree.list(name, function (err, files) { expect(err).toBeFalsy(); expect(files.length).toEqual(1); expect(files[0].isCreatedLocally()).toBeFalsy(); expect(files[0].getPath()).toEqual(name); c.expectLocalFileExistExt(name, true, workExist, false, cb); }); }; c.addDirectory(c.localTree, '/test', function () { c.addFile(c.localTree, '/file', function () { c.addFile(c.localTree, '/.tempfile', function () { validateItem('/test', false, function () { validateItem('/file', true, function () { validateItem('/.tempfile', false, done); }); }); }); }); }); }); it('testListEmpty', function (done) { c.localTree.list('/*', function (err, files) { expect(err).toBeFalsy(); expect(files.length).toEqual(0); c.localTree.list('/test/*', function (err, files) { expect(err).toBeFalsy(); expect(files.length).toEqual(0); c.localTree.list('/test', function (err, files) { expect(err).toBeFalsy(); expect(files.length).toEqual(0); done(); }); }); }); }); }); describe('Create', function () { it('testCreateFile', function (done) { c.localTree.createFile('/test', function (err, file) { expect(err).toBeFalsy(); expect(file).toBeTruthy(); expect(file.getDownloadedRemoteModifiedDate()).toBeFalsy(); expect(file.isCreatedLocally()).toBeTruthy(); c.expectLocalFileExistExt('/test', true, true, true, done); }); }); it('testCreateFileWorkAlreadyExist', function (done) { c.addFile(c.remoteTree, '/test', function (remote) { c.addFile(c.localRawTree, '/test', function (file) { c.localTree.createFromSource(file, remote, false, function (err) { expect(err).toBeFalsy(); c.localRawTree.delete('/test', function (err) { expect(err).toBeFalsy(); c.expectLocalFileExistExt('/test', false, true, false, function () { c.localTree.createFile('/test', function (err, file) { expect(err).toBeFalsy(); expect(file.getDownloadedRemoteModifiedDate()).toBeFalsy(); expect(file.isCreatedLocally()).toBeTruthy(); done(); }); }); }); }); }); }); }); it('testCreateDirectory', function (done) { c.localTree.createDirectory('/test', function (err, file) { expect(err).toBeFalsy(); expect(file.isDirectory()).toBeTruthy(); c.expectLocalFileExistExt('/test', true, false, false, done); }); }); }); describe('Delete', function () { it('testDelete', function (done) { c.localTree.createFile('/test', function (err) { expect(err).toBeFalsy(); c.localTree.delete('/test', function (err) { expect(err).toBeFalsy(); c.expectLocalFileExistExt('/test', false, false, false, done); }); }); }); it('testDeleteNoExist', function (done) { c.addFile(c.localRawTree, '/test', function () { c.expectLocalFileExistExt('/test', true, false, false, function () { c.localTree.delete('/test', function (err) { expect(err).toBeFalsy(); c.expectLocalFileExist('/test', false, false, function () { c.localTree.delete('/test', function (err) { expect(err).toBeTruthy(); done(); }); }); }); }); }); }); it('testDeleteDirectory', function (done) { c.localTree.createDirectory('/test', function (err) { expect(err).toBeFalsy(); c.localTree.createFile('/test/file', function (err) { expect(err).toBeFalsy(); c.localTree.delete('/test/file', function (err) { expect(err).toBeFalsy(); c.localTree.deleteDirectory('/test', function (err) { expect(err).toBeFalsy(); c.expectLocalFileExist('/test', false, false, function () { c.localRawTree.exists('/test/.aem', function (err, exists) { expect(err).toBeFalsy(); expect(exists).toBeFalsy(); c.localTree.deleteDirectory('/test', function (err) { expect(err).toBeTruthy(); done(); }); }); }); }); }); }); }); }); it('testDeleteDirectoryNotEmpty', function (done) { c.localTree.createDirectory('/test', function (err) { expect(err).toBeFalsy(); c.localTree.createFile('/test/file', function (err) { expect(err).toBeFalsy(); c.localTree.deleteDirectory('/test', function (err) { expect(err).toBeTruthy(); c.expectLocalFileExist('/test/file', true, true, function () { c.localRawTree.delete('/test/file', function (err) { expect(err).toBeFalsy(); c.localTree.deleteDirectory('/test', function (err) { expect(err).toBeFalsy(); c.localRawTree.exists('/test/.aem', function (err, exists) { expect(err).toBeFalsy(); expect(exists).toBeFalsy(); done(); }); }); }); }); }); }); }); }); }); describe('Rename', function () { it('testRename', function (done) { c.localTree.createFile('/test', function (err) { expect(err).toBeFalsy(); c.localTree.rename('/test', '/test2', function (err) { expect(err).toBeFalsy(); c.expectLocalFileExist('/test', false, false, function () { c.expectLocalFileExist('/test2', true, true, done); }); }); }); }); it('testRenameNoWork', function (done) { c.addFile(c.localRawTree, '/test', function () { c.expectLocalFileExistExt('/test', true, false, false, function () { c.localTree.rename('/test', '/test1', function (err) { expect(err).toBeFalsy(); c.expectLocalFileExist('/test', false, false, function () { c.expectLocalFileExistExt('/test1', true, true, true, done); }); }); }); }); }); it('testRenameTargetWorkExists', function (done) { c.localTree.createFile('/test', function (err) { expect(err).toBeFalsy(); c.addFile(c.localRawTree, c.localTree.getInfoFilePath('/test1'), function () { c.expectLocalFileExist('/test', true, true, function () { c.expectLocalFileExistExt('/test1', false, true, false, function () { c.localTree.rename('/test', '/test1', function (err) { expect(err).toBeFalsy(); c.expectLocalFileExist('/test', false, false, function () { c.expectLocalFileExist('/test1', true, true, done); }); }); }); }); }); }); }); it('testRenameTempToReal', function (done) { c.localTree.createFile('/.temp', function (err) { expect(err).toBeFalsy(); c.expectLocalFileExistExt('/.temp', true, false, false, function () { c.localTree.rename('/.temp', '/file', function (err) { expect(err).toBeFalsy(); c.expectLocalFileExist('/.temp', false, false, function () { c.expectLocalFileExist('/file', true, true, done); }); }); }); }); }); it('testRenameRealToTemp', function (done) { c.testTree.createFile('/file', function (err, file) { expect(err).toBeFalsy(); c.testTree.rename('/file', '/.temp', function (err) { expect(err).toBeFalsy(); c.expectLocalFileExist('/file', false, false, function () { c.expectLocalFileExistExt('/.temp', true, false, false, done); }); }); }); }); it('testRenameQueuedFile', function (done) { c.addQueuedFile('/testnewfile', function () { c.addFile(c.remoteTree, '/testfile', function () { c.testTree.open('/testfile', function (err, file) { expect(err).toBeFalsy(); file.cacheFile(function (err) { expect(err).toBeFalsy(); c.testTree.delete('/testfile', function (err) { expect(err).toBeFalsy(); c.testTree.rename('/testnewfile', '/testfile', function (err) { expect(err).toBeFalsy(); c.expectLocalFileExist('/testnewfile', false, false, function () { c.expectLocalFileExistExt('/testfile', true, true, false, function () { c.expectQueuedMethod('/', 'testfile', 'POST', function () { c.expectQueuedMethod('/', 'testnewfile', false, done); }) }); }); }); }); }); }); }); }); }); it('testRenameQueuedFileCached', function (done) { c.addFile(c.remoteTree, '/testfile', function () { c.testTree.open('/testfile', function (err, file) { expect(err).toBeFalsy(); file.cacheFile(function (err) { expect(err).toBeFalsy(); c.addFile(c.remoteTree, '/testfile1', function () { c.testTree.open('/testfile1', function (err, file) { expect(err).toBeFalsy(); file.cacheFile(function (err) { expect(err).toBeFalsy(); c.testTree.delete('/testfile1', function (err) { expect(err).toBeFalsy(); c.testTree.rename('/testfile', '/testfile1', function (err) { expect(err).toBeFalsy(); c.expectLocalFileExist('/testfile', false, false, function () { c.expectLocalFileExistExt('/testfile1', true, true, false, function () { c.expectQueuedMethod('/', 'testfile', 'DELETE', function () { c.expectQueuedMethod('/', 'testfile1', 'POST', done); }); }); }); }); }); }); }); }); }); }); }); }); it('testRenameFileExisting', function (done) { c.addFile(c.remoteTree, '/testfile', function () { c.testTree.open('/testfile', function (err, file) { expect(err).toBeFalsy(); file.cacheFile(function (err) { expect(err).toBeFalsy(); c.addFile(c.remoteTree, '/testfile1', function () { c.testTree.open('/testfile1', function (err, file) { expect(err).toBeFalsy(); file.cacheFile(function (err) { expect(err).toBeFalsy(); c.testTree.rename('/testfile', '/testfile1', function (err) { expect(err).toBeFalsy(); c.expectLocalFileExist('/testfile', false, false, function () { c.expectLocalFileExistExt('/testfile1', true, true, false, function () { c.expectQueuedMethod('/', 'testfile', 'DELETE', function () { c.expectQueuedMethod('/', 'testfile1', 'POST', done); }); }); }); }); }); }); }); }); }); }); }); it('testRenameTempToExisting', function (done) { c.addCachedFile('/testfile', function () { c.testTree.createFile('/.temp', function (err, file) { expect(err).toBeFalsy(); c.testTree.rename('/.temp', '/testfile', function (err) { expect(err).toBeFalsy(); c.expectLocalFileExist('/.temp', false, false, function () { c.expectLocalFileExistExt('/testfile', true, true, false, function () { c.expectQueuedMethod('/', 'testfile', 'POST', done); }); }); }); }); }); }); it('testRenameToExistingQueued', function (done) { c.addQueuedFile('/testfile', function () { c.addQueuedFile('/testfile1', function () { c.testTree.rename('/testfile', '/testfile1', function (err) { expect(err).toBeFalsy(); c.expectLocalFileExist('/testfile', false, false, function () { c.expectLocalFileExist('/testfile1', true, true, function () { c.expectQueuedMethod('/', 'testfile', false, function () { c.expectQueuedMethod('/', 'testfile1', 'PUT', done); }); }); }); }); }); }); }); it('testRenameTempToExistingCreated', function (done) { c.addFile(c.localTree, '/.temp', function () { c.addQueuedFile('/testfile', function () { c.testTree.rename('/.temp', '/testfile', function (err) { expect(err).toBeFalsy(); c.expectLocalFileExist('/.temp', false, false, function () { c.expectLocalFileExist('/testfile', true, true, function () { c.expectQueuedMethod('/', '.temp', false, function () { c.expectQueuedMethod('/', 'testfile', 'PUT', done); }); }); }); }); }); }); }); }); it('testDisconnect', function (done) { c.localTree.disconnect(function (err) { expect(err).toBeFalsy(); done(); }); }); });
{ "content_hash": "31d7f701f2df736c69592a60eb7c2300", "timestamp": "", "source": "github", "line_count": 688, "max_line_length": 116, "avg_line_length": 37.61773255813954, "alnum_prop": 0.5210385997449867, "repo_name": "adobe/node-smb-server", "id": "564e6cd401a7377ab8873dd7719a8c72372b9922", "size": "26529", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/lib/backends/rq/localtree-spec.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "895172" } ], "symlink_target": "" }
require 'selenium-webdriver' require 'show_me_the_cookies' Capybara.register_driver :chrome_headless do |app| Capybara::Selenium::Driver.load_selenium browser_options = ::Selenium::WebDriver::Chrome::Options.new.tap do |opts| opts.args << '--headless' opts.args << '--disable-gpu' if Gem.win_platform? opts.args << '--no-sandbox' # Workaround https://bugs.chromium.org/p/chromedriver/issues/detail?id=2650&q=load&sort=-id&colspec=ID%20Status%20Pri%20Owner%20Summary opts.args << '--disable-site-isolation-trials' opts.args << '--window-size=1920,1080' opts.args << '--enable-features=NetworkService,NetworkServiceInProcess' end Capybara::Selenium::Driver.new(app, browser: :chrome, options: browser_options) end Capybara::Screenshot.register_driver(:chrome_headless) do |driver, path| driver.browser.save_screenshot(path) end ShowMeTheCookies.register_adapter(:chrome_headless, ShowMeTheCookies::SeleniumChrome)
{ "content_hash": "f5f30c543e4e74abaee51d6528fca14d", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 139, "avg_line_length": 43.31818181818182, "alnum_prop": 0.7439664218258132, "repo_name": "PublicHealthEngland/ndr_dev_support", "id": "89a074e8ea26ad9225243aef6126213c11e9ae45", "size": "953", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/ndr_dev_support/integration_testing/drivers/chrome_headless.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "116753" }, { "name": "Shell", "bytes": "131" } ], "symlink_target": "" }
package sgw //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. // // Code generated by Alibaba Cloud SDK Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. // Snapshots is a nested struct in sgw response type Snapshots struct { Snapshot []Snapshot `json:"Snapshot" xml:"Snapshot"` }
{ "content_hash": "45183ea94d5163d036e85a37404dc1f3", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 84, "avg_line_length": 39.38095238095238, "alnum_prop": 0.7629987908101572, "repo_name": "aliyun/alibaba-cloud-sdk-go", "id": "cf3b1868a13b5c616f38be046e832f79e775de26", "size": "827", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "services/sgw/struct_snapshots.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "734307" }, { "name": "Makefile", "bytes": "183" } ], "symlink_target": "" }
<nav [attr.id]="id" class="mv-aside"> <div class="mv-aside__content" [@contentAnimation]="opened"> <ng-content></ng-content> </div> <div class="mv-aside__backdrop" [@backdropAnimation]="opened" (click)="close($event)"> </div> </nav>
{ "content_hash": "35f9276a066b8dd75577986300b585af", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 37, "avg_line_length": 27.88888888888889, "alnum_prop": 0.6175298804780877, "repo_name": "marcusvy/emeve-ui", "id": "03ae35c661696978652e791a9e7f6a07daf7bb9b", "size": "251", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/app/layout/aside/aside.component.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "95998" }, { "name": "HTML", "bytes": "54029" }, { "name": "JavaScript", "bytes": "1884" }, { "name": "TypeScript", "bytes": "117031" } ], "symlink_target": "" }
ACCEPTED #### According to Index Fungorum #### Published in null #### Original name Arthopyrenia subglobosa Vezda ### Remarks null
{ "content_hash": "259024c175814d6e5f2ae146828767a3", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 29, "avg_line_length": 10.307692307692308, "alnum_prop": 0.7238805970149254, "repo_name": "mdoering/backbone", "id": "78e834303b2ec587f3d99e852cb20145d497cb2d", "size": "201", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Ascomycota/Eurotiomycetes/Pyrenulales/Monoblastiaceae/Acrocordia/Acrocordia subglobosa/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }