public int FindColumn(string name)
        {
            int cc = ColumnCount();
            PyString stringName = new PyString(name);

            for (int i = 0; i < cc; i++)
            {
                if (stringName == columnList.Items[i])
                {
                    return i;
                }
            }

            return cc;
        }
Пример #2
0
        public void IsStringTrue()
        {
            var t = new PyString("foo");

            Assert.True(PyString.IsStringType(t));
        }
Пример #3
0
        /// <summary>
        /// Get the pandas.DataFrame of the current <see cref="PandasData"/> state
        /// </summary>
        /// <param name="levels">Number of levels of the multi index</param>
        /// <returns>pandas.DataFrame object</returns>
        public PyObject ToPandasDataFrame(int levels = 2)
        {
            var empty = new PyString(string.Empty);
            var list  = Enumerable.Repeat <PyObject>(empty, 5).ToList();

            list[3] = _symbol.ID.ToString().ToPython();

            if (_symbol.SecurityType == SecurityType.Future)
            {
                list[0] = _symbol.ID.Date.ToPython();
                list[3] = _symbol.ID.ToString().ToPython();
            }
            if (_symbol.SecurityType == SecurityType.Option)
            {
                list[0] = _symbol.ID.Date.ToPython();
                list[1] = _symbol.ID.StrikePrice.ToPython();
                list[2] = _symbol.ID.OptionRight.ToString().ToPython();
                list[3] = _symbol.ID.ToString().ToPython();
            }

            // Create the index labels
            var names = "expiry,strike,type,symbol,time";

            if (levels == 2)
            {
                names = "symbol,time";
                list.RemoveRange(0, 3);
            }
            if (levels == 3)
            {
                names = "expiry,symbol,time";
                list.RemoveRange(1, 2);
            }

            Func <object, bool> filter = x =>
            {
                var isNaNOrZero        = x is double && ((double)x).IsNaNOrZero();
                var isNullOrWhiteSpace = x is string && string.IsNullOrWhiteSpace((string)x);
                var isFalse            = x is bool && !(bool)x;
                return(x == null || isNaNOrZero || isNullOrWhiteSpace || isFalse);
            };
            Func <DateTime, PyTuple> selector = x =>
            {
                list[list.Count - 1] = x.ToPython();
                return(new PyTuple(list.ToArray()));
            };
            // creating the pandas MultiIndex is expensive so we keep a cash
            var indexCache = new Dictionary <List <DateTime>, dynamic>(new ListComparer <DateTime>());

            using (Py.GIL())
            {
                // Returns a dictionary keyed by column name where values are pandas.Series objects
                var pyDict     = new PyDict();
                var splitNames = names.Split(',');
                foreach (var kvp in _series)
                {
                    var values = kvp.Value.Item2;
                    if (values.All(filter))
                    {
                        continue;
                    }

                    dynamic index;
                    if (!indexCache.TryGetValue(kvp.Value.Item1, out index))
                    {
                        var tuples = kvp.Value.Item1.Select(selector).ToArray();
                        index = _pandas.MultiIndex.from_tuples(tuples, names: splitNames);
                        indexCache[kvp.Value.Item1] = index;
                    }

                    pyDict.SetItem(kvp.Key, _pandas.Series(values, index));
                }
                _series.Clear();
                return(ApplySymbolMapper(_pandas.DataFrame(pyDict)));
            }
        }
