Beispiel #1
0
 public static Array concat( Array lhs,Array rhs )
 {
     Array res=Array.CreateInstance( lhs.GetType().GetElementType(),lhs.Length+rhs.Length );
     Array.Copy( lhs,0,res,0,lhs.Length );
     Array.Copy( rhs,0,res,lhs.Length,rhs.Length );
     return res;
 }
Beispiel #2
0
    /// <summary>
    /// A simple bubble sort for two arrays, limited to some region of the arrays.
    /// This is a regular bubble sort, nothing fancy.
    /// </summary>
    public static void SimpleSort(Array array, Array items, int startingIndex, int length, IComparer comparer)
    {
        bool finished = false;
        while (!finished)
        {
            bool swapped = false;
            for (int g = startingIndex; g < startingIndex + length - 1; g++)
            {
                Object first = array.GetValue(g);
                Object second = array.GetValue(g + 1);
                int comparison = comparer.Compare(first, second);
                if (comparison == 1)
                {
                    Swap(g, g + 1, array, items);
                    swapped = true;

                    first = array.GetValue(g);
                    second = array.GetValue(g + 1);
                }
            }
            if (!swapped)
            {
                finished = true;
            }
        }
    }
        //Decrypt specified cypher with force
        public string decryptWithForce(string encryptedMessage)
        {


            byte[] originalMessageInAscii = Encoding.ASCII.GetBytes(encryptedMessage);
            byte[] changedMessage = new Array(originalMessageInAscii.GetLength());

            int length = originalMessageInAscii.GetLength();

            //Checks each letter of the alphabet (lower case only)
            for(int i = 0; i < 26; i++)
            {
                //Shifts ascii value in originalMessage by i to check
                for (int j = 0; j < length; j++)
                {
                    changedMessage[j] = originalMessageInAscii[j] + i;

                    if
                    Console.WriteLine(Encoding.ASCII.GetString(changedMessage, 0, length));
                }
            }
            
            /*
            foreach (byte b in messageInAscii)
            {
                Console.WriteLine(b);
            }*/
        }
Beispiel #4
0
 static void ArrayInfo(String name, Array a)
 {
     Console.Write("{0} has length={1} rank={2} [", name, a.Length, a.Rank);
     for (int i = 0, stop=a.Rank; i<stop; i++)
         Console.Write(" {0}", a.GetLength(i));
     Console.WriteLine(" ]");
 }
Beispiel #5
0
 public virtual void CopyTo(Array array, int index)
 {
     if (array == null)
     {
         throw new ArgumentNullException("array");
     }
     if (index < 0)
     {
         throw new ArgumentOutOfRangeException("index");
     }
     if ((array.Length - index) < this._size)
     {
         throw new ArgumentException();
     }
     int num = 0;
     if (array is object[])
     {
         object[] objArray = (object[])array;
         while (num < this._size)
         {
             objArray[num + index] = this._array[(this._size - num) - 1];
             num++;
         }
     }
     else
     {
         while (num < this._size)
         {
             array.SetValue(this._array[(this._size - num) - 1], (int)(num + index));
             num++;
         }
     }
 }
Beispiel #6
0
 public static void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count)
 {
     for (var i = 0; i < count; i++)
     {
         dst[i + dstOffset] = src[i + srcOffset];
     }
 }
		public static byte GetByte (Array array, int index)
		{
			if (index < 0 || index >= ByteLength (array))
				throw new ArgumentOutOfRangeException ("index");

			return _GetByte (array, index);
		}
		public static void InitializeArray (Array array, RuntimeFieldHandle fldHandle)
		{
			if ((array == null) || (fldHandle.Value == IntPtr.Zero))
				throw new ArgumentNullException ();

			InitializeArray (array, fldHandle.Value);
		}
		public static void BlockCopy (Array src, int srcOffset, Array dst, int dstOffset, int count)
		{
			if (src == null)
				throw new ArgumentNullException ("src");

			if (dst == null)
				throw new ArgumentNullException ("dst");

			if (srcOffset < 0)
				throw new ArgumentOutOfRangeException ("srcOffset", Locale.GetText(
					"Non-negative number required."));

			if (dstOffset < 0)
				throw new ArgumentOutOfRangeException ("dstOffset", Locale.GetText (
					"Non-negative number required."));

			if (count < 0)
				throw new ArgumentOutOfRangeException ("count", Locale.GetText (
					"Non-negative number required."));

			// We do the checks in unmanaged code for performance reasons
			bool res = InternalBlockCopy (src, srcOffset, dst, dstOffset, count);
			if (!res) {
				// watch for integer overflow
				if ((srcOffset > ByteLength (src) - count) || (dstOffset > ByteLength (dst) - count))
					throw new ArgumentException (Locale.GetText (
						"Offset and length were out of bounds for the array or count is greater than " + 
						"the number of elements from index to the end of the source collection."));
			}
		}
		public static void SetByte (Array array, int index, byte value)
		{
			if (index < 0 || index >= ByteLength (array))
				throw new ArgumentOutOfRangeException ("index");

			_SetByte (array, index, value);
		}
 static long ArrayLength(Array array, int i)
 {
     long n = 1;
     for ( ; i < array.Rank; i++ )
         n *= array.GetLength(i);
     return n;
 }
Beispiel #12
0
 public static string read_config(Array path, string default_val)
 {
     Hashtable current_crumb = mvid_config;
     foreach (string v in path)
     {
         if (current_crumb[v] != null)
         {
             if (current_crumb[v].GetType() == typeof(Hashtable))
             {
                 current_crumb = (Hashtable)current_crumb[v];
             }
             else
             {
                 return current_crumb[v].ToString();
             }
         }
         else
         {
             if (default_val != null)
             {
                 return default_val;
             }
             return null;
         }
     }
     return current_crumb.Values.ToString();
 }
Beispiel #13
0
 /// <summary>
 ///
 /// </summary>
 public static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length)
 {
     for (int s = 0, d = destinationIndex; s < length; s++, d++)
     {
         sourceArray.SetValue(destinationArray.GetValue(d), s + sourceIndex);
     }
 }
	// Implement the ICollection interface.
	void ICollection.CopyTo(Array array, int index)
			{
				lock(this)
				{
					list.CopyTo(array, index);
				}
			}
Beispiel #15
0
 /// <summary>
 /// Asserts that each element in the first array is equal to its corresponding element in the second array.
 /// </summary>
 public static void AssertAllArrayElementsAreEqual(Array first, Array second, IComparer comparer = null)
 {
     Assert.True(first.Length == second.Length, "The two arrays are not even the same size.");
     for (int g = first.GetLowerBound(0); g < first.GetUpperBound(0); g++)
     {
         AssertArrayElementsAreEqual(first, second, g, comparer);
     }
 }
Beispiel #16
0
 public static Array resizeArray( Array arr,int len )
 {
     Type ty=arr.GetType().GetElementType();
     Array res=Array.CreateInstance( ty,len );
     int n=Math.Min( arr.Length,len );
     if( n>0 ) Array.Copy( arr,res,n );
     return res;
 }
Beispiel #17
0
 void Awake()
 {
     powerup = Powerup.None;
     values = Enum.GetValues(typeof(Powerup));
     doors = GameObject.FindGameObjectsWithTag("Door");
     arrows = new List<Transform>();
     radar = false;
 }
Beispiel #18
0
		public void CopyTo (Array dest, int index)
		{
			/* XXX this is kind of gross and inefficient
			 * since it makes a copy of the superclass's
			 * list */
			object[] values = BaseGetAllValues();
			values.CopyTo (dest, index);
		}
 //a helper function for displaying the values of an Array
 public static void PrintValues(Array myArr)
 {
     foreach (int i in myArr)
     {
         Console.Write(i);
     }
     Console.WriteLine();
 }
Beispiel #20
0
 void printArr(Array ar) 
 {
     string temp = "";
     for (int i = 0; i < ar.Length; i++) 
     {
         temp += System.Environment.NewLine + ar.GetValue(i).ToString();
     }
     Console.WriteLine(temp);
 }
Beispiel #21
0
 private string catString(Array cat)
 {
     string str = "--";
     for(int i=0; i < cat.Length; i++)
     {
         str += cat.GetValue(i) + " |";
     }
     return str+"|\n";
 }
