public static void Main(string[] args) { // Unit Price for SkuIds SkuIdPrice('A', 50); SkuIdPrice('B', 30); SkuIdPrice('C', 20); SkuIdPrice('D', 15); // Active promotions BuildPromotionType1Dict('A', 3, 130); BuildPromotionType1Dict('B', 2, 45); BuildPromotionType2Dict('C', 'D', 30); // Scenario B Dictionary <char, int> items2 = new Dictionary <char, int>(); items2.put('A', 5); items2.put('B', 5); items2.put('C', 1); Console.WriteLine("Answer for scenario B: " + CalculateTotalPrice(items2)); totalPrice = 0; // resetting total price for new scenario // Scenario C Dictionary <char, int> items3 = new Dictionary <char, int>(); items3.put('A', 3); items3.put('B', 5); items3.put('C', 1); items3.put('D', 1); Console.WriteLine("Answer for scenario C: " + CalculateTotalPrice(items3)); }
/** * @return a map with all objects referenced by a peeled ref. */ public Dictionary <AnyObjectId, List <Ref> > getAllRefsByPeeledObjectId() { Dictionary <String, Ref> allRefs = getAllRefs(); var ret = new Dictionary <AnyObjectId, List <Ref> >(allRefs.Count); foreach (Ref @ref in allRefs.Values) { Ref ref2 = @ref; if (!ref2.Peeled) { ref2 = Peel(ref2); } AnyObjectId target = ref2.PeeledObjectId; if (target == null) { target = ref2.ObjectId; } // We assume most Sets here are singletons List <Ref> oset = ret.put(target, new List <Ref> { ref2 }); if (oset != null) { // that was not the case (rare) if (oset.Count == 1) { // Was a read-only singleton, we must copy to a new Set oset = new List <Ref>(oset); } ret.put(target, oset); oset.Add(ref2); } } return(ret); }
private static void readPackedRefsImpl(Dictionary <string, Ref> avail, StreamReader sr) { Ref last = null; bool peeled = false; for (; ;) { string line = sr.ReadLine(); if (line == null) { break; } if (line[0] == '#') { if (line.StartsWith(RefDirectory.PACKED_REFS_HEADER)) { line = line.Substring(RefDirectory.PACKED_REFS_HEADER.Length); peeled = line.Contains(RefDirectory.PACKED_REFS_PEELED); } continue; } if (line[0] == '^') { if (last == null) { throw new TransportException("Peeled line before ref"); } ObjectId pid = ObjectId.FromString(line.Substring(1)); last = new PeeledTag(Storage.Packed, last.Name, last.ObjectId, pid); avail.put(last.Name, last); continue; } int sp = line.IndexOf(' '); if (sp < 0) { throw new TransportException("Unrecognized ref: " + line); } ObjectId id = ObjectId.FromString(line.Slice(0, sp)); string name = line.Substring(sp + 1); if (peeled) { last = new PeeledNonTag(Storage.Packed, name, id); } else { last = new Unpeeled(Storage.Packed, name, id); } avail.put(last.Name, last); } }
/** * Add an inflectional variant to this word element. This method is intended * for use by a <code>Lexicon</code>. The idea is that words which have more * than one inflectional variant (for example, a regular and an irregular * form of the past tense), can have a default variant (for example, the * regular), but also store information about the other variants. This comes * in useful in case the default inflectional variant is reset to a new one. * In that case, the stored forms for the new variant are used to inflect * the word. * * <P> * <strong>An example:</strong> The verb <i>lie</i> has both a regular form * (<I>lies, lied, lying</I>) and an irregular form (<I>lay, lain,</I> etc). * Assume that the <code>Lexicon</code> provides this information and treats * this as variant information of the same word (as does the * <code>NIHDBLexicon</code>, for example). Typically, the default * inflectional variant is the <code>Inflection.REGULAR</code>. This means * that morphology proceeds to inflect the verb as <I>lies, lying</I> and so * on. If the default inflectional variant is reset to * <code>Inflection.IRREGULAR</code>, the stored irregular forms will be * used instead. * * @param infl * the Inflection pattern with which this form is associated * @param lexicalFeature * the actual inflectional feature being set, for example * <code>LexicalFeature.PRESENT_3S</code> * @param form * the actual inflected word form */ public void addInflectionalVariant(Inflection infl, string lexicalFeature, string form) { if (inflVars.containsKey(infl)) { inflVars[infl].addForm(lexicalFeature, form); } else { var set = new InflectionSet(infl); set.addForm(lexicalFeature, form); inflVars.put(infl, set); } }
/// <summary> /// Constructor. /// </summary> /// <param name="valueTextMap"> the map of values to text to store, assigned and not altered, not null </param> internal LocaleStore(IDictionary <TextStyle, IDictionary <Long, String> > valueTextMap) { this.ValueTextMap = valueTextMap; IDictionary <TextStyle, IList <Map_Entry <String, Long> > > map = new Dictionary <TextStyle, IList <Map_Entry <String, Long> > >(); IList <Map_Entry <String, Long> > allList = new List <Map_Entry <String, Long> >(); foreach (Map_Entry <TextStyle, IDictionary <Long, String> > vtmEntry in valueTextMap) { IDictionary <String, Map_Entry <String, Long> > reverse = new Dictionary <String, Map_Entry <String, Long> >(); foreach (Map_Entry <Long, String> entry in vtmEntry.Value) { if (reverse.put(entry.Value, CreateEntry(entry.Value, entry.Key)) != null) { // TODO: BUG: this has no effect continue; // not parsable, try next style } } IList <Map_Entry <String, Long> > list = new List <Map_Entry <String, Long> >(reverse.Values); list.Sort(COMPARATOR); map[vtmEntry.Key] = list; allList.AddRange(list); map[null] = allList; } allList.Sort(COMPARATOR); this.Parsable = map; }
//----------------------------------------------------------------------- public virtual void forEach() { Dictionary <object, object> mutableMap = new Dictionary <object, object>(); MapStream.of(map_Renamed).forEach((k, v) => mutableMap.put(k, v)); assertThat(mutableMap).isEqualTo(map_Renamed); }
private IDictionary <string, object> ToMap(DiscoverableURIs uris) { IDictionary <string, object> @out = new Dictionary <string, object>(); uris.ForEach((k, v) => @out.put(k, v.toASCIIString())); return(@out); }
public override object MapMap(MapValue value) { IDictionary <object, object> map = new Dictionary <object, object>(); value.Foreach((k, v) => map.put(k, v.map(this))); return(map); }
public void HashMap_ToCsharp_Dictionary() { var two = new Dictionary <string, string>(); two.put("cat", "lucy").ShouldBe("lucy"); two.put("dog", "benny").ShouldBe("benny"); two.Keys.Count.ShouldBe(2); two["cat"].ShouldBe("lucy"); two.put("cat", "emi").ShouldBe("emi"); two["cat"].ShouldBe("emi"); two.containsKey("dog").ShouldBe(true); two.containsKey("camel").ShouldBe(false); }
private void readBundleV2() { byte[] hdrbuf = new byte[1024]; var avail = new Dictionary <string, Ref>(); for (; ;) { string line = readLine(hdrbuf); if (line.Length == 0) { break; } if (line[0] == '-') { ObjectId id = ObjectId.FromString(line.Slice(1, 41)); String shortDesc = null; if (line.Length > 42) { shortDesc = line.Substring(42); } _prereqs.put(id, shortDesc); continue; } string name = line.Slice(41, line.Length); ObjectId id2 = ObjectId.FromString(line.Slice(0, 40)); Ref prior = avail.put(name, new Unpeeled(Storage.Network, name, id2)); if (prior != null) { throw duplicateAdvertisement(name); } } available(avail); }
public void setAssignment(Variable var, Object value) { if (!variableToValue.containsKey(var)) { variables.Add(var); } variableToValue.put(var, value); }
public BindableButton registerBindButton(SimpleUri bindId, String displayName, BindButtonEvent @event) { BindableButtonImpl bind = new BindableButtonImpl(bindId, displayName, @event); buttonLookup.put(bindId, bind); buttonBinds.add(bind); return(bind); }
public BindableAxis registerBindAxis(String id, BindAxisEvent @event, BindableButton positiveButton, BindableButton negativeButton) { BindableAxisImpl axis = new BindableAxisImpl(id, @event, positiveButton, negativeButton); axisBinds.add(axis); axisLookup.put(id, axis); return(axis); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @TestFactory Stream<org.junit.jupiter.api.DynamicTest> shouldGetAndSetRandomItems() internal virtual Stream <DynamicTest> ShouldGetAndSetRandomItems() { ThrowingConsumer <NumberArrayTestData> throwingConsumer = data => { using (NumberArray array = data.array) { IDictionary <int, object> key = new Dictionary <int, object>(); Reader reader = data.reader; object defaultValue = reader.read(array, 0); // WHEN setting random items for (int i = 0; i < INDEXES * 2; i++) { int index = _random.Next(INDEXES); object value = data.valueGenerator.apply(_random); data.writer.write(i % 2 == 0 ? array : array.at(index), index, value); key.put(index, value); } // THEN they should be read correctly AssertAllValues(key, defaultValue, reader, array); // AND WHEN swapping some for (int i = 0; i < INDEXES / 2; i++) { int fromIndex = _random.Next(INDEXES); int toIndex; do { toIndex = _random.Next(INDEXES); } while (toIndex == fromIndex); object fromValue = reader.read(array, fromIndex); object toValue = reader.read(array, toIndex); key.put(fromIndex, toValue); key.put(toIndex, fromValue); array.swap(fromIndex, toIndex); } // THEN they should end up in the correct places AssertAllValues(key, defaultValue, reader, array); } }; return(DynamicTest.stream(Arrays().GetEnumerator(), data => data.name, throwingConsumer)); }
protected void read(string file) { try { string rootDir = ""; try { rootDir = getClass().getProtectionDomain().getCodeSource().getLocation().getPath().replace("%20", " "); rootDir = new File(rootDir).getParent(); } catch (Exception e) { //throw e; } file = rootDir + FileUtils.FILE_SEPARATOR + file; DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = docBuilder.parse(new File(file)); doc.getDocumentElement().normalize(); NodeList childNodes = doc.getChildNodes(); parameters.clear(); for (int s = 0; s < childNodes.getLength(); s++) { Node item = childNodes.item(s); if (item.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element)item; NodeList tagName = element.getElementsByTagName("port"); parameters.put("port", tagName.item(0).getChildNodes().item(0).getNodeValue().trim()); } } } catch (SAXParseException err) { Console.Out.WriteLine("parsing error"); } catch (ParserConfigurationException e) { Console.Out.WriteLine("configuration error"); } catch (SAXException e) { Console.Out.WriteLine("general sax parser error"); } catch (IOException e) { Console.Out.WriteLine("config file error"); } catch (Exception e) { Console.Out.WriteLine("general parser error"); } }
public void TestMissingGenerics() { MissingGenerics example = new MissingGenerics(); Persister persister = new Persister(); Dictionary map = example.Map; map.put("a", "A"); map.put("b", "B"); map.put("c", "C"); map.put("d", "D"); map.put("e", "E"); List list = example.List; list.add("1"); list.add("2"); list.add("3"); list.add("4"); list.add("5"); StringWriter out = new StringWriter(); persister.write(example, out); String text = out.toString(); MissingGenerics recovered = persister.read(MissingGenerics.class, text);
private static IList <IDictionary <string, object> > NodeCounts(TokenRead tokens, Read read, Anonymizer anonymizer) { IList <IDictionary <string, object> > nodeCounts = new List <IDictionary <string, object> >(); IDictionary <string, object> nodeCount = new Dictionary <string, object>(); nodeCount["count"] = read.CountsForNodeWithoutTxState(-1); nodeCounts.Add(nodeCount); tokens.LabelsGetAllTokens().forEachRemaining(t => { long count = read.CountsForNodeWithoutTxState(t.id()); IDictionary <string, object> labelCount = new Dictionary <string, object>(); labelCount.put("label", anonymizer.Label(t.name(), t.id())); labelCount.put("count", count); nodeCounts.Add(labelCount); }); return(nodeCounts); }
private static IList <IDictionary <string, object> > RelationshipCounts(TokenRead tokens, Read read, Anonymizer anonymizer) { IList <IDictionary <string, object> > relationshipCounts = new List <IDictionary <string, object> >(); IDictionary <string, object> relationshipCount = new Dictionary <string, object>(); relationshipCount["count"] = read.CountsForRelationshipWithoutTxState(-1, -1, -1); relationshipCounts.Add(relationshipCount); IList <NamedToken> labels = Iterators.asList(tokens.LabelsGetAllTokens()); tokens.RelationshipTypesGetAllTokens().forEachRemaining(t => { long count = read.CountsForRelationshipWithoutTxState(-1, t.id(), -1); IDictionary <string, object> relationshipTypeCount = new Dictionary <string, object>(); relationshipTypeCount.put("relationshipType", anonymizer.RelationshipType(t.name(), t.id())); relationshipTypeCount.put("count", count); relationshipCounts.Add(relationshipTypeCount); foreach (NamedToken label in labels) { long startCount = read.CountsForRelationshipWithoutTxState(label.id(), t.id(), -1); if (startCount > 0) { IDictionary <string, object> x = new Dictionary <string, object>(); x.put("relationshipType", anonymizer.RelationshipType(t.name(), t.id())); x.put("startLabel", anonymizer.Label(label.name(), label.id())); x.put("count", startCount); relationshipCounts.Add(x); } long endCount = read.CountsForRelationshipWithoutTxState(-1, t.id(), label.id()); if (endCount > 0) { IDictionary <string, object> x = new Dictionary <string, object>(); x.put("relationshipType", anonymizer.RelationshipType(t.name(), t.id())); x.put("endLabel", anonymizer.Label(label.name(), label.id())); x.put("count", endCount); relationshipCounts.Add(x); } } }); return(relationshipCounts); }
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes: //ORIGINAL LINE: @Nonnull private java.util.Map<String, String> injectDefaultProviderIfMissing(@Nullable String indexName, @Nonnull Config dbConfig, @Nonnull Map<String, String> config) private IDictionary <string, string> InjectDefaultProviderIfMissing(string indexName, Config dbConfig, IDictionary <string, string> config) { string provider = config.get(PROVIDER); if (string.ReferenceEquals(provider, null)) { config = new Dictionary <string, string>(config); config.put(PROVIDER, GetDefaultProvider(indexName, dbConfig)); } return(config); }
public void loadJsonConfig() { using (StreamReader jsonReader = new StreamReader(CONFIG_FILENAME)) { string json = jsonReader.ReadToEnd(); dynamic configItem = JsonConvert.DeserializeObject.DeserializeObject(json); foreach (var item in array) { configuration.put(COMPILER_LOCATION_STR, item.compilerLocation); } } }
private void RecordError(AnyObjectId id, Exception what) { ObjectId objId = id.Copy(); List <Exception> errors = _fetchErrors.get(objId); if (errors == null) { errors = new List <Exception>(2); _fetchErrors.put(objId, errors); } errors.Add(what); }
private JSch getDefaultJSch() { if (_defaultJSch == null) { _defaultJSch = createDefaultJSch(); foreach (object name in _defaultJSch.getIdentityNames()) { _byIdentityFile.put((string)name, _defaultJSch); } } return(_defaultJSch); }
/// <summary> /// Sets the specified name/value pair in the additional HTTP headers. /// </summary> /// <param name="name">the name of the additional HTTP header</param> /// <param name="value">value the value of the additional HTTP header</param> public void SetAdditionalHeader(String name, String value) { foreach (String key in additionalHeaders_.keySet()) { if (name.equalsIgnoreCase(key)) { name = key; break; } } additionalHeaders_.put(name, value); }
/// <summary> /// Obtains an instance from a list of {@code CurrencyAmount} objects. /// <para> /// It is an error for the input to contain the same currency twice. /// /// </para> /// </summary> /// <param name="amounts"> the amounts </param> /// <returns> the amount </returns> public static MultiCurrencyAmount of(IEnumerable <CurrencyAmount> amounts) { ArgChecker.noNulls(amounts, "amounts"); IDictionary <Currency, CurrencyAmount> map = new Dictionary <Currency, CurrencyAmount>(); foreach (CurrencyAmount amount in amounts) { if (map.put(amount.Currency, amount) != null) { throw new System.ArgumentException("Currency is duplicated: " + amount.Currency); } } return(new MultiCurrencyAmount(ImmutableSortedSet.copyOf(map.Values))); }
public static Identifier create(String path) { Identifier identifier = null; lock (__cache) { Reference <Identifier> ref = __cache.get(path); if (ref != null && (identifier = ref.get()) != null) { return(identifier); } identifier = new Identifier(path); __cache.put(path, new IdentifierReference(identifier)); } return(identifier); }
/// <summary> /// This <c>populate</c> method will read the XML element map /// from the provided node and deserialize its children as entry types. /// Each entry type must contain a key and value so that the entry /// can be inserted in to the map as a pair. If either the key or /// value is composite it is read as a root object, which means its /// <c>Root</c> annotation must be present and the name of the /// object element must match that root element name. /// </summary> /// <param name="node"> /// this is the XML element that is to be deserialized /// </param> /// <param name="result"> /// this is the map object that is to be populated /// </param> /// <returns> /// this returns the item to attach to the object contact /// </returns> public Object Populate(InputNode node, Object result) { Dictionary map = (Map)result; while (true) { InputNode next = node.getNext(); if (next == null) { return(map); } Object index = key.Read(next); Object item = value.Read(next); map.put(index, item); } }
public virtual GlyphImage[] getGlyphs(CachedFont font) { #if PENDING GlyphImage[] r = (GlyphImage[])fontMap.get_Renamed(font); if (r == null) { //UPGRADE_ISSUE: Method 'java.awt.Font.getNumGlyphs' was not converted. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1000_javaawtFontgetNumGlyphs_3"' r = new GlyphImage[font.font.getNumGlyphs()]; fontMap.put(font, r); } return(r); #endif return(new GlyphImage[0]); }
/** Creates a new CSP for a fixed set of variables. */ public CSP(List<Variable> vars) { variables = new List<Variable>(vars.Count); domains = new List<Domain>(vars.Count); constraints = new List<Constraint>(); varIndexHash = new Dictionary<Variable, int>(); cnet = new Dictionary<Variable, List<Constraint>>(); Domain emptyDomain = new Domain(new List<Object>(0)); int index = 0; foreach (Variable var in vars) { variables.Add(var); domains.Add(emptyDomain); varIndexHash.put(var, index++); cnet.put(var, new List<Constraint>()); } }
/// <summary> /// Creates a dictionary. /// </summary> /// <param name="sampleStream"> stream of samples. </param> /// <returns> a {@code Dictionary} class containing the name dictionary /// built from the input file. </returns> /// <exception cref="IOException"> IOException </exception> public static Dictionary createDictionary(ObjectStream <StringList> sampleStream) { Dictionary mNameDictionary = new Dictionary(true); StringList entry; entry = sampleStream.read(); while (entry != null) { if (!mNameDictionary.contains(entry)) { mNameDictionary.put(entry); } entry = sampleStream.read(); } return(mNameDictionary); }
public V put(K1 k1, K2 k2, V v) { Dictionary <K2, V> data2 = data.get(k1); V prev = null; if (data2 == null) { data2 = new Dict <K2, V>(); data.put(k1, data2); } else { prev = data2.get(k2); } data2.put(k2, v); return(prev); }
/// <summary> /// This <c>read</c> method will read the XML element map from /// the provided node and deserialize its children as entry types. /// Each entry type must contain a key and value so that the entry /// can be inserted in to the map as a pair. If either the key or /// value is composite it is read as a root object, which means its /// <c>Root</c> annotation must be present and the name of the /// object element must match that root element name. /// </summary> /// <param name="node"> /// this is the XML element that is to be deserialized /// </param> /// <param name="map"> /// this is the map object that is to be populated /// </param> /// <returns> /// this returns the item to attach to the object contact /// </returns> public Object Read(InputNode node, Dictionary map) { InputNode from = node.getParent(); String name = node.getName(); while (node != null) { Object index = key.Read(node); Object item = value.Read(node); if (map != null) { map.put(index, item); } node = from.getNext(name); } return(map); }
private Dictionary<string, Host> parse(Stream stream) { var m = new Dictionary<string, Host>(); var sr = new StreamReader(stream); var current = new List<Host>(4); string line; while ((line = sr.ReadLine()) != null) { line = line.Trim(); if (line.Length == 0 || line.StartsWith("#")) continue; var regex = new Regex("[ \t]*[= \t]"); string[] parts = regex.Split(line, 2); string keyword = parts[0].Trim(); string argValue = parts[1].Trim(); var regex2 = new Regex("[ \t]"); if (StringUtils.equalsIgnoreCase("Host", keyword)) { current.Clear(); foreach (string pattern in regex2.Split(argValue)) { string name = dequote(pattern); Host c = m.get(name); if (c == null) { c = new Host(); m.put(name, c); } current.Add(c); } continue; } if (current.isEmpty()) { // We received an option outside of a Host block. We // don't know who this should match against, so skip. // continue; } if (StringUtils.equalsIgnoreCase("HostName", keyword)) { foreach (Host c in current) if (c.hostName == null) c.hostName = dequote(argValue); } else if (StringUtils.equalsIgnoreCase("User", keyword)) { foreach (Host c in current) if (c.user == null) c.user = dequote(argValue); } else if (StringUtils.equalsIgnoreCase("Port", keyword)) { try { int port = int.Parse(dequote(argValue)); foreach (Host c in current) if (c.port == 0) c.port = port; } catch (FormatException) { // Bad port number. Don't set it. } } else if (StringUtils.equalsIgnoreCase("IdentityFile", keyword)) { foreach (Host c in current) if (c.identityFile == null) c.identityFile = toFile(dequote(argValue)); } else if (StringUtils.equalsIgnoreCase("PreferredAuthentications", keyword)) { foreach (Host c in current) if (c.preferredAuthentications == null) c.preferredAuthentications = nows(dequote(argValue)); } else if (StringUtils.equalsIgnoreCase("BatchMode", keyword)) { foreach (Host c in current) if (c.batchMode == null) c.batchMode = yesno(dequote(argValue)); } else if (StringUtils.equalsIgnoreCase("StrictHostKeyChecking", keyword)) { string value = dequote(argValue); foreach (Host c in current) if (c.strictHostKeyChecking == null) c.strictHostKeyChecking = value; } } return m; }
private void verifyPrerequisites() { if (_prereqs.isEmpty()) return; using (var rw = new RevWalk.RevWalk(_transport.Local)) { RevFlag PREREQ = rw.newFlag("PREREQ"); RevFlag SEEN = rw.newFlag("SEEN"); IDictionary<ObjectId, string> missing = new Dictionary<ObjectId, string>(); var commits = new List<RevObject>(); foreach (KeyValuePair<ObjectId, string> e in _prereqs) { ObjectId p = e.Key; try { RevCommit c = rw.parseCommit(p); if (!c.has(PREREQ)) { c.add(PREREQ); commits.Add(c); } } catch (MissingObjectException) { missing.put(p, e.Value); } catch (IOException err) { throw new TransportException(_transport.Uri, "Cannot Read commit " + p.Name, err); } } if (!missing.isEmpty()) throw new MissingBundlePrerequisiteException(_transport.Uri, missing); foreach (Ref r in _transport.Local.getAllRefs().Values) { try { rw.markStart(rw.parseCommit(r.ObjectId)); } catch (IOException) { // If we cannot read the value of the ref skip it. } } int remaining = commits.Count; try { RevCommit c; while ((c = rw.next()) != null) { if (c.has(PREREQ)) { c.add(SEEN); if (--remaining == 0) break; } } } catch (IOException err) { throw new TransportException(_transport.Uri, "Cannot Read object", err); } if (remaining > 0) { foreach (RevObject o in commits) { if (!o.has(SEEN)) missing.put(o, _prereqs.get(o)); } throw new MissingBundlePrerequisiteException(_transport.Uri, missing); } } }
private void readBundleV2() { byte[] hdrbuf = new byte[1024]; var avail = new Dictionary<string, Ref>(); for (; ; ) { string line = readLine(hdrbuf); if (line.Length == 0) break; if (line[0] == '-') { ObjectId id = ObjectId.FromString(line.Slice(1, 41)); String shortDesc = null; if (line.Length > 42) shortDesc = line.Substring(42); _prereqs.put(id, shortDesc); continue; } string name = line.Slice(41, line.Length); ObjectId id2 = ObjectId.FromString(line.Slice(0, 40)); Ref prior = avail.put(name, new Unpeeled(Storage.Network, name, id2)); if (prior != null) { throw duplicateAdvertisement(name); } } available(avail); }
private void RefreshPackedRefs() { _packedRefsFile.Refresh(); if (!_packedRefsFile.Exists) return; DateTime currTime = _packedRefsFile.LastWriteTime; long currLen = currTime == DateTime.MinValue ? 0 : _packedRefsFile.Length; if (currTime == _packedRefsLastModified && currLen == _packedRefsLength) return; if (currTime == DateTime.MinValue) { _packedRefsLastModified = DateTime.MinValue; _packedRefsLength = 0; _packedRefs = new Dictionary<string, Ref>(); return; } var newPackedRefs = new Dictionary<string, Ref>(); try { using (var b = OpenReader(_packedRefsFile)) { string p; Ref last = null; while ((p = b.ReadLine()) != null) { if (p[0] == '#') continue; if (p[0] == '^') { if (last == null) { throw new IOException("Peeled line before ref."); } ObjectId id = ObjectId.FromString(p.Substring(1)); last = new Ref(Ref.Storage.Packed, last.Name, last.Name, last.ObjectId, id, true); newPackedRefs.put(last.Name, last); continue; } int sp = p.IndexOf(' '); ObjectId id2 = ObjectId.FromString(p.Slice(0, sp)); string name = p.Substring(sp + 1); last = new Ref(Ref.Storage.Packed, name, name, id2); newPackedRefs.Add(last.Name, last); } } _packedRefsLastModified = currTime; _packedRefsLength = currLen; _packedRefs = newPackedRefs; SetModified(); } catch (FileNotFoundException) { // Ignore it and leave the new map empty. // _packedRefsLastModified = DateTime.MinValue; _packedRefsLength = 0; _packedRefs = newPackedRefs; } catch (IOException e) { throw new GitException("Cannot read packed refs", e); } }
private static void readPackedRefsImpl(Dictionary<string, Ref> avail, StreamReader sr) { Ref last = null; bool peeled = false; for (; ; ) { string line = sr.ReadLine(); if (line == null) break; if (line[0] == '#') { if (line.StartsWith(RefDirectory.PACKED_REFS_HEADER)) { line = line.Substring(RefDirectory.PACKED_REFS_HEADER.Length); peeled = line.Contains(RefDirectory.PACKED_REFS_PEELED); } continue; } if (line[0] == '^') { if (last == null) throw new TransportException("Peeled line before ref"); ObjectId pid = ObjectId.FromString(line.Substring(1)); last = new PeeledTag(Storage.Packed, last.Name, last.ObjectId, pid); avail.put(last.Name, last); continue; } int sp = line.IndexOf(' '); if (sp < 0) throw new TransportException("Unrecognized ref: " + line); ObjectId id = ObjectId.FromString(line.Slice(0, sp)); string name = line.Substring(sp + 1); if (peeled) last = new PeeledNonTag(Storage.Packed, name, id); else last = new Unpeeled(Storage.Packed, name, id); avail.put(last.Name, last); } }
/// <summary> /// This <c>read</c> method will read the XML element map from /// the provided node and deserialize its children as entry types. /// Each entry type must contain a key and value so that the entry /// can be inserted in to the map as a pair. If either the key or /// value is composite it is read as a root object, which means its /// <c>Root</c> annotation must be present and the name of the /// object element must match that root element name. /// </summary> /// <param name="node"> /// this is the XML element that is to be deserialized /// </param> /// <param name="map"> /// this is the map object that is to be populated /// </param> /// <returns> /// this returns the item to attach to the object contact /// </returns> public Object Read(InputNode node, Dictionary map) { InputNode from = node.getParent(); String name = node.getName(); while(node != null) { Object index = key.Read(node); Object item = value.Read(node); if(map != null) { map.put(index, item); } node = from.getNext(name); } return map; }
private void readAdvertisedRefsImpl() { var avail = new Dictionary<string, Ref>(); while (true) { string line; try { line = pckIn.ReadString(); } catch (EndOfStreamException) { if (avail.Count == 0) { throw noRepository(); } throw; } if (line == PacketLineIn.END) break; if (avail.Count == 0) { int nul = line.IndexOf('\0'); if (nul >= 0) { // The first line (if any) may contain "hidden" // capability values after a NUL byte. foreach (string c in line.Substring(nul + 1).Split(' ')) remoteCapabilies.Add(c); line = line.Slice(0, nul); } } string name = line.Slice(41, line.Length); if (avail.Count == 0 && name.Equals("capabilities^{}")) { // special line from git-receive-pack to show // capabilities when there are no refs to advertise continue; } ObjectId id = ObjectId.FromString(line.Slice(0, 40)); if (name.Equals(".have")) additionalHaves.Add(id); else if (name.EndsWith("^{}")) { name = name.Slice(0, name.Length - 3); Ref prior = avail.get(name); if (prior == null) throw new PackProtocolException(uri, "advertisement of " + name + "^{} came before " + name); if (prior.PeeledObjectId != null) throw duplicateAdvertisement(name + "^{}"); avail.put(name, new PeeledTag(Storage.Network, name, prior.ObjectId, id)); } else { Ref prior = avail.put(name, new PeeledNonTag(Storage.Network, name, id)); if (prior != null) throw duplicateAdvertisement(name); } } available(avail); }
/** * @return a map with all objects referenced by a peeled ref. */ public Dictionary<AnyObjectId, List<Ref>> getAllRefsByPeeledObjectId() { Dictionary<String, Ref> allRefs = getAllRefs(); var ret = new Dictionary<AnyObjectId, List<Ref>>(allRefs.Count); foreach (Ref @ref in allRefs.Values) { Ref ref2 = @ref; if (!ref2.Peeled) ref2 = Peel(ref2); AnyObjectId target = ref2.PeeledObjectId; if (target == null) target = ref2.ObjectId; // We assume most Sets here are singletons List<Ref> oset = ret.put(target, new List<Ref>{ref2}); if (oset != null) { // that was not the case (rare) if (oset.Count == 1) { // Was a read-only singleton, we must copy to a new Set oset = new List<Ref>(oset); } ret.put(target, oset); oset.Add(ref2); } } return ret; }
private IDictionary<string, RemoteRefUpdate> PrepareRemoteUpdates() { IDictionary<string, RemoteRefUpdate> result = new Dictionary<string, RemoteRefUpdate>(); foreach (RemoteRefUpdate rru in _toPush.Values) { Ref advertisedRef = _connection.GetRef(rru.RemoteName); ObjectId advertisedOld = (advertisedRef == null ? ObjectId.ZeroId : advertisedRef.ObjectId); if (rru.NewObjectId.Equals(advertisedOld)) { if (rru.IsDelete) { // ref does exist neither locally nor remotely rru.Status = RemoteRefUpdate.UpdateStatus.NON_EXISTING; } else { // same object - nothing to do rru.Status = RemoteRefUpdate.UpdateStatus.UP_TO_DATE; } continue; } // caller has explicitly specified expected old object id, while it // has been changed in the mean time - reject if (rru.IsExpectingOldObjectId && !rru.ExpectedOldObjectId.Equals(advertisedOld)) { rru.Status = RemoteRefUpdate.UpdateStatus.REJECTED_REMOTE_CHANGED; continue; } // Create ref (hasn't existed on remote side) and delete ref // are always fast-forward commands, feasible at this level if (advertisedOld.Equals(ObjectId.ZeroId) || rru.IsDelete) { rru.FastForward = true; result.put(rru.RemoteName, rru); continue; } // check for fast-forward: // - both old and new ref must point to commits, AND // - both of them must be known for us, exist in repository, AND // - old commit must be ancestor of new commit bool fastForward = true; try { RevCommit oldRev = (_walker.parseAny(advertisedOld) as RevCommit); RevCommit newRev = (_walker.parseAny(rru.NewObjectId) as RevCommit); if (oldRev == null || newRev == null || !_walker.isMergedInto(oldRev, newRev)) fastForward = false; } catch (MissingObjectException) { fastForward = false; } catch (Exception x) { throw new TransportException(_transport.Uri, "reading objects from local repository failed: " + x.Message, x); } rru.FastForward = fastForward; if (!fastForward && !rru.ForceUpdate) { rru.Status = RemoteRefUpdate.UpdateStatus.REJECTED_NONFASTFORWARD; } else { result.put(rru.RemoteName, rru); } } return result; }
public void Commit(Dictionary map) { map.put(name, value); }