Пример #4
0
        public PyDataType SendMessage(PyDataType channel, PyString message, CallInformation call)
        {
            int callerCharacterID = call.Client.EnsureCharacterIsSelected();

            int    channelID;
            int?   entityID;
            string channelType;

            try
            {
                this.ParseChannelIdentifier(channel, out channelID, out channelType, out entityID);
            }
            catch (InvalidDataException)
            {
                throw new LSCCannotSendMessage("Cannot get channel information");
            }

            // ensure the player is allowed to chat in there
            if (channelType == ChatDB.CHANNEL_TYPE_NORMAL && this.DB.IsPlayerAllowedToChat(channelID, callerCharacterID) == false)
            {
                throw new LSCCannotSendMessage("Insufficient permissions");
            }
            if (channelType != ChatDB.CHANNEL_TYPE_NORMAL && this.DB.IsPlayerAllowedToChatOnRelatedEntity((int)entityID, callerCharacterID) == false)
            {
                throw new LSCCannotSendMessage("Insufficient permissions");
            }

            PyTuple notificationBody = new PyTuple(1)
            {
                [0] = message
            };

            if (channelType == ChatDB.CHANNEL_TYPE_NORMAL)
            {
                PyDataType notification =
                    GenerateLSCNotification("SendMessage", channelID, notificationBody, call.Client);

                call.Client.ClusterConnection.SendNotification(
                    "OnLSC",
                    "charid",
                    this.DB.GetOnlineCharsOnChannel(channelID),
                    notification
                    );
            }
            else
            {
                PyTuple identifier = new PyTuple(1)
                {
                    [0] = new PyTuple(2)
                    {
                        [0] = channelType,
                        [1] = entityID
                    }
                };

                PyDataType notification =
                    GenerateLSCNotification("SendMessage", identifier, notificationBody, call.Client);

                call.Client.ClusterConnection.SendNotification(
                    "OnLSC",
                    channelType,
                    new PyDataType [] { entityID },
                    notification
                    );
            }

            return(null);
        }
Пример #5
0
        /// <summary>
        /// Get the pandas.Series of the current <see cref="PandasData"/> state
        /// </summary>
        /// <param name="pandas">pandas module</param>
        /// <param name="levels">Number of levels of the multi index</param>
        /// <returns>Dictionary keyed by column name where values are pandas.Series objects</returns>
        private Dictionary <string, dynamic> GetPandasSeries(dynamic pandas, int levels = 2)
        {
            var pyObjectArray = new PyObject[levels];

            pyObjectArray[levels - 2] = _symbol.ToString().ToPython();

            if (_symbol.SecurityType == SecurityType.Future)
            {
                pyObjectArray[0] = _symbol.ID.Date.ToPython();
                pyObjectArray[1] = _symbol.Value.ToPython();
            }
            if (_symbol.SecurityType == SecurityType.Option)
            {
                pyObjectArray[0] = _symbol.ID.Date.ToPython();
                pyObjectArray[1] = _symbol.ID.StrikePrice.ToPython();
                pyObjectArray[2] = _symbol.ID.OptionRight.ToString().ToPython();
                pyObjectArray[3] = _symbol.Value.ToPython();
            }

            // Set null to python empty string
            for (var i = 0; i < levels - 1; i++)
            {
                if (pyObjectArray[i] == null)
                {
                    pyObjectArray[i] = new PyString(string.Empty);
                }
            }

            // Create the index labels
            var names = "symbol,time";

            if (levels == 3)
            {
                names = "expiry,symbol,time";
            }
            if (levels == 5)
            {
                names = "expiry,strike,type,symbol,time";
            }

            using (Py.GIL())
            {
                // Create a pandas multi index
                var tuples = _timeIndex.Select(x =>
                {
                    pyObjectArray[levels - 1] = x.ToPython();
                    return(new PyTuple(pyObjectArray));
                }).ToArray();

                var index = pandas.MultiIndex.from_tuples(tuples, names: names.Split(','));

                // Returns a dictionary keyed by column name where values are pandas.Series objects
                var pandasSeries = new Dictionary <string, dynamic>();
                foreach (var kvp in _series)
                {
                    if (kvp.Value.Count != tuples.Length)
                    {
                        continue;
                    }
                    pandasSeries.Add(kvp.Key, pandas.Series(kvp.Value, index));
                }
                return(pandasSeries);
            }
        }