Beispiel #22
0
 public static Array resize( Array arr,int newlen,Type elemTy )
 {
     Array res=Array.CreateInstance( elemTy,newlen );
     if( arr==null ) return res;
     int len=arr.Length;
     int n=Math.Min( len,newlen );
     if( n>0 ) Array.Copy( arr,res,n );
     return res;
 }
        private static void VerifyGetAllValues(NameObjectCollectionBase nameObjectCollection, Array values)
        {
            Assert.Equal(nameObjectCollection.Count, values.Length);

            for (int i = 0; i < values.Length; i++)
            {
                Assert.Equal(new Foo("Value_" + i), values.GetValue(i));
            }
        }
Beispiel #24
0
		public void CopyTo (Array array, int index) 
		{
			if (array == null)
				throw new ArgumentNullException ("array");
			if ((index < 0) || (index >= array.Length))
				throw new ArgumentOutOfRangeException ("index");

			_list.CopyTo (array, index);
		}
Beispiel #25
0
    public void CopyTo(Array array, int arrayIndex)
    {
      if (array == null)
      {
        throw new ArgumentNullException("array");
      }

      List.CopyTo(array, arrayIndex);
    }
Beispiel #26
0
 private static void ArrayRankInfo(String name, Array a) {
    Console.WriteLine("Number of dimensions in \"{0}\" array (of type {1}): ",
       name, a.GetType().ToString(), a.Rank);
    for (int r = 0; r < a.Rank; r++) {
       Console.WriteLine("Rank: {0}, LowerBound = {1},  UpperBound = {2}",
          r, a.GetLowerBound(r), a.GetUpperBound(r));
    }
    Console.WriteLine();
 }
Beispiel #27
0
 public string Copy(Array array2)
 {
     if (maxNumber != array2.maxNumber) return "FAILED";
     for (int i = 0; i < maxNumber; i++)
     {
         array2.array[i] = array[i];
     }
     return "";
 }
Beispiel #28
0
		public unsafe static void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count)
		{
			if (src == null) throw new ArgumentNullException("src");
			if (dst == null) throw new ArgumentNullException("dst");
			if (srcOffset < 0 || dstOffset < 0 || count < 0) throw new ArgumentOutOfRangeException();
			if ((srcOffset + count) > ByteLength(src)) throw new ArgumentException("srcOffset");
			if ((dstOffset + count) > ByteLength(dst)) throw new ArgumentException("dstOffset");
			// TODO: This may need to be adjusted for MSB systems
			Internal_FastCopy((byte*)src.Internal_ReferenceToPointer() + sizeof(int) + srcOffset, (byte*)dst.Internal_ReferenceToPointer() + sizeof(int) + dstOffset, count);
		}
Beispiel #29
0
    /// <summary>
    /// Returns a new array containing the input array's elements in reverse order.
    /// </summary>
    /// <param name="input">The input array.</param>
    /// <returns>A reversed clone of the input array.</returns>
    public static Array ReverseArray(Array input)
    {
        Array clone = (Array)input.Clone();
        for (int g = 0; g < clone.Length; g++)
        {
            clone.SetValue(input.GetValue(input.Length - g - 1), g);
        }

        return clone;
    }
    public object ConnectData(int topicId, ref Array Strings, ref bool GetNewValues)
    {
        m_source[topicId] = Strings.GetValue(0).ToString();
        m_bland[topicId] = Strings.GetValue(1).ToString();
        m_field[topicId] = Strings.GetValue(2).ToString();

        m_timer.Start();

        return "Data not found.";
    }
Beispiel #31
0
        public Form1()
        {
            InitializeComponent();
            if (urer.urer.login)
            {
                dSkinLabel6.Text = "注销";
            }
            else
            {
                dSkinLabel6.Text = "点击头像登陆";
            }
            #region 测试头像加载
            DSkin.Controls.DSkinBrush a = new c();
            a.Brush = new TextureBrush(new Bitmap(Properties.Resources.preferences_system_login_256px_572066_easyicon_net, 100, 100));
            duiPie1.EllipseBrush = a;
            #endregion
            #region 列表
            string[] tatle = { "关于", "网络书签[登陆]", "后端[公共库]", "前端[公共库]", "工具" };
            dSkinListBox1.InnerScrollBar.BackColor = Color.Transparent;
            for (int i = 0; i < 5; i++)//添加分组
            {
                dSkinListBox1.Items.Add(new GroupItem()
                {
                    Order = i, Text = tatle[i]
                });
            }
            for (int j = 0; j < 5; j++)//添加用户,GroupId要和分组的Order一致
            {
                if (j == 4)
                {
                    Image    head = Properties.Resources.wrench_1019_0009794319px_1152317_easyicon_net;
                    UserItem item = new UserItem()
                    {
                        GroupId = j, Order = 0, Text = "基础工具", Signature = "基本的", Head = head, Visible = false
                    };
                    item.MouseClick += (s, E) => {
                        dSkinLabel5.Text = "首页/工具/基础工具";
                        dSkinTabControl1.Controls.Clear();
                        Tables = dSkinTabControl1;
                        hm_siren cr = new hm_siren {
                            Dock = DockStyle.Fill
                        };
                        Tables.TabPages.Add(" ");
                        Tables.TabPages[Tables.TabCount - 1].Controls.Add(cr);
                        cr.Show();
                        Tables.SelectedTab = Tables.TabPages[Tables.TabCount - 1];
                    };
                    dSkinListBox1.Items.Add(item);
                }
                if (j == 3)
                {
                    Image[]  head = { Properties.Resources.css_512px_1168967_easyicon_net, Properties.Resources.html_512px_1168981_easyicon_net, Properties.Resources.js_512px_1168983_easyicon_net };
                    string[] addp = { "css[3]-此代码库代码[300]", "html[5]-此代码库代码[300]", "JS-此代码库代码[300]" };
                    string[] idd  = { "css[3]", "html[5]", "JS" };
                    for (int d = 0; d < 3; d++)
                    {
                        UserItem item = new UserItem()
                        {
                            GroupId = j, Order = d, Text = addp[d].Split('-')[0], Signature = addp[d].Split('-')[1], Head = head[d], Visible = false
                        };
                        item.MouseClick += (s, E) => { //MessageBox.Show(E.ToString());
                            core_coor(item.GroupId, item.Order, item.Head, item.Text);
                            dSkinLabel5.Text = "首页/前端[公共库]/" + idd[item.Order];
                        };
                        dSkinListBox1.Items.Add(item);
                    }
                }
                if (j == 2)
                {
                    Image    head = Properties.Resources.server_115_71084337349px_1156857_easyicon_net;
                    UserItem item = new UserItem()
                    {
                        GroupId = j, Order = 0, Text = "后端", Signature = "此库依靠标签分类", Head = head, Visible = false
                    };
                    item.MouseClick += (s, E) => { core_coor(item.GroupId, item.Order, item.Head, item.Text); dSkinLabel5.Text = "首页/后端[公共库]/后端"; };
                    dSkinListBox1.Items.Add(item);
                }
                if (j == 1)
                {
                    Image    head = Properties.Resources.Cloud_Signal_Black_256px_1171908_easyicon_net;
                    UserItem item = new UserItem()
                    {
                        GroupId = j, Order = 0, Text = "书签[云备份]", Signature = "依靠标签分类", Head = head, Visible = false
                    };
                    item.MouseClick += (s, E) => { core_coor(item.GroupId, item.Order, item.Head, item.Text); dSkinLabel5.Text = "首页/私人库[登陆]/私人库[云备份]"; };
                    dSkinListBox1.Items.Add(item);
                }
                if (j == 0)
                {
                    Image    head = Properties.Resources.about_1100px_1143831_easyicon_net;
                    UserItem item = new UserItem()
                    {
                        GroupId = j, Order = 0, Text = "关于此软件", Signature = "2017", Head = head, Visible = false
                    };
                    item.MouseClick += (s, E) => { core_coor(item.GroupId, item.Order, item.Head, item.Text); dSkinLabel5.Text = "首页/关于/关于此软件"; };
                    dSkinListBox1.Items.Add(item);
                }
            }



            dSkinListBox1.Items.Sort(new ChatItemSort());
            dSkinListBox1.LayoutContent();
            #endregion
        }
