public ArrayList GetFactionTopList( PlayerMobile from )
        {
            ArrayList members = new ArrayList();

            foreach ( PlayerState playerstate in CouncilOfMages.Instance.Members )
            {
                members.Add( playerstate );
            }

            foreach ( PlayerState playerstate in Shadowlords.Instance.Members )
            {
                members.Add( playerstate );
            }

            //Edit begin
            foreach ( PlayerState playerstate in Minax.Instance.Members )
            {
                members.Add( playerstate );
            }

            foreach ( PlayerState playerstate in TrueBritannians.Instance.Members )
            {
                members.Add( playerstate );
            }
            //Edit end

            WorstFactionScoreComparer comparer = new WorstFactionScoreComparer();
            members.Sort( comparer );

            return members;
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        SettingsPropertyCollection profileProperties = ProfileCommon.Properties;

        string[] settings;
        ArrayList keys = new ArrayList();
        ArrayList alias = new ArrayList();
        ArrayList name = new ArrayList();
        foreach (SettingsProperty prop in profileProperties)
        {
            if (prop.Attributes["CustomProviderData"].ToString() != "None")
            {
                settings = prop.Attributes["CustomProviderData"].ToString().Split(';');
                name.Add(settings[1] + prop.Name);
                alias.Add(settings[1] + settings[0]);
            }
        }
        name.Sort();
        alias.Sort();

        ArrayList name1 = ArrayList.Repeat("", name.Count);
        foreach (String item in name) name1[name.IndexOf(item)] = item.Substring(1);

        ArrayList alias1 = ArrayList.Repeat("", alias.Count);
        foreach (String item in alias) alias1[alias.IndexOf(item)] = item.Substring(1);

        int n = 0;
        StringDictionary properties = new StringDictionary();
        foreach (string item in name1) { properties[item] = alias1[n].ToString(); n++; }

        rptProfile.DataSource = properties;
        rptProfile.DataBind();
    }
    public static FishArbitratedBehaviour[][] GroupByPriorities(ArrayList behaviours)
    {
        // map priority -> behaviours
        Hashtable dict = new Hashtable();
        foreach(FishArbitratedBehaviour beh in behaviours){
            int priority = beh.priority;
            ArrayList list;
            if(!dict.ContainsKey(priority)){
                list = new ArrayList();
                dict[priority] = list;
            }else{
                list = (ArrayList)dict[priority];
            }
            list.Add(beh);
        }

        // arrange behaviour groups in execution order (highest priorities first)
        ArrayList priorities = new ArrayList(dict.Keys);
        FishArbitratedBehaviour[][] grouped = new FishArbitratedBehaviour[priorities.Count][];

        priorities.Sort();
        priorities.Reverse();
        for(int i = 0; i < priorities.Count; i++){
            int priority = (int)priorities[i];
            ArrayList group = (ArrayList)dict[priority];
            grouped[i] = (FishArbitratedBehaviour[])group.ToArray(typeof(FishArbitratedBehaviour));
        }

        return grouped;
    }
Example #4
0
File: ugly.cs Project: 0xb1dd1e/boo
	public static long ugly(int max)
	{		
		ArrayList uglies = new ArrayList();
		long counter = 1;
		Hashtable dict = new Hashtable();
		dict[counter] = new long[] { 0, 0, 0 };		
		
		while (uglies.Count < max)
		{	
			uglies.Add(counter);
			long[] array = (long[])dict[counter];
			long x = array[0];
			long y = array[1];
			long z = array[2];			
			
			dict[value(x+1, y, z)] = new long[] { x+1, y, z };
			dict[value(x, y+1, z)] = new long[] { x, y+1, z };
			dict[value(x, y, z+1)] = new long[] { x, y, z+1 };
			
			dict.Remove(counter);
			
			ArrayList keys = new ArrayList(dict.Keys);
			keys.Sort();
			
			counter = (long)keys[0];
		}
	
		return (long)uglies[uglies.Count-1];
	}
Example #5
0
    // Use this for initialization
    void Start()
    {
        ArrayList list = new ArrayList ();
        int score = PlayerPrefs.GetInt ("endScore");

        for (int i = 1; i<=10; i++) {
            key = "highScore" + i;
            keyscore = PlayerPrefs.GetInt(key);
            list.Add(keyscore);

            //PlayerPrefs.SetInt (key, 0);
        }

        lowestScore = PlayerPrefs.GetInt ("highScore10");
        Debug.Log ("lowest score" + lowestScore);

        if (score > lowestScore)
        {
            list.Add (score);
            list.Sort ();
            list.Reverse();
            list.RemoveAt(10);

            for (int i = 1; i<=10; i++) {
                key = "highScore" + i;
                PlayerPrefs.SetInt(key, (int)list[i-1]);
            }
        }
    }
 private void printLeaderboard()
 {
     Text text = GetComponentInChildren<Text>();
     text.text = "LEADERBOARD\n\n";
     ArrayList leaderBoard = new ArrayList();
     int k = 1;
     while (PlayerPrefs.HasKey(k.ToString())) {
         string player = PlayerPrefs.GetString(k.ToString());
         int score = PlayerPrefs.GetInt(player);
         leaderBoard.Add(new PlayerScore(player, score));
         k++;
     }
     leaderBoard.Sort ();
     for(int i = 0; i < 5; i++) {
         if(PlayerPrefs.HasKey((i+1).ToString())) {
             PlayerScore player = (PlayerScore)leaderBoard[i];
             int spaces = player.getPlayerName().Length;
             string playerName = player.getPlayerName();
             if(spaces < maxNameLength) {
                 for(int j = 0; j < maxNameLength - spaces; j++) {
                     playerName += " ";
                 }
             }
             string score;
             if(player.getScore() < 10) {
                 score = "0" + player.getScore().ToString();
             } else {
                 score = player.getScore().ToString();
             }
             text.text += (i+1).ToString() + ". " + playerName.Substring(0,10) + " " + score + "\n";
         }
     }
     text.text += "\nMake a circle with your finger to play again.";
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        Util util = new Util();
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        if (State == null || State.Count <= 2) { Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "timeOut('../Default.aspx');", true); return; }

        XmlDocument doc = util.GetStagingAppXml(State);
        XmlNode database_config = doc.SelectSingleNode("//application/data_sources/data_source"); //new config
        if (database_config == null)
        {
            database_config = doc.SelectSingleNode("//database_config"); //old config
            if (database_config == null)
            {
                return;
            }
        }

        XmlNodeList table_list = database_config.SelectNodes("//tables/table");
        table.Items.Clear();
        ArrayList tables = new ArrayList();
        foreach (XmlNode table_node in table_list)
        {
            XmlNode table_name = table_node.SelectSingleNode("table_name");
            tables.Add(table_name.InnerText);
        }
        tables.Sort();

        foreach(string name in tables)
        {
            table.Items.Add(new Telerik.Web.UI.RadComboBoxItem(name, name));
        }
    }
Example #8
0
        private static void LoadLists()
        {
            m_Monster = new ArrayList();
            m_Animal  = new ArrayList();
            m_Sea     = new ArrayList();
            m_Human   = new ArrayList();

            var entries = Docs.LoadBodies();

            for (var i = 0; i < entries.Count; ++i)
            {
                var oldEntry = entries[i];
                var bodyID   = oldEntry.Body.BodyID;

                if (((Body)bodyID).IsEmpty)
                {
                    continue;
                }

                ArrayList list = null;

                switch (oldEntry.BodyType)
                {
                case ModelBodyType.Monsters:
                    list = m_Monster;
                    break;

                case ModelBodyType.Animals:
                    list = m_Animal;
                    break;

                case ModelBodyType.Sea:
                    list = m_Sea;
                    break;

                case ModelBodyType.Human:
                    list = m_Human;
                    break;
                }

                if (list == null)
                {
                    continue;
                }

                var itemID = ShrinkTable.Lookup(bodyID, -1);

                if (itemID != -1)
                {
                    list.Add(new InternalEntry(bodyID, itemID, oldEntry.Name));
                }
            }

            m_Monster?.Sort();
            m_Animal?.Sort();
            m_Sea?.Sort();
            m_Human?.Sort();
        }
Example #9
0
        public void TestStandardArrayList()
        {
            //
            // Construct array list.
            //
            ArrayList list = new ArrayList();
            // Add items to the lists.
            for (int ii = 0; ii < strHeroes.Length; ++ii)
                list.Add(strHeroes[ii]);

            // Verify items added to list.
            Assert.Equal(strHeroes.Length, list.Count);

            //
            // []  Use BinarySearch to find selected items.
            //
            // Search and verify selected items.
            for (int ii = 0; ii < strFindHeroes.Length; ++ii)
            {
                // Locate item.
                int ndx = list.BinarySearch(strFindHeroes[ii]);
                Assert.True(ndx >= 0);

                // Verify item.
                Assert.Equal(0, strHeroes[ndx].CompareTo(strFindHeroes[ii]));
            }

            // Return Value;
            // The zero-based index of the value in the sorted ArrayList, if value is found; otherwise, a negative number,
            // which is the bitwise complement of the index of the next element.

            list = new ArrayList();
            for (int i = 0; i < 100; i++)
                list.Add(i);
            list.Sort();

            Assert.Equal(100, ~list.BinarySearch(150));

            //[]null - should return -1
            Assert.Equal(-1, list.BinarySearch(null));

            //[]we can add null as a value and then search it!!!
            list.Add(null);
            list.Sort();
            Assert.Equal(0, list.BinarySearch(null));

            //[]duplicate values, always return the first one
            list = new ArrayList();
            for (int i = 0; i < 100; i++)
                list.Add(5);

            list.Sort();
            //remember this is BinarySeearch
            Assert.Equal(49, list.BinarySearch(5));
        }
Example #10
0
 static void Main(string[] args)
 {
     ArrayList list = new ArrayList();
     list.Add(new ClassSample("two"));
     list.Add(new ClassSample("three"));
     list.Add(new ClassSample("one"));
     list.Sort();
     foreach (ClassSample cs in list) {
         Console.WriteLine(cs.number);
     }
 }
Example #11
0
    private ArrayList aStar(GameObject startTile, GameObject endTile)
    {
        if (!startTile || !endTile)
            return null;

        ArrayList openList;
        ArrayList closedList;
        GameObject currentTile = null;

        closedList = new ArrayList();
        openList = new ArrayList();
        openList.Add(startTile);

        Dictionary<GameObject, float> g = new Dictionary<GameObject, float>();
        g.Add(startTile, 0);
        Dictionary<GameObject, float> f = new Dictionary<GameObject, float>();
        f.Add(startTile, (startTile.transform.position - endTile.transform.position).magnitude);

        Dictionary<GameObject, GameObject> cameFrom = new Dictionary<GameObject, GameObject>();
        fScoreComparer fc = new fScoreComparer();
        fc.fList = f;

        do {
            openList.Sort(fc);
            currentTile = (GameObject)openList[0];
            if (currentTile == endTile)
                return reconstructPath(cameFrom, currentTile);

            openList.RemoveAt(0);
            closedList.Add(currentTile);

            foreach (GameObject item in currentTile.GetComponent<NeighboringTile>().getNeighbors()) {
                if (item == null || closedList.Contains(item))
                    continue;

                float currentScore = g[currentTile];
                float approx = currentScore + (currentTile.transform.position - endTile.transform.position).magnitude;

                if (!openList.Contains(item))
                    openList.Add(item);
                else if (approx >= g[item])
                    continue;

                cameFrom[item] = currentTile;
                g[item] = approx;
                f[item] = approx + 0; // 0 = heuristic cost. Not implemented yet.
            }

        } while (openList.Count > 0);

        return null;
    }
 public bool runTest()
   {
   int iCountErrors = 0;
   int iCountTestcases = 0;
   String strLoc="123_er";
   String strInfo = null;
   Console.Out.Write( s_strClassMethod );
   Console.Out.Write( ": " );
   Console.Out.Write( s_strTFPath + s_strTFName );
   Console.Out.Write( ": " );
   Console.Out.Write( s_strDtTmVer );
   Console.Out.WriteLine( " runTest started..." );
   Object o1;
   Char chValue;
   Int16 i16Value;
   int iReturnValue;
   Object[,] o2ArrValues;
   ArrayList lst1;
   try
     {
     LABEL_860_GENERAL:
     do
       {
       strLoc="536df";
       lst1 = new ArrayList( (cArr) );
       lst1.Sort();
       if ( cArr.Length != lst1.Count)
	 {
	 ++iCountErrors;
	 Console.WriteLine( s_strTFAbbrev + ", Err_623sd! cArr.Length==" + cArr.Length);
	 }
       ++iCountTestcases;
       for(int i=0; i<cArr.Length; i++)
	 {
	 chValue = cArr[i];
	 if ( lst1.BinarySearch(0, lst1.Count, chValue, null) < 0 )
	   {
	   ++iCountErrors;
	   Console.WriteLine( s_strTFAbbrev + "Err_320ye_" + i + " chValue==" + chValue);
	   }
	 }
       } while ( false );
     }
   catch (Exception exc_general)
     {
     ++iCountErrors;
     Console.WriteLine( s_strTFAbbrev + "Error Err_8888yyy!  strLoc=="+ strLoc +" ,exc_general=="+ exc_general );
     }
   if ( iCountErrors == 0 ) {   return true; }
   else {  return false;}
   }
Example #13
0
	void Update()
	{
		ArrayList ObjectList = new ArrayList();
		GameObject[] Objects = GameObject.FindObjectsOfType(typeof(GameObject)) as GameObject[];
		foreach (GameObject go in Objects)
		{
			ObjectList.Add(go);
		}
		DistanceComparer dComparer = new DistanceComparer();
		dComparer.Target = this.gameObject;
		ObjectList.Sort(dComparer);
		SortedByDistance = new GameObject[ObjectList.Count];
		ObjectList.CopyTo(SortedByDistance);
	}
Example #14
0
 static void Main(string[] args)
 {
     ArrayList list = new ArrayList();
     list.Add(2.2);
     list.Add(3.7);
     list.Add(1.5);
     list.Add(2.7);
     list.Add(3.2);
     list.Add(1.1);
     list.Sort(new ClassComparer());
     foreach (double d in list) {
         Console.WriteLine(d);
     }
 }
        public void testClassCostSortsByDescendingCost()
        {
            IList<ClassCost> classCosts = new ArrayList<ClassCost>();
            classCosts.Add(classCost1);
            classCosts.Add(classCost0);
            classCosts.Add(classCost2);

            //Collections.sort(classCosts, new ClassCost.CostComparator(new CostModel()));
            classCosts.Sort(new ClassCost.CostComparator(new CostModel()));

            Assert.AreEqual(classCost2, classCosts[0]);
            Assert.AreEqual(classCost1, classCosts[1]);
            Assert.AreEqual(classCost0, classCosts[2]);
        }
 public string GetSign(string key, string input_charset, params string[] requestarr)
 {
     ArrayList list = new ArrayList(requestarr);
     list.Sort();
     StringBuilder builder = new StringBuilder();
     for (int i = 0; i < list.Count; i++)
     {
         if ((!string.IsNullOrEmpty(list[i].ToString()) && (base.Request.Form[list[i].ToString()] != "")) && !list[i].ToString().Equals("sign"))
         {
             builder.Append(list[i].ToString() + "=" + base.Request.Form[list[i].ToString()].ToString().Trim() + "&");
         }
     }
     builder.Append("key=" + key);
     return this.GetMD5(builder.ToString().Trim(), input_charset).ToLower();
 }