Пример #6
0
        /*
         * [PyObjectEx Type1]
         *   header:
         *     [PyToken "blue.DBRowDescriptor"]
         *     [PyTuple 1]
         *       [PyTuple columns.Count]
         *         columns as
         *           [PyTuple 2]
         *             [PyString "columnName"]
         *             [PyInt columnDBType]
         *     [PyList] (optional)
         *       keywords
         * create with: new DBRowDescriptor();
         */
        public DBRowDescriptor(PyTuple header)
            : base()
        {
            if (header == null)
            {
                throw new InvalidDataException("DBRowDescriptor: null header.");
            }
            if (header.Items.Count < 2)
            {
                throw new InvalidDataException("DBRowDescriptor: Wrong tuple size expected 2 got " + header.Items.Count);
            }
            if (header.Items.Count == 3 && header.Items[2] is PyList)
            {
                keywords = header.Items[2] as PyList;
            }
            PyTuple tuple = header.Items[1] as PyTuple;

            if (tuple == null)
            {
                throw new InvalidDataException("DBRowDescriptor: null tuple.");
            }
            if (tuple.Items.Count > 1)
            {
                throw new InvalidDataException("DBRowDescriptor: Wrong tuple size expected 1 got" + tuple.Items.Count);
            }
            PyTuple columns = tuple.Items[0] as PyTuple;

            if (columns == null)
            {
                throw new InvalidDataException("DBRowDescriptor: no columns.");
            }

            int columnCount = columns.Items.Count;

            if (keywords != null)
            {
                columnCount += keywords.Items.Count;
            }
            Columns = new List <Column>(columnCount);

            foreach (var obj in columns.Items)
            {
                PyTuple entry = obj as PyTuple;
                if (entry == null || entry.Items.Count < 2)
                {
                    continue;
                }
                PyString name = entry.Items[0] as PyString;
                if (name == null)
                {
                    continue;
                }

                Columns.Add(new Column(name.Value, (FieldType)entry.Items[1].IntValue));
            }
            if (keywords != null)
            {
                foreach (var obj in keywords.Items)
                {
                    PyTuple entry = obj as PyTuple;
                    if (entry == null || entry.Items.Count < 2)
                    {
                        continue;
                    }
                    PyString name = entry.Items[0] as PyString;
                    if (name == null)
                    {
                        continue;
                    }
                    PyToken token = entry.Items[1] as PyToken;
                    if (token == null)
                    {
                        continue;
                    }

                    Columns.Add(new Column(name.Value, token.Token));
                }
            }
        }
Пример #7
0
        public PyDataType GetMultiAllianceShortNamesEx(PyList <PyInteger> ids)
        {
            MySqlConnection connection = null;
            MySqlDataReader reader     = Database.PrepareQuery(ref connection,
                                                               $"SELECT allianceID, shortName FROM alliance_shortnames WHERE allianceID IN ({PyString.Join(',', ids)}"
                                                               ).ExecuteReader();

            using (connection)
                using (reader)
                {
                    return(TupleSet.FromMySqlDataReader(Database, reader));
                }
        }
Пример #8
0
 public static bool IsString(this PyObject obj)
 {
     return(PyString.IsStringType(obj));
 }
 public void HighPosMinLowPosMaxNegStep()
 {
     PyString ps = new PyString("swords");
     Assert.That(ps[5, 1, -2], Is.EqualTo("sr"));
 }
Пример #10
0
        public void TestIsLongTypeFalse()
        {
            var s = new PyString("Foo");

            Assert.False(PyLong.IsLongType(s));
        }
Пример #11
0
        public override void Create(Stream output, IEnumerable <Entry> list, ResourceOptions options,
                                    EntryCallback callback)
        {
            var  rpa_options    = GetOptions <RpaOptions> (options);
            int  callback_count = 0;
            var  file_table     = new Dictionary <PyString, ArrayList>();
            long data_offset    = 0x22;

            output.Position = data_offset;
            foreach (var entry in list)
            {
                if (null != callback)
                {
                    callback(callback_count++, entry, arcStrings.MsgAddingFile);
                }

                string name      = entry.Name.Replace(@"\", "/");
                var    rpa_entry = new RpaEntry {
                    Name = name
                };
                using (var file = File.OpenRead(entry.Name))
                {
                    var size = file.Length;
                    if (size > uint.MaxValue)
                    {
                        throw new FileSizeException();
                    }
                    int header_size = (int)Math.Min(size, 0x10);
                    rpa_entry.Offset       = output.Position ^ rpa_options.Key;
                    rpa_entry.Header       = new byte[header_size];
                    rpa_entry.UnpackedSize = (uint)size ^ rpa_options.Key;
                    rpa_entry.Size         = (uint)(size - header_size);
                    file.Read(rpa_entry.Header, 0, header_size);
                    file.CopyTo(output);
                }
                var py_name = new PyString(name);
                if (file_table.ContainsKey(py_name))
                {
                    file_table[py_name].Add(rpa_entry);
                }
                else
                {
                    file_table[py_name] = new ArrayList {
                        rpa_entry
                    }
                };
            }
            long   index_pos = output.Position;
            string signature = string.Format(CultureInfo.InvariantCulture, "RPA-3.0 {0:x16} {1:x8}\n",
                                             index_pos, rpa_options.Key);
            var header = Encoding.ASCII.GetBytes(signature);

            if (header.Length > data_offset)
            {
                throw new ApplicationException("Signature serialization failed.");
            }

            if (null != callback)
            {
                callback(callback_count++, null, arcStrings.MsgWritingIndex);
            }

            using (var index = new ZLibStream(output, CompressionMode.Compress, CompressionLevel.Level9, true))
            {
                var pickle = new Pickle(index);
                if (!pickle.Dump(file_table))
                {
                    throw new ApplicationException("Archive index serialization failed.");
                }
            }
            output.Position = 0;
            output.Write(header, 0, header.Length);
        }
    }