Beispiel #32
0
        private async void StartClient()
        {
            int i = 0;

            while (true)
            {
                if (!UWconnectedflag)
                {
                    UI_Stream_ready_flag = false;
                    DRBE_softwarePage.UI_Stream_ready_flag = false;
                    DRBE_ap.UI_Stream_ready_flag           = false;
                    try
                    {
                        // Create the StreamSocket and establish a connection to the echo server.
                        DRBE_frontPage.Statues_tb.Text += "\r\n Client Try to Connect";
                        await Task.Delay(300);

                        await UWstreamsocket.ConnectAsync(UWhostname, UWPportnumber);

                        DRBE_frontPage.Statues_tb.Text += "\r\n Client Connected: " + UWstreamsocket.Information.LocalAddress.ToString();

                        DRBE_frontPage.DRBE_controlpanel.Message_tb.Text        += "\r\n" + DateTime.Now.ToString("HH: mm: ss~~") + "Server Connected";
                        DRBE_frontPage.DRBE_controlpanel.Server_ui_tb.Text       = "Connected";
                        DRBE_frontPage.DRBE_controlpanel.Server_ui_tb.Foreground = green_bright_button_brush;


                        UWconnectedflag = true;

                        UWoutputstream = UWstreamsocket.OutputStream.AsStreamForWrite();
                        UWinputstream  = UWstreamsocket.InputStream.AsStreamForRead();

                        UWbinarywriter = new BinaryWriter(UWoutputstream);
                        UWbinaryreader = new BinaryReader(UWinputstream);

                        DRBE_softwarePage.UWbinarywriter       = UWbinarywriter;
                        DRBE_softwarePage.UI_Stream_ready_flag = true;

                        DRBE_ap.UWbinarywriter       = UWbinarywriter;
                        DRBE_ap.UI_Stream_ready_flag = true;

                        UI_Stream_ready_flag = true;
                        testpacket           = new List <byte>(mpacket.Pass(new List <byte>()));

                        await Task.Delay(500);

                        //UWbinarywriter.Write(testpacket.ToArray(), 0, 255);
                        //UWbinarywriter.Flush();
                        StorageFolder storageFolder = ApplicationData.Current.LocalFolder;
                        string        path          = storageFolder.Path;
                        List <byte>   tosend        = new List <byte>();
                        byte[]        tbytes        = Encoding.ASCII.GetBytes(path);
                        tosend = new List <byte>(tbytes);
                        UInt16 totallen = Convert.ToUInt16(tosend.Count() + 3);
                        tosend.Insert(0, BitConverter.GetBytes(totallen)[0]);
                        tosend.Insert(0, BitConverter.GetBytes(totallen)[1]);
                        tosend.Insert(0, 0x90);
                        UWbinarywriter.Write(tosend.ToArray(), 0, tosend.Count);
                        UWbinarywriter.Flush();

                        ClientReading();
                        break;
                    }
                    catch (Exception ex)
                    {
                        await Task.Delay(1000);

                        i++;
                    }
                }
            }
            //}
        }
Beispiel #33
0
 static void Main(string[] args)
 {
 }
Beispiel #34
0
 public object[] ResolveAll(Type[] types, object tag = null)
 {
     return(ResolveMultiple(types, tag));
 }
Beispiel #35
0
        private static void Main(string[] args)
        {
            SqlCeConnection sqlCeCon = new SqlCeConnection("Data Source=\\endo.sdf");

            try
            {
                sqlCeCon.Open();
                Console.WriteLine("Connection is open");

                SqlCeCommand cmd = new SqlCeCommand();
                cmd.Connection  = sqlCeCon;
                cmd.CommandType = System.Data.CommandType.Text;

                cmd.CommandText = "SELECT * FROM Workout;";
                SqlCeResultSet rs = cmd.ExecuteResultSet(ResultSetOptions.Scrollable);

                List <Workout> workoutList = new List <Workout>();
                if (rs.HasRows)
                {
                    int ordId        = rs.GetOrdinal("Id");
                    int ordWorkoutId = rs.GetOrdinal("WorkoutId");
                    int ordSport     = rs.GetOrdinal("Sport");
                    int ordDuration  = rs.GetOrdinal("Duration");

                    while (rs.Read())
                    {
                        Guid   id        = rs.GetGuid(ordId);
                        string workoutId = rs.GetString(ordWorkoutId);
                        int    sport     = rs.GetInt32(ordSport);
                        double duration  = rs.GetDouble(ordDuration);

                        workoutList.Add(new Workout(id, workoutId, sport, duration));
                    }
                }

                int counter = 1;
                foreach (Workout workout in workoutList)
                {
                    cmd.CommandText = $"SELECT * FROM Track WHERE Track.WorkoutId='{workout.Id}';";
                    //Console.WriteLine(cmd.CommandText);

                    rs = cmd.ExecuteResultSet(ResultSetOptions.Scrollable);

                    List <Track> trackList = new List <Track>();
                    if (rs.HasRows)
                    {
                        int ordId           = rs.GetOrdinal("Id");
                        int ordWorkoutId    = rs.GetOrdinal("WorkoutId");
                        int ordTimestamp    = rs.GetOrdinal("Timestamp");
                        int ordInstruction  = rs.GetOrdinal("Instruction");
                        int ordLatitude     = rs.GetOrdinal("Latitude");
                        int ordLongitude    = rs.GetOrdinal("Longitude");
                        int ordDistance     = rs.GetOrdinal("Distance");
                        int ordSpeed        = rs.GetOrdinal("Speed");
                        int ordAltitude     = rs.GetOrdinal("Altitude");
                        int ordSentToServer = rs.GetOrdinal("SentToServer");

                        while (rs.Read())
                        {
                            int      id        = rs.GetInt32(ordId);
                            Guid     workoutId = rs.GetGuid(ordWorkoutId);
                            DateTime timestamp = rs.GetDateTime(ordTimestamp);
                            timestamp = timestamp.Subtract(new TimeSpan(2, 0, 0));

                            int    instruction  = rs.IsDBNull(ordInstruction) ? -1 : rs.GetInt32(ordInstruction);
                            double latitude     = rs.GetDouble(ordLatitude);
                            double longitude    = rs.GetDouble(ordLongitude);
                            double distance     = rs.GetDouble(ordDistance);
                            double speed        = rs.GetDouble(ordSpeed);
                            double altitude     = rs.GetDouble(ordAltitude);
                            bool   sentToServer = rs.GetBoolean(ordSentToServer);

                            trackList.Add(new Track(id, workoutId, timestamp, instruction, latitude, longitude, distance, speed, altitude, sentToServer));
                        }

                        string fileName;

                        fileName = String.Format("Endo_{0}_tcx.tcx", counter);
                        CreateXmlTcx(fileName, workout, trackList);
                        fileName = String.Format("Endo_{0}_gpx.gpx", counter);
                        CreateXmlGpx(fileName, workout, trackList);
                    }

                    counter++;
                }

                sqlCeCon.Close();
                Console.WriteLine("Connection is closed");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Source + " - " + ex.Message);
            }

            //Console.ReadKey();
        }
