public void TimestampCopy() { Timestamp timestamp1 = new Timestamp(); Timestamp timestamp2 = timestamp1; Assert.AreEqual(timestamp1, timestamp2); }
public FirstOrderHistory(Timestamp initialTime, decimal initialValue, Rate initialRate) { Moments = new SortedList<Timestamp, Snapshot> { { initialTime, new Snapshot(initialTime, initialValue, initialRate) } }; }
public Every And(Timestamp to) { _to = to; _b.AddConstraint(new Between(_from, _to)); return _b; }
public IRankedList<ITrack> GetMonthlyChart(string username, int year, int month, uint take) { //TODO: this method definitely needs to rely on some error handling as the throttle limit is met quite easy IUserService userService = new UserService(this.Session); var startDate = new DateTime(year, month, 1); var startTimestamp = new Timestamp(startDate); var endDate = new DateTime(year, month + 1, 1).AddSeconds(-1); var endTimestamp = new Timestamp(endDate); var tracks = new Collection<ITrack>(); int page = 1; int totalPages = 1; while (page <= totalPages && page < 50) { var recentTracks = userService.GetRecentTracks(username, 200, page, startTimestamp, endTimestamp); if (totalPages != recentTracks.TotalPages) { totalPages = recentTracks.TotalPages; } foreach (var recentTrack in recentTracks) { tracks.Add(recentTrack); } page++; } // TODO: refactor all over the place the use of int / uint / long / ulong return new RankedListBuilder<ITrack>(tracks).Skim((int)take); }
public static DateTime SetTime(this DateTime @this, Timestamp timestamp) { return @this.Date.AddHours(timestamp.Hour) .AddMinutes(timestamp.Minute) .AddSeconds(timestamp.Second) .AddMilliseconds(timestamp.Ms); }
public AllTypesRow(long uid, string s1, double d1, HiveDecimal @decimal, Timestamp ts) { this.userid = uid; this.string1 = s1; this.subtype = d1; this.decimal1 = @decimal; this.ts = ts; }
protected override DateTime ApplyRule(DateTime datetime, bool inclusive) { var comparison = new Timestamp(datetime).CompareTo(_timestamp); DateTime candidate; if (IsSameDay(datetime, _day)) { if (comparison == 0 && inclusive) { _stepFunc = x => x; return _stepFunc(datetime); } if (comparison > 0 || (comparison == 0 && !inclusive)) { _stepFunc = x => x.AddYears(1).SetDayInYear(_day).SetTime(_timestamp); candidate = _stepFunc(datetime); } else { _stepFunc = x => x.SetTime(_timestamp); candidate = _stepFunc(datetime); } } else { if (_day > 0) { if (_day > datetime.DayOfYear) { _stepFunc = x => x.SetDayInYear(_day).SetTime(_timestamp); candidate = _stepFunc(datetime); } else { _stepFunc = x => x.AddYears(1).SetDayInYear(_day).SetTime(_timestamp); candidate = _stepFunc(datetime); } } else { if (datetime.DaysOfMonth() + _day > datetime.Day) { _stepFunc = x => x.SetDayInYear(_day).SetTime(_timestamp); candidate = _stepFunc(datetime); } else { _stepFunc = x => x.AddYears(1).SetDayInYear(_day).SetTime(_timestamp); candidate = _stepFunc(datetime); } } } return candidate; }
public void Run() { using (var fs = File.OpenRead(IN_Path)) { BinaryReader br = new BinaryReader(fs); string sig = br.ReadStringFixedAscii(4); if (sig != "SBI\0") throw new SBIParseException("Missing magic number"); SubQPatchData ret = new SubQPatchData(); List<short> bytes = new List<short>(); //read records until done for (; ; ) { //graceful end if (fs.Position == fs.Length) break; if (fs.Position + 4 > fs.Length) throw new SBIParseException("Broken record"); var m = BCD2.BCDToInt(br.ReadByte()); var s = BCD2.BCDToInt(br.ReadByte()); var f = BCD2.BCDToInt(br.ReadByte()); var ts = new Timestamp(m, s, f); ret.ABAs.Add(ts.Sector); int type = br.ReadByte(); switch (type) { case 1: //Q0..Q9 if (fs.Position + 10 > fs.Length) throw new SBIParseException("Broken record"); for (int i = 0; i <= 9; i++) bytes.Add(br.ReadByte()); for (int i = 10; i <= 11; i++) bytes.Add(-1); break; case 2: //Q3..Q5 if (fs.Position + 3 > fs.Length) throw new SBIParseException("Broken record"); for (int i = 0; i <= 2; i++) bytes.Add(-1); for (int i = 3; i <= 5; i++) bytes.Add(br.ReadByte()); for (int i = 6; i <= 11; i++) bytes.Add(-1); break; case 3: //Q7..Q9 if (fs.Position + 3 > fs.Length) throw new SBIParseException("Broken record"); for (int i = 0; i <= 6; i++) bytes.Add(-1); for (int i = 7; i <= 9; i++) bytes.Add(br.ReadByte()); for (int i = 10; i <= 11; i++) bytes.Add(-1); break; default: throw new SBIParseException("Broken record"); } } ret.subq = bytes.ToArray(); OUT_Data = ret; } }
public OS9FileInfo(string name, int size, OS9FileAttributes attributes, Timestamp createdTime, Timestamp modifiedTime, int owner, int links, OS9FileSegment[] segments) { Name = name; Size = size; Attributes = attributes; CreateTime = createdTime; ModifiedTime = modifiedTime; OwnerId = owner; LinkCount = links; Segments = segments; }
public SubSeekableAudioStream(ISeekableAudioStream parent, Timestamp start, Timestamp end, bool disposeAfterUse = true) { _parent = parent; _disposeAfterUse = disposeAfterUse; _start = AudioStreamHelper.ConvertTimeToStreamPos(start, Rate, IsStereo); _pos = new Timestamp(0, Rate * (IsStereo ? 2 : 1)); _length = AudioStreamHelper.ConvertTimeToStreamPos(end, Rate, IsStereo) - _start; Debug.Assert(_length.TotalNumberOfFrames % (IsStereo ? 2 : 1) == 0); _parent.Seek(_start); }
public Snapshot At(Timestamp t) { var current = Moments.First(); foreach(var c in Moments) { if (c.Key > t) break; current = c; } return new Snapshot(t, current.Value.Project(t - current.Key), current.Value.rateOfChange); }
public uint GetFrameAtTime(Timestamp time) { Rational frameRate = FrameRate; // Easy conversion if (frameRate == time.Framerate) return (uint)time.TotalNumberOfFrames; // Create the rational based on the time first to hopefully cancel out // *something* when multiplying by the frameRate (which can be large in // some AVI videos). return (uint)(int)(new Rational(time.TotalNumberOfFrames, time.Framerate) * frameRate); }
private void Sanitize(Timestamp t, bool includeMin = true) { if (Latest.Time >= t) { // Clear out the times past this. We're just making this // easy for the editor, in the game you wouldn't be able to accidentally ovewrrite the past. var futureMoments = Moments.Keys.Where(x => x >= t).ToList(); futureMoments.ForEach(x => Moments.Remove(x)); } if (Moments.Count == 0 && includeMin) { // We cleared out all history, so add back the 0,0 state Moments.Add(Timestamp.Min(), new Snapshot(Timestamp.Min(), 0, Rate.Zero())); } }
public bool Seek(Timestamp wh) { _endOfData = true; if (wh > _playtime) return false; var seekSample = AudioStreamHelper.ConvertTimeToStreamPos(wh, Rate, IsStereo).TotalNumberOfFrames; _stream.Seek(seekSample * (_is16Bit ? 2 : 1), SeekOrigin.Begin); // In case of an error we will not continue stream playback. if (_stream.Position != _stream.Length) _endOfData = false; return true; }
public SubLoopingAudioStream(ISeekableAudioStream stream, uint loops, Timestamp loopStart, Timestamp loopEnd, bool disposeAfterUse = true) { _parent = stream; _loops = loops; _pos = new Timestamp(0, Rate * (IsStereo ? 2 : 1)); _loopStart = AudioStreamHelper.ConvertTimeToStreamPos(loopStart, Rate, IsStereo); _loopEnd = AudioStreamHelper.ConvertTimeToStreamPos(loopEnd, Rate, IsStereo); _done = false; Debug.Assert(loopStart < loopEnd); if (!_parent.Rewind()) _done = true; }
public RawStream(AudioFlags flags, int rate, bool disposeStream, Stream stream) { _is16Bit = flags.HasFlag(AudioFlags.Is16Bits); _isLE = flags.HasFlag(AudioFlags.LittleEndian); _isUnsigned = flags.HasFlag(AudioFlags.Unsigned); _rate = rate; _isStereo = flags.HasFlag(AudioFlags.Stereo); _playtime = new Timestamp(0, rate); _stream = stream; _disposeStream = disposeStream; // Setup our buffer for readBuffer _buffer = new byte[SampleBufferLength * (_is16Bit ? 2 : 1)]; // Calculate the total playtime of the stream _playtime = new Timestamp(0, (int)_stream.Length / (_isStereo ? 2 : 1) / (_is16Bit ? 2 : 1), rate); }
protected override Comparison Compare(Timestamp aFirst, Timestamp aSecond) { DummyTimestamp first = DummyTimestamp.FromString(aFirst.Serialization); DummyTimestamp second = DummyTimestamp.FromString(aSecond.Serialization); if (first.Id == second.Id) { return Comparison.Equal; } if (first.Predecessors.Contains(second.Id)) { return Comparison.MoreThan; } if (second.Predecessors.Contains(first.Id)) { return Comparison.LessThan; } return Comparison.Unordered; }
public PsxVideoTrack(Stream firstSector, CDSpeed speed, uint frameCount, PixelFormat screenFormat) { var br = new BinaryReader(firstSector); _nextFrameStartTime = new Timestamp(0, (int)speed); _frameCount = frameCount; firstSector.Seek(40, SeekOrigin.Begin); _width = br.ReadUInt16(); _height = br.ReadUInt16(); _surface = new Surface(_width, _height, screenFormat, false); _macroBlocksW = (ushort)((_width + 15) / 16); _macroBlocksH = (ushort)((_height + 15) / 16); _yBuffer = new byte[_macroBlocksW * _macroBlocksH * 16 * 16]; _cbBuffer = new byte[_macroBlocksW * _macroBlocksH * 8 * 8]; _crBuffer = new byte[_macroBlocksW * _macroBlocksH * 8 * 8]; _endOfTrack = false; _curFrame = -1; _acHuffman = new Huffman(0, AC_CODE_COUNT, s_huffmanACCodes, s_huffmanACLengths, s_huffmanACSymbols); _dcHuffmanChroma = new Huffman(0, DC_CODE_COUNT, s_huffmanDCChromaCodes, s_huffmanDCChromaLengths, s_huffmanDCSymbols); _dcHuffmanLuma = new Huffman(0, DC_CODE_COUNT, s_huffmanDCLumaCodes, s_huffmanDCLumaLengths, s_huffmanDCSymbols); }
public static Timestamp ConvertTimeToStreamPos(Timestamp where, int rate, bool isStereo) { var result = new Timestamp(where.ConvertToFramerate(rate * (isStereo ? 2 : 1))); // When the Stream is a stereo stream, we have to assure // that the sample position is an even number. if (isStereo && (result.TotalNumberOfFrames & 1) != 0) result = result.AddFrames(-1); // We cut off one sample here. // Since Timestamp allows sub-frame-precision it might lead to odd behaviors // when we would just return result. // // An example is when converting the timestamp 500ms to a 11025 Hz based // stream. It would have an internal frame counter of 5512.5. Now when // doing calculations at frame precision, this might lead to unexpected // results: The frame difference between a timestamp 1000ms and the above // mentioned timestamp (both with 11025 as framerate) would be 5512, // instead of 5513, which is what a frame-precision based code would expect. // // By creating a new Timestamp with the given parameters, we create a // Timestamp with frame-precision, which just drops a sub-frame-precision // information (i.e. rounds down). return new Timestamp(result.Seconds, result.NumberOfFrames, result.Framerate); }
private void RunMednaDisc() { var disc = new Disc(); OUT_Disc = disc; //create a MednaDisc and give it to the disc for ownership var md = new MednaDisc(IN_FromPath); disc.DisposableResources.Add(md); //"length of disc" for BizHawk's purposes (NOT a robust concept!) is determined by beginning of leadout track var m_leadoutTrack = md.TOCTracks[100]; int nSectors = (int)m_leadoutTrack.lba; //make synth param memos disc.SynthParams.MednaDisc = md; //this is the sole sector synthesizer we'll need var synth = new SS_MednaDisc(); OUT_Disc.SynthProvider = new SimpleSectorSynthProvider { SS = synth }; //ADR (q-Mode) is necessarily 0x01 for a RawTOCEntry const int kADR = 1; const int kUnknownControl = 0; //mednafen delivers us what is essentially but not exactly (or completely) a TOCRaw. //we need to synth RawTOCEntries from this and then turn it into a proper TOCRaw //when coming from mednafen, there are 101 entries. //entry[0] is placeholder junk, not to be used //entry[100] is the leadout track (A0) //A1 and A2 are in the form of FirstRecordedTrackNumber and LastRecordedTrackNumber for (int i = 1; i < 101; i++) { var m_te = md.TOCTracks[i]; //don't add invalid (absent) items if (!m_te.Valid) { continue; } var m_ts = new Timestamp((int)m_te.lba + 150); //these are supposed to be absolute timestamps var q = new SubchannelQ { q_status = SubchannelQ.ComputeStatus(kADR, (EControlQ)m_te.control), q_tno = BCD2.FromDecimal(0), //unknown with mednadisc q_index = BCD2.FromDecimal(i), min = BCD2.FromDecimal(0), //unknown with mednadisc sec = BCD2.FromDecimal(0), //unknown with mednadisc frame = BCD2.FromDecimal(0), //unknown with mednadisc zero = 0, //unknown with mednadisc ap_min = BCD2.FromDecimal(m_ts.MIN), ap_sec = BCD2.FromDecimal(m_ts.SEC), ap_frame = BCD2.FromDecimal(m_ts.FRAC), q_crc = 0 //meaningless }; //a special fixup: mednafen's entry 100 is the lead-out track, so change it into the A2 raw toc entry if (i == 100) { q.q_index.BCDValue = 0xA2; } disc.RawTOCEntries.Add(new RawTOCEntry { QData = q }); } // synth A0 and A1 entries (indicating first and last recorded tracks and also session type) var qA0 = new SubchannelQ { q_status = SubchannelQ.ComputeStatus(kADR, kUnknownControl), q_tno = BCD2.FromDecimal(0), //unknown with mednadisc q_index = BCD2.FromBCD(0xA0), min = BCD2.FromDecimal(0), //unknown with mednadisc sec = BCD2.FromDecimal(0), //unknown with mednadisc frame = BCD2.FromDecimal(0), //unknown with mednadisc zero = 0, //unknown with mednadisc ap_min = BCD2.FromDecimal(md.TOC.first_track), ap_sec = BCD2.FromDecimal(md.TOC.disc_type), ap_frame = BCD2.FromDecimal(0), q_crc = 0, //meaningless }; disc.RawTOCEntries.Add(new RawTOCEntry { QData = qA0 }); var qA1 = new SubchannelQ { q_status = SubchannelQ.ComputeStatus(kADR, kUnknownControl), q_tno = BCD2.FromDecimal(0), //unknown with mednadisc q_index = BCD2.FromBCD(0xA1), min = BCD2.FromDecimal(0), //unknown with mednadisc sec = BCD2.FromDecimal(0), //unknown with mednadisc frame = BCD2.FromDecimal(0), //unknown with mednadisc zero = 0, //unknown with mednadisc ap_min = BCD2.FromDecimal(md.TOC.last_track), ap_sec = BCD2.FromDecimal(0), ap_frame = BCD2.FromDecimal(0), q_crc = 0, //meaningless }; disc.RawTOCEntries.Add(new RawTOCEntry { QData = qA1 }); }
// ReSharper disable once MemberCanBeMadeStatic.Local private Timestamp GetTimestampWithOffset(Timestamp origin, int offset) { return(Timestamp.FromDateTime(origin.ToDateTime().AddMilliseconds(offset))); }
public override string ToString() { return(Timestamp.ToString()); }
public static Timestamp AddDays(this Timestamp timestamp, long days) { return(timestamp + new Duration { Seconds = days.Mul(24 * 60 * 60) }); }
public static Timestamp AddMinutes(this Timestamp timestamp, long minutes) { return(timestamp + new Duration { Seconds = minutes.Mul(60) }); }
/// <summary> /// Initializes a new TopicPartitionTimestamp instance. /// </summary> /// <param name="topic"> /// A Kafka topic name. /// </param> /// <param name="partition"> /// A Kafka partition. /// </param> /// <param name="timestamp"> /// A Kafka timestamp value. /// </param> public TopicPartitionTimestamp(string topic, Partition partition, Timestamp timestamp) { Topic = topic; Partition = partition; Timestamp = timestamp; }
static IFixture CreateFixture() { var fixture = new Fixture(); fixture.Customize <ToDoItem>(c => c .Without(p => p.Id) .Without(p => p.InsertedOn) .With(p => p.IsDone, false) .With(p => p.DueDate, (DateTimeOffset dto) => Timestamp.FromDateTimeOffset(dto)) .Do(item => fixture.AddManyTo(item.Tags))); return(fixture); }
/// <summary> /// Compares the current instance with another object of the same type. /// </summary> public int CompareTo(TrendPoint other) { return(Timestamp.CompareTo(other.Timestamp)); }
public bool IsSlashed(Timestamp time) { return(((time - StartTime) - DurationInSeconds) >= SlashLimitInSeconds); }
private void reset_next_shoot_timestamp() { next_shoot_timestamp = Timestamp.In(1f); }
public override string ToString() { return($"[{Timestamp.ToLocalTime():HH:mm:ss}]: {Description}"); }
public KafkaMessage(string key, string source, TopicPartitionOffset topicPartitionOffset, Timestamp timestamp) { Key = key; Source = source; TopicPartitionOffset = topicPartitionOffset; Timestamp = timestamp; }
// TODO: public void Start(Timestamp limit) { Stop(); throw new NotImplementedException(); var stream = AudioStream; if (stream == null) throw new InvalidOperationException("stream should not be null"); // stream = new LimitingAudioStream(stream, limit, false); _handle = Mixer.PlayStream(SoundType, stream, -1, _muted ? 0 : Volume, Balance, true); // Pause the audio again if we're still paused if (IsPaused) Mixer.PauseHandle(_handle, true); }
/// <summary> Initializes a new instance of the <see cref="HotkeyEvent"/> class. </summary> /// <param name="player"> The player pressing the hotkey. </param> /// <param name="time"> The time at which the event occured. </param> public HotkeyEvent(Player player, Timestamp time) : base(player, time) { this.EventType = GameEventType.Other; }
/// <summary> /// Return a text representation of this object. /// </summary> public override String ToString() => String.Concat(Timestamp.ToIso8601(), " / ", SampledValues.Count(), " sampled values");
public static Timestamp AddSeconds(this Timestamp timestamp, long seconds) { return(timestamp + new Duration { Seconds = seconds }); }
public int CompareTo(DurableEvent <T> other) => Timestamp.CompareTo(other.Timestamp);
public static Timestamp AddHours(this Timestamp timestamp, long hours) { return(timestamp + new Duration { Seconds = hours.Mul(60 * 60) }); }
public void ListToken(Address from, string baseSymbol, string quoteSymbol, BigInteger tokenID, BigInteger price, BigInteger endPrice, Timestamp startDate, Timestamp endDate, BigInteger extensionPeriod, BigInteger typeAuction, BigInteger listingFee, Address listingFeeAddress) { Runtime.Expect(Runtime.IsWitness(from), "invalid witness"); if (startDate < Runtime.Time) // initialize start date to Runtime.Time if its before that { startDate = Runtime.Time; } Runtime.Expect(Runtime.TokenExists(quoteSymbol), "invalid quote token"); var quoteToken = Runtime.GetToken(quoteSymbol); Runtime.Expect(quoteToken.Flags.HasFlag(TokenFlags.Fungible), "quote token must be fungible"); Runtime.Expect(Runtime.TokenExists(baseSymbol), "invalid base token"); var baseToken = Runtime.GetToken(baseSymbol); Runtime.Expect(!baseToken.Flags.HasFlag(TokenFlags.Fungible), "base token must be non-fungible"); var nft = Runtime.ReadToken(baseSymbol, tokenID); Runtime.Expect(nft.CurrentChain == Runtime.Chain.Name, "token not currently in this chain"); Runtime.Expect(nft.CurrentOwner == from, "invalid owner"); Runtime.Expect(listingFee <= 5, "listingFee has to be <= 5%"); Runtime.Expect(listingFee == 0 || listingFeeAddress != Address.Null, "Fee receiving address cannot be null"); TypeAuction type; if (typeAuction == 1) // Classic { Runtime.Expect(endDate > startDate, "end date must be later than start date"); Runtime.Expect(extensionPeriod <= oneHour, "extensionPeriod must be <= 1 hour"); var maxAllowedDate = Runtime.Time + TimeSpan.FromDays(30); Runtime.Expect(endDate <= maxAllowedDate, "end date is too distant, max: " + maxAllowedDate + ", received: " + endDate); endPrice = 0; type = TypeAuction.Classic; } else if (typeAuction == 2) // Reserve { Runtime.Expect(extensionPeriod <= oneHour, "extensionPeriod must be <= 1 hour"); endPrice = 0; startDate = 0; endDate = 0; type = TypeAuction.Reserve; } else if (typeAuction == 3) // Dutch { Runtime.Expect(endDate > startDate, "end date must be later than start date"); Runtime.Expect(endPrice < price, "final price has to be lower than initial price"); var maxAllowedDate = Runtime.Time + TimeSpan.FromDays(30); Runtime.Expect(endDate <= maxAllowedDate, "end date is too distant, max: " + maxAllowedDate + ", received: " + endDate); extensionPeriod = 0; type = TypeAuction.Dutch; } else // Default - Fixed { if (endDate != 0) { Runtime.Expect(endDate > Runtime.Time, "invalid end date"); } endPrice = 0; extensionPeriod = 0; type = TypeAuction.Fixed; } Runtime.TransferToken(baseToken.Symbol, from, this.Address, tokenID); var auction = new MarketAuction(from, startDate, endDate, baseSymbol, quoteSymbol, tokenID, price, endPrice, extensionPeriod, type, listingFee, listingFeeAddress, 0, Address.Null, Address.Null); var auctionID = baseSymbol + "." + tokenID; _auctionMap.Set(auctionID, auction); _auctionIds.Set(auctionID, auctionID); Runtime.Notify(EventKind.OrderCreated, from, new MarketEventData() { ID = tokenID, BaseSymbol = baseSymbol, QuoteSymbol = quoteSymbol, Price = price, EndPrice = endPrice, Type = type }); }
public static Timestamp Max(Timestamp timestamp1, Timestamp timestamp2) { return(timestamp1 > timestamp2 ? timestamp1 : timestamp2); }
public void BidToken(Address from, string symbol, BigInteger tokenID, BigInteger price, BigInteger buyingFee, Address buyingFeeAddress) { Runtime.Expect(Runtime.IsWitness(from), "invalid witness"); var auctionID = symbol + "." + tokenID; Runtime.Expect(_auctionMap.ContainsKey <string>(auctionID), "invalid auction"); var auction = _auctionMap.Get <string, MarketAuction>(auctionID); Runtime.Expect(buyingFee <= 5, "buyingFee has to be <= 5%"); Runtime.Expect(auction.StartDate < Runtime.Time, "you can not bid on an auction which has not started"); MarketAuction auctionNew; if (Runtime.Time >= auction.EndDate && auction.EndDate != 0) // if auction ended trigger sale end { if (auction.Type == TypeAuction.Dutch || auction.Type == TypeAuction.Fixed || auction.CurrentBidWinner == Address.Null) { // no winners, cancel the auction CancelSale(auction.BaseSymbol, auction.TokenID); } else { // current bid is winner EndSaleInternal(auction.CurrentBidWinner, auction.BaseSymbol, auction.TokenID, auction); Runtime.Notify(EventKind.OrderFilled, auction.CurrentBidWinner, new MarketEventData() { ID = auction.TokenID, BaseSymbol = auction.BaseSymbol, QuoteSymbol = auction.QuoteSymbol, Price = auction.Price, EndPrice = auction.EndPrice, Type = auction.Type }); } } else { if (auction.Type == TypeAuction.Classic || auction.Type == TypeAuction.Reserve) { Runtime.Expect(from != auction.Creator, "you can not bid on your own auctions"); if (auction.EndPrice == 0) { Runtime.Expect(price >= auction.Price, "bid has to be higher or equal to starting price"); } else { var minBid = (auction.EndPrice / 100) + auction.EndPrice; if (minBid == auction.EndPrice) { minBid = minBid + 1; } Runtime.Expect(price >= minBid, "bid has to be minimum 1% higher than last bid"); } Timestamp startDateNew = auction.StartDate; Timestamp endDateNew = auction.EndDate; if (auction.StartDate == 0) // if reserve auction not started { startDateNew = Runtime.Time; endDateNew = Runtime.Time + TimeSpan.FromDays(1); } else if ((auction.EndDate - Runtime.Time) < auction.ExtensionPeriod) // extend timer if < extensionPeriod { endDateNew = Runtime.Time + TimeSpan.FromSeconds((double)auction.ExtensionPeriod); } // calculate listing & buying & refund fees BigInteger combinedFees = 0; BigInteger combinedRefund = 0; if (auction.ListingFee != 0) { combinedFees += GetFee(auction.QuoteSymbol, price, auction.ListingFee); combinedRefund += GetFee(auction.QuoteSymbol, auction.EndPrice, auction.ListingFee); } if (buyingFee != 0) { combinedFees += GetFee(auction.QuoteSymbol, price, buyingFee); } if (auction.BuyingFee != 0) { combinedRefund += GetFee(auction.QuoteSymbol, auction.EndPrice, auction.BuyingFee); } combinedFees += price; combinedRefund += auction.EndPrice; // transfer price + listing + buying fees to contract Runtime.TransferTokens(auction.QuoteSymbol, from, this.Address, combinedFees); // refund old bid amount + listing + buying fees to previous current winner if any if (auction.CurrentBidWinner != Address.Null) { Runtime.TransferTokens(auction.QuoteSymbol, this.Address, auction.CurrentBidWinner, combinedRefund); } auctionNew = new MarketAuction(auction.Creator, startDateNew, endDateNew, auction.BaseSymbol, auction.QuoteSymbol, auction.TokenID, auction.Price, price, auction.ExtensionPeriod, auction.Type, auction.ListingFee, auction.ListingFeeAddress, buyingFee, buyingFeeAddress, from); _auctionMap.Set(auctionID, auctionNew); Runtime.Notify(EventKind.OrderBid, from, new MarketEventData() { ID = auctionNew.TokenID, BaseSymbol = auctionNew.BaseSymbol, QuoteSymbol = auctionNew.QuoteSymbol, Price = auctionNew.Price, EndPrice = auctionNew.EndPrice, Type = auctionNew.Type }); } if (auction.Type == TypeAuction.Dutch) { Runtime.Expect(from != auction.Creator, "you can not bid on your own auctions"); var priceDiff = auction.Price - auction.EndPrice; var timeDiff = auction.EndDate - auction.StartDate; var timeSinceStart = Runtime.Time - auction.StartDate; var priceDiffSinceStart = new BigInteger(timeSinceStart * priceDiff / timeDiff); var currentPrice = auction.Price - priceDiffSinceStart; if (currentPrice < auction.EndPrice) { currentPrice = auction.EndPrice; } // calculate listing & buying fees then transfer them to contract BigInteger combinedFees = 0; if (auction.ListingFee != 0) { combinedFees += GetFee(auction.QuoteSymbol, currentPrice, auction.ListingFee); } if (buyingFee != 0) { combinedFees += GetFee(auction.QuoteSymbol, currentPrice, buyingFee); } combinedFees += currentPrice; Runtime.TransferTokens(auction.QuoteSymbol, from, this.Address, combinedFees); auctionNew = new MarketAuction(auction.Creator, auction.StartDate, auction.EndDate, auction.BaseSymbol, auction.QuoteSymbol, auction.TokenID, auction.Price, currentPrice, auction.ExtensionPeriod, auction.Type, auction.ListingFee, auction.ListingFeeAddress, buyingFee, buyingFeeAddress, from); _auctionMap.Set(auctionID, auctionNew); EndSaleInternal(from, auction.BaseSymbol, auction.TokenID, auctionNew); Runtime.Notify(EventKind.OrderBid, auctionNew.CurrentBidWinner, new MarketEventData() { ID = auctionNew.TokenID, BaseSymbol = auctionNew.BaseSymbol, QuoteSymbol = auctionNew.QuoteSymbol, Price = auctionNew.Price, EndPrice = auctionNew.EndPrice, Type = auctionNew.Type }); Runtime.Notify(EventKind.OrderFilled, auctionNew.CurrentBidWinner, new MarketEventData() { ID = auctionNew.TokenID, BaseSymbol = auctionNew.BaseSymbol, QuoteSymbol = auctionNew.QuoteSymbol, Price = auctionNew.Price, EndPrice = auctionNew.EndPrice, Type = auctionNew.Type }); } if (auction.Type == TypeAuction.Fixed) { Runtime.Expect(price == auction.Price, "bid has to be equal to current price"); auctionNew = new MarketAuction(auction.Creator, auction.StartDate, auction.EndDate, auction.BaseSymbol, auction.QuoteSymbol, auction.TokenID, auction.Price, 0, auction.ExtensionPeriod, auction.Type, auction.ListingFee, auction.ListingFeeAddress, buyingFee, buyingFeeAddress, from); _auctionMap.Set(auctionID, auctionNew); EndSaleInternal(from, auction.BaseSymbol, auction.TokenID, auctionNew); Runtime.Notify(EventKind.OrderFilled, auctionNew.CurrentBidWinner, new MarketEventData() { ID = auctionNew.TokenID, BaseSymbol = auctionNew.BaseSymbol, QuoteSymbol = auctionNew.QuoteSymbol, Price = auctionNew.Price, EndPrice = auctionNew.EndPrice, Type = auctionNew.Type }); } } }
private async Task SetExtraBlockMiningTimeSlotOfSpecificRound(Timestamp timestamp) { await _timeForProducingExtraBlockField.SetAsync(timestamp); }
public Weekday(DayOfWeek day, Timestamp timestamp) { _day = day; _timestamp = timestamp; }
/// <summary> /// Return true if ts1 >= ts2 /// </summary> /// <param name="ts1"></param> /// <param name="ts2"></param> /// <returns></returns> // ReSharper disable once MemberCanBeMadeStatic.Local private bool CompareTimestamp(Timestamp ts1, Timestamp ts2) { return(ts1.ToDateTime() >= ts2.ToDateTime()); }
public void testTimestampSerialization() { // There is a kryo which after serialize/deserialize, // Timestamp becomes Date. We get around this issue in // SearchArgumentImpl.getLiteral. Once kryo fixed the issue // We can simplify SearchArgumentImpl.getLiteral Timestamp now = new Timestamp(new java.util.Date().getTime()); SearchArgument sarg = SearchArgumentFactory.newBuilder() .startAnd() .lessThan("x", PredicateLeaf.Type.TIMESTAMP, now) .end() .build(); string serializedSarg = TestInputOutputFormat.toKryo(sarg); SearchArgument sarg2 = ConvertAstToSearchArg.create(serializedSarg); Field literalField = typeof(PredicateLeafImpl).getDeclaredField("literal"); literalField.setAccessible(true); assertTrue(literalField.get(sarg2.getLeaves()[0]) is java.util.Date); Timestamp ts = (Timestamp)sarg2.getLeaves()[0].getLiteral(); Assert.Equal(ts, now); }
public EventDialog(Campaign campaign, Event evt, Timestamp timestamp, String title, String player, Window owner = null) { InitializeComponent(); this.evt = evt; this.timestamp = timestamp; this.campaign = campaign; this.Title = title; if (owner != null) { this.Owner = owner; } bool canEdit = this.evt.canEdit(player); ColumnDefinition cd; RowDefinition rd; Label lbl; Grid g; if (this.timestamp != null) { this.parentGrp.Header = "Date/Time"; if (this.evt.duration == null) { this.evt.duration = new TimeSpan(this.timestamp.calendar, 0); } cd = new ColumnDefinition(); cd.Width = GridLength.Auto; this.parentGrid.ColumnDefinitions.Add(cd); this.parentGrid.ColumnDefinitions.Add(new ColumnDefinition()); cd = new ColumnDefinition(); cd.Width = GridLength.Auto; this.parentGrid.ColumnDefinitions.Add(cd); this.parentGrid.ColumnDefinitions.Add(new ColumnDefinition()); rd = new RowDefinition(); rd.Height = GridLength.Auto; this.parentGrid.RowDefinitions.Add(rd); Button startBut = new Button(); startBut.Content = "Start:"; startBut.Click += this.setStart; Grid.SetRow(startBut, 0); Grid.SetColumn(startBut, 0); this.parentGrid.Children.Add(startBut); this.startBox = new TextBox(); this.startBox.IsReadOnly = true; this.startBox.Text = (this.timestamp - this.evt.duration).toString(true, true); Grid.SetRow(this.startBox, 0); Grid.SetColumn(this.startBox, 1); this.parentGrid.Children.Add(this.startBox); Button endBut = new Button(); endBut.Content = "End:"; endBut.Click += this.setEnd; Grid.SetRow(endBut, 0); Grid.SetColumn(endBut, 2); this.parentGrid.Children.Add(endBut); this.endBox = new TextBox(); this.endBox.IsReadOnly = true; this.endBox.Text = this.timestamp.toString(true, true); Grid.SetRow(this.endBox, 0); Grid.SetColumn(this.endBox, 3); this.parentGrid.Children.Add(this.endBox); rd = new RowDefinition(); rd.Height = GridLength.Auto; this.parentGrid.RowDefinitions.Add(rd); Button durBut = new Button(); durBut.Content = "Duration:"; durBut.Click += this.setDuration; Grid.SetRow(durBut, 1); Grid.SetColumn(durBut, 0); this.parentGrid.Children.Add(durBut); this.durBox = new TextBox(); this.durBox.IsReadOnly = true; this.durBox.Text = this.evt.duration.toString(true); Grid.SetRow(this.durBox, 1); Grid.SetColumn(this.durBox, 1); Grid.SetColumnSpan(this.durBox, 3); this.parentGrid.Children.Add(this.durBox); if (!canEdit) { startBut.IsEnabled = false; endBut.IsEnabled = false; durBox.IsEnabled = false; } } else { this.parentGrp.Header = "Parent"; this.parentGrid.ColumnDefinitions.Add(new ColumnDefinition()); rd = new RowDefinition(); rd.Height = GridLength.Auto; this.parentGrid.RowDefinitions.Add(rd); lbl = new Label(); if (this.evt != null) { lbl.Content = this.evt.parent.parent.title; } else { lbl.Content = "Event is in vault"; } Grid.SetRow(lbl, 0); Grid.SetColumn(lbl, 0); this.parentGrid.Children.Add(lbl); } g = new Grid(); rd = new RowDefinition(); rd.Height = GridLength.Auto; this.parentGrid.RowDefinitions.Add(rd); cd = new ColumnDefinition(); cd.Width = GridLength.Auto; g.ColumnDefinitions.Add(cd); g.ColumnDefinitions.Add(new ColumnDefinition()); rd = new RowDefinition(); rd.Height = GridLength.Auto; g.RowDefinitions.Add(rd); Button tsBut = new Button(); tsBut.Content = "Timestamp:"; ///// // //button click handler // ///// Grid.SetRow(tsBut, 0); Grid.SetColumn(tsBut, 0); g.Children.Add(tsBut); this.tsBox = new TextBox(); this.tsBox.IsReadOnly = true; this.tsBox.Text = this.evt.timestamp.ToLocalTime().ToString(); Grid.SetRow(this.tsBox, 0); Grid.SetColumn(this.tsBox, 1); g.Children.Add(this.tsBox); Grid.SetRow(g, this.parentGrid.RowDefinitions.Count); Grid.SetColumn(g, 0); Grid.SetColumnSpan(g, this.parentGrid.ColumnDefinitions.Count); this.parentGrid.Children.Add(g); ///// // //this.descGrid: //[notes label] if this.evt.canViewNotes(player) //[notes box] if this.evt.canViewNotes(player) (deal with notesBox if not canEdit) //anything dynamic for this.resGrid // ///// this.viewersLst.Items.SortDescriptions.Add(new SortDescription("", ListSortDirection.Ascending)); if (this.evt.viewers == null) { this.viewersLst.Items.Add("<Everyone>"); } else { foreach (String p in this.evt.viewers) { this.viewersLst.Items.Add(this.getPlayer(p)); } } this.viewersLst.Items.Refresh(); this.editorsLst.Items.SortDescriptions.Add(new SortDescription("", ListSortDirection.Ascending)); if (this.evt.editors == null) { this.editorsLst.Items.Add("<Everyone>"); } else { foreach (String p in this.evt.editors) { this.editorsLst.Items.Add(this.getPlayer(p)); } } this.editorsLst.Items.Refresh(); if (!canEdit) { tsBut.IsEnabled = false; this.titleBox.IsReadOnly = true; this.descBox.IsReadOnly = true; ///// // //disable results edit stuff // ///// this.virtBox.IsEnabled = false; ///// // //disable other edit stuff // ///// this.okBut.Visibility = Visibility.Hidden; this.cancelBut.Content = "Done"; } if ((!this.evt.canAssign(player)) && (!this.evt.canClaim(player))) { this.ownerBut.IsEnabled = false; } if (!this.evt.canSetPermissions(player)) { this.viewerAddBut.IsEnabled = false; this.viewerRemBut.IsEnabled = false; this.viewerAllBut.IsEnabled = false; this.viewerNoneBut.IsEnabled = false; this.editorAddBut.IsEnabled = false; this.editorRemBut.IsEnabled = false; this.editorAllBut.IsEnabled = false; this.editorNoneBut.IsEnabled = false; } }
public virtual void Close() { Status = ExampleStatus.Closed; Timestamp = Timestamp.Touch(); }
void LoadFromString(ParseCueJob job) { string cueString = job.IN_CueString; TextReader tr = new StringReader(cueString); for (; ; ) { job.CurrentLine++; string line = tr.ReadLine(); if (line == null) break; line = line.Trim(); if (line == "") continue; var clp = new CueLineParser(line); string key = clp.ReadToken().ToUpperInvariant(); //remove nonsense at beginning if (!IN_Strict) { while (key.Length > 0) { char c = key[0]; if(c == ';') break; if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) break; key = key.Substring(1); } } bool startsWithSemicolon = key.StartsWith(";"); if (startsWithSemicolon) { clp.EOF = true; OUT_CueFile.Commands.Add(new CUE_File.Command.COMMENT() { Value = line }); } else switch (key) { default: job.Warn("Unknown command: " + key); break; case "CATALOG": if (OUT_CueFile.GlobalDiscInfo.Catalog != null) job.Warn("Multiple CATALOG commands detected. Subsequent ones are ignored."); else if (clp.EOF) job.Warn("Ignoring empty CATALOG command"); else OUT_CueFile.Commands.Add(OUT_CueFile.GlobalDiscInfo.Catalog = new CUE_File.Command.CATALOG() { Value = clp.ReadToken() }); break; case "CDTEXTFILE": if (OUT_CueFile.GlobalDiscInfo.CDTextFile != null) job.Warn("Multiple CDTEXTFILE commands detected. Subsequent ones are ignored."); else if (clp.EOF) job.Warn("Ignoring empty CDTEXTFILE command"); else OUT_CueFile.Commands.Add(OUT_CueFile.GlobalDiscInfo.CDTextFile = new CUE_File.Command.CDTEXTFILE() { Path = clp.ReadPath() }); break; case "FILE": { var path = clp.ReadPath(); CueFileType ft; if (clp.EOF) { job.Error("FILE command is missing file type."); ft = CueFileType.Unspecified; } else { var strType = clp.ReadToken().ToUpperInvariant(); switch (strType) { default: job.Error("Unknown FILE type: " + strType); ft = CueFileType.Unspecified; break; case "BINARY": ft = CueFileType.BINARY; break; case "MOTOROLA": ft = CueFileType.MOTOROLA; break; case "BINARAIFF": ft = CueFileType.AIFF; break; case "WAVE": ft = CueFileType.WAVE; break; case "MP3": ft = CueFileType.MP3; break; } } OUT_CueFile.Commands.Add(new CUE_File.Command.FILE() { Path = path, Type = ft }); } break; case "FLAGS": { var cmd = new CUE_File.Command.FLAGS(); OUT_CueFile.Commands.Add(cmd); while (!clp.EOF) { var flag = clp.ReadToken().ToUpperInvariant(); switch (flag) { case "DATA": default: job.Warn("Unknown FLAG: " + flag); break; case "DCP": cmd.Flags |= CueTrackFlags.DCP; break; case "4CH": cmd.Flags |= CueTrackFlags._4CH; break; case "PRE": cmd.Flags |= CueTrackFlags.PRE; break; case "SCMS": cmd.Flags |= CueTrackFlags.SCMS; break; } } if (cmd.Flags == CueTrackFlags.None) job.Warn("Empty FLAG command"); } break; case "INDEX": { if (clp.EOF) { job.Error("Incomplete INDEX command"); break; } string strindexnum = clp.ReadToken(); int indexnum; if (!int.TryParse(strindexnum, out indexnum) || indexnum < 0 || indexnum > 99) { job.Error("Invalid INDEX number: " + strindexnum); break; } string str_timestamp = clp.ReadToken(); var ts = new Timestamp(str_timestamp); if (!ts.Valid && !IN_Strict) { //try cleaning it up str_timestamp = Regex.Replace(str_timestamp, "[^0-9:]", ""); ts = new Timestamp(str_timestamp); } if (!ts.Valid) { if (IN_Strict) job.Error("Invalid INDEX timestamp: " + str_timestamp); break; } OUT_CueFile.Commands.Add(new CUE_File.Command.INDEX() { Number = indexnum, Timestamp = ts }); } break; case "ISRC": if (OUT_CueFile.GlobalDiscInfo.ISRC != null) job.Warn("Multiple ISRC commands detected. Subsequent ones are ignored."); else if (clp.EOF) job.Warn("Ignoring empty ISRC command"); else { var isrc = clp.ReadToken(); if (isrc.Length != 12) job.Warn("Invalid ISRC code ignored: " + isrc); else { OUT_CueFile.Commands.Add(OUT_CueFile.GlobalDiscInfo.ISRC = new CUE_File.Command.ISRC() { Value = isrc }); } } break; case "PERFORMER": OUT_CueFile.Commands.Add(new CUE_File.Command.PERFORMER() { Value = clp.ReadPath() ?? "" }); break; case "POSTGAP": case "PREGAP": { var str_msf = clp.ReadToken(); var msf = new Timestamp(str_msf); if (!msf.Valid) job.Error("Ignoring {0} with invalid length MSF: " + str_msf, key); else { if (key == "POSTGAP") OUT_CueFile.Commands.Add(new CUE_File.Command.POSTGAP() { Length = msf }); else OUT_CueFile.Commands.Add(new CUE_File.Command.PREGAP() { Length = msf }); } } break; case "REM": OUT_CueFile.Commands.Add(new CUE_File.Command.REM() { Value = clp.ReadLine() }); break; case "SONGWRITER": OUT_CueFile.Commands.Add(new CUE_File.Command.SONGWRITER() { Value = clp.ReadPath() ?? "" }); break; case "TITLE": OUT_CueFile.Commands.Add(new CUE_File.Command.TITLE() { Value = clp.ReadPath() ?? "" }); break; case "TRACK": { if (clp.EOF) { job.Error("Incomplete TRACK command"); break; } string str_tracknum = clp.ReadToken(); int tracknum; if (!int.TryParse(str_tracknum, out tracknum) || tracknum < 1 || tracknum > 99) { job.Error("Invalid TRACK number: " + str_tracknum); break; } //TODO - check sequentiality? maybe as a warning CueTrackType tt; var str_trackType = clp.ReadToken(); switch (str_trackType.ToUpperInvariant()) { default: job.Error("Unknown TRACK type: " + str_trackType); tt = CueTrackType.Unknown; break; case "AUDIO": tt = CueTrackType.Audio; break; case "CDG": tt = CueTrackType.CDG; break; case "MODE1/2048": tt = CueTrackType.Mode1_2048; break; case "MODE1/2352": tt = CueTrackType.Mode1_2352; break; case "MODE2/2336": tt = CueTrackType.Mode2_2336; break; case "MODE2/2352": tt = CueTrackType.Mode2_2352; break; case "CDI/2336": tt = CueTrackType.CDI_2336; break; case "CDI/2352": tt = CueTrackType.CDI_2352; break; } OUT_CueFile.Commands.Add(new CUE_File.Command.TRACK() { Number = tracknum, Type = tt }); } break; } if (!clp.EOF) { var remainder = clp.ReadLine(); if (remainder.TrimStart().StartsWith(";")) { //add a comment OUT_CueFile.Commands.Add(new CUE_File.Command.COMMENT() { Value = remainder }); } else job.Warn("Unknown text at end of line after processing command: " + key); } } //end cue parsing loop job.FinishLog(); } //LoadFromString
private async ValueTask <ThumbnailGeneratorGetThumbnailResult> GetPictureThumbnailAsync(NestedPath filePath, ThumbnailGeneratorGetThumbnailOptions options, CancellationToken cancellationToken = default) { var ext = filePath.GetExtension().ToLower(); if (!_pictureTypeExtensionList.Contains(ext)) { return(new ThumbnailGeneratorGetThumbnailResult(ThumbnailGeneratorResultStatus.Failed)); } try { var fileLength = await _fileSystem.GetFileSizeAsync(filePath, cancellationToken); var fileLastWriteTime = await _fileSystem.GetFileLastWriteTimeAsync(filePath, cancellationToken); using (var inStream = await _fileSystem.GetFileStreamAsync(filePath, cancellationToken)) using (var outStream = new RecyclableMemoryStream(_bytesPool)) { this.ConvertImage(inStream, outStream, options.Width, options.Height, options.ResizeType, options.FormatType); outStream.Seek(0, SeekOrigin.Begin); var fileMeta = new FileMeta(filePath, (ulong)fileLength, Timestamp.FromDateTime(fileLastWriteTime)); var thumbnailMeta = new ThumbnailMeta(options.ResizeType, options.FormatType, (uint)options.Width, (uint)options.Height); var content = new ThumbnailContent(outStream.ToMemoryOwner()); var cache = new ThumbnailCache(fileMeta, thumbnailMeta, new[] { content }); await _thumbnailGeneratorRepository.ThumbnailCaches.InsertAsync(cache); return(new ThumbnailGeneratorGetThumbnailResult(ThumbnailGeneratorResultStatus.Succeeded, cache.Contents)); } } catch (NotSupportedException e) { _logger.Warn(e); } catch (OperationCanceledException e) { _logger.Debug(e); } catch (Exception e) { _logger.Error(e); throw; } return(new ThumbnailGeneratorGetThumbnailResult(ThumbnailGeneratorResultStatus.Failed)); }
public void Play(int track, int numLoops, int startFrame, int duration, bool only_emulate) { if (numLoops != 0 || startFrame != 0) { _cd.track = track; _cd.numLoops = numLoops; _cd.start = startFrame; _cd.duration = duration; // Try to load the track from a compressed data file, and if found, use // that. If not found, attempt to start regular Audio CD playback of // the requested track. string[] trackName = new string[2]; trackName[0] = string.Format("track{0}", track); trackName[1] = string.Format("track{0:00}", track); ISeekableAudioStream stream = null; var directory = ServiceLocator.FileStorage.GetDirectoryName(_vm.Game.Path); for (int i = 0; stream == null && i < 2; ++i) { var path = ScummHelper.LocatePath(directory, trackName[i]); if (path != null) { // TODO: open stream } } // Stop any currently playing emulated track _mixer.StopHandle(_handle); if (stream != null) { var start = new Timestamp(0, startFrame, 75); var end = duration != 0 ? new Timestamp(0, startFrame + duration, 75) : stream.Length; /* FIXME: Seems numLoops == 0 and numLoops == 1 both indicate a single repetition, while all other positive numbers indicate precisely the number of desired repetitions. Finally, -1 means infinitely many */ _emulating = true; _handle = _mixer.PlayStream(SoundType.Music, LoopingAudioStream.Create(stream, start, end, (numLoops < 1) ? numLoops + 1 : numLoops), -1, _cd.volume, _cd.balance); } else { _emulating = false; if (!only_emulate) PlayCD(track, numLoops, startFrame, duration); } } }
private void OpenOrder(Address from, Address provider, string baseSymbol, string quoteSymbol, ExchangeOrderSide side, ExchangeOrderType orderType, BigInteger orderSize, BigInteger price) { Runtime.Expect(IsWitness(from), "invalid witness"); Runtime.Expect(Runtime.GasTarget == provider, "invalid gas target"); Runtime.Expect(baseSymbol != quoteSymbol, "invalid base/quote pair"); Runtime.Expect(Runtime.Nexus.TokenExists(baseSymbol), "invalid base token"); var baseToken = Runtime.Nexus.GetTokenInfo(baseSymbol); Runtime.Expect(baseToken.Flags.HasFlag(TokenFlags.Fungible), "token must be fungible"); Runtime.Expect(Runtime.Nexus.TokenExists(quoteSymbol), "invalid quote token"); var quoteToken = Runtime.Nexus.GetTokenInfo(quoteSymbol); Runtime.Expect(quoteToken.Flags.HasFlag(TokenFlags.Fungible), "token must be fungible"); if (orderType != Market) { Runtime.Expect(orderSize >= GetMinimumTokenQuantity(baseToken), "order size is not sufficient"); Runtime.Expect(price >= GetMinimumTokenQuantity(quoteToken), "order price is not sufficient"); } var uid = Runtime.Chain.GenerateUID(this.Storage); //-------------- //perform escrow for non-market orders string orderEscrowSymbol = CalculateEscrowSymbol(baseToken, quoteToken, side); TokenInfo orderEscrowToken = orderEscrowSymbol == baseSymbol ? baseToken : quoteToken; BigInteger orderEscrowAmount; BigInteger orderEscrowUsage = 0; if (orderType == Market) { orderEscrowAmount = orderSize; Runtime.Expect(orderEscrowAmount >= GetMinimumTokenQuantity(orderEscrowToken), "market order size is not sufficient"); } else { orderEscrowAmount = CalculateEscrowAmount(orderSize, price, baseToken, quoteToken, side); } //BigInteger baseTokensUnfilled = orderSize; var balances = new BalanceSheet(orderEscrowSymbol); var balance = balances.Get(this.Storage, from); Runtime.Expect(balance >= orderEscrowAmount, "not enough balance"); Runtime.Expect(Runtime.Nexus.TransferTokens(Runtime, orderEscrowSymbol, from, this.Address, orderEscrowAmount), "transfer failed"); //------------ var thisOrder = new ExchangeOrder(); StorageList orderList; BigInteger orderIndex = 0; thisOrder = new ExchangeOrder(uid, Runtime.Time, from, provider, orderSize, baseSymbol, price, quoteSymbol, side, orderType); Runtime.Notify(EventKind.OrderCreated, from, uid); var key = BuildOrderKey(side, quoteSymbol, baseSymbol); orderList = _orders.Get <string, StorageList>(key); orderIndex = orderList.Add <ExchangeOrder>(thisOrder); _orderMap.Set <BigInteger, string>(uid, key); var makerSide = side == Buy ? Sell : Buy; var makerKey = BuildOrderKey(makerSide, quoteSymbol, baseSymbol); var makerOrders = _orders.Get <string, StorageList>(makerKey); do { int bestIndex = -1; BigInteger bestPrice = 0; Timestamp bestPriceTimestamp = 0; ExchangeOrder takerOrder = thisOrder; var makerOrdersCount = makerOrders.Count(); for (int i = 0; i < makerOrdersCount; i++) { var makerOrder = makerOrders.Get <ExchangeOrder>(i); if (side == Buy) { if (makerOrder.Price > takerOrder.Price && orderType != Market) // too expensive, we wont buy at this price { continue; } if (bestIndex == -1 || makerOrder.Price < bestPrice || (makerOrder.Price == bestPrice && makerOrder.Timestamp < bestPriceTimestamp)) { bestIndex = i; bestPrice = makerOrder.Price; bestPriceTimestamp = makerOrder.Timestamp; } } else { if (makerOrder.Price < takerOrder.Price && orderType != Market) // too cheap, we wont sell at this price { continue; } if (bestIndex == -1 || makerOrder.Price > bestPrice || (makerOrder.Price == bestPrice && makerOrder.Timestamp < bestPriceTimestamp)) { bestIndex = i; bestPrice = makerOrder.Price; bestPriceTimestamp = makerOrder.Timestamp; } } } if (bestIndex >= 0) { //since order "uid" has found a match, the creator of this order will be a taker as he will remove liquidity from the market //and the creator of the "bestIndex" order is the maker as he is providing liquidity to the taker var takerAvailableEscrow = orderEscrowAmount - orderEscrowUsage; var takerEscrowUsage = BigInteger.Zero; var takerEscrowSymbol = orderEscrowSymbol; var makerOrder = makerOrders.Get <ExchangeOrder>(bestIndex); var makerEscrow = _escrows.Get <BigInteger, BigInteger>(makerOrder.Uid); var makerEscrowUsage = BigInteger.Zero;; var makerEscrowSymbol = orderEscrowSymbol == baseSymbol ? quoteSymbol : baseSymbol; //Get fulfilled order size in base tokens //and then calculate the corresponding fulfilled order size in quote tokens if (takerEscrowSymbol == baseSymbol) { var makerEscrowBaseEquivalent = ConvertQuoteToBase(makerEscrow, makerOrder.Price, baseToken, quoteToken); takerEscrowUsage = takerAvailableEscrow < makerEscrowBaseEquivalent ? takerAvailableEscrow : makerEscrowBaseEquivalent; makerEscrowUsage = CalculateEscrowAmount(takerEscrowUsage, makerOrder.Price, baseToken, quoteToken, Buy); } else { var takerEscrowBaseEquivalent = ConvertQuoteToBase(takerAvailableEscrow, makerOrder.Price, baseToken, quoteToken); makerEscrowUsage = makerEscrow < takerEscrowBaseEquivalent ? makerEscrow : takerEscrowBaseEquivalent; takerEscrowUsage = CalculateEscrowAmount(makerEscrowUsage, makerOrder.Price, baseToken, quoteToken, Buy); } Runtime.Expect(takerEscrowUsage <= takerAvailableEscrow, "Taker tried to use more escrow than available"); Runtime.Expect(makerEscrowUsage <= makerEscrow, "Maker tried to use more escrow than available"); if (takerEscrowUsage < GetMinimumSymbolQuantity(takerEscrowSymbol) || makerEscrowUsage < GetMinimumSymbolQuantity(makerEscrowSymbol)) { break; } Runtime.Nexus.TransferTokens(Runtime, takerEscrowSymbol, this.Address, makerOrder.Creator, takerEscrowUsage); Runtime.Nexus.TransferTokens(Runtime, makerEscrowSymbol, this.Address, takerOrder.Creator, makerEscrowUsage); Runtime.Notify(EventKind.TokenReceive, makerOrder.Creator, new TokenEventData() { chainAddress = this.Address, symbol = takerEscrowSymbol, value = takerEscrowUsage }); Runtime.Notify(EventKind.TokenReceive, takerOrder.Creator, new TokenEventData() { chainAddress = this.Address, symbol = makerEscrowSymbol, value = makerEscrowUsage }); orderEscrowUsage += takerEscrowUsage; Runtime.Notify(EventKind.OrderFilled, takerOrder.Creator, takerOrder.Uid); Runtime.Notify(EventKind.OrderFilled, makerOrder.Creator, makerOrder.Uid); if (makerEscrowUsage == makerEscrow) { makerOrders.RemoveAt <ExchangeOrder>(bestIndex); _orderMap.Remove(makerOrder.Uid); Runtime.Expect(_escrows.ContainsKey(makerOrder.Uid), "An orderbook entry must have registered escrow"); _escrows.Remove(makerOrder.Uid); Runtime.Notify(EventKind.OrderClosed, makerOrder.Creator, makerOrder.Uid); } else { _escrows.Set(makerOrder.Uid, makerEscrow - makerEscrowUsage); } } else { break; } } while (orderEscrowUsage < orderEscrowAmount); var leftoverEscrow = orderEscrowAmount - orderEscrowUsage; if (leftoverEscrow == 0 || orderType != Limit) { orderList.RemoveAt <ExchangeOrder>(orderIndex); _orderMap.Remove(thisOrder.Uid); _escrows.Remove(thisOrder.Uid); if (leftoverEscrow > 0) { Runtime.Nexus.TransferTokens(Runtime, orderEscrowSymbol, this.Address, thisOrder.Creator, leftoverEscrow); Runtime.Notify(EventKind.TokenReceive, thisOrder.Creator, new TokenEventData() { chainAddress = this.Address, symbol = orderEscrowSymbol, value = leftoverEscrow }); Runtime.Notify(EventKind.OrderCancelled, thisOrder.Creator, thisOrder.Uid); } else { Runtime.Notify(EventKind.OrderClosed, thisOrder.Creator, thisOrder.Uid); } } else { _escrows.Set(uid, leftoverEscrow); } //TODO: ADD FEES, SEND THEM TO this.Address FOR NOW }
public DayInMonth(int day, Timestamp timestamp) { _day = day; _timestamp = timestamp; }
/// <summary> /// Initializes a new TopicPartitionTimestamp instance. /// </summary> /// <param name="tp"> /// Kafka topic name and partition. /// </param> /// <param name="timestamp"> /// A Kafka timestamp value. /// </param> public TopicPartitionTimestamp(TopicPartition tp, Timestamp timestamp) : this(tp.Topic, tp.Partition, timestamp) { }
public YearBuilder At(Timestamp timestamp) { _time = timestamp; return this; }
public async Task <List <Sentence> > GetSentencesAsync(string keyword, DateTime yearMonth) { var channel = new Channel("storage:7878", ChannelCredentials.Insecure); var client = new Storage.StorageClient(channel); var result = await client.GetSentencesAsync(new GetSentencesRequest { Keyword = keyword, YearMonth = Timestamp.FromDateTime(yearMonth.ToUniversalTime()) }); await channel.ShutdownAsync(); var yearMonths = new List <DateTime>(); var sentences = new List <Sentence>(); foreach (var s in result.Sentences) { sentences.Add(new Sentence() { Keyword = new Keyword() { Text = s.Keyword.Text }, Source = new Source() { Url = s.Source.Url }, Text = s.Text, Positive = s.Positive, Received = s.Received.ToDateTime(), SourceArticleHeader = s.Sourcearticleheader, SourceArticleUrl = s.Sourcearticleurl }); } return(sentences); }
public ExampleEntity(string name) { Name = name; Status = ExampleStatus.Open; Timestamp = Timestamp.Now(); }
public override int GetHashCode() { return(Id.GetHashCode() ^ Timestamp.GetHashCode() ^ Topic.GetHashCode() ^ Person.GetHashCode()); }
public void SellToken(Address from, string baseSymbol, string quoteSymbol, BigInteger tokenID, BigInteger price, Timestamp endDate) { Runtime.Expect(Runtime.IsWitness(from), "invalid witness"); Runtime.Expect(endDate > Runtime.Time, "invalid end date"); var maxAllowedDate = Runtime.Time + TimeSpan.FromDays(30); Runtime.Expect(endDate <= maxAllowedDate, "end date is too distant, max: " + maxAllowedDate + ", received: " + endDate); Runtime.Expect(Runtime.TokenExists(quoteSymbol), "invalid quote token"); var quoteToken = Runtime.GetToken(quoteSymbol); Runtime.Expect(quoteToken.Flags.HasFlag(TokenFlags.Fungible), "quote token must be fungible"); Runtime.Expect(Runtime.TokenExists(baseSymbol), "invalid base token"); var baseToken = Runtime.GetToken(baseSymbol); Runtime.Expect(!baseToken.Flags.HasFlag(TokenFlags.Fungible), "base token must be non-fungible"); var nft = Runtime.ReadToken(baseSymbol, tokenID); Runtime.Expect(nft.CurrentChain == Runtime.Chain.Name, "token not currently in this chain"); Runtime.Expect(nft.CurrentOwner == from, "invalid owner"); Runtime.TransferToken(baseToken.Symbol, from, this.Address, tokenID); var auction = new MarketAuction(from, Runtime.Time, endDate, baseSymbol, quoteSymbol, tokenID, price, 0, 0, TypeAuction.Fixed, 0, Address.Null, 0, Address.Null, Address.Null); var auctionID = baseSymbol + "." + tokenID; _auctionMap.Set(auctionID, auction); _auctionIds.Set(auctionID, auctionID); Runtime.Notify(EventKind.OrderCreated, from, new MarketEventData() { ID = tokenID, BaseSymbol = baseSymbol, QuoteSymbol = quoteSymbol, Price = price, EndPrice = 0, Type = TypeAuction.Fixed }); }
public void AddValue(Timestamp timestamp, object value) { this.timestore.AddValue(timestamp, value); }
protected override Comparison Compare(Timestamp aFirst, Timestamp aSecond) { return iComparer.Compare(ItcStamp.FromString(aFirst.Serialization), ItcStamp.FromString(aSecond.Serialization)); }
public void EditAuction(Address from, string baseSymbol, string quoteSymbol, BigInteger tokenID, BigInteger price, BigInteger endPrice, Timestamp startDate, Timestamp endDate, BigInteger extensionPeriod) { Runtime.Expect(Runtime.IsWitness(from), "invalid witness"); Runtime.Expect(Runtime.TokenExists(quoteSymbol), "invalid quote token"); var quoteToken = Runtime.GetToken(quoteSymbol); Runtime.Expect(quoteToken.Flags.HasFlag(TokenFlags.Fungible), "quote token must be fungible"); var nft = Runtime.ReadToken(baseSymbol, tokenID); Runtime.Expect(nft.CurrentChain == Runtime.Chain.Name, "token not currently in this chain"); var marketAddress = SmartContract.GetAddressForNative(NativeContractKind.Market); Runtime.Expect(nft.CurrentOwner == marketAddress, "invalid owner"); var auctionID = baseSymbol + "." + tokenID; Runtime.Expect(_auctionMap.ContainsKey <string>(auctionID), "invalid auction"); var auction = _auctionMap.Get <string, MarketAuction>(auctionID); Runtime.Expect(auction.Creator == from, "invalid auction creator"); if (auction.Type != TypeAuction.Fixed) // prevent edit already started auctions { Runtime.Expect(auction.StartDate > Runtime.Time, "EditAuction can only be used before listing start"); } if (price == 0) { price = auction.Price; } if (endPrice == 0) { endPrice = auction.EndPrice; } if (startDate == 0 || startDate == null) { startDate = auction.StartDate; } if (endDate == 0 || endDate == null) { endDate = auction.EndDate; } Runtime.Expect(endDate > startDate, "invalid end date"); if (extensionPeriod == 0 || auction.Type == TypeAuction.Fixed) { extensionPeriod = auction.ExtensionPeriod; } if (auction.Type == TypeAuction.Classic || auction.Type == TypeAuction.Reserve) { Runtime.Expect(extensionPeriod <= oneHour, "extensionPeriod must be <= 1 hour"); } var auctionNew = new MarketAuction(from, startDate, endDate, baseSymbol, quoteSymbol, tokenID, price, endPrice, extensionPeriod, auction.Type, auction.ListingFee, auction.ListingFeeAddress, auction.BuyingFee, auction.BuyingFeeAddress, auction.CurrentBidWinner); _auctionMap.Set(auctionID, auctionNew); Runtime.Notify(EventKind.OrderCancelled, auctionNew.Creator, new MarketEventData() { ID = auction.TokenID, BaseSymbol = auction.BaseSymbol, QuoteSymbol = auction.QuoteSymbol, Price = auction.Price, EndPrice = auction.EndPrice, Type = auction.Type }); Runtime.Notify(EventKind.OrderCreated, auctionNew.Creator, new MarketEventData() { ID = auctionNew.TokenID, BaseSymbol = auctionNew.BaseSymbol, QuoteSymbol = auctionNew.QuoteSymbol, Price = auctionNew.Price, EndPrice = auctionNew.EndPrice, Type = auctionNew.Type }); }