Пример #12
0
        public PyDataType SendClientStackTraceAlert(PyTuple stackInfo, PyString stackTrace, PyString type, PyDictionary namedPayload, Client client)
        {
            Log.Fatal(
                "Received the following client's stack trace:" + Environment.NewLine +
                $"------------------ {type.Value} ------------------" + Environment.NewLine +
                $"{(stackInfo[1] as PyString).Value}" + Environment.NewLine +
                stackTrace.Value
                );

            // The client should receive anything to know that the stack trace arrived to the server
            return(new PyNone());
        }
Пример #13
0
 /// <summary>
 /// Create a new Python exception based on a PyString message
 /// </summary>
 /// <param name="message">The exception message as a PyString</param>
 public PyException(PyString message) : this(message.InternalValue)
 {
 }
Пример #14
0
 private PyObject __init__impl(PyException self, PyString message)
 {
     return(__init__impl(self, message.InternalValue));
 }
Пример #15
0
        /// <summary>
        /// Creates a PyDataType of the given column (specified by <paramref name="index"/>) based off the given
        /// MySqlDataReader
        /// </summary>
        /// <param name="reader">Reader to get the data from</param>
        /// <param name="index">Column of the current result read in the MySqlDataReader to create the PyDataType</param>
        /// <returns></returns>
        /// <exception cref="InvalidDataException">If any error was found during the creation of the PyDataType</exception>
        public static PyDataType ObjectFromColumn(MySqlDataReader reader, int index)
        {
            Type       type   = reader.GetFieldType(index);
            PyDataType data   = null;
            bool       isnull = reader.IsDBNull(index);

            if (type == typeof(string))
            {
                data = new PyString((isnull) ? "" : reader.GetString(index), true);
            }
            else if (type == typeof(ulong))
            {
                data = (isnull) ? 0 : reader.GetUInt64(index);
            }
            else if (type == typeof(long))
            {
                data = (isnull) ? 0 : reader.GetInt64(index);
            }
            else if (type == typeof(uint))
            {
                data = (isnull) ? 0 : reader.GetUInt32(index);
            }
            else if (type == typeof(int))
            {
                data = (isnull) ? 0 : reader.GetInt32(index);
            }
            else if (type == typeof(ushort))
            {
                data = (isnull) ? 0 : reader.GetUInt16(index);
            }
            else if (type == typeof(short))
            {
                data = (isnull) ? 0 : reader.GetInt16(index);
            }
            else if (type == typeof(byte))
            {
                data = (isnull) ? 0 : reader.GetByte(index);
            }
            else if (type == typeof(sbyte))
            {
                data = (isnull) ? 0 : reader.GetSByte(index);
            }
            else if (type == typeof(byte[]))
            {
                data = (isnull) ? new byte[0] : (byte[])reader.GetValue(index);
            }
            else if (type == typeof(float))
            {
                data = (isnull) ? 0 : reader.GetFloat(index);
            }
            else if (type == typeof(double))
            {
                data = (isnull) ? 0 : reader.GetDouble(index);
            }
            else if (type == typeof(bool))
            {
                data = (!isnull) && reader.GetBoolean(index);
            }
            else
            {
                throw new InvalidDataException($"Unknown data type {type}");
            }

            return(data);
        }
        public void IsFloatFalse()
        {
            var i = new PyString("Foo");

            Assert.False(PyFloat.IsFloatType(i));
        }