Example #17
0
    private ArrayList GetAllCameraAngles()
    {
        ArrayList angles = new ArrayList();
        for( int i = 1; i < Config.ClientData.Count; i++ )
        {
            float angle = ( Config.ClientData[i] as ClientCameraInfo ).AngleOffset;
            if( !angles.Contains( angle ) )
            {
                angles.Add( angle );
            }
        }

        angles.Sort();
        return angles;
    }
 public string GetSign(string key, string input_charset, Dictionary<string, string> dict)
 {
     StringBuilder builder = new StringBuilder();
     ArrayList list = new ArrayList(dict.Keys);
     list.Sort();
     foreach (string str in list)
     {
         string strB = dict[str];
         if (((strB != null) && ("".CompareTo(strB) != 0)) && (("sign".CompareTo(str) != 0) && ("key".CompareTo(str) != 0)))
         {
             builder.Append(str + "=" + strB + "&");
         }
     }
     builder.Append("key=" + key);
     return this.GetMD5(builder.ToString(), input_charset).ToLower();
 }
Example #19
0
 static void GroundTaxonomy(ArrayList<Pair<string, string>> tax, string corpusFileOut, string cacheFileOut, string timeStart, string timeEnd)
 {
     ArrayList<KeyDat<int, Pair<string, string>>> tmp = new ArrayList<KeyDat<int, Pair<string, string>>>();
     foreach (Pair<string, string> item in tax)
     {
         int lvl = 1;
         foreach (char ch in item.First) { if (ch == '/') { lvl++; } }
         tmp.Add(new KeyDat<int, Pair<string, string>>(lvl, item));
     }
     tmp.Sort(DescSort<KeyDat<int, Pair<string, string>>>.Instance);
     foreach (KeyDat<int, Pair<string, string>> item in tmp)
     {
         Console.WriteLine("Grounding \"{0}\" with {1} ...", item.Dat.First, item.Dat.Second);
         RetrieveDocuments(item.Dat.Second, item.Dat.First, corpusFileOut, cacheFileOut, timeStart, timeEnd);
     }
     Console.WriteLine("Grounding done.");
 }
    public void SendTeamRecord(ArrayList names, int score)
    {
        string domain = ServerUtils.domainName + ":80";
        string storedDomain = PlayerPrefs.GetString("DataIp");
        if (ServerUtils.CheckIpAddress(storedDomain))
        {
            domain = storedDomain + ":80";
        }
        string serverUrl = ServerUtils.urlHeader + domain + "/sendTeamScore.php";

        names.Sort();
        for (int i = names.Count; i < 4; i++)
        {
            names.Add("");
        }
        StartCoroutine(SendTeamRecordData((string)names[0], (string)names[1], (string)names[2], (string)names[3], score, serverUrl));
    }
Example #21
0
    public void calcFrequencies()
    {
        ArrayList v = new ArrayList(m_histogramDictionary.Keys);
        v.Sort();

        double [] values = new double[m_histogramDictionary.Count];
        int[] counts = new int[m_histogramDictionary.Count];
        int i = 0;
        foreach (double d in v){
            values[i] = d;
            counts[i] = m_histogramDictionary[values[i]];
            i++;
        }

        m_histogramValues = values;
        m_histogramCounts = counts;
    }
Example #22
0
    public static void Main()
    {
        ArrayList arr = new ArrayList();

        arr.Add(new MyClass( 5 ));
        arr.Add(new MyClass( 3 ));
        arr.Add(new MyClass( 9 ));
        arr.Add(new MyClass(1 ));
        arr.Add(new MyClass( 6 ));

        arr.Sort();

        for (int i = 0; i < arr.Count; i++)
        {
            MyClass t = (MyClass) arr[i];
            Console.WriteLine( t.Num);
        }
    }
 static void Main()
 {
     ArrayList ar = new ArrayList(10);
     ar.Add("이승만");
     ar.Add("박정희");
     ar.Add("최규하");
     ar.Add("전두환");
     ar.Add("노태우");
     ar.Add("김영삼");
     ar.Add("김대중");
     ar.Add("노무현");
     ar.Add("이명박");
     foreach (object o in ar) Console.Write(o + ",");
     ar.Sort();
     ar.Reverse();
     Console.WriteLine();
     foreach (object o in ar) Console.Write(o + ",");
 }
Example #24
0
    // Use this for initialization
    void Start()
    {
        //creates an array of an undetermined size and type
        ArrayList aList = new ArrayList();

        //create an array of all objects in the scene
        Object[] AllObjects = GameObject.FindObjectsOfType(typeof(Object)) as Object[];

        //iterate through all objects
        foreach (Object o in AllObjects)
        {
            if (o.GetType() == typeof(GameObject))
            {
                aList.Add(o);
            }
        }

        if (aList.Contains(SpecificObject))
        {
            Debug.Log(aList.IndexOf(SpecificObject));
        }

        if (aList.Contains(gameObject))
        {
            aList.Remove(gameObject);
        }

        //initialize the AllGameObjects array
        AllGameObjects = new GameObject[aList.Count];

        //copy the list to the array
        DistanceComparer dc = new DistanceComparer();
        dc.Target = gameObject;
        aList.Sort(dc);

        aList.CopyTo(AllGameObjects);
        ArrayList sorted = new ArrayList();
        sorted.AddRange(messyInts);
        sorted.Sort();
        sorted.Reverse();
        sorted.CopyTo(messyInts);
    }
Example #25
0
    public ArrayList getRouteBFS()
    {
        ArrayList path = new ArrayList();

        Boolean[] visited = new Boolean[NUM_NODES];
        for (int i = 0; i < NUM_NODES; i++) { visited[i] = false; }

        Queue queue = new Queue();
        queue.Enqueue(0);         //Add origin

        int it = 0;
        while (queue.Count != 0 && it <= LEVELS)
        {
            int parent = (int)queue.Dequeue();
            path.Add(parent);
            visited[parent] = true;

            ArrayList childs = new ArrayList();
            for (int i = 0; i < NUM_NODES; i++) {
                int   childPos   = i;
                float childValue = nodeValues[childPos];
                if (((nodeEdges[parent, childPos] == INF) && (nodeEdges[childPos, parent] == INF)) || //No edges
                    visited[childPos]) {                                                              //If the node isn't visited
                    childValue = INF;
                }
                childs.Add(childValue);
            }
            ArrayList values = new ArrayList(childs);
            values.Sort();
            float minValue = (float)values[0];
            int   indexMax = childs.IndexOf(minValue);

            if ((indexMax != -1) && (minValue < INF)) {
                queue.Enqueue(indexMax);
            }

            it++;
        }

        return path;
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        Util util = new Util();
        Hashtable State = (Hashtable)HttpRuntime.Cache[Session.SessionID];
        if (State == null || State.Count <= 2) { Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), "timeOut('../Default.aspx');", true); return; }

        XmlDocument doc = util.GetStagingAppXml(State);
        XmlNode database_config = doc.SelectSingleNode("//application/data_sources/data_source"); //new config
        if (database_config == null)
        {
            database_config = doc.SelectSingleNode("//database_config"); //old config
            if (database_config == null)
            {
                return;
            }
        }

        string table =  State["SelectedDatabaseTable"].ToString();
        XmlNode table_name_node = database_config.SelectSingleNode("//tables/table/table_name[.='" + table + "'] | //tables/table/table_name[.='" + table.ToLower() + "']");
        if (table_name_node == null)
        {
            State["SpreadsheetError"] = "Query Error: A saved worksheet or table: " + table + " does not exist. All queries for this event have been deleted to avoid runtime errors.";
            State["SelectedDatabaseTable"] = null;
            return;
        }
        XmlNodeList field_list = table_name_node.ParentNode.SelectNodes("fields/field/name");

        // init database fields
        sort_field.Items.Clear();
        ArrayList fields = new ArrayList();
        foreach (XmlNode field_node in field_list)
        {
            fields.Add(field_node.InnerText);
        }
        fields.Sort();

        foreach (string name in fields)
        {
            sort_field.Items.Add(new Telerik.Web.UI.RadComboBoxItem(name, name));
        }
    }
Example #27
0
	/// <summary>
	/// Gets the properties.
	/// </summary>
	/// <param name="context">Context.</param>
	/// <param name="value">Value.</param>
	/// <param name="attributes">Attributes.</param>
	/// <returns></returns>
	public override PropertyDescriptorCollection GetProperties (ITypeDescriptorContext context, object value, Attribute [] attributes)
	{
		//
		// This override returns a list of properties in order
		//
		PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties (value, attributes);
		ArrayList orderedProperties = new ArrayList ();
		foreach (PropertyDescriptor pd in pdc) {
			Attribute attribute = pd.Attributes [typeof (PropertyOrderAttribute)];
			if (attribute != null) {
				//
				// If the attribute is found, then create an pair object to hold it
				//
				PropertyOrderAttribute poa = (PropertyOrderAttribute) attribute;
				orderedProperties.Add (new PropertyOrderPair (pd.Name, poa.Order));
			} else {
				//
				// If no order attribute is specifed then given it an order of 0
				//
				orderedProperties.Add (new PropertyOrderPair (pd.Name, 0));
			}
		}
		//
		// Perform the actual order using the value PropertyOrderPair classes
		// implementation of IComparable to sort
		//
		orderedProperties.Sort ();
		//
		// Build a string list of the ordered names
		//
		ArrayList propertyNames = new ArrayList ();
		foreach (PropertyOrderPair pop in orderedProperties) {
			propertyNames.Add (pop.Name);
		}
		//
		// Pass in the ordered list for the PropertyDescriptorCollection to sort by
		//
		return pdc.Sort ((string []) propertyNames.ToArray (typeof (string)));
	}
 static void ExplainToString(ArrayList<KeyDat<double, int>> expl, out string wPos, out string wNeg)
 {
     wPos = "";
     wNeg = "";
     expl.Sort(DescSort<KeyDat<double, int>>.Instance);
     foreach (KeyDat<double, int> word in expl)
     {
         if (word.First > 0 && word.Second != -1)
         {
             wPos += string.Format("{0} ({1:0.00}), ", (word.Second == -1 ? "(bias)" : mBowSpace.Words[word.Second].MostFrequentForm), word.First);
         }
     }
     expl.Sort();
     foreach (KeyDat<double, int> word in expl)
     {
         if (word.First < 0 && word.Second != -1)
         {
             wNeg += string.Format("{0} ({1:0.00}), ", (word.Second == -1 ? "(bias)" : mBowSpace.Words[word.Second].MostFrequentForm), word.First);
         }
     }
     wPos = wPos.TrimEnd(',', ' ');
     wNeg = wNeg.TrimEnd(',', ' ');
 }
    /*
     * Julia's comment:
     */
    public static string LargestNumber(int[] num)
    {
        ArrayList l = new ArrayList();

        int len = num.Length;

        for (int i = 0; i < len; ++i)
        {
            l.Add(num[i].ToString());
        }

        IComparer myComparer = new largestNumberclass();
        l.Sort(myComparer);

        string output = "";
        foreach (string sin in l)
            output = output + sin;

        if (output.Length > 1 && output[0] == '0')
            return "0";

        return output;
    }
Example #30
0
    void Update()
    {
        if (!active) return;

        float[] data = new float[735];

        audio.GetOutputData(data, 0);

        //take the median of the recorded samples

        ArrayList s = new ArrayList();

        foreach (float f in data)
        {

            s.Add(Mathf.Abs(f));

        }

        s.Sort();

        FUI.Volume = (float)s[735 / 2];
    }
Example #31
0
    public void DoCount(TimeSpan overhead)
    {
        string line = null;
        Hashtable wordTable = new Hashtable();
        DateTime startTime = DateTime.Now;
        int wordCount = 0;
        while ((line = stream.ReadLine()) != null)
        {
            foreach (string word in regexSplit.Split(line.ToLower()))
            {
                wordCount++;
                //Console.WriteLine("Word: {0}", word);
                object value = wordTable[word];
                int count = 0;
                if (value != null)
                    count = (int) value;
                wordTable[word] = count + 1;
            }
        }
        stream.Close();
        f.Close();
        DateTime endTime = DateTime.Now;

        ArrayList words = new ArrayList();
        foreach (string word in wordTable.Keys)
        {
            words.Add(word);
        }
        words.Sort();

        //foreach (string word in words)
        {
            //Console.WriteLine("{0} = {1}", word, wordTable[word]);
        }

        Console.WriteLine("BoxedInt: Counted {0} words ({1} unique) in {2}, delta = {3}", wordCount, words.Count, endTime - startTime, (endTime - startTime) - overhead);
    }
Example #32
0
    // Update is called once per frame
    public void UpdateKnowledgeBase()
    {
        bool newAgentUpdate = false;

        /* Process every incoming message */
        while (incoming.Count != 0)
        {
            Packet p = (Packet)incoming.Dequeue();
            if (p.src.ID == this.agent.ID)
            {
                // Debug.Log("ERROR: Received our own message");
                continue;
            }
            //Filter the packet out
            if (FILTER_RANGE_PACKETS && Vector3.Distance(p.src.sensorModule.gps.position, this.agent.sensorModule.gps.position) > MESH_NETWORK_RANGE)
            {
                continue;
            }

            if (RANDOM_DROPS && random.NextDouble() > 0.9)
            {
                continue;                 // 10% chance of dropping packets randomly.
            }

            if (p.message.type == Message.MessageType.UPDATE)
            {
                this.ProcessAgentUpdate(p);
                newAgentUpdate = true;
            }
            else if (p.message.type == Message.MessageType.BID)
            {
                this.ProcessBid(p);                  // Debug.Log("PROCESSING BID");
            }
            else if (p.message.type == Message.MessageType.CLAIM)
            {
                this.ProcessClaim(p);
            }
            else if (p.message.type == Message.MessageType.SEARCHED)
            {
                this.ProcessSearched(p);
            }
            p.CleanUp();
        }

        /* If a new agent update has been recieved, the list should be resorted */
        if (newAgentUpdate)
        {
            updates = new ArrayList(agentStates.Values);
            // Get the list of updates and calculate each agents distance to the desired pos
            foreach (AgentUpdate update in updates)
            {
                update.distance = Vector3.Distance(this.agent.sensorModule.gps.position, update.lastUpdate.position);
            }

            // Sort the list
            updates.Sort(new AgentUpdateComparer());
        }

        /* Update bidding knowledge */
        this.bidKnowledge.Update();
    }