Beispiel #36
0
        /// <summary>
        /// Returns true if the text passed is a private message sent to the bot
        /// </summary>
        /// <param name="text">text to test</param>
        /// <param name="message">if it's a private message, this will contain the message</param>
        /// <param name="sender">if it's a private message, this will contain the player name that sends the message</param>
        /// <returns>Returns true if the text is a private message</returns>
        protected static bool IsPrivateMessage(string text, ref string message, ref string sender)
        {
            if (String.IsNullOrEmpty(text))
            {
                return(false);
            }

            text = GetVerbatim(text);

            //User-defined regex for private chat messages
            if (Settings.ChatFormat_Private != null)
            {
                Match regexMatch = Settings.ChatFormat_Private.Match(text);
                if (regexMatch.Success && regexMatch.Groups.Count >= 3)
                {
                    sender  = regexMatch.Groups[1].Value;
                    message = regexMatch.Groups[2].Value;
                    return(IsValidName(sender));
                }
            }

            //Built-in detection routine for private messages
            if (Settings.ChatFormat_Builtins)
            {
                string[] tmp = text.Split(' ');
                try
                {
                    //Detect vanilla /tell messages
                    //Someone whispers message (MC 1.5)
                    //Someone whispers to you: message (MC 1.7)
                    if (tmp.Length > 2 && tmp[1] == "whispers")
                    {
                        if (tmp.Length > 4 && tmp[2] == "to" && tmp[3] == "you:")
                        {
                            message = text.Substring(tmp[0].Length + 18); //MC 1.7
                        }
                        else
                        {
                            message = text.Substring(tmp[0].Length + 10);  //MC 1.5
                        }
                        sender = tmp[0];
                        return(IsValidName(sender));
                    }

                    //Detect Essentials (Bukkit) /m messages
                    //[Someone -> me] message
                    //[~Someone -> me] message
                    else if (text[0] == '[' && tmp.Length > 3 && tmp[1] == "->" &&
                             (tmp[2].ToLower() == "me]" || tmp[2].ToLower() == "moi]"))   //'me' is replaced by 'moi' in french servers
                    {
                        message = text.Substring(tmp[0].Length + 4 + tmp[2].Length + 1);
                        sender  = tmp[0].Substring(1);
                        if (sender[0] == '~')
                        {
                            sender = sender.Substring(1);
                        }
                        return(IsValidName(sender));
                    }

                    //Detect Modified server messages. /m
                    //[Someone @ me] message
                    else if (text[0] == '[' && tmp.Length > 3 && tmp[1] == "@" &&
                             (tmp[2].ToLower() == "me]" || tmp[2].ToLower() == "moi]"))   //'me' is replaced by 'moi' in french servers
                    {
                        message = text.Substring(tmp[0].Length + 4 + tmp[2].Length + 0);
                        sender  = tmp[0].Substring(1);
                        if (sender[0] == '~')
                        {
                            sender = sender.Substring(1);
                        }
                        return(IsValidName(sender));
                    }

                    //Detect Essentials (Bukkit) /me messages with some custom prefix
                    //[Prefix] [Someone -> me] message
                    //[Prefix] [~Someone -> me] message
                    else if (text[0] == '[' && tmp[0][tmp[0].Length - 1] == ']' &&
                             tmp[1][0] == '[' && tmp.Length > 4 && tmp[2] == "->" &&
                             (tmp[3].ToLower() == "me]" || tmp[3].ToLower() == "moi]"))
                    {
                        message = text.Substring(tmp[0].Length + 1 + tmp[1].Length + 4 + tmp[3].Length + 1);
                        sender  = tmp[1].Substring(1);
                        if (sender[0] == '~')
                        {
                            sender = sender.Substring(1);
                        }
                        return(IsValidName(sender));
                    }

                    //Detect Essentials (Bukkit) /me messages with some custom rank
                    //[Someone [rank] -> me] message
                    //[~Someone [rank] -> me] message
                    else if (text[0] == '[' && tmp.Length > 3 && tmp[2] == "->" &&
                             (tmp[3].ToLower() == "me]" || tmp[3].ToLower() == "moi]"))
                    {
                        message = text.Substring(tmp[0].Length + 1 + tmp[1].Length + 4 + tmp[2].Length + 1);
                        sender  = tmp[0].Substring(1);
                        if (sender[0] == '~')
                        {
                            sender = sender.Substring(1);
                        }
                        return(IsValidName(sender));
                    }

                    //Detect HeroChat PMsend
                    //From Someone: message
                    else if (text.StartsWith("From "))
                    {
                        sender  = text.Substring(5).Split(':')[0];
                        message = text.Substring(text.IndexOf(':') + 2);
                        return(IsValidName(sender));
                    }
                    else
                    {
                        return(false);
                    }
                }
                catch (IndexOutOfRangeException) { /* Not an expected chat format */ }
                catch (ArgumentOutOfRangeException) { /* Same here */ }
            }

            return(false);
        }
Beispiel #37
0
 public static void Main(string[] args)
 {
     CreateWebHostBuilder(args).Build().Run();
 }
Beispiel #38
0
    /// <summary>
    /// Adds the shadow material to material list. SubMeshes will be reconfigured so that each subMeshIndex is increased by one.
    /// Tht is done, because shadow material must be the first submesh.
    /// </summary>
    void AddShadowMaterialToList()
    {
        Material SharedShadowMaterial = Resources.Load <Material>("ShadowPlane/PlaneShadow");

        Shader ShadowPlaneShader = SharedShadowMaterial.shader;

        if (RenderComponent.sharedMaterials[0] &&
            RenderComponent.sharedMaterials[0].shader.Equals(ShadowPlaneShader))
        {
            return;
        }

        MeshFilter mf = gameObject.GetComponent <MeshFilter>();

        if (null != mf && mf.mesh.subMeshCount > 1)
        {
            Mesh mesh = mf.mesh;
            mesh.subMeshCount++;


            List <int> triangles = new List <int>();
            List <int> indices   = new List <int>();

            MeshTopology mt = MeshTopology.Triangles;

            for (int j = mesh.subMeshCount - 2; j >= 0; --j)
            {
                if (j == 0)
                {
                    mt = mf.mesh.GetTopology(j);
                }
                else
                {
                    if (mt != mf.mesh.GetTopology(j))
                    {
                        Debug.LogError("Inconsitent Mesh Topology");
                    }
                }
                int [] subMesh    = mf.sharedMesh.GetTriangles(j);
                int [] subIndices = mf.sharedMesh.GetIndices(j);
                triangles.AddRange(subMesh);
                indices.AddRange(subIndices);
                mesh.SetTriangles(subMesh, j + 1);
                mesh.SetIndices(subIndices, mt, j + 1);
            }

            if (IncludeAllSubMeshes)
            {
                mesh.SetTriangles(triangles.ToArray(), 0);
                mesh.SetIndices(indices.ToArray(), mt, 0);
            }

            mf.mesh = mesh;
        }



        Material [] newList = new Material[RenderComponent.sharedMaterials.Length + 1];

        newList[0] = new Material(SharedShadowMaterial);
        for (int i = 1; i < newList.Length; ++i)
        {
            newList[i] = RenderComponent_.sharedMaterials[i - 1];
        }
        RenderComponent_.sharedMaterials = newList;
    }
Beispiel #39
0
        static void Main(string[] args)
        {
            /*1. StringRequestInfo: 命令行协议(默认协议)
             * 命令行协议定义了每个请求必须以回车换行结尾 "\r\n"
             */

            // 1.1. 自定义命令行协议
            var stringRequestInfoServer1 = new StringRequestInfoServer1();

            stringRequestInfoServer1.Setup(2004);
            stringRequestInfoServer1.NewRequestReceived += StringRequestInfoServer_NewRequestReceived;
            stringRequestInfoServer1.Start();

            // 1.2. 基于接口 IRequestInfoParser 来实现一个 RequestInfoParser 类
            var stringRequestInfoServer2 = new StringRequestInfoServer2();

            stringRequestInfoServer2.Setup(2005);
            stringRequestInfoServer2.NewRequestReceived += StringRequestInfoServer_NewRequestReceived;
            stringRequestInfoServer2.Start();

            /*2. 内置的常用协议实现模版
             */

            // 2.1. TerminatorReceiveFilter (结束符协议): 用结束符来确定一个请求
            var terminatorAppServer = new TerminatorAppServer();

            terminatorAppServer.Setup(2006);
            terminatorAppServer.NewRequestReceived += StringRequestInfoServer_NewRequestReceived;
            terminatorAppServer.Start();

            // 2.2. CountSpliterReceiveFilter (CountSpliterReceiveFilter): 像 "#part1#part2#part3#part4#part5#part6#part7#". 每个请求有7个由 '#' 分隔的部分
            var countSpliterAppServer = new CountSpliterAppServer();

            countSpliterAppServer.Setup(2007);
            countSpliterAppServer.NewRequestReceived += StringRequestInfoServer_NewRequestReceived;
            countSpliterAppServer.Start();

            // 2.3. FixedSizeReceiveFilter (固定请求大小的协议): 所有请求的大小都是相同的
            var fixedSizeAppServer = new FixedSizeAppServer();

            fixedSizeAppServer.Setup(2008);
            fixedSizeAppServer.NewRequestReceived += StringRequestInfoServer_NewRequestReceived;
            fixedSizeAppServer.Start();

            // 2.4. BeginEndMarkReceiveFilter (带起止符的协议): 每个请求都有固定的开始和结束标记
            var beginEndMarkAppServer = new BeginEndMarkAppServer();

            beginEndMarkAppServer.Setup(2009);
            beginEndMarkAppServer.NewRequestReceived += StringRequestInfoServer_NewRequestReceived;
            beginEndMarkAppServer.Start();

            // 2.5. FixedHeaderReceiveFilter (头部格式固定并且包含内容长度的协议): 这种协议将一个请求定义为两大部分, 第一部分定义了包含第二部分长度等等基础信息. 我们通常称第一部分为头部
            var fixedHeaderAppServer = new FixedHeaderAppServer();

            fixedHeaderAppServer.Setup(2010);
            fixedHeaderAppServer.NewRequestReceived += FixedHeaderAppServer_NewRequestReceived;
            fixedHeaderAppServer.Start();


            Console.ReadLine();
            stringRequestInfoServer1.Stop();
            stringRequestInfoServer2.Stop();
            terminatorAppServer.Stop();
            countSpliterAppServer.Stop();
            fixedSizeAppServer.Stop();
            beginEndMarkAppServer.Stop();
            fixedHeaderAppServer.Stop();
            Console.ReadLine();
        }