Пример #17
0
        public PyDataType SetPlayerStanding(PyInteger characterID, PyDecimal standing, PyString reason, CallInformation call)
        {
            int callerCharacterID = call.Client.EnsureCharacterIsSelected();

            this.DB.CreateStandingTransaction((int)StandingEventType.StandingPlayerSetStanding, callerCharacterID, characterID, standing, reason);
            this.DB.SetPlayerStanding(callerCharacterID, characterID, standing);

            // send standing change notification to the player
            PyTuple notification = new PyTuple(3)
            {
                [0] = callerCharacterID,
                [1] = characterID,
                [2] = standing
            };

            // send the same notification to both players
            call.Client.ClusterConnection.SendNotification("OnStandingSet", "charid", callerCharacterID, call.Client, notification);
            call.Client.ClusterConnection.SendNotification("OnStandingSet", "charid", characterID, notification);

            return(null);
        }
 public void LowPosMinHighPosMax()
 {
     PyString ps = new PyString("words");
     Assert.That(ps[1, 3], Is.EqualTo("or"));
 }
Пример #19
0
        public async Task <FutureAwaiter <PyInteger> > dialog_wrapper(IInterpreter interpreter, IScheduler scheduler, FrameContext context, PyString message, PyList choices)
        {
            var choicesStr = new string[choices.list.Count];

            for (int i = 0; i < choices.list.Count; ++i)
            {
                var iPyStr = (PyString)choices.list[i];
                choicesStr[i] = iPyStr.str;
            }
            ShowDialogs(choicesStr);

            // Prep the integer since we have all the things we need to invoke the constructor right here.
            choicePyInt = (PyInteger)await PyIntegerClass.Instance.Call(interpreter, context, new object[0]);

            dialogFuture = new FutureAwaiter <PyInteger>(scheduler, context);

            scheduler.NotifyBlocked(context, dialogFuture);
            //dialogFuture.SetResult(choicePyInt);
            await dialogFuture;

            return(dialogFuture);
        }
 public void NegIndex()
 {
     PyString ps = new PyString("words");
     Assert.That(ps[-5], Is.EqualTo("w"));
 }
Пример #21
0
        public PyDataType SendClientStackTraceAlert(PyTuple stackInfo, PyString stackTrace, PyString type, PyDataType extra = null, CallInformation call = null)
        {
            Log.Fatal(
                "Received the following client's stack trace:" + Environment.NewLine +
                $"------------------ {type.Value} ------------------" + Environment.NewLine +
                $"{(stackInfo[1] as PyString).Value}" + Environment.NewLine +
                stackTrace.Value
                );

            // the client should receive anything to know that the stack trace arrived to the server
            return(null);
        }
 public void NegMinNullMax()
 {
     PyString ps = new PyString("words");
     Assert.That(ps[-4, null], Is.EqualTo("ords"));
 }
Пример #23
0
        public PyDataType BookmarkLocation(PyInteger itemID, PyNone unk, PyString name, PyString comment, CallInformation call)
        {
            if (ItemManager.IsStaticData(itemID) == false)
            {
                throw new CustomError("Bookmarks for non-static locations are not supported yet!");
            }

            ItemEntity item = this.ItemManager.GetItem(itemID);

            if (item.HasPosition == false)
            {
                throw new CustomError("Cannot bookmark a non-location item");
            }

            ulong bookmarkID = this.DB.CreateBookmark(call.Client.EnsureCharacterIsSelected(), item.ID, item.Type.ID,
                                                      name, comment, (double)item.X, (double)item.Y, (double)item.Z, item.LocationID);

            PyDataType bookmark = KeyVal.FromDictionary(new PyDictionary
            {
                ["bookmarkID"] = bookmarkID,
                ["itemID"]     = item.ID,
                ["typeID"]     = item.Type.ID,
                ["memo"]       = name,
                ["comment"]    = comment,
                ["x"]          = item.X,
                ["y"]          = item.Y,
                ["z"]          = item.Z,
                ["locationID"] = item.LocationID,
                ["created"]    = DateTime.UtcNow.ToFileTimeUtc()
            }
                                                        );

            // send a request to the client to update the bookmarks
            call.Client.ClusterConnection.SendServiceCall(call.Client, "addressbook", "OnBookmarkAdd",
                                                          new PyTuple(1)
            {
                [0] = bookmark
            }, new PyDictionary(), null, null, null, 0);

            return(new PyTuple(7)
            {
                [0] = bookmarkID,     // bookmarkID
                [1] = itemID,         // itemID
                [2] = item.Type.ID,   // typeID
                [3] = item.X,         // x
                [4] = item.Y,         // y
                [5] = item.Z,         // z
                [6] = item.LocationID //locationID
            });
        }
 public void NegMinNullMaxNegStep()
 {
     PyString ps = new PyString("swords");
     Assert.That(ps[-3, null, -1], Is.EqualTo("rows"));
 }