Example #33
0
        static void Main(string[] args)
        {
            if (args == null || args.Length == 0)
            {
                throw new ApplicationException("Specify the URI of the resource to retrieve.");
            }

            var results = new Hashtable();
            var uri     = ConfigurationManager.AppSettings["api_url"];

            foreach (var word in args)
            {
                var endpoint = string.Format(uri, word);
                var client   = new WebClient();
                client.Headers.Add("app_id", ConfigurationManager.AppSettings["app_id"]);
                client.Headers.Add("app_key", ConfigurationManager.AppSettings["app_key"]);
                client.Headers.Add("Content-Type", "application/json");
                try
                {
                    using (Stream data = client.OpenRead(endpoint))
                    {
                        using (StreamReader reader = new StreamReader(data))
                        {
                            string s = reader.ReadToEnd();
                            using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(s)))
                            {
                                DataContractJsonSerializer des =
                                    new DataContractJsonSerializer(typeof(DictionaryApiResult));
                                DictionaryApiResult apiResult = (DictionaryApiResult)des.ReadObject(ms);

                                results[word] = new ArrayList(apiResult.results
                                                              .SelectMany(result => result.lexicalEntries
                                                                          .SelectMany(lexicalEntry => lexicalEntry.entries
                                                                                      .SelectMany(entry => entry.senses
                                                                                                  .SelectMany(sense => sense?.definitions ?? new List <string>())
                                                                                                  )
                                                                                      )
                                                                          ).ToList());
                            }
                        }
                    }
                }
                catch (WebException webException)
                {
                    var response = (HttpWebResponse)webException.Response;
                    switch (response.StatusCode)
                    {
                    case HttpStatusCode.NotFound:
                        results[word] = new ArrayList {
                            "No entry found"
                        };
                        break;

                    case HttpStatusCode.InternalServerError:
                        results[word] = "Unable to contact server";
                        break;
                    }
                }

                catch (Exception generalException)
                {
                    Console.WriteLine("Api call error");
                    Console.WriteLine(generalException.GetBaseException().ToString());
                }
            }

            var i          = 1;
            var sortedKeys = new ArrayList(results.Keys);

            sortedKeys.Sort();
            foreach (var key in sortedKeys)
            {
                Console.WriteLine(key);

                foreach (var definition in (ArrayList)results[key])
                {
                    Console.WriteLine($"\t{i}.\t{definition}");
                    i++;
                }
            }
        }
Example #34
0
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        PageErrors errors = PageErrors.getErrors(db, Page.Master);

        errors.clear();

        if (BatchFile.HasFile)
        {
            string strTmpFolder = HROne.Common.Folder.GetOrCreateSessionTempFolder(Session.SessionID).FullName;;  //Environment.GetFolderPath(Environment.SpecialFolder.InternetCache);
            string strTmpFile   = System.IO.Path.Combine(strTmpFolder, AppUtils.ServerDateTime().ToString("~yyyyMMddHHmmss_") + BatchFile.FileName);
            BatchFile.SaveAs(strTmpFile);

            ArrayList pendingList = new ArrayList();

            try
            {
                DataTable rawDataTable = HROne.Import.ExcelImport.parse(strTmpFile, string.Empty).Tables[TABLE_NAME];

                if (rawDataTable.Columns.Contains("Scheme Code") &&
                    rawDataTable.Columns.Contains("Capacity") &&
                    rawDataTable.Columns.Contains("First Point") &&
                    rawDataTable.Columns.Contains("Mid Point") &&
                    rawDataTable.Columns.Contains("Last Point"))
                {
                    int     row_count = 0;
                    Decimal point;
                    //int id;
                    foreach (DataRow row in rawDataTable.Rows)
                    {
                        row_count++;

                        EPayScale c = new EPayScale();

                        if (!row.IsNull("Scheme Code"))
                        {
                            c.SchemeCode = ((String)row["Scheme Code"]).Trim();
                        }
                        else
                        {
                            errors.addError("Missing Scheme Code in row " + row_count.ToString());
                            if (errors.errors.Count > 10)
                            {
                                return;
                            }
                        }

                        if (!row.IsNull("Capacity"))
                        {
                            c.Capacity = ((String)row["Capacity"]).Trim();
                        }
                        else
                        {
                            errors.addError("Missing Capacity in row " + row_count.ToString());
                            if (errors.errors.Count > 10)
                            {
                                return;
                            }
                        }

                        if (!row.IsNull("First Point") && Decimal.TryParse(((String)row["First Point"]), out point))
                        {
                            c.FirstPoint = point;
                        }
                        else
                        {
                            errors.addError("Missing First Point in row " + row_count.ToString());
                            if (errors.errors.Count > 10)
                            {
                                return;
                            }
                        }

                        if (!row.IsNull("Mid Point") && Decimal.TryParse(((String)row["Mid Point"]), out point))
                        {
                            c.MidPoint = point;
                        }
                        else
                        {
                            errors.addError("Missing Mid Point in row " + row_count.ToString());
                            if (errors.errors.Count > 10)
                            {
                                return;
                            }
                        }

                        if (!row.IsNull("Last Point") && Decimal.TryParse(((String)row["Last Point"]), out point))
                        {
                            c.LastPoint = point;
                        }
                        else
                        {
                            errors.addError("Missing Mid Point in row " + row_count.ToString());
                            if (errors.errors.Count > 10)
                            {
                                return;
                            }
                        }
                        pendingList.Add(c);
                    }
                }
                else
                {
                    errors.addError(HROne.Translation.PageErrorMessage.ERROR_INVALID_FILE);
                }
            }
            catch (Exception)
            {
                errors.addError(HROne.Translation.PageErrorMessage.ERROR_INVALID_FILE);
            }

            pendingList.Sort(new PayScaleComparer());

            if (pendingList.Count > 0)
            {
                try
                {
                    dbConn.BeginTransaction();
                    WebUtils.StartFunction(Session, FUNCTION_CODE);

                    DBFilter filter = sbinding.createFilter();
                    filter.add("SchemeCode", true);
                    filter.add("Capacity", true);
                    ArrayList currentList = EPayScale.db.select(dbConn, filter);
                    foreach (EPayScale currentItem in currentList)
                    {
                        EPayScale updateItem = null;
                        foreach (EPayScale pendingItem in pendingList)
                        {
                            if (pendingItem.SchemeCode.Equals(currentItem.SchemeCode) && pendingItem.Capacity.Equals(currentItem.Capacity))
                            {
                                updateItem = pendingItem;

                                if (//!currentItem.PayScaleCDesc.Equals(pendingItem.PayScaleCDesc) ||
                                    !currentItem.FirstPoint.Equals(pendingItem.FirstPoint) ||
                                    !currentItem.MidPoint.Equals(pendingItem.MidPoint) ||
                                    !currentItem.LastPoint.Equals(pendingItem.LastPoint))
                                {
                                    //currentItem.FirstPoint = pendingItem.FirstPoint;
                                    //currentItem.MidPoint = pendingItem.MidPoint;
                                    //currentItem.LastPoint = pendingItem.LastPoint;
                                    EPayScale.db.update(dbConn, currentItem);
                                }
                                break;
                            }
                        }
                        if (updateItem != null)
                        {
                            pendingList.Remove(updateItem);
                        }
                        else
                        {
                            if (!EPayScale.db.delete(dbConn, currentItem))
                            {
                                // failed to delete
                            }
                        }
                    }
                    foreach (EPayScale insertItem in pendingList)
                    {
                        AND andFilterTerm = new AND();
                        andFilterTerm.add(new Match("SchemeCode", insertItem.SchemeCode));
                        andFilterTerm.add(new Match("Capacity", insertItem.Capacity));
                        //if (!AppUtils.checkDuplicate(dbConn, db, insertItem, errors, "Capacity", andFilterTerm))
                        //{
                        //    //errors.addError("Duplicated Rank Description : " + insertItem.PayScaleDesc);
                        //    break;
                        //}
                        try
                        {
                            //                            throw new SqlException();

                            EPayScale.db.insert(dbConn, insertItem);
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine("Fail to clear temp table: " + ex.Message);
                        }
                    }

                    if (errors.errors.Count > 0)
                    {
                        dbConn.RollbackTransaction();
                    }
                    else
                    {
                        dbConn.CommitTransaction();
                    }

                    WebUtils.EndFunction(dbConn);
                }

                catch (Exception ex)
                {
                    errors.addError(HROne.Translation.PageErrorMessage.ERROR_INVALID_FILE);
                    dbConn.RollbackTransaction();
                    WebUtils.EndFunction(dbConn);
                }
            }
            else
            {
                errors.addError(HROne.Translation.PageErrorMessage.ERROR_NO_RECORD_IMPORT);
            }
            System.IO.File.Delete(strTmpFile);
        }
        else
        {
            errors.addError(HROne.Translation.PageErrorMessage.ERROR_INVALID_FILE);
        }

        Repeater.EditItemIndex = -1;
        view = loadData(info, db, Repeater);
        if (errors.isEmpty())
        {
            errors.addError(HROne.Translation.PageMessage.IMPORT_SUCCESSFUL);
        }
    }
Example #35
0
        /// <summary>
        /// 将数据转换为相对应X轴、Y轴的DataTable
        /// </summary>
        //public DataTable ConvertDataTable()
        //{
        //    DataTable dt = new DataTable();

        //    //此列用来显示有变描述
        //    dt.Columns.Add(new DataColumn("Name", typeof(string)));
        //    ArrayList columnName = new ArrayList();

        //    foreach (NewReportDomainObject domainObject in DataSource) //X轴
        //    {
        //        if (!columnName.Contains(domainObject.PeriodCode))
        //        {
        //            columnName.Add(domainObject.PeriodCode);
        //        }
        //    }

        //    //排序名称
        //    columnName.Sort();

        //    for (int i = 0; i < columnName.Count; i++)
        //    {
        //        dt.Columns.Add(new DataColumn(columnName[i].ToString(), typeof(double)));
        //    }

        //    Hashtable nameColumn = new Hashtable();
        //    string name = string.Empty;

        //    #region //Y轴
        //    string[] groupColumns = m_ChartGroupByString.Split(',');
        //    ArrayList nameList = new ArrayList();
        //    foreach (NewReportDomainObject domainObject in DataSource)
        //    {
        //        name = string.Empty;
        //        if (groupColumns.Length > 0)
        //        {
        //            for (int i = 0; i < groupColumns.Length; i++)
        //            {
        //                if (groupColumns[i].Trim().ToLower() == "sscode")
        //                {
        //                    name += domainObject.SSCode + "-";
        //                }

        //                else if (groupColumns[i].Trim().ToLower() == "opcode")
        //                {
        //                    name += domainObject.OPCode + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "rescode")
        //                {
        //                    name += domainObject.ResCode + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "bigsscode")
        //                {
        //                    name += domainObject.BigSSCode + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "segcode")
        //                {
        //                    name += domainObject.SegCode + "-";
        //                }

        //                else if (groupColumns[i].Trim().ToLower() == "faccode")
        //                {
        //                    name += domainObject.FacCode + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "momemo")
        //                {
        //                    name += domainObject.MOMemo + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "newmass")
        //                {
        //                    name += domainObject.NewMass + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "itemcode")
        //                {
        //                    name += domainObject.ItemCode + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "mmodelcode" || groupColumns[i].Trim().ToLower() == "materialmodelcode")
        //                {
        //                    name += domainObject.MaterialModelCode + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "mmachinetype" || groupColumns[i].Trim().ToLower() == "materialmachinetype")
        //                {
        //                    name += domainObject.MaterialMachineType + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "mexportimport" || groupColumns[i].Trim().ToLower() == "materialexportimport")
        //                {
        //                    name += domainObject.MaterialExportImport + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "mocode")
        //                {
        //                    name += domainObject.MOCode + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "firstclass")
        //                {
        //                    name += domainObject.FirstClass + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "secondclass")
        //                {
        //                    name += domainObject.SecondClass + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "thirdclass")
        //                {
        //                    name += domainObject.SSCode + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "lotno")
        //                {
        //                    name += domainObject.LotNo + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "productiontype")
        //                {
        //                    name += domainObject.ProductionType + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "oqclottype")
        //                {
        //                    name += domainObject.OQCLotType + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "inspectorandname")
        //                {
        //                    name += domainObject.InspectorAndName + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "iqclineitemtype")
        //                {
        //                    name += domainObject.IQCLineItemType + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "iqcitemtype")
        //                {
        //                    name += domainObject.IQCItemType + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "rohs")
        //                {
        //                    name += domainObject.Rohs + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "concessionstatus")
        //                {
        //                    name += domainObject.ConcessionStatus + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "vendorcode")
        //                {
        //                    name += domainObject.VendorCode + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "materialcode")
        //                {
        //                    name += domainObject.MaterialCode + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "tpcode")
        //                {
        //                    name += domainObject.PeriodCode + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToUpper() == "shiftcode")
        //                {
        //                    name += domainObject.ShiftCode + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "shiftday")
        //                {
        //                    name += domainObject.ShiftDay + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "dweek")
        //                {
        //                    name += domainObject.Week + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "dmonth")
        //                {
        //                    name += domainObject.Month + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "year")
        //                {
        //                    name += domainObject.Year + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "goodsemigood")
        //                {
        //                    name += domainObject.GoodSemiGood + "-";
        //                }
        //                else if (groupColumns[i].Trim().ToLower() == "crewcode")
        //                {
        //                    name += domainObject.CrewCode + "-";
        //                }
        //            }
        //            name += domainObject.EAttribute1;
        //        }

        //        if (!nameColumn.Contains(name))
        //        {
        //            nameColumn.Add(name, name);
        //        }

        //        nameList.Add(name);
        //    }

        //    #endregion

        //    foreach (System.Collections.DictionaryEntry objDE in nameColumn)
        //    {
        //        DataRow dr = dt.NewRow();
        //        dr[0] = objDE.Value.ToString();
        //        for (int i = 1; i < columnName.Count + 1; i++)
        //        {
        //            dr[i] = 0;
        //        }
        //        for (int m = 0; m < DataSource.Length; m++)
        //        {
        //            NewReportDomainObject domainObject = DataSource[m] as NewReportDomainObject;

        //            if (objDE.Value.ToString() == nameList[m].ToString())
        //            {
        //                dr[domainObject.PeriodCode] = domainObject.TempValue;
        //            }
        //        }

        //        dt.Rows.Add(dr);
        //    }

        //    return dt;
        //}

        /// <summary>
        ///当X轴的值等于EAttribute1的值时,将数据转换为相对应X轴、Y轴的DataTable
        /// </summary>
        public DataTable ConvertDataTableOQC()
        {
            DataTable dt = new DataTable();

            //此列用来显示有变描述
            dt.Columns.Add(new DataColumn("Name", typeof(string)));
            ArrayList columnName = new ArrayList();

            foreach (NewReportDomainObject domainObject in DataSource) //X轴
            {
                if (!columnName.Contains(domainObject.PeriodCode))
                {
                    columnName.Add(domainObject.PeriodCode);
                }
            }

            //排序名称
            columnName.Sort();

            for (int i = 0; i < columnName.Count; i++)
            {
                dt.Columns.Add(new DataColumn(columnName[i].ToString(), typeof(double)));
            }

            Hashtable nameColumn = new Hashtable();
            string    name       = string.Empty;

            #region //Y轴
            string[]  groupColumns = m_ChartGroupByString.Split(',');
            ArrayList nameList     = new ArrayList();
            foreach (NewReportDomainObject domainObject in DataSource)
            {
                name = string.Empty;
                if (groupColumns.Length > 0)
                {
                    for (int i = 0; i < groupColumns.Length; i++)
                    {
                        if (groupColumns[i].Trim().ToLower() == "sscode")
                        {
                            name += domainObject.SSCode + "-";
                        }

                        else if (groupColumns[i].Trim().ToLower() == "opcode")
                        {
                            name += domainObject.OPCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "rescode")
                        {
                            name += domainObject.ResCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "bigsscode")
                        {
                            name += domainObject.BigSSCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "segcode")
                        {
                            name += domainObject.SegCode + "-";
                        }

                        else if (groupColumns[i].Trim().ToLower() == "faccode")
                        {
                            name += domainObject.FacCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "momemo")
                        {
                            name += domainObject.MOMemo + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "newmass")
                        {
                            name += domainObject.NewMass + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "itemcode")
                        {
                            name += domainObject.ItemCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "mmodelcode")
                        {
                            name += domainObject.MaterialModelCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "mmachinetype")
                        {
                            name += domainObject.MaterialMachineType + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "mexportimport")
                        {
                            name += domainObject.MaterialExportImport + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "mocode")
                        {
                            name += domainObject.MOCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "firstclass")
                        {
                            name += domainObject.FirstClass + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "secondclass")
                        {
                            name += domainObject.SecondClass + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "thirdclass")
                        {
                            name += domainObject.SSCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "lotno")
                        {
                            name += domainObject.LotNo + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "productiontype")
                        {
                            name += domainObject.ProductionType + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "oqclottype")
                        {
                            name += domainObject.OQCLotType + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "inspectorandname")
                        {
                            name += domainObject.InspectorAndName + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "iqclineitemtype")
                        {
                            name += domainObject.IQCLineItemType + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "iqcitemtype")
                        {
                            name += domainObject.IQCItemType + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "rohs")
                        {
                            name += domainObject.Rohs + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "concessionstatus")
                        {
                            name += domainObject.ConcessionStatus + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "vendorcode")
                        {
                            name += domainObject.VendorCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "materialcode")
                        {
                            name += domainObject.MaterialCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "tpcode")
                        {
                            name += domainObject.PeriodCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToUpper() == "shiftcode")
                        {
                            name += domainObject.ShiftCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "shiftday")
                        {
                            name += domainObject.ShiftDay + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "dweek")
                        {
                            name += domainObject.Week + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "dmonth")
                        {
                            name += domainObject.Month + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "year")
                        {
                            name += domainObject.Year + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "goodsemigood")
                        {
                            name += domainObject.GoodSemiGood + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "dutydesc")
                        {
                            name += domainObject.DutyDesc + "-";
                        }
                    }
                    if (name == string.Empty)
                    {
                        name += "系列";
                    }
                    else
                    {
                        name = name.Substring(0, name.Length - 1);
                    }
                }

                if (!nameColumn.Contains(name))
                {
                    nameColumn.Add(name, name);
                }

                nameList.Add(name);
            }

            #endregion

            foreach (System.Collections.DictionaryEntry objDE in nameColumn)
            {
                DataRow dr = dt.NewRow();
                dr[0] = objDE.Value.ToString();
                for (int i = 1; i < columnName.Count + 1; i++)
                {
                    dr[i] = 0;
                }
                for (int m = 0; m < DataSource.Length; m++)
                {
                    NewReportDomainObject domainObject = DataSource[m] as NewReportDomainObject;

                    if (objDE.Value.ToString() == nameList[m].ToString())
                    {
                        dr[domainObject.PeriodCode] = domainObject.TempValue;
                    }
                }

                dt.Rows.Add(dr);
            }

            return(dt);
        }