Beispiel #40
0
 protected override void HashCore(byte[] rgb, int ibStart, int cbSize)
 {
     throw new NotImplementedException();
 }
Beispiel #41
0
        static void Main(string[] args)
        {
            Tertris ingameteritrs = new Tertris();

            ingameteritrs.InGame();
        }
        public static async Task<int> CopyBufferedToAsync(this Stream source, Stream destination, byte[] buffer,
            CancellationToken cancellationToken = default)
        {
            var bytesCopied = await source.ReadAsync(buffer, cancellationToken);
            await destination.WriteAsync(buffer, 0, bytesCopied, cancellationToken);

            return bytesCopied;
        }
 /// <remarks/>
 public ExchangeOrganization EndGetOrganizationDetails(System.IAsyncResult asyncResult) {
     object[] results = this.EndInvoke(asyncResult);
     return ((ExchangeOrganization)(results[0]));
 }
 public ExchangeOrganization GetOrganizationDetails(string organizationId) {
     object[] results = this.Invoke("GetOrganizationDetails", new object[] {
                 organizationId});
     return ((ExchangeOrganization)(results[0]));
 }
Beispiel #45
0
        /// <summary>
        /// Returns true if the text passed is a public message written by a player on the chat
        /// </summary>
        /// <param name="text">text to test</param>
        /// <param name="message">if it's message, this will contain the message</param>
        /// <param name="sender">if it's message, this will contain the player name that sends the message</param>
        /// <returns>Returns true if the text is a chat message</returns>
        protected static bool IsChatMessage(string text, ref string message, ref string sender)
        {
            if (String.IsNullOrEmpty(text))
            {
                return(false);
            }

            text = GetVerbatim(text);

            //User-defined regex for public chat messages
            if (Settings.ChatFormat_Public != null)
            {
                Match regexMatch = Settings.ChatFormat_Public.Match(text);
                if (regexMatch.Success && regexMatch.Groups.Count >= 3)
                {
                    sender  = regexMatch.Groups[1].Value;
                    message = regexMatch.Groups[2].Value;
                    return(IsValidName(sender));
                }
            }

            //Built-in detection routine for public messages
            if (Settings.ChatFormat_Builtins)
            {
                string[] tmp = text.Split(' ');

                //Detect vanilla/factions Messages
                //<Someone> message
                //<*Faction Someone> message
                //<*Faction Someone>: message
                //<*Faction ~Nicknamed>: message
                if (text[0] == '<')
                {
                    try
                    {
                        text = text.Substring(1);
                        string[] tmp2 = text.Split('>');
                        sender  = tmp2[0];
                        message = text.Substring(sender.Length + 2);
                        if (message.Length > 1 && message[0] == ' ')
                        {
                            message = message.Substring(1);
                        }
                        tmp2   = sender.Split(' ');
                        sender = tmp2[tmp2.Length - 1];
                        if (sender[0] == '~')
                        {
                            sender = sender.Substring(1);
                        }
                        return(IsValidName(sender));
                    }
                    catch (IndexOutOfRangeException) { /* Not a vanilla/faction message */ }
                    catch (ArgumentOutOfRangeException) { /* Same here */ }
                }

                //Detect HeroChat Messages
                //Public chat messages
                //[Channel] [Rank] User: Message
                else if (text[0] == '[' && text.Contains(':') && tmp.Length > 2)
                {
                    try
                    {
                        int name_end   = text.IndexOf(':');
                        int name_start = text.Substring(0, name_end).LastIndexOf(']') + 2;
                        sender  = text.Substring(name_start, name_end - name_start);
                        message = text.Substring(name_end + 2);
                        return(IsValidName(sender));
                    }
                    catch (IndexOutOfRangeException) { /* Not a herochat message */ }
                    catch (ArgumentOutOfRangeException) { /* Same here */ }
                }

                //Detect (Unknown Plugin) Messages
                //**Faction<Rank> User : Message
                else if (text[0] == '*' &&
                         text.Length > 1 &&
                         text[1] != ' ' &&
                         text.Contains('<') && text.Contains('>') &&
                         text.Contains(' ') && text.Contains(':') &&
                         text.IndexOf('*') < text.IndexOf('<') &&
                         text.IndexOf('<') < text.IndexOf('>') &&
                         text.IndexOf('>') < text.IndexOf(' ') &&
                         text.IndexOf(' ') < text.IndexOf(':'))
                {
                    try
                    {
                        string prefix    = tmp[0];
                        string user      = tmp[1];
                        string semicolon = tmp[2];
                        if (prefix.All(c => char.IsLetterOrDigit(c) || new char[] { '*', '<', '>', '_' }.Contains(c)) &&
                            semicolon == ":")
                        {
                            message = text.Substring(prefix.Length + user.Length + 4);
                            return(IsValidName(user));
                        }
                    }
                    catch (IndexOutOfRangeException) { /* Not a <unknown plugin> message */ }
                    catch (ArgumentOutOfRangeException) { /* Same here */ }
                }
            }

            return(false);
        }
Beispiel #46
0
 public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
 WebHost.CreateDefaultBuilder(args)
 .UseStartup <Startup>();
Beispiel #47
0
 /// <summary>
 /// Called when a plugin channel message is received.
 /// The given channel must have previously been registered with RegisterPluginChannel.
 /// This can be used to communicate with server mods or plugins.  See wiki.vg for more
 /// information about plugin channels: http://wiki.vg/Plugin_channel
 /// </summary>
 /// <param name="channel">The name of the channel</param>
 /// <param name="data">The payload for the message</param>
 public virtual void OnPluginMessage(string channel, byte[] data)
 {
 }
 internal GetOrganizationDetailsCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : 
         base(exception, cancelled, userState) {
     this.results = results;
 }
 public static void ColorizeWriteLine(AlCConfigScheme preset, string message, ConsoleColor[] colors, bool isAlConsole = true) {
     ColorizeWrite(preset, message, colors, isAlConsole);
     Console.WriteLine();
 }
Beispiel #50
0
        public ModelDescription GetOrCreateModelDescription(Type modelType)
        {
            if (modelType == null)
            {
                throw new ArgumentNullException("modelType");
            }

            Type underlyingType = Nullable.GetUnderlyingType(modelType);

            if (underlyingType != null)
            {
                modelType = underlyingType;
            }

            ModelDescription modelDescription;
            string           modelName = ModelNameHelper.GetModelName(modelType);

            if (GeneratedModels.TryGetValue(modelName, out modelDescription))
            {
                if (modelType != modelDescription.ModelType)
                {
                    throw new InvalidOperationException(
                              String.Format(
                                  CultureInfo.CurrentCulture,
                                  "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
                                  "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
                                  modelName,
                                  modelDescription.ModelType.FullName,
                                  modelType.FullName));
                }

                return(modelDescription);
            }

            if (DefaultTypeDocumentation.ContainsKey(modelType))
            {
                return(GenerateSimpleTypeModelDescription(modelType));
            }

            if (modelType.IsEnum)
            {
                return(GenerateEnumTypeModelDescription(modelType));
            }

            if (modelType.IsGenericType)
            {
                Type[] genericArguments = modelType.GetGenericArguments();

                if (genericArguments.Length == 1)
                {
                    Type enumerableType = typeof(IEnumerable <>).MakeGenericType(genericArguments);
                    if (enumerableType.IsAssignableFrom(modelType))
                    {
                        return(GenerateCollectionModelDescription(modelType, genericArguments[0]));
                    }
                }
                if (genericArguments.Length == 2)
                {
                    Type dictionaryType = typeof(IDictionary <,>).MakeGenericType(genericArguments);
                    if (dictionaryType.IsAssignableFrom(modelType))
                    {
                        return(GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]));
                    }

                    Type keyValuePairType = typeof(KeyValuePair <,>).MakeGenericType(genericArguments);
                    if (keyValuePairType.IsAssignableFrom(modelType))
                    {
                        return(GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]));
                    }
                }
            }

            if (modelType.IsArray)
            {
                Type elementType = modelType.GetElementType();
                return(GenerateCollectionModelDescription(modelType, elementType));
            }

            if (modelType == typeof(NameValueCollection))
            {
                return(GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)));
            }

            if (typeof(IDictionary).IsAssignableFrom(modelType))
            {
                return(GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)));
            }

            if (typeof(IEnumerable).IsAssignableFrom(modelType))
            {
                return(GenerateCollectionModelDescription(modelType, typeof(object)));
            }

            return(GenerateComplexTypeModelDescription(modelType));
        }
