public void CanCompareToOtherBytes() { var lhs = new Binary(new Byte[] { 1, 2, 3 }); var rhs = new Binary(new Byte[] { 1, 2, 3 }); Assert.Equal(0, lhs.CompareTo(rhs)); }
public void SaveMacroPlanTest(string imagepath) { //assign var shapemodelpath = "filepath"; var note = "note"; var exportUnit = "mm"; var image = new HImage(imagepath); var imageBinData = new Binary(ImageConventer.ConvertHalconImageToByteArray(image, false)); var matchingParam = new MatchingParam(); var matchingParamByteArray = ModelSerializer.DoSerialize(matchingParam); var matchingParamBinData = new Binary(matchingParamByteArray); BindingList<GeoDataGridViewModel> a = new BindingList<GeoDataGridViewModel>(); a.Add(new GeoDataGridViewModel() { RecordID = "aaa" }); var measureBinData = ModelSerializer.DoSerialize(a); //BindingList a; var ma = new MeasureAssistant(); var maParam = ma.GetMeasureAssistantParam(); var maParamBin = ModelSerializer.DoSerialize(maParam); LightChannel upper = new LightChannel() { Channel = "00", Intensity = 100, OnOff = LightSwitch.On }; LightChannel bottom = new LightChannel() { Channel = "01", Intensity = 200, OnOff = LightSwitch.OFF }; //act var success = SDMSRepo.SaveMacroPlan("Test", Guid.NewGuid().ToString(), shapemodelpath, note, imageBinData, exportUnit, matchingParamBinData, measureBinData, maParamBin, upper, bottom, new ShapeViewModel() { }, "system", ""); //assert Assert.True(success); }
protected void fluDocument_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e) { if (this.fluDocument.HasFile) { if (this.fluDocument.PostedFile.ContentType.Equals("image/pjpeg") || this.fluDocument.PostedFile.ContentType.Equals("image/x-png")) { byte[] fileByte = this.fluDocument.FileBytes; Binary binaryObj = new Binary(fileByte); Ajancy.Kimia_Ajancy db = new Ajancy.Kimia_Ajancy(Public.ConnectionString); Ajancy.Doument doc = db.Douments.FirstOrDefault<Ajancy.Doument>(d => d.PersonID == Public.ActiveUserRole.User.PersonID && d.DocumentType == 1); if (doc == null) { doc = new Ajancy.Doument { DocumentType = Public.ToByte(this.drpType.SelectedValue), PersonID = Public.ActiveUserRole.User.PersonID, Picture = binaryObj, SubmitDate = DateTime.Now }; db.Douments.InsertOnSubmit(doc); } else { doc.Picture = binaryObj; } db.SubmitChanges(); db.Dispose(); } } }
public BinaryExpression(Binary Operator, Expression Left, Expression Right) { this.op = Operator; this.left = Left; this.right = Right; }
public void WrapUnderlyingBytes() { var rawBytes = new Byte[0]; var bytes = new Binary(rawBytes); Assert.Same(rawBytes, (Byte[])bytes); }
public void CanCompareToBoxedRawBytes() { var lhs = new Binary(new Byte[] { 1, 2, 3 }); var rhs = new Byte[] { 1, 2, 3 }; Assert.Equal(0, lhs.CompareTo((Object)rhs)); }
public void CanSerializeToJson() { var binary = new Binary(Guid.Parse("a6c45a28-c572-4d5b-ac18-7b0ec2d723fb").ToByteArray()); var json = WriteJson(binary); Validate(json, "\"KFrEpnLFW02sGHsOwtcj+w==\""); }
public void TestUpdates() { SessionStateItemCollection items = new SessionStateItemCollection(); items["Val1"] = "value"; byte[] serializedItems = Serialize(items); Binary b = new Binary(serializedItems); List<string> ids = new List<string>(); ICursor allSessions; using (var mongo = new Mongo(config)) { mongo.Connect(); allSessions = mongo["session_store"]["sessions"].FindAll(); foreach (Document session in allSessions.Documents) { string id = (string)session["SessionId"]; ids.Add(id); } } foreach (string s in ids) { var sessionStore = new SessionStore("test"); sessionStore.UpdateSession(s, 2, b, "AppName", items.Count, 0); } }
private string ConvertBinaryToItemId(Binary binary) { byte[] binaryString = binary.ToArray(); // if the original encoding was ASCII string x = Encoding.ASCII.GetString(binaryString); // if the original encoding was UTF-8 string y = Encoding.UTF8.GetString(binaryString); // if the original encoding was UTF-16 string z = Encoding.Unicode.GetString(binaryString); string strBinary = binary.ToString(); StringBuilder result = new StringBuilder(strBinary.Length / 8 + 1); // TODO: check all 1's or 0's... Will throw otherwise int mod4Len = binary.Length % 8; if (mod4Len != 0) { // pad to length multiple of 8 strBinary = strBinary.PadLeft(((strBinary.Length / 8) + 1) * 8, '0'); } for (int i = 0; i < binary.Length; i += 8) { string eightBits = strBinary.Substring(i, 8); result.AppendFormat("{0:X2}", System.Convert.ToByte(eightBits, 2)); } return result.ToString(); }
public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem) { var sessionStore = SessionStore.Instance; try { byte[] serializedItems = Serialize((SessionStateItemCollection)item.Items); Binary sessionItems = new Binary(serializedItems); if (newItem) { // Delete an existing expired session if it exists. sessionStore.EvictExpiredSession(id, _applicationName); // insert new session item. Session session = new Session(id, this._applicationName, item.Timeout, sessionItems, item.Items.Count, 0); sessionStore.Insert(session); } else { sessionStore.UpdateSession(id, item.Timeout, sessionItems, this._applicationName, item.Items.Count, lockId); } } catch (Exception e) { if (WriteExceptionsToEventLog) { WriteToEventLog(e, "SetAndReleaseItemExclusive"); throw new ProviderException(e.Message, e.InnerException); } else throw e; } }
public void CanDeserializeValidJson() { var expected = new Binary(Guid.Parse("a6c45a28-c572-4d5b-ac18-7b0ec2d723fb").ToByteArray()); var actual = ReadJson<Binary>("\"KFrEpnLFW02sGHsOwtcj+w==\""); Assert.Equal(expected, actual); }
/// <summary> /// Converts binary value to string. /// </summary> /// <param name="version">Binary version number.</param> /// <returns>Base64 version number.</returns> public static string ToString(Binary version) { if (version == null) return null; return Convert.ToBase64String(version.ToArray()); }
public static UIConfig Load() { var cfg = XConfig.Current; if (cfg.Extend.IsNullOrWhiteSpace()) return null; Byte[] buf = null; try { buf = cfg.Extend.ToBase64(); } catch { return null; } var ms = new MemoryStream(buf); var binary = new Binary(); binary.EncodeInt = true; binary.AddHandler<BinaryFont>(11); binary.AddHandler<BinaryColor>(12); binary.AddHandler<BinaryUnknown>(20); binary.Stream = ms; //binary.Debug = true; //binary.EnableTrace(); try { return binary.Read(typeof(UIConfig)) as UIConfig; } catch { return null; } }
internal Binary Compile() { //CSharpCompiler = new CSharpCodeProvider().CreateCompiler(); //parameters = new CompilerParameters(); //foreach (var require in Require) { // parameters.ReferencedAssemblies.Add(string.Format("{0}.dll", require)); //} //parameters.GenerateInMemory = true; var compiler = CodeDomProvider.CreateProvider("CSharp"); var parameters = new CompilerParameters(Require.ToArray()); var codeUnit = new CodeCompileUnit(); codeNamespace = new CodeNamespace("Unahi.CRake.RuntimeGenerated"); codeUnit.Namespaces.Add(codeNamespace); binary = new Binary(); foreach (var item in Imports) { codeNamespace.Imports.Add(new CodeNamespaceImport(item)); } CompileClass("", Tasks, Namespaces, null); //CompileTasks(binary, "", Tasks, this, codeNamespace, null); //CompileNamespaces(binary, "", Namespaces, codeNamespace, null); binary.CompiledResult = compiler.CompileAssemblyFromDom(parameters, codeUnit); return binary; }
public void CanImplicitConvertedToBytes(){ var bytes = new byte[]{10,12}; var binary = new Binary(bytes); var converted = (byte[])binary; Assert.IsNotNull(converted); Assert.AreEqual(bytes, converted); }
public void CanBeCloned(){ var binarySource = new Binary(new byte[] {10, 20}, BinarySubtype.UserDefined); var binaryDest = binarySource.Clone() as Binary; Assert.IsNotNull(binaryDest); Assert.AreEqual(binarySource.Bytes,binaryDest.Bytes); Assert.AreEqual(binarySource.Subtype,binaryDest.Subtype); }
public void CanSerializeToBson() { var binary = new Binary(Guid.Parse("a6c45a28-c572-4d5b-ac18-7b0ec2d723fb").ToByteArray()); var bson = WriteBson(new BinaryContainer { Value = binary }); Validate(bson, "IQAAAAVWYWx1ZQAQAAAAAChaxKZyxVtNrBh7DsLXI/sA"); }
public void CanDeserializeValidBson() { var expected = new Binary(Guid.Parse("a6c45a28-c572-4d5b-ac18-7b0ec2d723fb").ToByteArray()); var bson = "IQAAAAV2YWx1ZQAQAAAAAChaxKZyxVtNrBh7DsLXI/sA"; var actual = ReadBson<BinaryContainer>(bson); Assert.Equal(expected, actual.Value); }
public void ConvertToIntTest() { Binary bin = new Binary(new byte[] { 0, 0, 4 }); int expected = 4; int actual; actual = Extensions.ConvertToInt(bin); Assert.AreEqual(expected, actual); }
/// <summary> /// 將二進位資料轉換為 Bitmap,指定寬高 /// </summary> /// <param name="data"></param> /// <param name="width">長</param> /// <param name="height">寬</param> /// <returns></returns> public static Bitmap BinaryToImage(Binary data, int width, int height) { var image = BinaryToImage(data); if (image != null) return new Bitmap(image, new Size(width, height)); else return null; }
public void ConvertStateToBinaryTest() { TaskState state = TaskState.In_Progress; Binary expected = new Binary(new byte[] { 0, 0, 1 }); Binary actual; actual = Extensions.ConvertToBinary(state); Assert.AreEqual(expected, actual); }
public void ConvertTypeToBinaryTest() { TaskType type = TaskType.Development; Binary expected = new Binary(new byte[] { 0, 0, 1 }); Binary actual; actual = Extensions.ConvertToBinary(type); Assert.AreEqual(expected, actual); }
public void Equals() { Binary a = new Binary(Encoding.UTF8.GetBytes("a")); Assert.IsFalse(a.Equals((Binary)null)); Assert.IsFalse(a.Equals((object)null)); Assert.IsFalse(a.Equals(new Binary(Encoding.UTF8.GetBytes("b")))); Assert.IsTrue(a.Equals(a)); Assert.IsTrue(a.Equals(new Binary(Encoding.UTF8.GetBytes("a")))); }
public void CanBeEnumerated() { var binary = new Binary(new byte[] { 10, 20 }); var array = binary.ToArray(); Assert.AreEqual(2,array.Length); Assert.AreEqual(10, array[0]); Assert.AreEqual(20, array[1]); }
public ComplexRegionEquation(SimpleRegionEquation simple) : base() { target = simple.target; expr = new Binary(simple.bigger, simple.op, simple.smaller); thisArea = -1; }
public static int? DownloadDocument(string url, FT.DB.P20Question question) { //make sure url is normalized url = url.Trim().ToLower(); // check to see if we already have document downloaded from this Uri var db = new DBDataContext(); var doc = db.Documents.SingleOrDefault(d => d.Uri == url); if (doc != null) { return doc.DocumentId; } try { HttpWebResponse resp = GetResponse(url, 0); byte[] arrBuffer = new byte[0]; using (BinaryReader reader = new BinaryReader(resp.GetResponseStream())) { byte[] arrScratch = null; while ((arrScratch = reader.ReadBytes(4096)).Length > 0) { if (arrBuffer.Length == 0) arrBuffer = arrScratch; else { byte[] arrTemp = new byte[arrBuffer.Length + arrScratch.Length]; Array.Copy(arrBuffer, arrTemp, arrBuffer.Length); Array.Copy(arrScratch, 0, arrTemp, arrBuffer.Length, arrScratch.Length); arrBuffer = arrTemp; } } } Binary bin = new Binary(arrBuffer); FT.DB.Document newdoc = new DB.Document(); newdoc.Data = bin; newdoc.ContentType = resp.ContentType; newdoc.Uri = url; var scribdids = UpLoadToScribd(url, question); newdoc.ScribdId = scribdids.Item1; newdoc.ScribdAccessKey = scribdids.Item2; db.Documents.InsertOnSubmit(newdoc); db.SubmitChanges(); return newdoc.DocumentId; } catch (Exception e) { return null; } }
public PilotEntry(t_Pilot Pilot) { this.ID = Pilot.ID.ToString(); this.LastName = Pilot.LastName; this.SureName = Pilot.SureName; this.PilotColor = Pilot.Color.ToString(); this.Picture =Pilot.Picture; this.Flag = null; this.FlagId = (int)Pilot.ID_Flag; }
public override BaseVariable[] CreateVariables() { var variables = new BaseVariable[Problema.NumberOfVariables]; for (var var = 0; var < Problema.NumberOfVariables; var++) { variables[var] = new Binary(Problema.GetLength(var)); } return variables; }
public static void OuvrirDefaut(byte[] photo, string descr, string pos, string mail, string com) { Binary b = new Binary(photo); int idDefaut = DAL.AddDefaut(null, descr, pos, DateTime.Now); if(DAL.SelectPersonneByMail(mail) == null) DAL.AddPersonne(mail, null, null, null, "CITOYEN"); DAL.AddIntervention("OUVERT", com, DateTime.Now, idDefaut, mail); }
public void CanBeBinarySerialized() { var source = new Binary(new byte[] {10, 20}, BinarySubtype.Md5); var formatter = new BinaryFormatter(); var mem = new MemoryStream(); formatter.Serialize(mem, source); mem.Position = 0; var dest = (Binary)formatter.Deserialize(mem); Assert.AreEqual(source, dest); }
public static ulong TimestampToUlong(this Binary binary) { return(BitConverter.ToUInt64(binary.ToArray(), 0)); }
/// <summary> /// Returns <see cref="Stream"/> of the dynamically generated thumbnail image. /// </summary> /// <param name="width">Desired width of the thumbnail image.</param> /// <param name="height">Desired height of the thumbnail image.</param> /// <param name="contentType">Image format specifier. The value can be: /// png, bmp, jpeg, jpg, gif, tiff, wmf, emf, exif. Note that gif will be converted to png.</param> public Stream GetDynamicThumbnailStream(int width, int height, string contentType) { return(ImageResizer.CreateResizedImageFile(Binary.GetStream(), width, height, 80, getImageFormat(contentType))); }
public override void Emit(EmitContext ec) { if (IsBitwiseBoolean && UserOperator == null) { EmitBitwiseBoolean(ec); return; } if ((Binary.Oper & Binary.Operator.EqualityMask) != 0) { EmitEquality(ec); return; } Label is_null_label = ec.DefineLabel(); Label end_label = ec.DefineLabel(); if (ec.HasSet(BuilderContext.Options.AsyncBody) && Right.ContainsEmitWithAwait()) { Left = Left.EmitToField(ec); Right = Right.EmitToField(ec); } if (UnwrapLeft != null) { UnwrapLeft.EmitCheck(ec); } // // Don't emit HasValue check when left and right expressions are same // if (UnwrapRight != null && !Binary.Left.Equals(Binary.Right)) { UnwrapRight.EmitCheck(ec); if (UnwrapLeft != null) { ec.Emit(OpCodes.And); } } ec.Emit(OpCodes.Brfalse, is_null_label); if (UserOperator != null) { var args = new Arguments(2); args.Add(new Argument(Left)); args.Add(new Argument(Right)); var call = new CallEmitter(); call.EmitPredefined(ec, UserOperator, args); } else { Binary.EmitOperator(ec, Left, Right); } // // Wrap the result when the operator return type is nullable type // if (type.IsNullableType) { ec.Emit(OpCodes.Newobj, NullableInfo.GetConstructor(type)); } ec.Emit(OpCodes.Br_S, end_label); ec.MarkLabel(is_null_label); if ((Binary.Oper & Binary.Operator.ComparisonMask) != 0) { ec.EmitInt(0); } else { LiftedNull.Create(type, loc).Emit(ec); } ec.MarkLabel(end_label); }
public override SoundInput TryOpen(Stream file) { uint offset = 4 + Binary.BigEndian(FormatCatalog.ReadSignature(file)); return(base.TryOpen(new StreamRegion(file, offset))); }
public void TestOfSpectralIndices() { var sourceRecording = PathHelper.ResolveAsset(@"Recordings\BAC2_20071008-085040.wav"); var configFile = PathHelper.ResolveConfigFile(@"Towsey.Acoustic.yml"); var indexPropertiesConfig = PathHelper.ResolveConfigFile(@"IndexPropertiesConfig.yml"); // var outputDir = this.outputDirectory; var resourcesDir = PathHelper.ResolveAssetPath("Indices"); if (!this.outputDirectory.Exists) { this.outputDirectory.Create(); } var indexCalculateConfig = ConfigFile.Deserialize <IndexCalculateConfig>(configFile); // CHANGE CONFIG PARAMETERS HERE IF REQUIRED //indexCalculateConfig.IndexCalculationDuration = TimeSpan.FromSeconds(20); //indexCalculateConfig.SetTypeOfFreqScale("Octave"); var results = IndexCalculate.Analysis( new AudioRecording(sourceRecording), TimeSpan.Zero, indexCalculateConfig.IndexProperties, 22050, TimeSpan.Zero, indexCalculateConfig, returnSonogramInfo: true); var spectralIndices = results.SpectralIndexValues; // TEST the SPECTRAL INDICES // After serialising the expected vector and writing to the resources directory, comment the Binary.Serialise line. // ACI var expectedSpectrumFile = new FileInfo(resourcesDir + "\\ACI.bin"); // Binary.Serialize(expectedSpectrumFile, spectralIndices.ACI); var expectedVector = Binary.Deserialize <double[]>(expectedSpectrumFile); CollectionAssert.That.AreEqual(expectedVector, spectralIndices.ACI, AllowedDelta); // BGN expectedSpectrumFile = new FileInfo(resourcesDir + "\\BGN.bin"); // Binary.Serialize(expectedSpectrumFile, spectralIndices.BGN); expectedVector = Binary.Deserialize <double[]>(expectedSpectrumFile); CollectionAssert.That.AreEqual(expectedVector, spectralIndices.BGN, AllowedDelta); // CVR expectedSpectrumFile = new FileInfo(resourcesDir + "\\CVR.bin"); // Binary.Serialize(expectedSpectrumFile, spectralIndices.CVR); expectedVector = Binary.Deserialize <double[]>(expectedSpectrumFile); CollectionAssert.That.AreEqual(expectedVector, spectralIndices.CVR, AllowedDelta); // DMN expectedSpectrumFile = new FileInfo(resourcesDir + "\\PMN.bin"); // Binary.Serialize(expectedSpectrumFile, spectralIndices.PMN); expectedVector = Binary.Deserialize <double[]>(expectedSpectrumFile); CollectionAssert.That.AreEqual(expectedVector, spectralIndices.PMN, AllowedDelta); // ENT expectedSpectrumFile = new FileInfo(resourcesDir + "\\ENT.bin"); // Binary.Serialize(expectedSpectrumFile, spectralIndices.ENT); expectedVector = Binary.Deserialize <double[]>(expectedSpectrumFile); CollectionAssert.That.AreEqual(expectedVector, spectralIndices.ENT, AllowedDelta); // EVN expectedSpectrumFile = new FileInfo(resourcesDir + "\\EVN.bin"); // Binary.Serialize(expectedSpectrumFile, spectralIndices.EVN); expectedVector = Binary.Deserialize <double[]>(expectedSpectrumFile); CollectionAssert.That.AreEqual(expectedVector, spectralIndices.EVN, AllowedDelta); // POW expectedSpectrumFile = new FileInfo(resourcesDir + "\\POW.bin"); // Binary.Serialize(expectedSpectrumFile, spectralIndices.POW); expectedVector = Binary.Deserialize <double[]>(expectedSpectrumFile); CollectionAssert.That.AreEqual(expectedVector, spectralIndices.POW, AllowedDelta); // RHZ expectedSpectrumFile = new FileInfo(resourcesDir + "\\RHZ.bin"); // Binary.Serialize(expectedSpectrumFile, spectralIndices.RHZ); expectedVector = Binary.Deserialize <double[]>(expectedSpectrumFile); CollectionAssert.That.AreEqual(expectedVector, spectralIndices.RHZ, AllowedDelta); // RNG expectedSpectrumFile = new FileInfo(resourcesDir + "\\RNG.bin"); // Binary.Serialize(expectedSpectrumFile, spectralIndices.RNG); expectedVector = Binary.Deserialize <double[]>(expectedSpectrumFile); CollectionAssert.That.AreEqual(expectedVector, spectralIndices.RNG, AllowedDelta); // RPS expectedSpectrumFile = new FileInfo(resourcesDir + "\\RPS.bin"); // Binary.Serialize(expectedSpectrumFile, spectralIndices.RPS); expectedVector = Binary.Deserialize <double[]>(expectedSpectrumFile); CollectionAssert.That.AreEqual(expectedVector, spectralIndices.RPS, AllowedDelta); // RVT expectedSpectrumFile = new FileInfo(resourcesDir + "\\RVT.bin"); // Binary.Serialize(expectedSpectrumFile, spectralIndices.RVT); expectedVector = Binary.Deserialize <double[]>(expectedSpectrumFile); CollectionAssert.That.AreEqual(expectedVector, spectralIndices.RVT, AllowedDelta); // R3D expectedSpectrumFile = new FileInfo(resourcesDir + "\\R3D.bin"); // Binary.Serialize(expectedSpectrumFile, spectralIndices.R3D); expectedVector = Binary.Deserialize <double[]>(expectedSpectrumFile); CollectionAssert.That.AreEqual(expectedVector, spectralIndices.R3D, AllowedDelta); // SPT expectedSpectrumFile = new FileInfo(resourcesDir + "\\SPT.bin"); // Binary.Serialize(expectedSpectrumFile, spectralIndices.SPT); expectedVector = Binary.Deserialize <double[]>(expectedSpectrumFile); CollectionAssert.That.AreEqual(expectedVector, spectralIndices.SPT, AllowedDelta); var outputImagePath = Path.Combine(this.outputDirectory.FullName, "SpectralIndices.png"); var image = SpectralIndexValues.CreateImageOfSpectralIndices(spectralIndices); image.Save(outputImagePath); }
public void SendResponseWhileCommit(Binary fullEncodedProtocol) { Transaction.Current.RunWhileCommit(() => SendResponse(fullEncodedProtocol)); }
private static void BinaryMessageRead(NetworkingPlayer player, Binary frame, NetWorker sender) { responsePlayer = player; response = ObjectMapper.Instance.Map <string>(frame.StreamData); responseCounter++; }
public byte[] Unpack() { int dst = 0; uint src = 0; uint ctl = 0; uint mask = 0; while (dst < m_output.Length && src < m_packed_size) { if (0 == mask) { ctl = m_input.ReadUInt32(); src += 4; mask = 0x80000000; } if (0 != (ctl & mask)) { int copy_count, offset; offset = m_input.ReadUInt8(); src++; copy_count = offset >> 4; offset &= 0x0f; if (15 == copy_count) { copy_count = m_input.ReadUInt16(); src += 2; } else if (14 == copy_count) { copy_count = m_input.ReadUInt8(); src++; } else { copy_count++; } if (offset < 10) { offset++; } else { offset = ((offset - 10) << 8) | m_input.ReadUInt8(); src++; } if (dst + copy_count > m_output.Length) { copy_count = m_output.Length - dst; } Binary.CopyOverlapped(m_output, dst - offset, dst, copy_count); dst += copy_count; } else { m_output[dst++] = m_input.ReadUInt8(); src++; } mask >>= 1; } return(m_output); }
void UnpackColorData(byte[] output, int src_pixel_size, int dst_pixel_size) { int[] offset_step = new int[16]; int stride = ((int)m_info.Width * dst_pixel_size + 3) & ~3; int delta = stride - (int)m_info.Width * dst_pixel_size; for (int i = 0; i < 16; i++) { offset_step[i] = OffsetTable[0, i] * stride + OffsetTable[1, i] * dst_pixel_size; } int dst = 0; for (uint y = 0; y < m_info.Height; ++y) { int w = (int)m_info.Width; while (w > 0) { int flag = m_input.ReadByte(); if (-1 == flag) { throw new InvalidFormatException(); } int count = flag & 3; if (0 != (flag & 4)) { count |= m_input.ReadByte() << 2; } w -= ++count; if (0 == (flag & 0xF0)) { if (0 != (flag & 8)) { if (src_pixel_size == dst_pixel_size) { count *= dst_pixel_size; if (count != m_input.Read(output, dst, count)) { throw new InvalidFormatException(); } dst += count; } else { for (int i = 0; i < count; ++i) { if (src_pixel_size != m_input.Read(output, dst, src_pixel_size)) { throw new InvalidFormatException(); } dst += dst_pixel_size; } } } else { if (src_pixel_size != m_input.Read(output, dst, src_pixel_size)) { throw new InvalidFormatException(); } --count; dst += dst_pixel_size; for (int i = count * dst_pixel_size; i > 0; i--) { output[dst] = output[dst - dst_pixel_size]; dst++; } } } else { int src = dst + offset_step[flag >> 4]; if (0 == (flag & 8)) { for (int i = 0; i < count; i++) { for (int j = 0; j < src_pixel_size; ++j) { output[dst + j] = output[src + j]; } dst += dst_pixel_size; } } else { count *= dst_pixel_size; Binary.CopyOverlapped(output, src, dst, count); dst += count; } } } dst += delta; } }
public static int?Length(Binary value) { return(value == null ? null : (int?)value.Length); }
/// <summary> /// Construct a SimplePofValue instance wrapping the supplied binary. /// </summary> /// <param name="valueParent"> /// Parent value within the POF stream. /// </param> /// <param name="binValue"> /// Binary representation of this value. /// </param> /// <param name="ctx"> /// POF context to use when reading or writing properties. /// </param> /// <param name="of"> /// Offset of this value from the beginning of POF stream. /// </param> /// <param name="nType"> /// POF type identifier for this value. /// </param> public SimplePofValue(IPofValue valueParent, Binary binValue, IPofContext ctx, int of, int nType) : base(valueParent, binValue, ctx, of, nType) { }
public string VisitBinaryExpr(Binary expr) { return(Parenthesize(expr.Operator.Lexeme, expr.Left, expr.Right)); }
/// <summary> /// Returns the u value defined in ZDT5 for a encodings.variable. /// </summary> /// <param name="variable"></param> /// <returns></returns> private double U(Binary variable) { return(variable.Bits.Cardinality()); }
public void Binary_can_convert_formatted_strings() { Assert.That(Binary.ToDecimal("011"), Is.EqualTo(3)); }
public int Registration(string Name, string Username, string Password, string Email, Binary Image, string Security_Question, string Security_ans) { int result = 0; u.Name = Name; u.Username = Username; u.Password = Password; u.Email = Email; u.Image = Image; u.Security_Question = Security_Question; u.Security_Ans = Security_ans; context.Users.InsertOnSubmit(u); context.SubmitChanges(); result = 1; return(result); }
public MiniFloat(char sign, Binary exponent, Binary mantissa) { this.Signbit = sign; this.Exponent = exponent; this.Mantissa = mantissa; }
private void SendResponseWhileRollback(Binary fullEncodedProtocol) { Transaction.Current.RunWhileRollback(() => SendResponse(fullEncodedProtocol)); }
public MiniFloat(char sign, string exponent, string mantissa) { this.Signbit = sign; this.Exponent = new Binary(exponent); this.Mantissa = new Binary(mantissa); }
/// <summary> /// Execute the command /// </summary> /// <param name="Arguments">Command line arguments</param> /// <returns>Exit code</returns> public override int Execute(CommandLineArguments Arguments) { Arguments.ApplyTo(this); // Create the build configuration object, and read the settings BuildConfiguration BuildConfiguration = new BuildConfiguration(); XmlConfig.ApplyTo(BuildConfiguration); Arguments.ApplyTo(BuildConfiguration); // Parse the filter argument FileFilter FileFilter = null; if (FilterRules.Count > 0) { FileFilter = new FileFilter(FileFilterType.Exclude); foreach (string FilterRule in FilterRules) { FileFilter.AddRules(FilterRule.Split(';')); } } // Parse all the target descriptors List <TargetDescriptor> TargetDescriptors = TargetDescriptor.ParseCommandLine(Arguments, BuildConfiguration.bUsePrecompiled, BuildConfiguration.bSkipRulesCompile); // Generate the compile DB for each target using (ISourceFileWorkingSet WorkingSet = new EmptySourceFileWorkingSet()) { // Find the compile commands for each file in the target Dictionary <FileReference, string> FileToCommand = new Dictionary <FileReference, string>(); foreach (TargetDescriptor TargetDescriptor in TargetDescriptors) { // Disable PCHs and unity builds for the target TargetDescriptor.AdditionalArguments = TargetDescriptor.AdditionalArguments.Append(new string[] { "-NoPCH", "-DisableUnity" }); // Create a makefile for the target UEBuildTarget Target = UEBuildTarget.Create(TargetDescriptor, BuildConfiguration.bSkipRulesCompile, BuildConfiguration.bUsePrecompiled); // Find the location of the compiler VCEnvironment Environment = VCEnvironment.Create(WindowsCompiler.Clang, Target.Platform, Target.Rules.WindowsPlatform.Architecture, null, Target.Rules.WindowsPlatform.WindowsSdkVersion); FileReference ClangPath = FileReference.Combine(Environment.CompilerDir, "bin", "clang++.exe"); // Create all the binaries and modules CppCompileEnvironment GlobalCompileEnvironment = Target.CreateCompileEnvironmentForProjectFiles(); foreach (UEBuildBinary Binary in Target.Binaries) { CppCompileEnvironment BinaryCompileEnvironment = Binary.CreateBinaryCompileEnvironment(GlobalCompileEnvironment); foreach (UEBuildModuleCPP Module in Binary.Modules.OfType <UEBuildModuleCPP>()) { if (!Module.Rules.bUsePrecompiled) { UEBuildModuleCPP.InputFileCollection InputFileCollection = Module.FindInputFiles(Target.Platform, new Dictionary <DirectoryItem, FileItem[]>()); List <FileItem> InputFiles = new List <FileItem>(); InputFiles.AddRange(InputFileCollection.CPPFiles); InputFiles.AddRange(InputFileCollection.CCFiles); CppCompileEnvironment ModuleCompileEnvironment = Module.CreateModuleCompileEnvironment(Target.Rules, BinaryCompileEnvironment); StringBuilder CommandBuilder = new StringBuilder(); CommandBuilder.AppendFormat("\"{0}\"", ClangPath.FullName); foreach (FileItem ForceIncludeFile in ModuleCompileEnvironment.ForceIncludeFiles) { CommandBuilder.AppendFormat(" -include \"{0}\"", ForceIncludeFile.FullName); } foreach (string Definition in ModuleCompileEnvironment.Definitions) { CommandBuilder.AppendFormat(" -D\"{0}\"", Definition); } foreach (DirectoryReference IncludePath in ModuleCompileEnvironment.UserIncludePaths) { CommandBuilder.AppendFormat(" -I\"{0}\"", IncludePath); } foreach (DirectoryReference IncludePath in ModuleCompileEnvironment.SystemIncludePaths) { CommandBuilder.AppendFormat(" -I\"{0}\"", IncludePath); } foreach (FileItem InputFile in InputFiles) { if (FileFilter == null || FileFilter.Matches(InputFile.Location.MakeRelativeTo(UnrealBuildTool.RootDirectory))) { FileToCommand[InputFile.Location] = String.Format("{0} \"{1}\"", CommandBuilder, InputFile.FullName); } } } } } } // Write the compile database FileReference DatabaseFile = FileReference.Combine(UnrealBuildTool.RootDirectory, "compile_commands.json"); using (JsonWriter Writer = new JsonWriter(DatabaseFile)) { Writer.WriteArrayStart(); foreach (KeyValuePair <FileReference, string> FileCommandPair in FileToCommand.OrderBy(x => x.Key.FullName)) { Writer.WriteObjectStart(); Writer.WriteValue("file", FileCommandPair.Key.FullName); Writer.WriteValue("command", FileCommandPair.Value); Writer.WriteValue("directory", UnrealBuildTool.EngineSourceDirectory.ToString()); Writer.WriteObjectEnd(); } Writer.WriteArrayEnd(); } } return(0); }
public MiniFloat(char sign) { this.Signbit = sign; this.Exponent = BIAS.Copy(); this.Mantissa = new Binary("000"); }
protected virtual void CreateMockQuestion(ApplicationDbContext context, int id, IList <Tag> tags) { Question question = new Question() { Explanation = $"Explanation{id}", Text = $"Text{id}", User = new CranUser() { UserId = $"UserId{id}", }, Container = new Container() { }, Status = QuestionStatus.Released, Language = Language.De, QuestionType = QuestionType.MultipleChoice, }; context.Questions.Add(question); //Options for (int i = 1; i <= 4; i++) { QuestionOption option = new QuestionOption() { IdQuestion = question.Id, Text = $"OptionText{i}", IsTrue = i % 2 == 0, Question = question, }; question.Options.Add(option); context.QuestionOptions.Add(option); } //Tags foreach (Tag tag in tags.Where(x => x.TagType == TagType.Standard)) { RelQuestionTag relTag = new RelQuestionTag { Question = question, Tag = tag, }; context.RelQuestionTags.Add(relTag); } //Binary for (int i = 1; i <= 3; i++) { Binary binary = new Binary() { ContentType = "image/png", FileName = $"Filename{i + id * 1000}", ContentDisposition = $"form-data; name=\"files\"; filename=\"Untitled.png\"", Length = 20618, }; context.Binaries.Add(binary); Image image = new Image() { Binary = binary, Height = 300, }; context.Images.Add(image); RelQuestionImage relQuestionImage = new RelQuestionImage { Question = question, Image = image, }; context.RelQuestionImages.Add(relQuestionImage); } context.SaveChanges(); }
/* Constructors */ public MiniFloat() { this.Signbit = '0'; this.Exponent = BIAS.Copy(); this.Mantissa = new Binary("000"); }
public void TestOfSpectralIndices_Octave() { // create a two-minute artificial recording containing five harmonics. int sampleRate = 64000; double duration = 120; // signal duration in seconds int[] harmonics = { 500, 1000, 2000, 4000, 8000 }; var recording = DspFilters.GenerateTestRecording(sampleRate, duration, harmonics, WaveType.Sine); // cut out one minute from 30 - 90 seconds and incorporate into AudioRecording int startSample = sampleRate * 30; // start two minutes into recording int subsegmentSampleCount = sampleRate * 60; // get 60 seconds double[] subsamples = DataTools.Subarray(recording.WavReader.Samples, startSample, subsegmentSampleCount); var wr = new Acoustics.Tools.Wav.WavReader(subsamples, 1, 16, sampleRate); var subsegmentRecording = new AudioRecording(wr); var configFile = PathHelper.ResolveConfigFile(@"Towsey.Acoustic.yml"); var indexPropertiesConfig = PathHelper.ResolveConfigFile(@"IndexPropertiesConfig.yml"); // Create temp directory to store output if (!this.outputDirectory.Exists) { this.outputDirectory.Create(); } // CHANGE CONFIG PARAMETERS HERE IF REQUIRED var indexCalculateConfig = ConfigFile.Deserialize <IndexCalculateConfig>(configFile); indexCalculateConfig.FrequencyScale = FreqScaleType.Octave; var freqScale = new FrequencyScale(indexCalculateConfig.FrequencyScale); indexCalculateConfig.FrameLength = freqScale.WindowSize; var results = IndexCalculate.Analysis( subsegmentRecording, TimeSpan.Zero, indexCalculateConfig.IndexProperties, sampleRate, TimeSpan.Zero, indexCalculateConfig, returnSonogramInfo: true); var spectralIndices = results.SpectralIndexValues; // draw the output image of all spectral indices var outputImagePath1 = Path.Combine(this.outputDirectory.FullName, "SpectralIndices_Octave.png"); var image = SpectralIndexValues.CreateImageOfSpectralIndices(spectralIndices); image.Save(outputImagePath1); // TEST the BGN SPECTRAL INDEX Assert.AreEqual(256, spectralIndices.BGN.Length); var resourcesDir = PathHelper.ResolveAssetPath("Indices"); var expectedSpectrumFile = new FileInfo(resourcesDir + "\\BGN_OctaveScale.bin"); //Binary.Serialize(expectedSpectrumFile, spectralIndices.BGN); var expectedVector = Binary.Deserialize <double[]>(expectedSpectrumFile); CollectionAssert.That.AreEqual(expectedVector, spectralIndices.BGN, AllowedDelta); expectedSpectrumFile = new FileInfo(resourcesDir + "\\CVR_OctaveScale.bin"); //Binary.Serialize(expectedSpectrumFile, spectralIndices.CVR); expectedVector = Binary.Deserialize <double[]>(expectedSpectrumFile); CollectionAssert.That.AreEqual(expectedVector, spectralIndices.CVR, AllowedDelta); }
public uint ToBytes(Binary serializer, ref Binary.Buffer buffer, uint start) { return(serializer.ToBytes(ref buffer, start, serialized)); }
public SendMessageCommand(Binary data) { Data = data; }
public uint FromBytes(Binary serializer, Binary.Buffer buffer, uint start) { return(serializer.FromBytes(buffer, start, out serialized)); }
void UnpackFlat() { var channel = new byte[m_width * m_height]; for (int i = 0; i < 3; ++i) { m_input.Position = bits_pos[i]; var bits = m_input.ReadBytes(bits_pos[i + 1] - bits_pos[i]); m_input.Position = data_pos[i]; if (1 == m_info.Method) { int bits_src = 0; int bit_mask = 0x80; int cdst = 0; while (cdst < channel.Length) { if (0 == bit_mask) { ++bits_src; bit_mask = 0x80; } if ((bits[bits_src] & bit_mask) != 0) { int offset = m_input.ReadUInt16(); int count = (offset & 0xF) + 3; offset = (offset >> 4) + 1; Binary.CopyOverlapped(channel, cdst - offset, cdst, count); cdst += count; } else { channel[cdst++] = m_input.ReadUInt8(); } bit_mask >>= 1; } } else if (2 == m_info.Method) { LzssUnpack(bits, 0, channel, channel.Length); } int dst = i; byte accum = 0; for (int csrc = 0; csrc < channel.Length; ++csrc) { accum += channel[csrc]; m_output[dst] = accum; dst += 4; } } if (4 == m_channels) { m_input.Position = data_pos[3]; int dst = 3; while (dst < m_output.Length) { byte a = m_input.ReadUInt8(); int count = 1; if (a == 0 || a == 0xFF) { count += m_input.ReadUInt8(); } while (count-- > 0) { m_output[dst] = a; dst += 4; } } } }
public override AstNode VisitBinary(Binary ast) { Visit(ast.Left); Visit(ast.Right); bool checkFailed = false; switch (ast.Operator) { case BinaryOperator.Add: checkFailed |= ast.Left.ExpressionType != PrimaryType.Int; checkFailed |= ast.Right.ExpressionType != PrimaryType.Int; ast.ExpressionType = PrimaryType.Int; break; case BinaryOperator.Substract: checkFailed |= ast.Left.ExpressionType != PrimaryType.Int; checkFailed |= ast.Right.ExpressionType != PrimaryType.Int; ast.ExpressionType = PrimaryType.Int; break; case BinaryOperator.Multiply: checkFailed |= ast.Left.ExpressionType != PrimaryType.Int; checkFailed |= ast.Right.ExpressionType != PrimaryType.Int; ast.ExpressionType = PrimaryType.Int; break; case BinaryOperator.Divide: checkFailed |= ast.Left.ExpressionType != PrimaryType.Int; checkFailed |= ast.Right.ExpressionType != PrimaryType.Int; ast.ExpressionType = PrimaryType.Int; break; case BinaryOperator.Less: checkFailed |= ast.Left.ExpressionType != PrimaryType.Int; checkFailed |= ast.Right.ExpressionType != PrimaryType.Int; ast.ExpressionType = PrimaryType.Boolean; break; case BinaryOperator.Greater: checkFailed |= ast.Left.ExpressionType != PrimaryType.Int; checkFailed |= ast.Right.ExpressionType != PrimaryType.Int; ast.ExpressionType = PrimaryType.Boolean; break; case BinaryOperator.Equal: // use proper comparison instruction in translation stage // == is allowed on: // 1. class type and class type (compare ref) // 2. array type and array type (compare ref) // 3. int and int (compare value) // 4. bool and bool (compare value) checkFailed |= ast.Left.ExpressionType.GetType() != ast.Right.ExpressionType.GetType(); if (ast.Left.ExpressionType is PrimaryType && ast.Right.ExpressionType is PrimaryType) { checkFailed |= ast.Left.ExpressionType != ast.Right.ExpressionType; } ast.ExpressionType = PrimaryType.Boolean; break; case BinaryOperator.LogicalAnd: checkFailed |= ast.Left.ExpressionType != PrimaryType.Boolean; checkFailed |= ast.Right.ExpressionType != PrimaryType.Boolean; ast.ExpressionType = PrimaryType.Boolean; break; case BinaryOperator.LogicalOr: checkFailed |= ast.Left.ExpressionType != PrimaryType.Boolean; checkFailed |= ast.Right.ExpressionType != PrimaryType.Boolean; ast.ExpressionType = PrimaryType.Boolean; break; default: ast.ExpressionType = PrimaryType.Unknown; break; } if (checkFailed) { m_errorManager.AddError(c_SE_BinaryOpTypeInvalid, ast.OpLexeme.Span, ast.OpLexeme.Value, ast.Left.ExpressionType.Name, ast.Right.ExpressionType.Name); } return(ast); }
private string FindImageKey() { var arc_fs = VFS.Top as ArchiveFileSystem; if (null == arc_fs) { return(null); } try { // look for "start.mjo" within "scenario.arc" archive var src_name = arc_fs.Source.File.Name; var scenario_arc_name = Path.Combine(Path.GetDirectoryName(src_name), "scenario.arc"); if (!File.Exists(scenario_arc_name)) { return(null); } byte[] script; using (var file = new ArcView(scenario_arc_name)) using (var arc = s_Majiro.Value.TryOpen(file)) { if (null == arc) { return(null); } var start_mjo = arc.Dir.First(e => e.Name == "start.mjo"); using (var mjo = arc.OpenEntry(start_mjo)) { script = new byte[mjo.Length]; mjo.Read(script, 0, script.Length); } } if (Binary.AsciiEqual(script, "MajiroObjX1.000")) { DecryptMjo(script); } else if (!Binary.AsciiEqual(script, "MjPlainBytecode")) { return(null); } // locate key within start.mjo script int n = script.ToInt32(0x18); for (int offset = 0x20 + n * 8; offset < script.Length - 4; ++offset) { offset = Array.IndexOf <byte> (script, 1, offset); if (-1 == offset) { break; } if (8 != script[offset + 1]) { continue; } int str_length = script.ToUInt16(offset + 2); if (0 == str_length || str_length + 12 > script.Length - offset || 0x0835 != script.ToUInt16(offset + str_length + 4) || 0x7A7B6ED4 != script.ToUInt32(offset + str_length + 6)) { continue; } offset += 4; int end = Array.IndexOf <byte> (script, 0, offset, str_length); if (-1 != end) { str_length = end - offset; } var password = Encodings.cp932.GetString(script, offset, str_length); Trace.WriteLine(string.Format("Found key in start.mjo [{0}]", password), "[RCT]"); return(password); } } catch { /* ignore errors */ } return(null); }
private void ShiftUp() { this.Mantissa = '0' + this.Mantissa; this.Exponent += new Binary("0001"); }