Example #36
0
        /// <summary>
        /// Creates single h-line at the specified vertical offset.
        /// </summary>
        private PointList BuildLine(float yOff)
        {
            PointF p11 = new PointF(_bounds.Left - 1, 0);
            PointF p12 = new PointF(_bounds.Right + 1, 0);
            PointF p21 = new PointF(_bounds.Left - 1, 0);
            PointF p22 = new PointF(_bounds.Right + 1, 0);

            p11.Y = p12.Y = yOff;
            yOff += _text.Height;
            if (yOff > _bounds.Bottom)
            {
                return(null);
            }
            p21.Y = p22.Y = yOff;

            ArrayList merge  = new ArrayList();
            PointList result = new PointList();
            PointList row1   = PolygonIntersect(p11, p12);
            PointList row2   = PolygonIntersect(p21, p22);

            int i;

            for (i = 0; i < row1.Count; i++)
            {
                merge.Add(new DirPt(row1[i], i % 2 == 1 ? 2 : 0));
            }
            for (i = 0; i < row2.Count; i++)
            {
                merge.Add(new DirPt(row2[i], i % 2 == 1 ? 3 : 1));
            }

            merge.Sort();

            PointF pt    = PointF.Empty;
            int    inter = -1;          // 0 - for first line, 2 for second line, 4 - for both

            for (i = 0; i < merge.Count; i++)
            {
                DirPt temp = merge[i] as DirPt;

                if (temp.Direction == 2 || temp.Direction == 3)                 // out
                {
                    if (inter != 4)
                    {
                        if (inter == 0 && temp.Direction == 2)
                        {
                            inter = -1;
                        }
                        else if (inter == 2 && temp.Direction == 3)
                        {
                            inter = -1;
                        }
                        continue;
                    }

                    pt.Y       = yOff - _text.Height;
                    temp.Point = new PointF(temp.Point.X, yOff);

                    // Make points relative to the upper-left point of the polygon
                    pt.X      -= _bounds.Left;
                    pt.Y      -= _bounds.Top;
                    temp.Point = new PointF(
                        temp.Point.X - _bounds.Left,
                        temp.Point.Y - _bounds.Top);

                    result.Add(pt);
                    result.Add(temp.Point);

                    if (temp.Direction == 2)
                    {
                        inter = 2;
                    }
                    else
                    {
                        inter = 0;
                    }
                }
                else
                {
                    pt = temp.Point;

                    if (temp.Direction == 0)
                    {
                        if (inter == -1)
                        {
                            inter = 0;
                        }
                        else if (inter == 2)
                        {
                            inter = 4;
                        }
                    }
                    else
                    {
                        if (inter == -1)
                        {
                            inter = 2;
                        }
                        else if (inter == 0)
                        {
                            inter = 4;
                        }
                    }
                }
            }

            // Check if the center point of each
            // rectangle lies within the polygon
            for (i = 0; i < result.Count;)
            {
                PointF pt1 = result[i];
                PointF pt2 = result[i + 1];
                PointF ptc = PointF.Empty;

                ptc.X = (pt1.X + pt2.X) / 2 + _bounds.Left;
                ptc.Y = (pt1.Y + pt2.Y) / 2 + _bounds.Top;

                if (!_polygon.Contains(ptc))
                {
                    result.RemoveAt(i);
                    result.RemoveAt(i);
                }
                else
                {
                    i += 2;
                }
            }

            return(result);
        }
Example #37
0
        protected void Page_Load(object sender, System.EventArgs e)
        {
            Response.ContentType     = "text/xml";
            Response.ContentEncoding = new System.Text.UTF8Encoding();
            Response.Write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");

            int           SkinID   = 1; // not sure what to do about this...google can't invoke different skins easily
            String        StoreLoc = AppLogic.GetStoreHTTPLocation(false, false);
            bool          filter   = AppLogic.GlobalConfigBool("AllowTopicFiltering");
            List <String> dupes    = new List <string>();


            Response.Write("<urlset xmlns=\"" + AppLogic.AppConfig("GoogleSiteMap.Xmlns") + "\">");

            if (AppLogic.AppConfigBool("SiteMap.ShowTopics"))
            {
                // DB Topics:
                using (SqlConnection conn = DB.dbConn())
                {
                    conn.Open();
                    if (filter)
                    {
                        using (IDataReader rs = DB.GetRS(string.Format("select Name from Topic with (NOLOCK) where {0} Deleted=0 and (SkinID IS NULL or SkinID=0 or SkinID={1}) and (StoreID=0 OR StoreID=" + AppLogic.StoreID() + ") Order By StoreID DESC, DisplayOrder, Name ASC", CommonLogic.IIF(AppLogic.IsAdminSite, "", "ShowInSiteMap=1 and "), SkinID.ToString()), conn))
                        {
                            while (rs.Read())
                            {
                                //Only display the first instance of the topic name, store-specific version first
                                if (!dupes.Contains(DB.RSFieldByLocale(rs, "Name", Localization.GetDefaultLocale())))
                                {
                                    Response.Write("<url>");
                                    Response.Write("<loc>" + XmlCommon.XmlEncode(StoreLoc + SE.MakeDriverLink(DB.RSFieldByLocale(rs, "Name", Localization.GetDefaultLocale()))) + "</loc> ");
                                    Response.Write("<changefreq>" + AppLogic.AppConfig("GoogleSiteMap.TopicChangeFreq") + "</changefreq> ");
                                    Response.Write("<priority>" + AppLogic.AppConfig("GoogleSiteMap.TopicPriority") + "</priority> ");
                                    Response.Write("</url>");
                                    dupes.Add(DB.RSFieldByLocale(rs, "Name", Localization.GetDefaultLocale()));
                                }
                            }
                        }
                    }
                    else
                    {
                        using (IDataReader rs = DB.GetRS(string.Format("select Name from Topic with (NOLOCK) where {0} Deleted=0 and (SkinID IS NULL or SkinID=0 or SkinID={1}) and (StoreID=0) Order By DisplayOrder, Name ASC", CommonLogic.IIF(AppLogic.IsAdminSite, "", "ShowInSiteMap=1 and "), SkinID.ToString()), conn))
                        {
                            while (rs.Read())
                            {
                                Response.Write("<url>");
                                Response.Write("<loc>" + XmlCommon.XmlEncode(StoreLoc + SE.MakeDriverLink(DB.RSFieldByLocale(rs, "Name", Localization.GetDefaultLocale()))) + "</loc> ");
                                Response.Write("<changefreq>" + AppLogic.AppConfig("GoogleSiteMap.TopicChangeFreq") + "</changefreq> ");
                                Response.Write("<priority>" + AppLogic.AppConfig("GoogleSiteMap.TopicPriority") + "</priority> ");
                                Response.Write("</url>");
                                dupes.Add(DB.RSFieldByLocale(rs, "Name", Localization.GetDefaultLocale()));
                            }
                        }
                    }
                }

                // File Topics:
                // create an array to hold the list of files
                ArrayList fArray = new ArrayList();

                // get information about our initial directory
                String SFP = CommonLogic.SafeMapPath(CommonLogic.IIF(AppLogic.IsAdminSite, "../", "") + "~/App_Templates/Skin_" + SkinID.ToString() + "/template.htm").Replace("template.htm", "");

                DirectoryInfo dirInfo = new DirectoryInfo(SFP);

                // retrieve array of files & subdirectories
                FileSystemInfo[] myDir = dirInfo.GetFileSystemInfos();

                for (int i = 0; i < myDir.Length; i++)
                {
                    // check the file attributes

                    // if a subdirectory, add it to the sArray
                    // otherwise, add it to the fArray
                    if (((Convert.ToUInt32(myDir[i].Attributes) & Convert.ToUInt32(FileAttributes.Directory)) > 0))
                    {
                    }
                    else
                    {
                        bool skipit = false;
                        if (!myDir[i].FullName.EndsWith("htm", StringComparison.InvariantCultureIgnoreCase) || (myDir[i].FullName.IndexOf("TEMPLATE", StringComparison.InvariantCultureIgnoreCase) != -1) || (myDir[i].FullName.IndexOf("AFFILIATE_", StringComparison.InvariantCultureIgnoreCase) != -1) || (myDir[i].FullName.IndexOf(AppLogic.ro_PMMicropay, StringComparison.InvariantCultureIgnoreCase) != -1))
                        {
                            skipit = true;
                        }
                        if (!skipit)
                        {
                            fArray.Add(Path.GetFileName(myDir[i].FullName));
                        }
                    }
                }

                if (fArray.Count != 0)
                {
                    // sort the files alphabetically
                    fArray.Sort(0, fArray.Count, null);
                    for (int i = 0; i < fArray.Count; i++)
                    {
                        Response.Write("<url>");
                        Response.Write("<loc>" + StoreLoc + SE.MakeDriverLink(fArray[i].ToString().Replace(".htm", "")) + "</loc> ");
                        Response.Write("<changefreq>" + AppLogic.AppConfig("GoogleSiteMap.TopicChangeFreq") + "</changefreq> ");
                        Response.Write("<priority>" + AppLogic.AppConfig("GoogleSiteMap.TopicPriority") + "</priority> ");
                        Response.Write("</url>");
                    }
                }
            }

            Response.Write("</urlset>");
        }
        protected override void OnLayout(LayoutEventArgs e)
        {
            // Don't see any reason to layout if we aren't created
            if (!this.Created)
            {
                return;
            }

            // The first time through, we have to layout everything where it belongs.
            // The key is that when we resize and stuff, we don't resize or move toolstrips.
            if (!done_first_layout)
            {
                ArrayList al = new ArrayList(this.Controls);
                al.Sort(new TabIndexComparer());

                foreach (ToolStrip ts in al)
                {
                    this.AddControlToRows(ts);
                }

                done_first_layout = true;
            }

            // Lay out all the rows
            Point position = this.DisplayRectangle.Location;

            if (this.Dock == DockStyle.Left || this.Dock == DockStyle.Right)
            {
                foreach (ToolStripPanelRow row in this.rows)
                {
                    row.SetBounds(new Rectangle(position, new Size(row.Bounds.Width, this.Height)));

                    position.X += row.Bounds.Width;
                }

                // Find how big we are so we can autosize ourself
                if (this.rows.Count > 0)
                {
                    int last_row_right = this.rows[this.rows.Count - 1].Bounds.Right;

                    if (last_row_right != this.Width)
                    {
                        this.SetBounds(bounds.X, bounds.Y, last_row_right, bounds.Bottom);
                    }
                }
            }
            else
            {
                foreach (ToolStripPanelRow row in this.rows)
                {
                    row.SetBounds(new Rectangle(position, new Size(this.Width, row.Bounds.Height)));

                    position.Y += row.Bounds.Height;
                }

                // Find how big we are so we can autosize ourself
                if (this.rows.Count > 0)
                {
                    int last_row_bottom = this.rows[this.rows.Count - 1].Bounds.Bottom;

                    if (last_row_bottom != this.Height)
                    {
                        this.SetBounds(bounds.X, bounds.Y, bounds.Width, last_row_bottom);
                    }
                }
            }

            this.Invalidate();

            return;
        }