Beispiel #51
0
        static void Main(string[] args)
        {

            string marka;
            string model;
            double pojemnosc;
            double ilosc_paliwa;
            double pojemnosc_baku;

            Menuserializacji operacjieserializacji;
            Console.WriteLine("1-Nowy użytkownik \n2-Wczytaj ostatni zapis");
            bool czypoprawnemenuserializaji = Enum.TryParse<Menuserializacji>(Console.ReadLine(), out operacjieserializacji);
            if (!czypoprawnemenuserializaji)
            {
                Console.WriteLine("Wybrałeś nieprawidłową opcję");
            }
            switch (operacjieserializacji)
            {
                case Menuserializacji.Nowy_użytkowik:
                    Console.WriteLine("Witaj w symulatorze jazdy samochodem");
                    Console.WriteLine("Wpisz markę samochodu");
                    marka = Console.ReadLine();
                    Console.WriteLine("Wpisz model");
                    model = Console.ReadLine();
                    do { Console.WriteLine("Wpisz pojemność"); }
                    while (!double.TryParse(Console.ReadLine(), out pojemnosc) || pojemnosc > 20 || pojemnosc < 0.5);
                    do { Console.WriteLine("Wpisz pojemność baku"); }
                    while (!double.TryParse(Console.ReadLine(), out pojemnosc_baku) || pojemnosc_baku > 100 || pojemnosc_baku < 1);
                    do { Console.WriteLine("Wpisz ilość paliwa"); }
                    while (!double.TryParse(Console.ReadLine(), out ilosc_paliwa) || ilosc_paliwa > pojemnosc_baku || ilosc_paliwa < 1);
                    samochod test = new samochod(marka, model, pojemnosc, ilosc_paliwa, pojemnosc_baku);
                    Console.Clear();
                    bool powrotdomenu = true;
                    while (powrotdomenu)
                    {
                        Console.Clear();
                        Console.WriteLine("Wybierz jedną z opcji");
                        Console.WriteLine("1-Podróż");
                        Console.WriteLine("2-Zatankuj");
                        Console.WriteLine("3-Licznik");
                        Console.WriteLine("4-Zapisz");
                        Console.WriteLine("5-Koniec jazdy");

                        Menu operacje;
                        bool czypoprawna = Enum.TryParse<Menu>(Console.ReadLine(), out operacje);
                        if (!czypoprawna)
                        {
                            Console.WriteLine("Wybrałeś nieprawidłową opcję");
                        }
                        switch (operacje)
                        {
                            case Menu.Dalsza_jazda:
                                test.jedz();
                                break;
                            case Menu.Tankowanie:
                                test.tankuj();
                                break;
                            case Menu.Licznik:
                                Console.WriteLine("Licznik przejechanych kilometrów wynosi " + test.Licznik); ;
                                Console.ReadKey();
                                break;
                            case Menu.Zapisz:
                                Console.WriteLine("Informacje o samochodzie zostały zapisane ");
                                test.Save(test);
                                //test.SaveXML(test);
                                Console.ReadKey();
                                break; 

                            case Menu.Wyjście:
                                Console.WriteLine("Koniec symulatora");
                                test = test.deSave(test);
                                powrotdomenu = false;
                                break;
                        }

                    }
                    break;
                case Menuserializacji.Wczytaj:
                    Console.WriteLine("Witaj w symulatorze jazdy samochodem");
                    samochod test1 = new samochod("", "", 1, 1, 1);
                    test1 = test1.deSave(test1);
                    //test1 = test1.UNSaveXML(test1);
                    Console.Clear();
                    bool powrotdomenu2 = true; 
                    while (powrotdomenu2)
                    {
                        Console.Clear();
                        Console.WriteLine("Wybierz jedną z opcji");
                        Console.WriteLine("1-Podróż");
                        Console.WriteLine("2-Zatankuj");
                        Console.WriteLine("3-Licznik");
                        Console.WriteLine("4-Zapisz");
                        Console.WriteLine("5-Koniec jazdy");

                        Menu operacje;
                        bool czypoprawna = Enum.TryParse<Menu>(Console.ReadLine(), out operacje);
                        if (!czypoprawna)
                        {
                            Console.WriteLine("Wybrałeś nieprawidłową opcję");
                        }
                        switch (operacje)
                        {
                            case Menu.Dalsza_jazda:
                                test1.jedz();
                                break;
                            case Menu.Tankowanie:
                                test1.tankuj();
                                break;
                            case Menu.Licznik:
                                Console.WriteLine("Licznik przejechanych kilometrów wynosi " + test1.Licznik); ;
                                Console.ReadKey();

                                break;
                            case Menu.Zapisz:
                                Console.WriteLine("Informacje o samochodzie zostały zapisane"); ;
                                test1.Save(test1);
                                Console.ReadKey();

                                break;
                            case Menu.Wyjście:
                                Console.WriteLine("Koniec symulatora");
                                powrotdomenu2 = false;
                                break;
                        }

                    }
                    break;
                default:
                    break;
            }


        }
Beispiel #52
0
        /// <summary>
        /// x86 32 bit implementation of Murmur Hash 3 initializer
        /// </summary>
        /// <param name="data"></param>
        /// <param name="length"></param>
        /// <param name="seed"></param>
        /// <returns></returns>
        static public uint MurmurHash3(byte[] data, uint length, uint seed)
        {
            uint nblocks = length >> 2;

            uint h1 = seed;

            const uint c1 = 0xcc9e2d51;
            const uint c2 = 0x1b873593;

            //----------
            // body

            int i = 0;

            for (uint j = nblocks; j > 0; --j)
            {
                uint k1l = BitConverter.ToUInt32(data, i);

                k1l *= c1;
                k1l  = rotl(k1l, 15);
                k1l *= c2;

                h1 ^= k1l;
                h1  = rotl(h1, 13);
                h1  = h1 * 5 + 0xe6546b64;

                i += 4;
            }

            //----------
            // tail

            nblocks <<= 2;

            uint k1 = 0;

            uint tailLength = length & 3;

            if (tailLength == 3)
            {
                k1 ^= (uint)data[2 + nblocks] << 16;
            }
            if (tailLength >= 2)
            {
                k1 ^= (uint)data[1 + nblocks] << 8;
            }
            if (tailLength >= 1)
            {
                k1 ^= data[nblocks];
                k1 *= c1; k1 = rotl(k1, 15); k1 *= c2; h1 ^= k1;
            }

            //----------
            // finalization

            h1 ^= length;

            h1 = fmix(h1);

            return(h1);
        }
