public bool startswith(PythonTuple /*!*/ prefix, int start) { return(_bytes.StartsWith(prefix, start)); }
public override int GetHashCode() { return((PythonTuple.MakeTuple(_bytes.ToArray())).GetHashCode()); }
public PythonFunction(CodeContext context, FunctionCode code, PythonDictionary globals, string name, PythonTuple defaults) : this(context, code, globals, name, defaults, null) { }
/// <summary> /// 用于测试 /// </summary> /// <returns></returns> public static ArrayList test() { ArrayList returnList = new ArrayList(); string serverpath = "D:\\projects\\recommandSystem\\UserCFRecommend.py"; ScriptRuntime pyRuntime = Python.CreateRuntime(); ScriptEngine Engine = pyRuntime.GetEngine("python"); ICollection <string> Paths = Engine.GetSearchPaths(); Paths.Add("D:\\Anaconda2-32\\Lib"); Paths.Add("D:\\Anaconda2-32\\DLLs"); Paths.Add("D:\\Anaconda2-32\\Lib\\site-packages"); ScriptScope pyScope = Engine.CreateScope(); //Engine.ImportModule("pandas"); //Engine.ImportModule("math"); //Engine.ImportModule("pickle"); Engine.SetSearchPaths(Paths); IronPython.Runtime.PythonDictionary pyDic = new IronPython.Runtime.PythonDictionary(); ArrayList A = new ArrayList(); A.Add('a'); A.Add('b'); A.Add('d'); ArrayList B = new ArrayList(); B.Add('a'); B.Add('c'); ArrayList C = new ArrayList(); C.Add('b'); C.Add('e'); ArrayList D = new ArrayList(); D.Add('c'); D.Add('d'); D.Add('e'); pyDic.Add('A', A); pyDic.Add('B', B); pyDic.Add('C', C); pyDic.Add('D', D); dynamic obj = Engine.ExecuteFile(serverpath, pyScope); IronPython.Runtime.List result = obj.recommmend_user_cf('A', pyDic, 3); for (int i = 0; i < result.Count; i++) { IronPython.Runtime.PythonTuple pySet = (IronPython.Runtime.PythonTuple)result.ElementAt(i); Console.WriteLine(pySet.ElementAt(0)); Console.WriteLine(pySet.ElementAt(1)); returnList.Add(pySet.ElementAt(0)); } Console.WriteLine(result); return(returnList); }
/// <summary> /// Gateway into importing ... called from Ops. Performs the initial import of /// a module and returns the module. /// </summary> public static object Import(CodeContext /*!*/ context, string fullName, PythonTuple from, int level) { return(LightExceptions.CheckAndThrow(ImportLightThrow(context, fullName, from, level))); }
/// <summary> /// Return the code object for the module named by 'fullname' from the /// Zip archive as a new reference. /// </summary> /// <param name="context"></param> /// <param name="ispackage"></param> /// <param name="isbytecode"></param> /// <param name="mtime"></param> /// <param name="toc_entry"></param> /// <returns></returns> private string GetCodeFromData(CodeContext /*!*/ context, bool ispackage, bool isbytecode, int mtime, PythonTuple toc_entry) { byte[] data = GetData(_archive, toc_entry); string modpath = (string)toc_entry[0]; string code = null; if (data != null) { if (isbytecode) { // would put in code to unmarshal the bytecode here... } else { code = context.LanguageContext.DefaultEncoding.GetString(data, 0, data.Length); } } return(code); }
private PythonTuple ToTuple() => PythonTuple.MakeTuple(start, stop, step);
public bool startswith(PythonTuple /*!*/ prefix) { lock (this) { return(_bytes.StartsWith(prefix)); } }
public MemoryView cast([NotNull] string format, [NotNull, AllowNull] object shape) { if (!_isCContig) { throw PythonOps.TypeError("memoryview: casts are restricted to C-contiguous views"); } if (_shape.Contains(0) || _strides.Contains(0)) { throw PythonOps.TypeError("memoryview: cannot cast view with zeros in shape or strides"); } PythonTuple?shapeAsTuple = null; if (shape != null) { if (!(shape is PythonList) && !(shape is PythonTuple)) { throw PythonOps.TypeError("shape must be a list or a tuple"); } shapeAsTuple = PythonTuple.Make(shape); int newNDim = shapeAsTuple.Count; if (newNDim > MaximumDimensions) { throw PythonOps.TypeError("memoryview: number of dimensions must not exceed {0}", MaximumDimensions); } if (_numDims != 1 && newNDim != 1) { throw PythonOps.TypeError("memoryview: cast must be 1D -> ND or ND -> 1D"); } } int newItemsize; if (!TypecodeOps.TryGetTypecodeWidth(format, out newItemsize)) { throw PythonOps.ValueError( "memoryview: destination format must be a native single character format prefixed with an optional '@'"); } if (!TypecodeOps.IsByteFormat(this._format) && !TypecodeOps.IsByteFormat(format)) { throw PythonOps.TypeError("memoryview: cannot cast between two non-byte formats"); } if ((_numItems * _itemSize) % newItemsize != 0) { throw PythonOps.TypeError("memoryview: length is not a multiple of itemsize"); } int newLength = _numItems * _itemSize / newItemsize; int[] newShape; if (shapeAsTuple != null) { newShape = new int[shapeAsTuple.Count]; int lengthGivenShape = 1; for (int i = 0; i < shapeAsTuple.Count; i++) { newShape[i] = Converter.ConvertToInt32(shapeAsTuple[i]); lengthGivenShape *= newShape[i]; } if (lengthGivenShape != newLength) { throw PythonOps.TypeError("memoryview: product(shape) * itemsize != buffer size"); } } else { newShape = new int[] { newLength }; } return(new MemoryView(this, format, newItemsize, newShape)); }
private int GetItemOffset(PythonTuple tuple) { int flatIndex = _offset; int tupleLength = tuple.Count; int ndim = (int)this.ndim; int firstOutOfRangeIndex = -1; bool allInts = true; bool allSlices = true; // A few notes about the ordering of operations here: // 0) Before anything else, CPython handles indexing of // 0-dim memory as a special case, the tuple elements // are not checked // 1) CPython checks the types of the objects in the tuple // first, then the dimensions, then finally for the range. // Because we do a range check while we go through the tuple, // we have to remember that we had something out of range // 2) CPython checks for a multislice tuple, then for all ints, // and throws an invalid slice key otherwise. We again try to // do this in one pass, so we remember whether we've seen an int // and whether we've seen a slice if (_numDims == 0) { if (tupleLength != 0) { throw PythonOps.TypeError("invalid indexing of 0-dim memory"); } return(flatIndex); } for (int i = 0; i < tupleLength; i++) { object?indexObject = tuple[i]; if (Converter.TryConvertToInt32(indexObject, out int indexValue)) { allSlices = false; // If we have a "bad" tuple, we no longer care // about the resulting flat index, but still need // to check the rest of the tuple in case it has a // non-int value if (i >= ndim || firstOutOfRangeIndex > -1) { continue; } int dimensionWidth = _shape[i]; // If we have an out of range exception, that will only // be thrown if the tuple length is correct, so we have to // defer throwing to later if (!PythonOps.TryFixIndex(indexValue, dimensionWidth, out indexValue)) { firstOutOfRangeIndex = i; continue; } flatIndex += indexValue * _strides[i]; } else if (indexObject is Slice) { allInts = false; } else { throw PythonOps.TypeError("memoryview: invalid slice key"); } } if (!allInts) { if (allSlices) { throw PythonOps.NotImplementedError("multi-dimensional slicing is not implemented"); } else { throw PythonOps.TypeError("memoryview: invalid slice key"); } } if (tupleLength < ndim) { throw PythonOps.NotImplementedError("sub-views are not implemented"); } if (tupleLength > ndim) { throw PythonOps.TypeError("cannot index {0}-dimension view with {1}-element tuple", ndim, tupleLength); } if (firstOutOfRangeIndex != -1) { PythonOps.IndexError("index out of bounds on dimension {0}", firstOutOfRangeIndex + 1); } return(flatIndex); }
/// <summary> /// Runs the formatting operation on the given format and keyword arguments /// </summary> public static string /*!*/ FormatString(PythonContext /*!*/ context, string /*!*/ format, PythonTuple /*!*/ args, IDictionary <object, object> /*!*/ kwArgs) { ContractUtils.RequiresNotNull(context, "context"); ContractUtils.RequiresNotNull(format, "format"); ContractUtils.RequiresNotNull(args, "args"); ContractUtils.RequiresNotNull(kwArgs, "kwArgs"); return(Formatter.FormatString(context, format, args, kwArgs)); }
public static string /*!*/ FormatString(PythonContext /*!*/ context, string /*!*/ format, PythonTuple /*!*/ args, IDictionary <object, object> /*!*/ kwArgs) { Assert.NotNull(context, args, kwArgs, format); return(new Formatter(context, args, kwArgs).ReplaceText(format)); }
internal static object ImportLightThrow(CodeContext /*!*/ context, string fullName, PythonTuple from, int level) { Debug.Assert(level >= 0); PythonContext pc = context.LanguageContext; var site = pc.ImportSite; return(site.Target( site, context, FindImportFunction(context), fullName, Builtin.globals(context), context.Dict, from, level )); }
public bool endswith(PythonTuple /*!*/ suffix) { lock (this) { return(_bytes.EndsWith(suffix)); } }
/// <summary> /// Return the code object for the module named by 'fullname' from the /// Zip archive as a new reference. /// </summary> /// <param name="context"></param> /// <param name="ispackage"></param> /// <param name="isbytecode"></param> /// <param name="mtime"></param> /// <param name="toc_entry"></param> /// <returns></returns> private byte[] GetCodeFromData(CodeContext /*!*/ context, bool ispackage, bool isbytecode, int mtime, PythonTuple toc_entry) { byte[] data = GetData(context, _archive, toc_entry); string modpath = (string)toc_entry[0]; byte[] code = null; if (data != null) { if (isbytecode) { // would put in code to unmarshal the bytecode here... } else { code = data; } } return(code); }
public bool endswith(PythonTuple /*!*/ suffix, int start, int end) { lock (this) { return(_bytes.EndsWith(suffix, start, end)); } }
public MemoryView cast(object format, [NotNull] object shape) { if (!(format is string formatAsString)) { throw PythonOps.TypeError("memoryview: format argument must be a string"); } if (_step != 1) { throw PythonOps.TypeError("memoryview: casts are restricted to C-contiguous views"); } if ((shape != null || ndim != 0) && this.shape.Contains(0)) { throw PythonOps.TypeError("memoryview: cannot cast view with zeros in shape or strides"); } PythonTuple shapeAsTuple = null; if (shape != null) { if (!(shape is PythonList) && !(shape is PythonTuple)) { throw PythonOps.TypeError("shape must be a list or a tuple"); } shapeAsTuple = PythonOps.MakeTupleFromSequence(shape); int newNDim = shapeAsTuple.Count; if (newNDim > MaximumDimensions) { throw PythonOps.TypeError("memoryview: number of dimensions must not exceed {0}", MaximumDimensions); } if (ndim != 1 && newNDim != 1) { throw PythonOps.TypeError("memoryview: cast must be 1D -> ND or ND -> 1D"); } } int newItemsize; if (!TypecodeOps.TryGetTypecodeWidth(formatAsString, out newItemsize)) { throw PythonOps.ValueError( "memoryview: destination format must be a native single character format prefixed with an optional '@'"); } bool thisIsBytes = this.format == "B" || this.format == "b" || this.format == "c"; bool otherIsBytes = formatAsString == "B" || formatAsString == "b" || formatAsString == "c"; if (!thisIsBytes && !otherIsBytes) { throw PythonOps.TypeError("memoryview: cannot cast between two non-byte formats"); } int length = numberOfElements(); if (length % newItemsize != 0) { throw PythonOps.TypeError("memoryview: length is not a multiple of itemsize"); } int newLength = length * _itemsize / newItemsize; if (shapeAsTuple != null) { int lengthGivenShape = 1; for (int i = 0; i < shapeAsTuple.Count; i++) { lengthGivenShape *= Converter.ConvertToInt32(shapeAsTuple[i]); } if (lengthGivenShape != newLength) { throw PythonOps.TypeError("memoryview: product(shape) * itemsize != buffer size"); } } return(new MemoryView(_buffer, _start, _end, _step, formatAsString, shapeAsTuple ?? PythonOps.MakeTuple(newLength))); }
public bool startswith(PythonTuple /*!*/ prefix, int start, int end) { lock (this) { return(_bytes.StartsWith(prefix, start, end)); } }
internal MemoryView(IBufferProtocol @object, int start, int?end, int step, string format, PythonTuple shape) { _buffer = @object; _format = format; _shape = shape; _start = start; _end = end; _step = step; if (!TypecodeOps.TryGetTypecodeWidth(format, out _itemsize)) { _itemsize = (int)_buffer.ItemSize; } _matchesBuffer = _format == _buffer.Format && _start % itemsize == 0; }
internal static object ImportLightThrow(CodeContext /*!*/ context, string fullName, PythonTuple from, int level) { PythonContext pc = context.LanguageContext; if (level == -1) { // no specific level provided, call the 4 param version so legacy code continues to work var site = pc.OldImportSite; return(site.Target( site, context, FindImportFunction(context), fullName, Builtin.globals(context), context.Dict, from )); } else { // relative import or absolute import, in other words: // // from . import xyz // or // from __future__ import absolute_import var site = pc.ImportSite; return(site.Target( site, context, FindImportFunction(context), fullName, Builtin.globals(context), context.Dict, from, level )); } }
internal PythonTuple(PythonTuple other, object o) { this._data = other.Expand(o); }
/// <summary> /// Given a path to a Zip archive, build a dict, mapping file names /// (local to the archive, using SEP as a separator) to toc entries. /// /// A toc_entry is a tuple: /// (__file__, # value to use for __file__, available for all files /// compress, # compression kind; 0 for uncompressed /// data_size, # size of compressed data on disk /// file_size, # size of decompressed data /// file_offset, # offset of file header from start of archive /// time, # mod time of file (in dos format) /// date, # mod data of file (in dos format) /// crc, # crc checksum of the data /// ) /// Directories can be recognized by the trailing SEP in the name, /// data_size and file_offset are 0. /// </summary> /// <param name="archive"></param> /// <returns></returns> private PythonDictionary ReadDirectory(string archive) { string path, name = string.Empty; BinaryReader fp = null; int header_position, header_size, header_offset, count, compress; int time, date, crc, data_size, name_size, file_size, file_offset; int arc_offset; // offset from beginning of file to start of zip-archive PythonDictionary files = null; byte[] endof_central_dir = new byte[22]; if (archive.Length > MAXPATHLEN) { throw PythonOps.OverflowError("Zip path name is too long"); } path = archive; try { try { fp = new BinaryReader(new FileStream(archive, FileMode.Open, FileAccess.Read)); } catch { throw MakeError("can't open Zip file: '{0}'", archive); } if (fp.BaseStream.Length < 2) { throw MakeError("can't read Zip file: '{0}'", archive); } fp.BaseStream.Seek(-22, SeekOrigin.End); header_position = (int)fp.BaseStream.Position; if (fp.Read(endof_central_dir, 0, 22) != 22) { throw MakeError("can't read Zip file: '{0}'", archive); } if (BitConverter.ToUInt32(endof_central_dir, 0) != 0x06054B50) { // Bad: End of Central Dir signature fp.Close(); throw MakeError("not a Zip file: '{0}'", archive); } header_size = BitConverter.ToInt32(endof_central_dir, 12); header_offset = BitConverter.ToInt32(endof_central_dir, 16); arc_offset = header_position - header_offset - header_size; header_offset += arc_offset; files = new PythonDictionary(); path += Path.DirectorySeparatorChar; // Start of Central Directory count = 0; while (true) { name = string.Empty; fp.BaseStream.Seek(header_offset, SeekOrigin.Begin); // Start of file header int l = fp.ReadInt32(); if (l != 0x02014B50) { break; // Bad: Central Dir File Header } fp.BaseStream.Seek(header_offset + 10, SeekOrigin.Begin); compress = fp.ReadInt16(); time = fp.ReadInt16(); date = fp.ReadInt16(); crc = fp.ReadInt32(); data_size = fp.ReadInt32(); file_size = fp.ReadInt32(); name_size = fp.ReadInt16(); header_size = 46 + name_size + fp.ReadInt16() + fp.ReadInt16(); fp.BaseStream.Seek(header_offset + 42, SeekOrigin.Begin); file_offset = fp.ReadInt32() + arc_offset; if (name_size > MAXPATHLEN) { name_size = MAXPATHLEN; } for (int i = 0; i < name_size; i++) { char c = fp.ReadChar(); if (c == '/') { c = Path.DirectorySeparatorChar; } name += c; } header_offset += header_size; PythonTuple t = PythonOps.MakeTuple(path + name, compress, data_size, file_size, file_offset, time, date, crc); files.Add(name, t); count++; } } catch { throw; } finally { if (fp != null) { fp.Close(); } } return(files); }
public bool endswith(PythonTuple /*!*/ suffix, int start) { return(_bytes.EndsWith(suffix, start)); }
/// <summary> /// Python ctor - maps to function.__new__ /// /// y = func(x.__code__, globals(), 'foo', None, (a, )) /// </summary> public PythonFunction(CodeContext context, FunctionCode code, PythonDictionary globals, string name, PythonTuple defaults, PythonTuple closure) { if (closure != null && closure.__len__() != 0) { throw new NotImplementedException("non empty closure argument is not supported"); } if (globals == context.GlobalDict) { _module = context.Module.GetName(); _context = context; } else { _module = null; _context = new CodeContext(new PythonDictionary(), new ModuleContext(globals, DefaultContext.DefaultPythonContext)); } _defaults = defaults == null ? ArrayUtils.EmptyObjects : defaults.ToArray(); _code = code; _name = name; _doc = code._initialDoc; Closure = null; var scopeStatement = _code.PythonCode; if (scopeStatement.IsClosure) { throw new NotImplementedException("code containing closures is not supported"); } scopeStatement.RewriteBody(FunctionDefinition.ArbitraryGlobalsVisitorInstance); _compat = CalculatedCachedCompat(); }
private static int _CurrentId = 1; // The current ID for functions which are called in complex ways. /// <summary> /// Python ctor - maps to function.__new__ /// /// y = func(x.__code__, globals(), 'foo', None, (a, )) /// </summary> public PythonFunction(CodeContext context, FunctionCode code, PythonDictionary globals, string name, PythonTuple defaults, PythonTuple closure) { throw new NotImplementedException(); }