Пример #25
0
        public void TestStringIsListType()
        {
            var s = new PyString("foo");

            Assert.False(PyList.IsListType(s));
        }
 public void NegMinNullMaxPosStep()
 {
     PyString ps = new PyString("words");
     Assert.That(ps[-2, null, 1], Is.EqualTo("ds"));
 }
Пример #27
0
        public PyDataType Invite(PyInteger characterID, PyInteger channelID, PyString channelTitle, PyBool addAllowed, CallInformation call)
        {
            int callerCharacterID = call.Client.EnsureCharacterIsSelected();

            try
            {
                if (characterID == callerCharacterID)
                {
                    throw new ChtCannotInviteSelf();
                }

                if (ItemManager.IsNPC(characterID) == true)
                {
                    // NPCs should be loaded, so the character instance can be used willy-nilly
                    Character npcChar = this.ItemManager.GetItem(characterID) as Character;

                    throw new ChtNPC(npcChar.Name);
                }

                // ensure our character has admin perms first
                if (this.DB.IsCharacterOperatorOrAdminOfChannel(channelID, callerCharacterID) == false)
                {
                    throw new ChtWrongRole(this.DB.GetChannelName(channelID), "Operator");
                }

                // ensure the character is not there already
                if (this.DB.IsCharacterMemberOfChannel(channelID, characterID) == true)
                {
                    throw new ChtAlreadyInChannel(this.CharacterDB.GetCharacterName(characterID));
                }

                Character character = this.ItemManager.GetItem(callerCharacterID) as Character;

                PyTuple args = new PyTuple(4)
                {
                    [0] = callerCharacterID,
                    [1] = character.Name,
                    [2] = character.Gender,
                    [3] = channelID
                };

                InviteExtraInfo info = new InviteExtraInfo
                {
                    OriginalCall    = call,
                    Arguments       = args,
                    ChannelID       = channelID,
                    ToCharacterID   = characterID,
                    FromCharacterID = callerCharacterID
                };

                // no timeout for this call
                call.Client.ClusterConnection.SendServiceCall(
                    characterID,
                    "LSC", "ChatInvite", args, new PyDictionary(),
                    InviteAnswerCallback, InviteTimeoutCallback,
                    info, ProvisionalResponse.DEFAULT_TIMEOUT - 5
                    );

                // subscribe the user to the chat
                this.DB.JoinChannel(channelID, characterID);
            }
            catch (ArgumentOutOfRangeException)
            {
                Log.Warning("Trying to invite a non-online character, aborting...");
            }

            // return SOMETHING to the client with the provisional data
            // the real answer will come later on
            throw new ProvisionalResponse(new PyString("OnDummy"), new PyTuple(0));
        }
 public void PosIndex()
 {
     PyString ps = new PyString("words");
     Assert.That(ps[4], Is.EqualTo("s"));
 }
Пример #29
0
 private void ProcessString(PyString str)
 {
     this.mStringBuilder.AppendFormat("[PyString {0} char(s): '{1}']", str.Length, str.Value);
     this.mStringBuilder.AppendLine();
 }
 public void PosMinNullMaxNegStep()
 {
     PyString ps = new PyString("words");
     Assert.That(ps[2, null, -1], Is.EqualTo("row"));
 }
Пример #31
0
        public void IsStringFalse()
        {
            var t = new PyInt(5);

            Assert.False(PyString.IsStringType(t));
        }
 public void PosMinNullMaxPosStep()
 {
     PyString ps = new PyString("swords");
     Assert.That(ps[1, null, 2], Is.EqualTo("wrs"));
 }