Example #39
0
        public void UpdateGUI(SimPe.Interfaces.Plugin.IFileWrapper wrapper)
        {
            Wrapper.Objd objd = (Wrapper.Objd)wrapper;
            form.wrapper = objd;

            form.tbsimid.Text    = "0x" + Helper.HexString(objd.SimId);
            form.tbsimname.Text  = objd.FileName;
            form.tblottype.Text  = "0x" + Helper.HexString(objd.Type);
            form.lbtypename.Text = ((Data.ObjectTypes)objd.Type).ToString().Trim();
            form.tborgguid.Text  = "0x" + Helper.HexString(objd.OriginalGuid);
            form.tbproxguid.Text = "0x" + Helper.HexString(objd.ProxyGuid);

            Hashtable list = objd.Attributes;

            form.pnelements.Controls.Clear();

            int       top  = 4;
            ArrayList keys = new ArrayList();

            foreach (string k in list.Keys)
            {
                keys.Add("0x" + Helper.HexString((ushort)objd.GetAttributePosition(k)) + ": " + k);
            }
            keys.Sort();

            foreach (string k in keys)
            {
                string[] s  = k.Split(":".ToCharArray(), 2);
                Label    lb = new Label();
                lb.Parent   = form.pnelements;
                lb.AutoSize = true;
                lb.Text     = k + " = ";
                lb.Top      = top;
                lb.Visible  = true;

                TextBox tb = new TextBox();
                tb.BorderStyle  = BorderStyle.None;
                tb.Parent       = form.pnelements;
                tb.Left         = lb.Left + lb.Width;
                tb.Top          = lb.Bottom - tb.Height;
                tb.Width        = 50;
                tb.Text         = "0x" + Helper.HexString(objd.GetAttributeShort(s[1].Trim()));
                tb.Tag          = s[1].Trim();
                tb.Visible      = true;
                tb.TextChanged += new EventHandler(HexTextChanged);

                TextBox tb2 = new TextBox();
                tb2.BorderStyle  = BorderStyle.None;
                tb2.Parent       = form.pnelements;
                tb2.Left         = tb.Left + tb.Width + 4;
                tb2.Top          = lb.Bottom - tb.Height;
                tb2.Width        = 100;
                tb2.Text         = ((short)objd.GetAttributeShort(s[1].Trim())).ToString();
                tb2.Tag          = null;
                tb2.Visible      = true;
                tb2.TextChanged += new EventHandler(DecTextChanged);


                top += Math.Max(lb.Height, tb.Height) + 2;
            }
        }
Example #40
0
        internal override void PrintBody(StreamWriter writer,
                                         HttpRequest request,
                                         IDirectory directory,
                                         ICollection dirs,
                                         ICollection files
                                         )
        {
            bool reverse = request.Query["desc"] != null;

            ResourceColumn sort = ResourceColumn.None;

            try
            {
                string sortString = request.Query["sort"];
                if (sortString != null && sortString != string.Empty)
                {
                    sort = (ResourceColumn)Enum.Parse(typeof(ResourceColumn), sortString);
                }
            }
            catch (ArgumentException)
            {
            }

            writer.WriteLine("<h2>Index of " + MakeLinkPath(directory, request) + "</h2>");

            writer.WriteLine("<table cellspacing=\"0\">");

            writer.WriteLine("<tr>");
            foreach (ResourceColumn column in columns)
            {
                writer.Write(GetColumnTd(column) + "<b><a href=\"" + "." + "?sort=" + column.ToString());
                if (sort == column && !reverse)
                {
                    writer.Write("&desc");
                }
                writer.Write("\"/>");
                writer.WriteLine(column.ToString() + "</a></b></td>");
            }
            writer.WriteLine("</tr>");

            ArrayList entries = new ArrayList(dirs.Count + files.Count);

            foreach (IDirectory dir in dirs)
            {
                entries.Add(new ResourceEntry(dir));
            }
            foreach (IFile file in files)
            {
                entries.Add(new ResourceEntry(file));
            }

            if (sort != ResourceColumn.None)
            {
                entries.Sort(new ResourceComparer(reverse, sort));
            }

            foreach (ResourceEntry entry in entries)
            {
                entry.WriteHtml(writer, columns);
            }

            writer.WriteLine("</table>");
        }
Example #41
0
        public static void Show()
        {
            {
                Console.WriteLine("***************Array******************");
                int[] intArray = new int[3];
                intArray[0] = 123;
                string[] stringArray = new string[] { "123", "234" };
            }
            {
                Console.WriteLine("***************多维Array******************");

                int[,] a = new int[3, 4] {
                    { 0, 1, 2, 3 },               /*  初始化索引号为 0 的行 */
                    { 4, 5, 6, 7 },               /*  初始化索引号为 1 的行 */
                    { 8, 9, 10, 11 }              /*  初始化索引号为 2 的行 */
                };
            }

            {
                Console.WriteLine("***************锯齿Array******************");
                int[][] a = new int[2][];     //每个数组的元素不确定
                a[0] = new int[] { 1, 2, 3 }; /*  初始化索引号为 0 的行 */
                a[1] = new int[] { 2 };       /*  初始化索引号为 1 的行 */
            }

            {
                Console.WriteLine("***************ArrayList******************");
                ArrayList arrayList = new ArrayList();
                arrayList.Add("wxw");
                arrayList.Add("Is");
                arrayList.Add("wxw");
                arrayList.Add(3);//add增加长度
                ArrayList list2 = new ArrayList();
                list2.Add("tt");
                list2.Add("dd");
                arrayList.InsertRange(2, list2);
                foreach (var item in arrayList)
                {
                    Console.WriteLine(item.ToString() + ",");
                }
                Console.WriteLine(arrayList.Count);
                Console.WriteLine(arrayList.Capacity);
                //arrayList[4] = 26;//索引复制,不会增加长度
                //删除数据
                //arrayList.RemoveAt(4);
                var value = arrayList[2];
                arrayList.RemoveAt(0);        //开辟空间--copy
                arrayList.Remove("wxw");
                arrayList.RemoveRange(1, 3);  //Index表示索引,count表示从索引处开始的数目
                arrayList.Sort();             //排序
                arrayList.Reverse();          //反转
                arrayList.IndexOf("wxw");
                arrayList.LastIndexOf("wxw"); //从最后面找

                //Capacity 每次都是增长一倍 *2,默认大小是4
                //Capacity是ArrayList可以存储的元素数。Count是ArrayList中实际包含的元素数。Capacity总是大于或等于Count。如果在添加元素时,Count超过Capacity,则该列表的容量会通过自动重新分配内部数组加倍。  如果Capacity的值显式设置,则内部数组也需要重新分配以容纳指定的容量。如果Capacity被显式设置为0,则公共语言运行库将其设置为默认容量。默认容量为16。
                {
                    ArrayList arrayList1 = new ArrayList();
                    arrayList1.Add("wxw");
                    arrayList1.Add("Is");
                    Console.WriteLine(arrayList1.Capacity);
                    arrayList1.TrimToSize();
                    Console.WriteLine(arrayList1.Capacity);
                }
                {
                    ArrayList arrayList1 = new ArrayList(6);
                    arrayList1.Add("wxw");
                    arrayList1.Add("Is");
                    arrayList1.Add("wxw");
                    arrayList1.Add("Is");
                    Console.WriteLine(arrayList1.Capacity);
                    arrayList1.TrimToSize();
                    Console.WriteLine(arrayList1.Capacity);
                }
            }
            {
                //List:也是Array,内存上都是连续摆放;不定长;泛型,保证类型安全,避免装箱拆箱
                //读取快--增删慢
                Console.WriteLine("***************List<T>******************");
                List <int> intList = new List <int>()
                {
                    1, 2, 3, 4
                };
                intList.Add(123);
                intList.Add(123);
                //intList.Add("123");
                //intList[0] = 123;
                List <string> stringList = new List <string>();
                //stringList[0] = "123";//异常的

                {
                    List <int> intList1 = new List <int>()
                    {
                        1, 2, 3, 4, 5
                    };
                    intList1.Add(123);
                    intList1.Add(123);
                    intList1.Add(123);
                    intList1.Add(123);
                    Console.WriteLine(intList1.Capacity);
                    intList1.TrimExcess();
                    Console.WriteLine(intList1.Capacity);
                }
                {
                    List <int> intList1 = new List <int>(3)
                    {
                        1, 2, 3, 4
                    };
                    intList1.Add(123);
                    intList1.Add(123);
                    intList1.Add(123);
                    Console.WriteLine(intList1.Capacity);
                    //intList1.TrimToSize();
                    Console.WriteLine(intList1.Capacity);
                }
            }
        }
Example #42
0
        /// <summary>
        /// Creates a {@link Section} instance from a byte array.
        /// </summary>
        /// <param name="src">Contains the complete property Set stream.</param>
        /// <param name="offset">The position in the stream that points To the
        /// section's format ID.</param>
        public Section(byte[] src, int offset)
        {
            int o1 = offset;

            /*
             * Read the format ID.
             */
            formatID = new ClassID(src, o1);
            o1      += ClassID.LENGTH;

            /*
             * Read the offset from the stream's start and positions To
             * the section header.
             */
            this.offset = LittleEndian.GetUInt(src, o1);
            o1          = (int)this.offset;

            /*
             * Read the section Length.
             */
            size = (int)LittleEndian.GetUInt(src, o1);
            o1  += LittleEndianConsts.INT_SIZE;

            /*
             * Read the number of properties.
             */
            int propertyCount = (int)LittleEndian.GetUInt(src, o1);

            o1 += LittleEndianConsts.INT_SIZE;

            /*
             * Read the properties. The offset is positioned at the first
             * entry of the property list. There are two problems:
             *
             * 1. For each property we have To Find out its Length. In the
             *    property list we Find each property's ID and its offset relative
             *    To the section's beginning. Unfortunately the properties in the
             *    property list need not To be in ascending order, so it is not
             *    possible To calculate the Length as
             *    (offset of property(i+1) - offset of property(i)). Before we can
             *    that we first have To sort the property list by ascending offsets.
             *
             * 2. We have To Read the property with ID 1 before we Read other
             *    properties, at least before other properties containing strings.
             *    The reason is that property 1 specifies the codepage. If it Is
             *    1200, all strings are in Unicode. In other words: Before we can
             *    Read any strings we have To know whether they are in Unicode or
             *    not. Unfortunately property 1 is not guaranteed To be the first in
             *    a section.
             *
             *    The algorithm below Reads the properties in two passes: The first
             *    one looks for property ID 1 and extracts the codepage number. The
             *    seconds pass Reads the other properties.
             */
            properties = new Property[propertyCount];

            /* Pass 1: Read the property list. */
            int               pass1OffSet  = o1;
            ArrayList         propertyList = new ArrayList(propertyCount);
            PropertyListEntry ple;

            for (int i = 0; i < properties.Length; i++)
            {
                ple = new PropertyListEntry();

                /* Read the property ID. */
                ple.id       = (int)LittleEndian.GetUInt(src, pass1OffSet);
                pass1OffSet += LittleEndianConsts.INT_SIZE;

                /* OffSet from the section's start. */
                ple.offset   = (int)LittleEndian.GetUInt(src, pass1OffSet);
                pass1OffSet += LittleEndianConsts.INT_SIZE;

                /* Add the entry To the property list. */
                propertyList.Add(ple);
            }

            /* Sort the property list by ascending offsets: */
            propertyList.Sort();

            /* Calculate the properties' Lengths. */
            for (int i = 0; i < propertyCount - 1; i++)
            {
                PropertyListEntry ple1 =
                    (PropertyListEntry)propertyList[i];
                PropertyListEntry ple2 =
                    (PropertyListEntry)propertyList[i + 1];
                ple1.Length = ple2.offset - ple1.offset;
            }
            if (propertyCount > 0)
            {
                ple        = (PropertyListEntry)propertyList[propertyCount - 1];
                ple.Length = size - ple.offset;
                //if (ple.Length <= 0)
                //{
                //    StringBuilder b = new StringBuilder();
                //    b.Append("The property Set claims To have a size of ");
                //    b.Append(size);
                //    b.Append(" bytes. However, it exceeds ");
                //    b.Append(ple.offset);
                //    b.Append(" bytes.");
                //    throw new IllegalPropertySetDataException(b.ToString());
                //}
            }

            /* Look for the codepage. */
            int codepage = -1;

            for (IEnumerator i = propertyList.GetEnumerator();
                 codepage == -1 && i.MoveNext();)
            {
                ple = (PropertyListEntry)i.Current;

                /* Read the codepage if the property ID is 1. */
                if (ple.id == PropertyIDMap.PID_CODEPAGE)
                {
                    /* Read the property's value type. It must be
                     * VT_I2. */
                    int  o    = (int)(this.offset + ple.offset);
                    long type = LittleEndian.GetUInt(src, o);
                    o += LittleEndianConsts.INT_SIZE;

                    if (type != Variant.VT_I2)
                    {
                        throw new HPSFRuntimeException
                                  ("Value type of property ID 1 is not VT_I2 but " +
                                  type + ".");
                    }

                    /* Read the codepage number. */
                    codepage = LittleEndian.GetUShort(src, o);
                }
            }

            /* Pass 2: Read all properties - including the codepage property,
             * if available. */
            int i1 = 0;

            for (IEnumerator i = propertyList.GetEnumerator(); i.MoveNext();)
            {
                ple = (PropertyListEntry)i.Current;
                Property p = new Property(ple.id, src,
                                          this.offset + ple.offset,
                                          ple.Length, codepage);
                if (p.ID == PropertyIDMap.PID_CODEPAGE)
                {
                    p = new Property(p.ID, p.Type, codepage);
                }
                properties[i1++] = p;
            }

            /*
             * Extract the dictionary (if available).
             * Tony changed the logic
             */
            this.dictionary = (IDictionary)GetProperty(0);
        }