Beispiel #53
0
        private static IFormatter CreateFormatter(Type type, ISerializationPolicy policy)
        {
            if (FormatterUtilities.IsPrimitiveType(type))
            {
                throw new ArgumentException("Cannot create formatters for a primitive type like " + type.Name);
            }

            // First call formatter locators before checking for registered formatters
            for (int i = 0; i < FormatterLocators.Count; i++)
            {
                try
                {
                    IFormatter result;
                    if (FormatterLocators[i].LocatorInstance.TryGetFormatter(type, FormatterLocationStep.BeforeRegisteredFormatters, policy, out result))
                    {
                        return(result);
                    }
                }
                catch (TargetInvocationException ex)
                {
                    throw ex;
                }
                catch (TypeInitializationException ex)
                {
                    throw ex;
                }
#pragma warning disable CS0618 // Type or member is obsolete
                catch (ExecutionEngineException ex)
#pragma warning restore CS0618 // Type or member is obsolete
                {
                    throw ex;
                }
                catch (Exception ex)
                {
                    Debug.LogException(new Exception("Exception was thrown while calling FormatterLocator " + FormatterLocators[i].GetType().FullName + ".", ex));
                }
            }

            // Then check for valid registered formatters
            for (int i = 0; i < FormatterInfos.Count; i++)
            {
                var info = FormatterInfos[i];

                Type formatterType = null;

                if (type == info.TargetType)
                {
                    formatterType = info.FormatterType;
                }
                else if (info.FormatterType.IsGenericType && info.TargetType.IsGenericParameter)
                {
                    Type[] inferredArgs;

                    if (info.FormatterType.TryInferGenericParameters(out inferredArgs, type))
                    {
                        formatterType = info.FormatterType.GetGenericTypeDefinition().MakeGenericType(inferredArgs);
                    }
                }
                else if (type.IsGenericType && info.FormatterType.IsGenericType && info.TargetType.IsGenericType && type.GetGenericTypeDefinition() == info.TargetType.GetGenericTypeDefinition())
                {
                    Type[] args = type.GetGenericArguments();

                    if (info.FormatterType.AreGenericConstraintsSatisfiedBy(args))
                    {
                        formatterType = info.FormatterType.GetGenericTypeDefinition().MakeGenericType(args);
                    }
                }

                if (formatterType != null)
                {
                    var instance = GetFormatterInstance(formatterType);

                    if (instance == null)
                    {
                        continue;
                    }

                    if (info.AskIfCanFormatTypes && !((IAskIfCanFormatTypes)instance).CanFormatType(type))
                    {
                        continue;
                    }

                    return(instance);
                }
            }

            // Then call formatter locators after checking for registered formatters
            for (int i = 0; i < FormatterLocators.Count; i++)
            {
                try
                {
                    IFormatter result;
                    if (FormatterLocators[i].LocatorInstance.TryGetFormatter(type, FormatterLocationStep.AfterRegisteredFormatters, policy, out result))
                    {
                        return(result);
                    }
                }
                catch (TargetInvocationException ex)
                {
                    throw ex;
                }
                catch (TypeInitializationException ex)
                {
                    throw ex;
                }
#pragma warning disable CS0618 // Type or member is obsolete
                catch (ExecutionEngineException ex)
#pragma warning restore CS0618 // Type or member is obsolete
                {
                    throw ex;
                }
                catch (Exception ex)
                {
                    Debug.LogException(new Exception("Exception was thrown while calling FormatterLocator " + FormatterLocators[i].GetType().FullName + ".", ex));
                }
            }

            // If we can, emit a formatter to handle serialization of this object
            {
                if (EmitUtilities.CanEmit)
                {
                    var result = FormatterEmitter.GetEmittedFormatter(type, policy);
                    if (result != null)
                    {
                        return(result);
                    }
                }
            }

            if (EmitUtilities.CanEmit)
            {
                Debug.LogWarning("Fallback to reflection for type " + type.Name + " when emit is possible on this platform.");
            }

            // Finally, we fall back to a reflection-based formatter if nothing else has been found
            return((IFormatter)Activator.CreateInstance(typeof(ReflectionFormatter <>).MakeGenericType(type)));
        }
 public ExchangeOrganizationDomain[] GetOrganizationDomains(string organizationId) {
     object[] results = this.Invoke("GetOrganizationDomains", new object[] {
                 organizationId});
     return ((ExchangeOrganizationDomain[])(results[0]));
 }
Beispiel #55
0
        internal static List <IFormatter> GetAllCompatiblePredefinedFormatters(Type type, ISerializationPolicy policy)
        {
            if (FormatterUtilities.IsPrimitiveType(type))
            {
                throw new ArgumentException("Cannot create formatters for a primitive type like " + type.Name);
            }

            List <IFormatter> formatters = new List <IFormatter>();

            // First call formatter locators before checking for registered formatters
            for (int i = 0; i < FormatterLocators.Count; i++)
            {
                try
                {
                    IFormatter result;
                    if (FormatterLocators[i].LocatorInstance.TryGetFormatter(type, FormatterLocationStep.BeforeRegisteredFormatters, policy, out result))
                    {
                        formatters.Add(result);
                    }
                }
                catch (TargetInvocationException ex)
                {
                    throw ex;
                }
                catch (TypeInitializationException ex)
                {
                    throw ex;
                }
#pragma warning disable CS0618 // Type or member is obsolete
                catch (ExecutionEngineException ex)
#pragma warning restore CS0618 // Type or member is obsolete
                {
                    throw ex;
                }
                catch (Exception ex)
                {
                    Debug.LogException(new Exception("Exception was thrown while calling FormatterLocator " + FormatterLocators[i].GetType().FullName + ".", ex));
                }
            }

            // Then check for valid registered formatters
            for (int i = 0; i < FormatterInfos.Count; i++)
            {
                var info = FormatterInfos[i];

                Type formatterType = null;

                if (type == info.TargetType)
                {
                    formatterType = info.FormatterType;
                }
                else if (info.FormatterType.IsGenericType && info.TargetType.IsGenericParameter)
                {
                    Type[] inferredArgs;

                    if (info.FormatterType.TryInferGenericParameters(out inferredArgs, type))
                    {
                        formatterType = info.FormatterType.GetGenericTypeDefinition().MakeGenericType(inferredArgs);
                    }
                }
                else if (type.IsGenericType && info.FormatterType.IsGenericType && info.TargetType.IsGenericType && type.GetGenericTypeDefinition() == info.TargetType.GetGenericTypeDefinition())
                {
                    Type[] args = type.GetGenericArguments();

                    if (info.FormatterType.AreGenericConstraintsSatisfiedBy(args))
                    {
                        formatterType = info.FormatterType.GetGenericTypeDefinition().MakeGenericType(args);
                    }
                }

                if (formatterType != null)
                {
                    var instance = GetFormatterInstance(formatterType);

                    if (instance == null)
                    {
                        continue;
                    }

                    if (info.AskIfCanFormatTypes && !((IAskIfCanFormatTypes)instance).CanFormatType(type))
                    {
                        continue;
                    }

                    formatters.Add(instance);
                }
            }

            // Then call formatter locators after checking for registered formatters
            for (int i = 0; i < FormatterLocators.Count; i++)
            {
                try
                {
                    IFormatter result;
                    if (FormatterLocators[i].LocatorInstance.TryGetFormatter(type, FormatterLocationStep.AfterRegisteredFormatters, policy, out result))
                    {
                        formatters.Add(result);
                    }
                }
                catch (TargetInvocationException ex)
                {
                    throw ex;
                }
                catch (TypeInitializationException ex)
                {
                    throw ex;
                }
#pragma warning disable CS0618 // Type or member is obsolete
                catch (ExecutionEngineException ex)
#pragma warning restore CS0618 // Type or member is obsolete
                {
                    throw ex;
                }
                catch (Exception ex)
                {
                    Debug.LogException(new Exception("Exception was thrown while calling FormatterLocator " + FormatterLocators[i].GetType().FullName + ".", ex));
                }
            }

            formatters.Add((IFormatter)Activator.CreateInstance(typeof(ReflectionFormatter <>).MakeGenericType(type)));

            return(formatters);
        }
    public override Vector3 CalculateMove(FlockAgent agent, List<Transform> context, Flock flock, Transform[] waypoints)
    {
        //if no neighbors, maintain current alignment
        if (context.Count == 0)
            return agent.transform.forward;

        //Add all points together and average
        Vector3 alignmentMove = Vector3.zero;

        //Adding Filter List of agents
        List<Transform> filteredContext = (filter == null) ? context : filter.Filter(agent, context);

        for (int i = 0; i < filteredContext.Count; i++)
        {
            alignmentMove += filteredContext[i].forward;
        }

        alignmentMove /= context.Count;

        return alignmentMove;
    }
			public ConstructorDefinition(object[] argValues, ObjectActivator objectActivator)
			{
				this.objectActivator = objectActivator;
				this.contructorArgValues = argValues;
			}
Beispiel #58
0
 public static void Main(string[] args) => Run(args);
 /// <summary>
 ///
 /// </summary>
 /// <param name="cmd"></param>
 /// <param name="s1"></param>
 /// <param name="s2"></param>
 /// <returns></returns>
 public static CommunicateProtocol InitProtocolHeader(int cmd, byte[] s1, Stream s2)
 {
     return(InitProtocolHeader(new CommunicateProtocol {
         Command = cmd,
     }, s1, s2));
 }