Пример #33
0
        /// <summary>
        /// Get the pandas.DataFrame of the current <see cref="PandasData"/> state
        /// </summary>
        /// <param name="levels">Number of levels of the multi index</param>
        /// <returns>pandas.DataFrame object</returns>
        public PyObject ToPandasDataFrame(int levels = 2)
        {
            var empty = new PyString(string.Empty);
            var list  = Enumerable.Repeat <PyObject>(empty, 5).ToList();

            list[3] = _symbol.ID.ToString().ToPython();

            if (_symbol.SecurityType == SecurityType.Future)
            {
                list[0] = _symbol.ID.Date.ToPython();
                list[3] = _symbol.ID.ToString().ToPython();
            }
            if (_symbol.SecurityType.IsOption())
            {
                list[0] = _symbol.ID.Date.ToPython();
                list[1] = _symbol.ID.StrikePrice.ToPython();
                list[2] = _symbol.ID.OptionRight.ToString().ToPython();
                list[3] = _symbol.ID.ToString().ToPython();
            }

            // Create the index labels
            var names = "expiry,strike,type,symbol,time";

            if (levels == 2)
            {
                names = "symbol,time";
                list.RemoveRange(0, 3);
            }
            if (levels == 3)
            {
                names = "expiry,symbol,time";
                list.RemoveRange(1, 2);
            }

            Func <object, bool> filter = x =>
            {
                var isNaNOrZero        = x is double && ((double)x).IsNaNOrZero();
                var isNullOrWhiteSpace = x is string && string.IsNullOrWhiteSpace((string)x);
                var isFalse            = x is bool && !(bool)x;
                return(x == null || isNaNOrZero || isNullOrWhiteSpace || isFalse);
            };
            Func <DateTime, PyTuple> selector = x =>
            {
                list[list.Count - 1] = x.ToPython();
                return(new PyTuple(list.ToArray()));
            };
            // creating the pandas MultiIndex is expensive so we keep a cash
            var indexCache = new Dictionary <List <DateTime>, dynamic>(new ListComparer <DateTime>());

            using (Py.GIL())
            {
                // Returns a dictionary keyed by column name where values are pandas.Series objects
                var pyDict     = new PyDict();
                var splitNames = names.Split(',');
                foreach (var kvp in _series)
                {
                    var values = kvp.Value.Item2;
                    if (values.All(filter))
                    {
                        continue;
                    }

                    dynamic index;
                    if (!indexCache.TryGetValue(kvp.Value.Item1, out index))
                    {
                        var tuples = kvp.Value.Item1.Select(selector).ToArray();
                        index = _pandas.MultiIndex.from_tuples(tuples, names: splitNames);
                        indexCache[kvp.Value.Item1] = index;
                    }

                    // Adds pandas.Series value keyed by the column name
                    // CreateSeries will create an original pandas.Series
                    // We are not using the wrapper class to avoid unnecessary and expensive
                    // index wrapping operations when the Series are packed into a DataFrame
                    pyDict.SetItem(kvp.Key, _pandas.CreateSeries(values, index));
                }
                _series.Clear();

                // Create a DataFrame with wrapper class.
                // This is the starting point. The types of all DataFrame and Series that result from any operation will
                // be wrapper classes. Index and MultiIndex will be converted when required by index operations such as
                // stack, unstack, merge, union, etc.
                return(_pandas.DataFrame(pyDict));
            }
        }