Example #43
0
        public bool Show(Point location, string hint, CodeModel.ICodeElement[] hints, int fontheight, Type[] filters)
        {
            SuspendLayout();

            if (this.filters == null)
            {
                this.filters = filters;
            }

            DialogResult = DialogResult.Cancel;
            choices.Items.Clear();

            lasthint = hint;

            //System.Diagnostics.Trace.WriteLine(Join(this.filters),     "Filters       ");

            IImageListProviderService ims = ServiceHost.ImageListProvider;

            ArrayList all = new ArrayList();

            foreach (CodeModel.ICodeElement s in hints)
            {
                if (Languages.Language.FilterType(this.filters, s))
                {
                    all.Add(s);
                }
            }

            all.Sort(CODEELEMCOMPARER);
            choices.Items.AddRange(all.ToArray());

            if (choices.Items.Count == 0)
            {
                ResumeLayout();
                if (Visible)
                {
                    Hide();

                    return(true);
                }
                else
                {
                    DialogResult = DialogResult.No;
                    return(false);
                }
            }

            choices.SelectedIndex = 0;

            if (choices.Items.Count == 1)
            {
                if (this.filters == filters || lastguess == ((CodeModel.ICodeElement)(choices.SelectedItem)).Fullname)
                {
                    ResumeLayout();
                    DialogResult = DialogResult.OK;
                    if (Visible)
                    {
                        Hide();
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }

                lastguess = ((CodeModel.ICodeElement)(choices.SelectedItem)).Fullname;
            }

            int diff = Height - ClientSize.Height;

            if (choices.Items.Count < 12)
            {
                Height = choices.ItemHeight * choices.Items.Count + diff + 2;
            }
            else
            {
                Height = choices.ItemHeight * 12 + diff + 2;
            }

            Screen ss = Screen.FromPoint(location);

            //x

            if (location.X + Width > ss.WorkingArea.Width)
            {
                location.X = ss.WorkingArea.Width - Width;
            }

            //y

            if (location.Y + Height > ss.WorkingArea.Bottom)
            {
                location.Y = location.Y - fontheight - Height;
            }

            Location = location;

            ResumeLayout();

            if (!Visible)
            {
                Show();
            }
            return(true);
        }
Example #44
0
        /// <summary>
        /// 获取品牌,并按照首字母建立层级结构
        /// </summary>
        /// <param name="classid"></param>
        /// <returns></returns>
        public IList <VWTreeBrandEntity> GetTreeBrandAll(int classid, bool iscache = false)
        {
            IList <VWTreeBrandEntity> resultlist = new List <VWTreeBrandEntity>();

            string _cachekey = "GetTreeBrandAll" + classid;

            if (iscache)
            {
                object obj = MemCache.GetCache(_cachekey);
                if (obj == null)
                {
                    int rediclassid = classid;
                    ClassesFoundEntity _classentity = ClassesFoundBLL.Instance.GetClassesFound(classid, false);
                    if (_classentity.RedirectClassId > 0)
                    {
                        rediclassid = _classentity.RedirectClassId;
                    }
                    IList <int> classintlist = new List <int>();
                    classintlist = ClassesFoundBLL.Instance.GetSubClassEndList(rediclassid);
                    string classidstr = "";
                    if (classintlist != null && classintlist.Count > 0)
                    {
                        classidstr = string.Join("_", classintlist);
                    }
                    else
                    {
                        classidstr = StringUtils.GetDbString(classid);
                    }

                    IList <VWTreeBrandEntity> list = null;
                    list = BrandDA.Instance.GetBrandAllByClassStr(classidstr);
                    if (list != null && list.Count > 0)
                    {
                        //string[] firstletter = new Array();
                        ArrayList firstletter = new ArrayList();
                        foreach (VWTreeBrandEntity entity in list)
                        {
                            if (!firstletter.Contains(entity.PYFirst))
                            {
                                firstletter.Add(entity.PYFirst);
                            }
                            firstletter.Sort();
                        }
                        foreach (string letter in firstletter)
                        {
                            VWTreeBrandEntity entity = new VWTreeBrandEntity();
                            entity.PYFirst = letter;
                            resultlist.Add(entity);
                        }
                        foreach (VWTreeBrandEntity entity in list)
                        {
                            foreach (VWTreeBrandEntity entity2 in resultlist)
                            {
                                if (entity.PYFirst == entity2.PYFirst)
                                {
                                    if (entity2.Children == null)
                                    {
                                        entity2.Children = new List <VWTreeBrandEntity>();
                                    }
                                    entity2.Children.Add(entity);
                                    break;
                                }
                            }
                        }
                    }
                    MemCache.AddCache(_cachekey, resultlist);
                }
                else
                {
                    resultlist = (IList <VWTreeBrandEntity>)obj;
                }
            }
            else
            {
                int rediclassid = classid;
                ClassesFoundEntity _classentity = ClassesFoundBLL.Instance.GetClassesFound(classid, false);
                if (_classentity.RedirectClassId > 0)
                {
                    rediclassid = _classentity.RedirectClassId;
                }
                IList <int> classintlist = new List <int>();
                classintlist = ClassesFoundBLL.Instance.GetSubClassEndList(rediclassid);
                string classidstr = "";
                if (classintlist != null && classintlist.Count > 0)
                {
                    classidstr = string.Join("_", classintlist);
                }
                else
                {
                    classidstr = StringUtils.GetDbString(classid);
                }

                IList <VWTreeBrandEntity> list = null;
                list = BrandDA.Instance.GetBrandAllByClassStr(classidstr);
                if (list != null && list.Count > 0)
                {
                    //string[] firstletter = new Array();
                    ArrayList firstletter = new ArrayList();
                    foreach (VWTreeBrandEntity entity in list)
                    {
                        if (!firstletter.Contains(entity.PYFirst))
                        {
                            firstletter.Add(entity.PYFirst);
                        }
                        firstletter.Sort();
                    }
                    foreach (string letter in firstletter)
                    {
                        VWTreeBrandEntity entity = new VWTreeBrandEntity();
                        entity.PYFirst = letter;
                        resultlist.Add(entity);
                    }
                    foreach (VWTreeBrandEntity entity in list)
                    {
                        foreach (VWTreeBrandEntity entity2 in resultlist)
                        {
                            if (entity.PYFirst == entity2.PYFirst)
                            {
                                if (entity2.Children == null)
                                {
                                    entity2.Children = new List <VWTreeBrandEntity>();
                                }
                                entity2.Children.Add(entity);
                                break;
                            }
                        }
                    }
                }
            }
            return(resultlist);
        }
Example #45
0
        private void GenerateBinaryFileList(string aDataDir)
        {
            // Determine number of receivers

            string rec1Dir = aDataDir + "\\1";
            string rec2Dir = aDataDir + "\\2";

            int numRec = 0;

            if (Directory.Exists(rec1Dir))
            {
                numRec++;
            }
            if (Directory.Exists(rec2Dir))
            {
                numRec++;
            }

            if (numRec == 0)
            {
                return;
            }

            string[] someDays1 = new string[0];
            string[] someDays2 = new string[0];

            // First, find all days
            someDays1 = Directory.GetDirectories(rec1Dir);
            if (numRec == 2)
            {
                someDays2 = Directory.GetDirectories(rec2Dir);
            }

            //Merge and sort the days from both receiver directories
            ArrayList someDays = new ArrayList();

            foreach (string d in someDays1)
            {
                someDays.Add(Path.GetFileName(d));
            }
            foreach (string d in someDays2)
            {
                if (!someDays.Contains(Path.GetFileName(d)))
                {
                    someDays.Add(Path.GetFileName(d));
                }
            }
            someDays.Sort();

            foreach (string d in someDays)
            {
                Console.WriteLine("DAY: " + d);
            }

            // Now that we have a list of days sorted by date, go into each folder
            // for both receivers, and put together ordered list of binary files.

            foreach (string d in someDays)
            {
                // Loop over possible hours and add to list
                for (int i = 0; i < 24; i++)
                {
                    BFileInfo aBFileInfo = new BFileInfo();
                    // Check for hour dir in rec 1
                    if (Directory.Exists(rec1Dir + "\\" + d + "\\" + i))
                    {
                        aBFileInfo.fileRec1 = GetBinaryMITesFile(rec1Dir + "\\" + d + "\\" + i);
                    }
                    if (Directory.Exists(rec2Dir + "\\" + d + "\\" + i))
                    {
                        aBFileInfo.fileRec2 = GetBinaryMITesFile(rec2Dir + "\\" + d + "\\" + i);
                    }

                    // Add if one of the receiver directories had a file
                    if ((aBFileInfo.fileRec1 != "") || (aBFileInfo.fileRec2 != ""))
                    {
                        someBinaryFiles.Add(aBFileInfo);
                    }
                }
            }
            Console.WriteLine(someBinaryFiles);
        }
Example #46
0
        /// <summary>
        /// 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名
        /// <para>key和value通常用于填充最后一组参数</para>
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="value">参数值</param>
        /// <param name="workPaySignType">企业支付签名(workwx_sign)类型,默认为 None</param>
        /// <returns></returns>
        public virtual string CreateMd5Sign(string key, string value, WorkPaySignType workPaySignType = WorkPaySignType.None)
        {
            StringBuilder sb = new StringBuilder();

            ArrayList akeys = new ArrayList(Parameters.Keys);

            akeys.Sort(ASCIISort.Create());

            foreach (string k in akeys)
            {
                string v = (string)Parameters[k];
                if (null != v && "".CompareTo(v) != 0 &&
                    "sign".CompareTo(k) != 0
                    //&& "sign_type".CompareTo(k) != 0
                    && "key".CompareTo(k) != 0)
                {
                    //过滤企业支付特殊情况
                    if (workPaySignType == WorkPaySignType.WorkSendRedPackage)
                    {
                        //企业支付微信红包,仅保留以下字段
                        if ("act_name".CompareTo(k) != 0 ||
                            "mch_billno".CompareTo(k) != 0 ||
                            "mch_id".CompareTo(k) != 0 ||
                            "nonce_str".CompareTo(k) != 0 ||
                            "re_openid".CompareTo(k) != 0 ||
                            "total_amount".CompareTo(k) != 0 ||
                            "wxappid".CompareTo(k) != 0
                            )
                        {
                            continue;
                        }
                    }
                    else if (workPaySignType == WorkPaySignType.WorkPayApi)
                    {
                        //企业支付微信红包,仅保留以下字段
                        if ("amount".CompareTo(k) != 0 ||
                            "appid".CompareTo(k) != 0 ||
                            "desc".CompareTo(k) != 0 ||
                            "mch_id".CompareTo(k) != 0 ||
                            "nonce_str".CompareTo(k) != 0 ||
                            "openid".CompareTo(k) != 0 ||
                            "partner_trade_no".CompareTo(k) != 0 ||
                            "ww_msg_type".CompareTo(k) != 0
                            )
                        {
                            continue;
                        }
                    }
                    sb.Append(k + "=" + v + "&");
                }
            }

            sb.Append(key + "=" + value);

            //string sign = EncryptHelper.GetMD5(sb.ToString(), GetCharset()).ToUpper();

            //编码强制使用UTF8:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_1
            string sign = EncryptHelper.GetMD5(sb.ToString(), "UTF-8").ToUpper();

            return(sign);
        }
Example #47
0
 /// <summary>
 /// Sorts the array
 /// </summary>
 private void Sort()
 {
     strings.Sort();
 }
Example #48
0
        static void Main(string[] args)
        {
            /*
             *  ArrayList
             */
            ArrayList arrPersons = new ArrayList();

            arrPersons.Add(new Person("Nguyen Van A", 18));
            arrPersons.Add(new Person("Nguyen Van B", 25));
            arrPersons.Add(new Person("Nguyen Van C", 20));

            //Console.WriteLine("Danh sach Person ban dau: ");
            foreach (Person item in arrPersons)
            {
                //Console.WriteLine(item.ToString());
            }

            arrPersons.Sort(new SortPersons());
            //Console.WriteLine("Danh sach Person da duoc sap xep theo tuoi tang dan: ");
            foreach (Person item in arrPersons)
            {
                //Console.WriteLine(item.ToString());
            }

            /*
             * Hashtable
             */
            Hashtable MyHash = new Hashtable();

            MyHash.Add("T", "Thai Hoang");
            MyHash.Add("B", "Binh");
            MyHash.Add("D", "Duc");

            Hashtable newHash = new Hashtable(MyHash);

            //Console.WriteLine(newHash.ContainsKey("G"));
            newHash["G"] = "Giang";
            //Console.WriteLine("MyHash : \n");
            //Console.WriteLine("So phan tu MyHash " + MyHash.Count + "\n");

            foreach (DictionaryEntry item in MyHash)
            {
                //Console.WriteLine(item.Key + "\t" + item.Value);
            }

            //Console.WriteLine("\nnewHash : \n");
            //Console.WriteLine("So phan tu newHash " + newHash.Count + "\n");
            foreach (DictionaryEntry item in newHash)
            {
                //Console.WriteLine(item.Key + "\t" + item.Value);
            }

            /*
             * SortedList
             * (ArrayList X Hashtable)
             */
            SortedList MySL = new SortedList();

            /*
             * Stack
             */
            ArrayList MyArray = new ArrayList();

            MyArray.Add(5);
            MyArray.Add(7);
            MyArray.Add(9);
            Stack MyStack = new Stack(MyArray);

            MyStack.Push("Education");
            MyStack.Push("Free");
            MyStack.Push("HowKteam");
            Console.WriteLine(" So phan tu hien tai cua Stack la: {0}", MyStack.Count);
            Console.ReadKey();
        }
    public virtual bool runTest()
    {
        int iCountErrors    = 0;
        int iCountTestcases = 0;

        Console.Error.WriteLine(s_strClassMethod + ": " + s_strTFName + " runTest started...");
        ArrayList list   = null;
        String    strLoc = "Loc_000oo";

        String [] strHeroes =
        {
            "Aquaman",
            "Atom",
            "Batman",
            "Black Canary",
            "Captain America",
            "Captain Atom",
            "Catwoman",
            "Cyborg",
            "Flash",
            "Green Arrow",
            "Green Lantern",
            "Hawkman",
            "Huntress",
            "Ironman",
            "Nightwing",
            "Robin",
            "SpiderMan",
            "Steel",
            "Superman",
            "Thor",
            "Wildcat",
            "Wonder Woman",
        };
        String [] strFindHeroes =
        {
            "Batman",
            "Superman",
            "SpiderMan",
            "Wonder Woman",
            "Green Lantern",
            "Flash",
            "Steel"
        };
        try
        {
            strLoc = "Loc_001o1";
            ++iCountTestcases;
            try
            {
                list = new ArrayList();
                if (list == null)
                {
                    Console.WriteLine(s_strTFName + "E_101: Failed to construct new ArrayList");
                    ++iCountErrors;
                }
                for (int ii = 0; ii < strHeroes.Length; ++ii)
                {
                    list.Add(strHeroes[ii]);
                }
                if (list.Count != strHeroes.Length)
                {
                    Console.WriteLine("E_202: ");
                    ++iCountErrors;
                }
            }
            catch (Exception ex)
            {
                ++iCountErrors;
                Console.WriteLine(s_strTFName + "E_10001: Unexpected Exception: " + ex.ToString());
            }
            ++iCountTestcases;
            try
            {
                for (int ii = 0; ii < strFindHeroes.Length; ++ii)
                {
                    int ndx = list.BinarySearch(strFindHeroes[ii], new Co8598BinarySearch_obj_ic());
                    if (ndx >= strHeroes.Length)
                    {
                        ++iCountErrors;
                        Console.WriteLine("Err_753fg unexpected value returned");
                    }
                    if (strHeroes[ndx].CompareTo(strFindHeroes[ii]) != 0)
                    {
                        ++iCountErrors;
                        Console.WriteLine("Err_853deg! unexpected value returned");
                    }
                }
            }
            catch (Exception ex)
            {
                ++iCountErrors;
                Console.WriteLine(s_strTFName + "E_10002: Unexpected Exception: " + ex.ToString());
            }
            strLoc = "Loc_00437sg";
            iCountTestcases++;
            list = new ArrayList();
            for (int i = 0; i < 100; i++)
            {
                list.Add(i);
            }
            list.Sort();
            if (~list.BinarySearch(150, new Co8598BinarySearch_obj_ic()) != 100)
            {
                iCountErrors++;
                Console.WriteLine("Err_437sdg! wrong value returned, " + list.BinarySearch(150));
            }
            strLoc = "Loc_347sg";
            iCountTestcases++;
            if (list.BinarySearch(null, new Co8598BinarySearch_obj_ic()) != -1)
            {
                iCountErrors++;
                Console.WriteLine("Err_247sg! wrong value returned, " + list.BinarySearch(null, new Co8598BinarySearch_obj_ic()));
            }
            strLoc = "Loc_87245dsg";
            iCountTestcases++;
            list.Add(null);
            list.Sort();
            if (list.BinarySearch(null, new CompareWithNullEnabled()) != 0)
            {
                iCountErrors++;
                Console.WriteLine("Err_983475dsg! wrong value returned, " + list.BinarySearch(null, new Co8598BinarySearch_obj_ic()));
            }
            strLoc = "Loc_9437tsdfg";
            iCountTestcases++;
            list = new ArrayList();
            for (int i = 0; i < 100; i++)
            {
                list.Add(5);
            }
            list.Sort();
            if (list.BinarySearch(5, new Co8598BinarySearch_obj_ic()) != 49)
            {
                iCountErrors++;
                Console.WriteLine("Err_3846tsdg! wrong value returned, " + list.BinarySearch(5));
            }
            strLoc = "Loc_9437tsdfg";
            iCountTestcases++;
            list = new ArrayList();
            for (int i = 0; i < 100; i++)
            {
                list.Add(5);
            }
            list.Sort();
            if (list.BinarySearch(5, null) != 49)
            {
                iCountErrors++;
                Console.WriteLine("Err_3846tsdg! wrong value returned, " + list.BinarySearch(5));
            }
        }
        catch (Exception exc_general)
        {
            ++iCountErrors;
            Console.WriteLine(s_strTFAbbrev + " : Error Err_8888yyy!  strLoc==" + strLoc + ", exc_general==\n" + exc_general.ToString());
        }
        Console.Error.Write(s_strClassMethod);
        Console.Error.Write(": ");
        if (iCountErrors == 0)
        {
            Console.Error.WriteLine(s_strTFName + " iCountTestcases==" + iCountTestcases + " paSs");
            return(true);
        }
        else
        {
            Console.WriteLine(s_strTFName + s_strTFPath);
            Console.WriteLine(s_strTFName + "FAiL");
            Console.Error.WriteLine(s_strTFName + " iCountErrors==" + iCountErrors);
            return(false);
        }
    }
Example #50
0
        public static bool LocTrungVi(Bitmap img)
        {
            //Loc trung vi
            Bitmap     imgtmp  = (Bitmap)img.Clone();
            BitmapData imgdata = img.LockBits(new Rectangle(0, 0, img.Width, img.Height),
                                              ImageLockMode.ReadWrite,
                                              PixelFormat.Format24bppRgb);
            BitmapData imgtmpdata = imgtmp.LockBits(new Rectangle(0, 0, img.Width, img.Height),
                                                    ImageLockMode.ReadWrite,
                                                    PixelFormat.Format24bppRgb);
            int       stride  = imgdata.Stride;
            int       stride2 = stride * 2;
            ArrayList list;

            unsafe
            {
                byte *p       = (byte *)imgdata.Scan0;
                byte *p1      = (byte *)imgtmpdata.Scan0;
                int   nOffset = stride - img.Width * 3;
                int   nWidth  = img.Width - 2;
                //trừ đi các rìa ảnh
                int nHeight = img.Height - 2;
                int nPixel;
                list = new ArrayList();
                for (int y = 0; y < nHeight; ++y)
                {
                    for (int x = 0; x < nWidth; ++x)
                    {
                        for (int i = 0; i < 3; ++i)
                        {
                            list.Add(p1[0]);
                            list.Add(p1[3]);
                            list.Add(p1[6]);
                            list.Add(p1[0 + stride]);
                            list.Add(p1[3 + stride]);
                            list.Add(p1[6 + stride]);
                            list.Add(p1[0 + stride2]);
                            list.Add(p1[3 + stride2]);
                            list.Add(p1[6 + stride2]);
                            list.Sort();
                            nPixel = Convert.ToInt32(list[4]);
                            if (nPixel < 0)
                            {
                                nPixel = 0;
                            }
                            if (nPixel > 255)
                            {
                                nPixel = 255;
                            }
                            p[3 + stride] = (byte)nPixel;
                            ++p;
                            ++p1;
                            list.Clear();
                        }
                    }
                    p  += nOffset;
                    p1 += nOffset;
                }
            }
            img.UnlockBits(imgdata);
            return(true);
        }
    public static void Main()
    {
        // Creates and initializes a new ArrayList.
        ArrayList myAL = new ArrayList();

        myAL.Add("The");
        myAL.Add("quick");
        myAL.Add("brown");
        myAL.Add("fox");
        myAL.Add("jumped");
        myAL.Add("over");
        myAL.Add("the");
        myAL.Add("lazy");
        myAL.Add("dog");

        // Create a fixed-size wrapper around the ArrayList.
        ArrayList myFixedSizeAL = ArrayList.FixedSize(myAL);

        // Display whether the ArrayLists have a fixed size or not.
        Console.WriteLine("myAL {0}.", myAL.IsFixedSize ? "has a fixed size" : "does not have a fixed size");
        Console.WriteLine("myFixedSizeAL {0}.", myFixedSizeAL.IsFixedSize ? "has a fixed size" : "does not have a fixed size");
        Console.WriteLine();

        // Display both ArrayLists.
        Console.WriteLine("Initially,");
        Console.Write("Standard  :");
        PrintValues(myAL, ' ');
        Console.Write("Fixed size:");
        PrintValues(myFixedSizeAL, ' ');

        // Sort is allowed in the fixed-size ArrayList.
        myFixedSizeAL.Sort();

        // Display both ArrayLists.
        Console.WriteLine("After Sort,");
        Console.Write("Standard  :");
        PrintValues(myAL, ' ');
        Console.Write("Fixed size:");
        PrintValues(myFixedSizeAL, ' ');

        // Reverse is allowed in the fixed-size ArrayList.
        myFixedSizeAL.Reverse();

        // Display both ArrayLists.
        Console.WriteLine("After Reverse,");
        Console.Write("Standard  :");
        PrintValues(myAL, ' ');
        Console.Write("Fixed size:");
        PrintValues(myFixedSizeAL, ' ');

        // Add an element to the standard ArrayList.
        myAL.Add("AddMe");

        // Display both ArrayLists.
        Console.WriteLine("After adding to the standard ArrayList,");
        Console.Write("Standard  :");
        PrintValues(myAL, ' ');
        Console.Write("Fixed size:");
        PrintValues(myFixedSizeAL, ' ');
        Console.WriteLine();

        // Adding or inserting elements to the fixed-size ArrayList throws an exception.
        try  {
            myFixedSizeAL.Add("AddMe2");
        } catch (Exception myException)  {
            Console.WriteLine("Exception: " + myException.ToString());
        }
        try  {
            myFixedSizeAL.Insert(3, "InsertMe");
        } catch (Exception myException)  {
            Console.WriteLine("Exception: " + myException.ToString());
        }
    }
 public void SortDescending()
 {
     _nBestList.Sort();
 }
        public void OnNewPropertyGridItem(object sender, EventArgs e)
        {
            WixFiles.UndoManager.BeginNewCommandRange();

            // Temporarily store the XmlAttributeAdapter
            XmlAttributeAdapter attAdapter = (XmlAttributeAdapter)CurrentGrid.SelectedObject;

            ArrayList attributes = new ArrayList();

            XmlNodeList xmlAttributes = attAdapter.XmlNodeDefinition.SelectNodes("xs:attribute", WixFiles.XsdNsmgr);

            foreach (XmlNode at in xmlAttributes)
            {
                string attName = at.Attributes["name"].Value;
                if (attAdapter.XmlNode.Attributes[attName] == null)
                {
                    attributes.Add(attName);
                }
            }

            if (attAdapter.XmlNodeDefinition.Name == "xs:extension")
            {
                bool hasInnerText = false;
                foreach (GridItem it in CurrentGrid.SelectedGridItem.Parent.GridItems)
                {
                    if (it.Label == "InnerText")
                    {
                        hasInnerText = true;
                        break;
                    }
                }
                if (hasInnerText == false)
                {
                    attributes.Add("InnerText");
                }
            }

            attributes.Sort();

            SelectStringForm frm = new SelectStringForm();

            frm.PossibleStrings = attributes.ToArray(typeof(String)) as String[];
            if (DialogResult.OK != frm.ShowDialog() ||
                frm.SelectedStrings.Length == 0)
            {
                return;
            }

            // Show dialog to choose from available items.
            XmlAttribute att = null;

            foreach (string newAttributeName in frm.SelectedStrings)
            {
                if (string.Equals(newAttributeName, "InnerText"))
                {
                    attAdapter.ShowInnerTextIfEmpty = true;
                }
                else
                {
                    att = WixFiles.WxsDocument.CreateAttribute(newAttributeName);
                    attAdapter.XmlNode.Attributes.Append(att);
                }
            }

            CurrentGrid.SelectedObject = null;
            // Update the CurrentGrid.
            CurrentGrid.SelectedObject = attAdapter;
            CurrentGrid.Update();

            string firstNewAttributeName = frm.SelectedStrings[0];

            foreach (GridItem it in CurrentGrid.SelectedGridItem.Parent.GridItems)
            {
                if (it.Label == firstNewAttributeName)
                {
                    CurrentGrid.SelectedGridItem = it;
                    break;
                }
            }
        }
Example #54
0
        // Collect lines with intesities greater or equal then specified
        private void CollectLines(short minLineIntensity)
        {
            int maxTheta  = houghMap.GetLength(0);
            int maxRadius = houghMap.GetLength(1);

            short intensity;
            bool  foundGreater;

            int halfHoughWidth = maxRadius >> 1;

            // clean lines collection
            lines.Clear( );

            // for each Theta value
            for (int theta = 0; theta < maxTheta; theta++)
            {
                // for each Radius value
                for (int radius = 0; radius < maxRadius; radius++)
                {
                    // get current value
                    intensity = houghMap[theta, radius];

                    if (intensity < minLineIntensity)
                    {
                        continue;
                    }

                    foundGreater = false;

                    // check neighboors
                    for (int tt = theta - localPeakRadius, ttMax = theta + localPeakRadius; tt < ttMax; tt++)
                    {
                        // skip out of map values
                        if (tt < 0)
                        {
                            continue;
                        }
                        if (tt >= maxTheta)
                        {
                            break;
                        }

                        // break if it is not local maximum
                        if (foundGreater == true)
                        {
                            break;
                        }

                        for (int tr = radius - localPeakRadius, trMax = radius + localPeakRadius; tr < trMax; tr++)
                        {
                            // skip out of map values
                            if (tr < 0)
                            {
                                continue;
                            }
                            if (tr >= maxRadius)
                            {
                                break;
                            }

                            // compare the neighboor with current value
                            if (houghMap[tt, tr] > intensity)
                            {
                                foundGreater = true;
                                break;
                            }
                        }
                    }

                    // was it local maximum ?
                    if (!foundGreater)
                    {
                        // we have local maximum
                        lines.Add(new HoughLine(90.0 - maxSkewToDetect + (double)theta / stepsPerDegree, (short)(radius - halfHoughWidth), intensity, (double)intensity / maxMapIntensity));
                    }
                }
            }

            lines.Sort( );
        }
Example #55
0
        /// <summary>
        /// 将数据转换为相对应X轴、Y轴的DataTable
        /// </summary>
        public DataTable ConvertDataTableNewQty(string planQtyName)
        {
            DataTable dt = new DataTable();

            //此列用来显示时间
            dt.Columns.Add(new DataColumn("Time", typeof(string)));
            ArrayList columnNameList = new ArrayList();

            #region //其他ColunmName
            string    name         = string.Empty;
            string[]  groupColumns = m_ChartGroupByString.Split(',');
            ArrayList allNameList  = new ArrayList();
            foreach (NewReportDomainObject domainObject in DataSource)
            {
                name = string.Empty;
                #region
                if (groupColumns.Length > 0)
                {
                    for (int i = 0; i < groupColumns.Length; i++)
                    {
                        if (groupColumns[i].Trim().ToLower() == "sscode")
                        {
                            name += domainObject.SSCode + "-";
                        }

                        else if (groupColumns[i].Trim().ToLower() == "opcode")
                        {
                            name += domainObject.OPCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "rescode")
                        {
                            name += domainObject.ResCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "bigsscode")
                        {
                            name += domainObject.BigSSCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "segcode")
                        {
                            name += domainObject.SegCode + "-";
                        }

                        else if (groupColumns[i].Trim().ToLower() == "faccode")
                        {
                            name += domainObject.FacCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "momemo")
                        {
                            name += domainObject.MOMemo + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "newmass")
                        {
                            name += domainObject.NewMass + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "itemcode")
                        {
                            name += domainObject.ItemCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "mmodelcode" || groupColumns[i].Trim().ToLower() == "materialmodelcode")
                        {
                            name += domainObject.MaterialModelCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "mmachinetype" || groupColumns[i].Trim().ToLower() == "materialmachinetype")
                        {
                            name += domainObject.MaterialMachineType + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "mexportimport" || groupColumns[i].Trim().ToLower() == "materialexportimport")
                        {
                            name += domainObject.MaterialExportImport + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "mocode")
                        {
                            name += domainObject.MOCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "firstclass")
                        {
                            name += domainObject.FirstClass + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "secondclass")
                        {
                            name += domainObject.SecondClass + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "thirdclass")
                        {
                            name += domainObject.SSCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "lotno")
                        {
                            name += domainObject.LotNo + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "productiontype")
                        {
                            name += domainObject.ProductionType + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "oqclottype")
                        {
                            name += domainObject.OQCLotType + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "inspectorandname")
                        {
                            name += domainObject.InspectorAndName + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "iqclineitemtype")
                        {
                            name += domainObject.IQCLineItemType + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "iqcitemtype")
                        {
                            name += domainObject.IQCItemType + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "rohs")
                        {
                            name += domainObject.Rohs + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "concessionstatus")
                        {
                            name += domainObject.ConcessionStatus + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "vendorcode")
                        {
                            name += domainObject.VendorCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "materialcode")
                        {
                            name += domainObject.MaterialCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "tpcode")
                        {
                            name += domainObject.PeriodCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToUpper() == "shiftcode")
                        {
                            name += domainObject.ShiftCode + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "shiftday")
                        {
                            name += domainObject.ShiftDay + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "dweek")
                        {
                            name += domainObject.Week + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "dmonth")
                        {
                            name += domainObject.Month + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "year")
                        {
                            name += domainObject.Year + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "goodsemigood")
                        {
                            name += domainObject.GoodSemiGood + "-";
                        }
                        else if (groupColumns[i].Trim().ToLower() == "crewcode")
                        {
                            name += domainObject.CrewCode + "-";
                        }
                    }
                    #endregion
                    name += domainObject.EAttribute1;
                }

                if (!columnNameList.Contains(name))
                {
                    columnNameList.Add(name);
                }

                allNameList.Add(name);
            }

            #endregion

            //排序名称
            columnNameList.Sort();


            dt.Columns.Add(new DataColumn(planQtyName, typeof(double)));
            for (int i = 0; i < columnNameList.Count; i++)
            {
                dt.Columns.Add(new DataColumn(columnNameList[i].ToString(), typeof(double)));
            }



            ArrayList columnValueList = new ArrayList();
            foreach (NewReportDomainObject domainObject in DataSource) //Y轴
            {
                if (!columnValueList.Contains(domainObject.PeriodCode))
                {
                    columnValueList.Add(domainObject.PeriodCode);
                }
            }


            columnValueList.Sort();



            foreach (string value in columnValueList)
            {
                DataRow dr = dt.NewRow();
                dr[0] = value;
                dr[1] = 0;
                for (int i = 2; i < columnNameList.Count + 2; i++)
                {
                    dr[i] = 0;
                }
                for (int m = 0; m < DataSource.Length; m++)
                {
                    NewReportDomainObject domainObject = DataSource[m] as NewReportDomainObject;

                    if (value == domainObject.PeriodCode)
                    {
                        dr[planQtyName] = domainObject.PlanQty;


                        dr[allNameList[m].ToString()] = domainObject.TempValue;
                    }
                }

                dt.Rows.Add(dr);
            }



            return(dt);
        }
Example #56
0
        static void Main(string[] args)
        {
            ArrayList list = new ArrayList();

            list.Add(new Person("서은광", "010-0321-1121", "*****@*****.**"));
            list.Add(new Person("이민혁", "010-0321-1129", "*****@*****.**"));
            list.Add(new Person("이창섭", "010-0321-0226", "*****@*****.**"));
            list.Add(new Person("임현식", "010-0321-0310", "*****@*****.**"));
            list.Add(new Person("프니엘", "010-0321-0307", "*****@*****.**"));
            list.Add(new Person("정일훈", "010-0321-1004", "*****@*****.**"));
            list.Add(new Person("육성재", "010-0321-0503", "*****@*****.**"));



            for (int i = 0; i < list.Count; i++)
            {
                Console.WriteLine(list[i]);
            }

            Console.WriteLine("-------- 중간에 데이터 껴넣은 후");
            list.Insert(3, new Person("차은우", "010-1234-5678", "*****@*****.**"));

            Console.WriteLine("-------- 중간에 데이터 껴넣은 후");
            int pos = list.IndexOf(new Person("육성재", "010-0321-0503", "*****@*****.**"));

            Console.WriteLine("위치값 : " + pos);
            //indexof는  int같은 원래 있는 자료형만 찾아짐
            //Equal랑 getHashCodegk함수 override함.

            Console.WriteLine("--------정열 후");
            list.Sort();
            foreach (Person item in list)
            {
                Console.WriteLine(item);
            }

            Stack s = new Stack();

            s.Push('A');
            s.Push('B');
            s.Push('C');
            s.Push('D');
            s.Push('E');

            while (s.Count > 0)
            {
                Console.WriteLine(s.Pop());
            }

            Queue q = new Queue();

            q.Enqueue('A');
            q.Enqueue('B');
            q.Enqueue('C');
            q.Enqueue('D');
            q.Enqueue('E');

            while (q.Count < 0)
            {
                Console.WriteLine(q.Dequeue());
            }
            //해쉬테이블-검색속도 최적
            //데이터를 키와 값 쌍으로 저장, 키 값으로 검색하면
            //이론상 한번에 데이터를 가져올 수 있다.
            //메모리는 많이 차지함
            Hashtable ht = new Hashtable();

            ht.Add("apple", "사과");
            //키,값 쌍으로 구성되는데 이미 존재하는 키일 경우에는 덮어씀
            ht.Add("orange", "오렌지");
            ht.Add("banana", "바나나");
            ht.Add("lemon", "레몬");
            ht.Add("mango", "망고");
            ht.Add("peach", "복숭아");


            ht["apple"] = "부사";//있으면 덮어쓰기,키값 하나당 값 하나
            Console.WriteLine(ht["apple"]);

            ht["pineapple"] = "파인애플";//Add랑 같음
            Console.WriteLine(ht["pineapple"]);

            Console.WriteLine("해쉬테이블 데이터 차례대로 출력하기");
            foreach (String key in ht.Keys)
            {
                Console.WriteLine("키:{0} 값:{1}", key, ht[key]);
            }

            Console.WriteLine("검색");
            String mykey = Console.ReadLine();

            if (ht.Contains(mykey))
            {
                Console.WriteLine(ht[mykey]);
            }
            else
            {
                Console.WriteLine(mykey + "는 존재하지 않습니다");
            }
        }
    public static void Main(string[] args)
    {
        string fileName1, fileName2;

        if (args.Length < 2)
        {
            Console.Write("First file to merge and sort? ");
            fileName1 = Console.ReadLine();

            Console.Write("Second file to merge and sort? ");
            fileName2 = Console.ReadLine();
        }
        else
        {
            fileName1 = args[0];
            fileName2 = args[1];
        }

        if (!File.Exists(fileName1) || !File.Exists(fileName2))
        {
            Console.WriteLine("One of the files doesn't exist");
        }
        else
        {
            try
            {
                StreamReader file1     = File.OpenText(fileName1);
                StreamReader file2     = File.OpenText(fileName2);
                ArrayList    sentences = new ArrayList();
                string       line;

                do
                {
                    line = file1.ReadLine();
                    if (line != null)
                    {
                        sentences.Add(line);
                    }
                }while (line != null);
                file1.Close();

                do
                {
                    line = file2.ReadLine();
                    if (line != null)
                    {
                        sentences.Add(line);
                    }
                }while (line != null);
                file2.Close();

                sentences.Sort();

                foreach (string word in sentences)
                {
                    Console.WriteLine(word);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
        static void Main(string[] args)
        {
            Rectangle rect   = new Rectangle(1, 9);
            Square    square = new Square(9);
            Circle    circle = new Circle(7);

            Console.WriteLine("ArrayList");
            ArrayList AL = new ArrayList();

            AL.Add(circle);
            AL.Add(rect);
            AL.Add(square);

            foreach (var x in AL)
            {
                Console.WriteLine(x);
            }
            Console.WriteLine("\nArrayList - сортировка");
            AL.Sort();
            foreach (var x in AL)
            {
                Console.WriteLine(x);
            }

            Console.WriteLine("\nList<GeometricFigure>");
            List <GeometricFigure> L = new List <GeometricFigure>();

            L.Add(circle);
            L.Add(rect);
            L.Add(square);

            foreach (var x in L)
            {
                Console.WriteLine(x);
            }
            Console.WriteLine("\nList<GeometricFigure> - сортировка");
            L.Sort();
            foreach (var x in AL)
            {
                Console.WriteLine(x);
            }

            Console.WriteLine("\nМатрица");
            Matrix 3D < GeometricFigure > MATRIX = newMatrix 3D < GeometricFigure > (3, 3, 3, null);
            MATRIX[0, 0, 0] = rect;
            MATRIX[1, 1, 1] = square;
            MATRIX[2, 2, 2] = circle;
            Console.WriteLine(MATRIX.ToString());

            Console.WriteLine("\nСписок");
            SimpleList <GeometricFigure> list = new SimpleList <GeometricFigure>();

            list.Add(square);
            list.Add(rect);
            list.Add(circle);
            foreach (var x in list)
            {
                Console.WriteLine(x);
            }
            list.Sort();
            Console.WriteLine("\nСортировкасписка");
            foreach (var x in list)
            {
                Console.WriteLine(x);
            }

            Console.WriteLine("\nСтек");
            SimpleStack <GeometricFigure> stack = new SimpleStack <GeometricFigure>();

            stack.Push(rect);
            stack.Push(square);
            stack.Push(circle);
            while (stack.Count > 0)
            {
                GeometricFigure f = stack.Pop();
                Console.WriteLine(f);
            }

            Console.ReadLine();
        }
Example #59
0
        public static void DisplayTo(bool success, Mobile from, int type)
        {
            if (!success)
            {
                from.SendLocalizedMessage(1018092);                 // You see no evidence of those in the area.
                return;
            }

            Map map = from.Map;

            if (map == null)
            {
                return;
            }

            TrackTypeDelegate check = m_Delegates[type];

            from.CheckSkill(SkillName.Tracking, 0, 21.1);

            int range = 10 + (int)(from.Skills[SkillName.Tracking].Value / 10);

            // Adam: 5/29/10 - triple tracking range.
            // Adam: 9/19/04 - Return tracking to it's original distance.
            // Pixie: 9/11/04 - increase tracking range (double it)
            if (Core.UOAI || Core.UOAR || Core.UOMO)
            {
                range *= 3;
            }

            ArrayList list = new ArrayList();

            IPooledEnumerable eable = from.GetMobilesInRange(range);

            foreach (Mobile m in eable)
            {
                if (Core.UOSP)
                {
                    #region NEW SIEGE CODE
                    // Ghosts can no longer be tracked
                    if (m != from && (!Core.AOS || m.Alive) && (!m.Hidden || m.AccessLevel == AccessLevel.Player || from.AccessLevel > m.AccessLevel) && check(m) && CheckDifficulty(from, m))
                    {
                        list.Add(m);
                    }
                    #endregion
                }
                else
                {
                    #region OLD AI CODE
                    if (m != from && (!m.Hidden || m.AccessLevel == AccessLevel.Player || from.AccessLevel > m.AccessLevel) && check(m))
                    {
                        // At this point, we have a list of all mobiles in range, whether hidden or not.
                        // Now we check to see if the current mobile, m, is a player.
                        if (!m.Player)
                        {
                            list.Add(m);
                        }
                        else
                        {
                            bool TRACKINGSKILLDEBUG = (from.AccessLevel > AccessLevel.Player);

                            double Tracking  = from.Skills[SkillName.Tracking].Value;
                            double Forensics = from.Skills[SkillName.Forensics].Value;
                            double Hiding    = m.Skills[SkillName.Hiding].Value;
                            double Stealth   = m.Skills[SkillName.Stealth].Value;

                            double trackersSkill = Tracking;
                            double targetSkill   = Stealth;

                            double chance = 0;
                            if (targetSkill == 0)                             // if target's stealth is 0, start with a base of 100%
                            {
                                chance = 1;
                            }
                            else                             // chance is tracking/stealth*2 (giving 50% at equal levels)
                            {
                                chance = trackersSkill / (targetSkill * 2);
                            }

                            //Special case - if tracking is < 20 and hiding >= 80,
                            // make sure there's difficulty in tracking
                            if (from.Skills[SkillName.Tracking].Base < 20.0 &&
                                m.Skills[SkillName.Hiding].Base >= 80.0)
                            {
                                if (TRACKINGSKILLDEBUG)
                                {
                                    from.SendMessage(string.Format("Changing chance to track {0} from {1} because tracker is below 20.0 base tracking", m.Name, chance));
                                }

                                chance = 0;
                            }

                            //if tracker can see the other, it's much
                            //easier to track them
                            if (from.CanSee(m))
                            {
                                if (TRACKINGSKILLDEBUG)
                                {
                                    from.SendMessage(string.Format("Changing chance to track {0} from {1} because he can be seen", m.Name, chance));
                                }

                                double newchance = Tracking / 25.0;                     //25 tracking == 100% success when visible
                                if (newchance > chance)                                 // make sure we're not killing their chances
                                {
                                    chance = newchance;
                                }
                            }

                            // add bonus for fonensics (10% at GM forensics)
                            chance += Forensics / 1000;

                            // make sure there's always a small chance to
                            // succeed and a small chance to fail
                            if (chance <= 0)
                            {
                                chance = 0.001;                                 // minimum .1% (1/1000) chance
                            }
                            if (chance >= 1.0)
                            {
                                chance = 0.999;                                 // maximum 99.9% chance
                            }

                            if (TRACKINGSKILLDEBUG)
                            {
                                from.SendMessage(
                                    string.Format("Your chance to track {0} is {1}.  T:{2:0.00} F:{3:0.00} S:{4:0.00} H{5:0.00}",
                                                  m.Name, chance, Tracking, Forensics, Stealth, Hiding)
                                    );
                            }

                            // Check Skill takes two arguments, the skill to check, and the chance to succeed.
                            bool succeeded = from.CheckSkill(SkillName.Tracking, chance);

                            // If our skill check succeeds, add the mobile to the list.
                            if (succeeded)
                            {
                                //Can't track > Player level
                                if (m.AccessLevel <= AccessLevel.Player)
                                {
                                    list.Add(m);
                                }
                            }
                        }
                    }

                    #endregion
                }
            }
            eable.Free();

            if (list.Count > 0)
            {
                list.Sort(new InternalSorter(from));

                from.SendGump(new TrackWhoGump(from, list, range));
                from.SendLocalizedMessage(1018093);                 // Select the one you would like to track.
            }
            else
            {
                if (type == 0)
                {
                    from.SendLocalizedMessage(502991);                     // You see no evidence of animals in the area.
                }
                else if (type == 1)
                {
                    from.SendLocalizedMessage(502993);                     // You see no evidence of creatures in the area.
                }
                else
                {
                    from.SendLocalizedMessage(502995);                     // You see no evidence of people in the area.
                }
            }
        }
Example #60
0
    /**
     * Retrieves a list of IDs for recommended opportunities for a given user. Opportunities are
     * returned, sorted in order from most-impactful to least-impactful on the user's two
     * weakest dimensions (so if a user's weakest dimensions are GA and SCIC, the earliest
     * results will be the opportunities with the highest reward for those dimensions). Only
     * searches through the first 500 opportunities or so; this can be adjusted pretty easily.
     */
    public static ArrayList get_recommended_opportunities(string username, string password)
    {
        const int MAX_RETURNED_OPPORTUNITIES = 500;

        // setup
        ArrayList result = new ArrayList();

        if (!checkInfo(username, password))             // make sure we're the right user
        {
            return(result);
        }
        Student user  = Database.get_student(username);
        Date    today = Date.get_today();

        // figure out which dimension we're looking to increase
        bool IA   = false;
        bool GA   = false;
        bool WB   = false;
        bool SCIC = false;
        bool PPE  = false;

        // get our current dimension scores
        ArrayList dimensions = new ArrayList();

        dimensions.Add(new DictionaryEntry(user.score.GA, "GA"));
        dimensions.Add(new DictionaryEntry(user.score.WB, "WB"));
        dimensions.Add(new DictionaryEntry(user.score.SCIC, "SCIC"));
        dimensions.Add(new DictionaryEntry(user.score.IA, "IA"));
        dimensions.Add(new DictionaryEntry(user.score.PPE, "PPE"));

        // sort by score - the first two (smallest!) dimensions are what we're trying to increase
        dimensions.Sort(new DictionarySort());
        for (int j = 0; j < 2; j++)
        {
            string dimension = (string)((DictionaryEntry)dimensions [j]).Value;
            if (dimension == "GA")
            {
                GA = true;
            }
            if (dimension == "WB")
            {
                WB = true;
            }
            if (dimension == "SCIC")
            {
                SCIC = true;
            }
            if (dimension == "IA")
            {
                IA = true;
            }
            if (dimension == "PPE")
            {
                PPE = true;
            }
        }

        // iterate through first 500? opportunities
        int i = 0;

        foreach (DictionaryEntry pair in Database.opportunityHash)
        {
            Opportunity op = (Opportunity)pair.Value;
            // skip opportunities we've already done or that are expired
            if (user.opportunity_history.Contains(pair.Key) ||
                today > op.end_date)
            {
                // do nothing
            }
            else
            {
                // store each valid opportunity along with it's score for the two
                // dimensions we're looking at
                Score s = op.get_base_score();
                int   score_multiplier = (int)op.engagement * (int)op.length;
                s *= score_multiplier;
                int op_value = 0;
                if (GA)
                {
                    op_value += s.GA;
                }
                if (WB)
                {
                    op_value += s.WB;
                }
                if (IA)
                {
                    op_value += s.IA;
                }
                if (SCIC)
                {
                    op_value += s.SCIC;
                }
                if (PPE)
                {
                    op_value += s.PPE;
                }
                result.Add(new DictionaryEntry(op_value, op.opportunityID));
            }
            // exit after the max num of entries
            if (i++ > MAX_RETURNED_OPPORTUNITIES)
            {
                break;
            }
        }
        // sort our result by their stored scores: earlier entires will offer better
        // rewards in the desired dimensions
        result.Sort(new ReverseDictionarySort());

        // strip out all of the score values; we just need IDs
        for (i = 0; i < result.Count; i++)
        {
            result [i] = ((DictionaryEntry)result [i]).Value;
        }
        return(result);
    }