Beispiel #60
0
        public Errno Mount(IMediaImage imagePlugin, Partition partition, Encoding encoding,
                           Dictionary<string, string> options, string @namespace)
        {
            Encoding      = Encoding.GetEncoding("iso-8859-15");
            _littleEndian = true;

            options ??= GetDefaultOptions();

            if(options.TryGetValue("debug", out string debugString))
                bool.TryParse(debugString, out _debug);

            if(imagePlugin.Info.SectorSize < 512)
                return Errno.InvalidArgument;

            AaruConsole.DebugWriteLine("Xbox FAT plugin", "Reading superblock");

            byte[] sector = imagePlugin.ReadSector(partition.Start);

            _superblock = Marshal.ByteArrayToStructureLittleEndian<Superblock>(sector);

            if(_superblock.magic == FATX_CIGAM)
            {
                _superblock   = Marshal.ByteArrayToStructureBigEndian<Superblock>(sector);
                _littleEndian = false;
            }

            if(_superblock.magic != FATX_MAGIC)
                return Errno.InvalidArgument;

            AaruConsole.DebugWriteLine("Xbox FAT plugin",
                                       _littleEndian ? "Filesystem is little endian" : "Filesystem is big endian");

            int logicalSectorsPerPhysicalSectors = partition.Offset == 0 && _littleEndian ? 8 : 1;

            AaruConsole.DebugWriteLine("Xbox FAT plugin", "logicalSectorsPerPhysicalSectors = {0}",
                                       logicalSectorsPerPhysicalSectors);

            string volumeLabel = StringHandlers.CToString(_superblock.volumeLabel,
                                                          !_littleEndian ? Encoding.BigEndianUnicode : Encoding.Unicode,
                                                          true);

            XmlFsType = new FileSystemType
            {
                Type = "FATX filesystem",
                ClusterSize = (uint)(_superblock.sectorsPerCluster * logicalSectorsPerPhysicalSectors *
                                     imagePlugin.Info.SectorSize),
                VolumeName   = volumeLabel,
                VolumeSerial = $"{_superblock.id:X8}"
            };

            XmlFsType.Clusters = (((partition.End - partition.Start) + 1) * imagePlugin.Info.SectorSize) /
                                 XmlFsType.ClusterSize;

            _statfs = new FileSystemInfo
            {
                Blocks         = XmlFsType.Clusters,
                FilenameLength = MAX_FILENAME,
                Files          = 0, // Requires traversing all directories
                FreeFiles      = 0,
                Id =
                {
                    IsInt    = true,
                    Serial32 = _superblock.magic
                },
                PluginId   = Id,
                Type       = _littleEndian ? "Xbox FAT" : "Xbox 360 FAT",
                FreeBlocks = 0 // Requires traversing the FAT
            };

            AaruConsole.DebugWriteLine("Xbox FAT plugin", "XmlFsType.ClusterSize: {0}", XmlFsType.ClusterSize);
            AaruConsole.DebugWriteLine("Xbox FAT plugin", "XmlFsType.VolumeName: {0}", XmlFsType.VolumeName);
            AaruConsole.DebugWriteLine("Xbox FAT plugin", "XmlFsType.VolumeSerial: {0}", XmlFsType.VolumeSerial);
            AaruConsole.DebugWriteLine("Xbox FAT plugin", "stat.Blocks: {0}", _statfs.Blocks);
            AaruConsole.DebugWriteLine("Xbox FAT plugin", "stat.FilenameLength: {0}", _statfs.FilenameLength);
            AaruConsole.DebugWriteLine("Xbox FAT plugin", "stat.Id: {0}", _statfs.Id.Serial32);
            AaruConsole.DebugWriteLine("Xbox FAT plugin", "stat.Type: {0}", _statfs.Type);

            byte[] buffer;
            _fatStartSector = (FAT_START / imagePlugin.Info.SectorSize) + partition.Start;
            uint fatSize;

            AaruConsole.DebugWriteLine("Xbox FAT plugin", "fatStartSector: {0}", _fatStartSector);

            if(_statfs.Blocks > MAX_XFAT16_CLUSTERS)
            {
                AaruConsole.DebugWriteLine("Xbox FAT plugin", "Reading FAT32");

                fatSize = (uint)(((_statfs.Blocks + 1) * sizeof(uint)) / imagePlugin.Info.SectorSize);

                if((uint)(((_statfs.Blocks + 1) * sizeof(uint)) % imagePlugin.Info.SectorSize) > 0)
                    fatSize++;

                long fatClusters = (fatSize * imagePlugin.Info.SectorSize) / 4096;

                if((fatSize * imagePlugin.Info.SectorSize) % 4096 > 0)
                    fatClusters++;

                fatSize = (uint)((fatClusters * 4096) / imagePlugin.Info.SectorSize);

                AaruConsole.DebugWriteLine("Xbox FAT plugin", "FAT is {0} sectors", fatSize);

                buffer = imagePlugin.ReadSectors(_fatStartSector, fatSize);

                AaruConsole.DebugWriteLine("Xbox FAT plugin", "Casting FAT");
                _fat32 = MemoryMarshal.Cast<byte, uint>(buffer).ToArray();

                if(!_littleEndian)
                    for(int i = 0; i < _fat32.Length; i++)
                        _fat32[i] = Swapping.Swap(_fat32[i]);

                AaruConsole.DebugWriteLine("Xbox FAT plugin", "fat32[0] == FATX32_ID = {0}", _fat32[0] == FATX32_ID);

                if(_fat32[0] != FATX32_ID)
                    return Errno.InvalidArgument;
            }
            else
            {
                AaruConsole.DebugWriteLine("Xbox FAT plugin", "Reading FAT16");

                fatSize = (uint)(((_statfs.Blocks + 1) * sizeof(ushort)) / imagePlugin.Info.SectorSize);

                if((uint)(((_statfs.Blocks + 1) * sizeof(ushort)) % imagePlugin.Info.SectorSize) > 0)
                    fatSize++;

                long fatClusters = (fatSize * imagePlugin.Info.SectorSize) / 4096;

                if((fatSize * imagePlugin.Info.SectorSize) % 4096 > 0)
                    fatClusters++;

                fatSize = (uint)((fatClusters * 4096) / imagePlugin.Info.SectorSize);

                AaruConsole.DebugWriteLine("Xbox FAT plugin", "FAT is {0} sectors", fatSize);

                buffer = imagePlugin.ReadSectors(_fatStartSector, fatSize);

                AaruConsole.DebugWriteLine("Xbox FAT plugin", "Casting FAT");
                _fat16 = MemoryMarshal.Cast<byte, ushort>(buffer).ToArray();

                if(!_littleEndian)
                    for(int i = 0; i < _fat16.Length; i++)
                        _fat16[i] = Swapping.Swap(_fat16[i]);

                AaruConsole.DebugWriteLine("Xbox FAT plugin", "fat16[0] == FATX16_ID = {0}", _fat16[0] == FATX16_ID);

                if(_fat16[0] != FATX16_ID)
                    return Errno.InvalidArgument;
            }

            _sectorsPerCluster  = (uint)(_superblock.sectorsPerCluster * logicalSectorsPerPhysicalSectors);
            _imagePlugin        = imagePlugin;
            _firstClusterSector = _fatStartSector + fatSize;
            _bytesPerCluster    = _sectorsPerCluster * imagePlugin.Info.SectorSize;

            AaruConsole.DebugWriteLine("Xbox FAT plugin", "sectorsPerCluster = {0}", _sectorsPerCluster);
            AaruConsole.DebugWriteLine("Xbox FAT plugin", "bytesPerCluster = {0}", _bytesPerCluster);
            AaruConsole.DebugWriteLine("Xbox FAT plugin", "firstClusterSector = {0}", _firstClusterSector);

            uint[] rootDirectoryClusters = GetClusters(_superblock.rootDirectoryCluster);

            if(rootDirectoryClusters is null)
                return Errno.InvalidArgument;

            byte[] rootDirectoryBuffer = new byte[_bytesPerCluster * rootDirectoryClusters.Length];

            AaruConsole.DebugWriteLine("Xbox FAT plugin", "Reading root directory");

            for(int i = 0; i < rootDirectoryClusters.Length; i++)
            {
                buffer =
                    imagePlugin.ReadSectors(_firstClusterSector + ((rootDirectoryClusters[i] - 1) * _sectorsPerCluster),
                                            _sectorsPerCluster);

                Array.Copy(buffer, 0, rootDirectoryBuffer, i * _bytesPerCluster, _bytesPerCluster);
            }

            _rootDirectory = new Dictionary<string, DirectoryEntry>();

            int pos = 0;

            while(pos < rootDirectoryBuffer.Length)
            {
                DirectoryEntry entry = _littleEndian
                                           ? Marshal.
                                               ByteArrayToStructureLittleEndian<DirectoryEntry
                                               >(rootDirectoryBuffer, pos, Marshal.SizeOf<DirectoryEntry>())
                                           : Marshal.ByteArrayToStructureBigEndian<DirectoryEntry>(rootDirectoryBuffer,
                                               pos, Marshal.SizeOf<DirectoryEntry>());

                pos += Marshal.SizeOf<DirectoryEntry>();

                if(entry.filenameSize == UNUSED_DIRENTRY ||
                   entry.filenameSize == FINISHED_DIRENTRY)
                    break;

                if(entry.filenameSize == DELETED_DIRENTRY ||
                   entry.filenameSize > MAX_FILENAME)
                    continue;

                string filename = Encoding.GetString(entry.filename, 0, entry.filenameSize);

                _rootDirectory.Add(filename, entry);
            }

            _cultureInfo    = new CultureInfo("en-US", false);
            _directoryCache = new Dictionary<string, Dictionary<string, DirectoryEntry>>();
            _mounted        = true;

            return Errno.NoError;
        }