Пример #34
0
        public bool Decode(PyObject data)
        {
            if (data.Type != PyObjectType.ObjectEx)
            {
                Log.Error("PyException", "Wrong container type");
                return(false);
            }

            PyObjectEx p = data.As <PyObjectEx>();

            if (p.IsType2 == true)
            {
                Log.Error("PyException", "Wrong PyObjectEx type, expected Normal, but got Type2");
                return(false);
            }

            if (p.Header.Type != PyObjectType.Tuple)
            {
                Log.Error("PyException", "Wrong item 1 type");
                return(false);
            }

            PyTuple args = p.Header.As <PyTuple>();

            if (args.Items.Count != 3)
            {
                Log.Error("PyException", "Wrong tuple 1 item count, expected 3 but got " + args.Items.Count);
                return(false);
            }

            if (args.Items[0].Type != PyObjectType.Token)
            {
                Log.Error("PyException", "Wrong tuple item 1 type");
                return(false);
            }

            PyToken type = args.Items[0].As <PyToken>();

            exception_type = type.Token;

            if (exception_type.StartsWith("exceptions.") == false)
            {
                Log.Warning("PyException", "Trying to decode a non-exception packet: " + exception_type);
                return(false);
            }

            if (args.Items[1].Type != PyObjectType.Tuple)
            {
                Log.Error("PyException", "Wrong tuple item 2 type");
                return(false);
            }

            PyTuple msg = args.Items[1].As <PyTuple>();

            if (msg.Items.Count != 1)
            {
                Log.Error("PyException", "Wrong item 2 tuple count, expected 1 but got " + msg.Items.Count);
                return(false);
            }

            if (msg.Items[0].Type != PyObjectType.String)
            {
                Log.Error("PyException", "Wrong tuple 2 item 1 type");
                return(false);
            }

            PyString msg_data = msg.Items[0].As <PyString>();

            message = msg_data.Value;

            if (args.Items[2].Type != PyObjectType.Dict)
            {
                Log.Error("PyException", "Wrong tuple 1 item 3 type");
                return(false);
            }

            PyDict info = args.Items[2].As <PyDict>();

            if (info.Contains("origin") == false)
            {
                Log.Error("PyException", "Dict item 1 doesnt has key origin");
                return(false);
            }

            origin = info.Get("origin").As <PyString>().Value;

            if (info.Contains("reasonArgs") == false)
            {
                Log.Error("PyException", "Dict item 1 doesn has key reasonArgs");
                return(false);
            }

            reasonArgs = info.Get("reasonArgs").As <PyDict>();

            if (info.Contains("clock") == false)
            {
                Log.Error("PyException", "Dict item 1 doesnt has key clock");
                return(false);
            }

            clock = info.Get("clock").IntValue;

            if (info.Contains("loggedOnUserCount") == false)
            {
                Log.Error("PyException", "Dict item 1 doesnt has key loggedOnUserCount");
                return(false);
            }

            loggedOnUserCount = info.Get("loggedOnUserCount");

            if (info.Contains("region") == false)
            {
                Log.Error("PyException", "Dict item 1 doesnt has key region");
                return(false);
            }

            region = info.Get("region").As <PyString>().Value;

            if (info.Contains("reason") == false)
            {
                Log.Error("PyException", "Dict item 1 doesnt has key reason");
                return(false);
            }

            reason = info.Get("reason").As <PyString>().Value;

            if (info.Contains("version") == false)
            {
                Log.Error("PyException", "Dict item 1 doesnt has key version");
                return(false);
            }

            version = info.Get("version").As <PyFloat>().Value;

            if (info.Contains("build") == false)
            {
                Log.Error("PyException", "Dict item 1 doesnt has key build");
                return(false);
            }

            build = info.Get("build").As <PyInt>().Value;

            if (info.Contains("reasonCode") == false)
            {
                Log.Error("PyException", "Dict item 1 doesnt has key reasonCode");
                return(false);
            }

            reasonCode = info.Get("reasonCode").StringValue;

            if (info.Contains("codename") == false)
            {
                Log.Error("PyException", "Dict item 1 doesnt has key codename");
                return(false);
            }

            codename = info.Get("codename").As <PyString>().Value;

            if (info.Contains("machoVersion") == false)
            {
                Log.Error("PyException", "Dict item 1 doesnt has key machoVersion");
                return(false);
            }

            machoVersion = info.Get("machoVersion").As <PyInt>().Value;

            return(true);
        }
Пример #35
0
 public PyObjectData(PyString name, PyDataType arguments) : base(PyObjectType.ObjectData)
 {
     this.Name      = name;
     this.Arguments = arguments;
 }
Пример #36
0
 public PyAddressClient(PyInteger clientID, PyInteger callID = null, PyString service = null) : this(clientID)
 {
     this.CallID  = callID;
     this.Service = service;
 }
Пример #37
0
 protected PyAddress(PyString type)
 {
     this.Type = type;
 }
Пример #38
0
        public void TestIsIntTypeFalse()
        {
            var s = new PyString("Foo");

            Assert.False(PyInt.IsIntType(s));
        }
Пример #39
0
 public PyAddressNode(PyInteger nodeID, PyInteger callID = null, PyString service = null) : this(nodeID)
 {
     this.CallID  = callID;
     this.Service = service;
 }
Пример #40
0
        public PyDataType GetMultiLocationsEx(PyList <PyInteger> ids)
        {
            MySqlConnection connection = null;
            MySqlDataReader reader     = Database.PrepareQuery(ref connection,
                                                               $"SELECT itemID as locationID, itemName as locationName, x, y, z FROM invItems LEFT JOIN eveNames USING(itemID) LEFT JOIN invPositions USING (itemID) WHERE itemID IN ({PyString.Join(',', ids)})"
                                                               ).ExecuteReader();

            using (connection)
                using (reader)
                {
                    return(TupleSet.FromMySqlDataReader(Database, reader));
                }
        }