How to use apply method in localstack

Best Python code snippet using localstack_python

buttons.html5.min.js

Source:buttons.html5.min.js Github

copy

Full Screen

1(function (e) {2 "function" === typeof define && define.amd ? define(["jquery", "datatables.net", "datatables.net-buttons"], function (i) {3 return e(i, window, document)4 }) : "object" === typeof exports ? module.exports = function (i, l, t, s) {5 i || (i = window);6 if (!l || !l.fn.dataTable) l = require("datatables.net")(i, l).$;7 l.fn.dataTable.Buttons || require("datatables.net-buttons")(i, l);8 return e(l, i, i.document, t, s)9 } : e(jQuery, window, document)10})(function (e, i, l, t, s, q) {11 function y(a) {12 for (var b = ""; 0 <= a;) b = String.fromCharCode(a % 26 + 65) + b, a = Math.floor(a /13 26) - 1;14 return b15 }16 function z(a, b) {17 u === q && (u = -1 === x.serializeToString(e.parseXML(A["xl/worksheets/sheet1.xml"])).indexOf("xmlns:r"));18 e.each(b, function (d, c) {19 if (e.isPlainObject(c)) {20 var b = a.folder(d);21 z(b, c)22 } else {23 if (u) {24 var b = c.childNodes[0],25 h, g, v = [];26 for (h = b.attributes.length - 1; 0 <= h; h--) {27 g = b.attributes[h].nodeName;28 var f = b.attributes[h].nodeValue; - 1 !== g.indexOf(":") && (v.push({29 name: g,30 value: f31 }), b.removeAttribute(g))32 }33 h = 0;34 for (g = v.length; h < g; h++) f = c.createAttribute(v[h].name.replace(":", "_dt_b_namespace_token_")),35 f.value = v[h].value, b.setAttributeNode(f)36 }37 b = x.serializeToString(c);38 u && (-1 === b.indexOf("<?xml") && (b = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' + b), b = b.replace(/_dt_b_namespace_token_/g, ":"));39 b = b.replace(/<([^<>]*?) xmlns=""([^<>]*?)>/g, "<$1 $2>");40 a.file(d, b)41 }42 })43 }44 function o(a, b, d) {45 var c = a.createElement(b);46 d && (d.attr && e(c).attr(d.attr), d.children && e.each(d.children, function (a, b) {47 c.appendChild(b)48 }), null !== d.text && d.text !== q && c.appendChild(a.createTextNode(d.text)));49 return c50 }51 function J(a, b) {52 var d =53 a.header[b].length,54 c;55 a.footer && a.footer[b].length > d && (d = a.footer[b].length);56 for (var e = 0, h = a.body.length; e < h; e++)57 if (c = a.body[e][b], c = null !== c && c !== q ? c.toString() : "", -1 !== c.indexOf("\n") ? (c = c.split("\n"), c.sort(function (a, b) {58 return b.length - a.length59 }), c = c[0].length) : c = c.length, c > d && (d = c), 40 < d) return 52;60 d *= 1.3;61 return 6 < d ? d : 662 }63 var p = e.fn.dataTable,64 r;65 var f = "undefined" !== typeof self && self || "undefined" !== typeof i && i || this.content;66 if ("undefined" === typeof f || "undefined" !== typeof navigator && /MSIE [1-9]\./.test(navigator.userAgent)) r =67 void 0;68 else {69 var w = f.document.createElementNS("http://www.w3.org/1999/xhtml", "a"),70 K = "download" in w,71 L = /constructor/i.test(f.HTMLElement) || f.safari,72 B = /CriOS\/[\d]+/.test(navigator.userAgent),73 M = function (a) {74 (f.setImmediate || f.setTimeout)(function () {75 throw a;76 }, 0)77 },78 C = function (a) {79 setTimeout(function () {80 "string" === typeof a ? (f.URL || f.webkitURL || f).revokeObjectURL(a) : a.remove()81 }, 4E4)82 },83 D = function (a) {84 return /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(a.type) ? new Blob([String.fromCharCode(65279),85 a86 ], {87 type: a.type88 }) : a89 },90 E = function (a, b, d) {91 d || (a = D(a));92 var c = this,93 d = "application/octet-stream" === a.type,94 e, h = function () {95 for (var a = ["writestart", "progress", "write", "writeend"], a = [].concat(a), b = a.length; b--;) {96 var d = c["on" + a[b]];97 if ("function" === typeof d) try {98 d.call(c, c)99 } catch (g) {100 M(g)101 }102 }103 };104 c.readyState = c.INIT;105 if (K) e = (f.URL || f.webkitURL || f).createObjectURL(a), setTimeout(function () {106 w.href = e;107 w.download = b;108 var a = new MouseEvent("click");109 w.dispatchEvent(a);110 h();111 C(e);112 c.readyState = c.DONE113 });114 else if ((B || d && L) && f.FileReader) {115 var g =116 new FileReader;117 g.onloadend = function () {118 var a = B ? g.result : g.result.replace(/^data:[^;]*;/, "data:attachment/file;");119 f.open(a, "_blank") || (f.location.href = a);120 c.readyState = c.DONE;121 h()122 };123 g.readAsDataURL(a);124 c.readyState = c.INIT125 } else e || (e = (f.URL || f.webkitURL || f).createObjectURL(a)), d ? f.location.href = e : f.open(e, "_blank") || (f.location.href = e), c.readyState = c.DONE, h(), C(e)126 },127 k = E.prototype;128 "undefined" !== typeof navigator && navigator.msSaveOrOpenBlob ? r = function (a, b, d) {129 b = b || a.name || "download";130 d || (a = D(a));131 return navigator.msSaveOrOpenBlob(a,132 b)133 } : (k.abort = function () {}, k.readyState = k.INIT = 0, k.WRITING = 1, k.DONE = 2, k.error = k.onwritestart = k.onprogress = k.onwrite = k.onabort = k.onerror = k.onwriteend = null, r = function (a, b, d) {134 return new E(a, b || a.name || "download", d)135 })136 }137 p.fileSave = r;138 var N = function (a) {139 var b = "Sheet1";140 a.sheetName && (b = a.sheetName.replace(/[\[\]\*\/\\\?\:]/g, ""));141 return b142 },143 F = function (a) {144 return a.newline ? a.newline : navigator.userAgent.match(/Windows/) ? "\r\n" : "\n"145 },146 G = function (a, b) {147 for (var d = F(b), c = a.buttons.exportData(b.exportOptions), e = b.fieldBoundary,148 h = b.fieldSeparator, g = RegExp(e, "g"), f = b.escapeChar !== q ? b.escapeChar : "\\", i = function (a) {149 for (var b = "", c = 0, d = a.length; c < d; c++) 0 < c && (b += h), b += e ? e + ("" + a[c]).replace(g, f + e) + e : a[c];150 return b151 }, l = b.header ? i(c.header) + d : "", j = b.footer && c.footer ? d + i(c.footer) : "", n = [], m = 0, k = c.body.length; m < k; m++) n.push(i(c.body[m]));152 return {153 str: l + n.join(d) + j,154 rows: n.length155 }156 },157 H = function () {158 if (!(-1 !== navigator.userAgent.indexOf("Safari") && -1 === navigator.userAgent.indexOf("Chrome") && -1 === navigator.userAgent.indexOf("Opera"))) return !1;159 var a = navigator.userAgent.match(/AppleWebKit\/(\d+\.\d+)/);160 return a && 1 < a.length && 603.1 > 1 * a[1] ? !0 : !1161 };162 try {163 var x = new XMLSerializer,164 u165 } catch (O) {}166 var A = {167 "_rels/.rels": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>',168 "xl/_rels/workbook.xml.rels": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>',169 "[Content_Types].xml": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="xml" ContentType="application/xml" /><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" /><Default Extension="jpeg" ContentType="image/jpeg" /><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml" /><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml" /><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml" /></Types>',170 "xl/workbook.xml": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><fileVersion appName="xl" lastEdited="5" lowestEdited="5" rupBuild="24816"/><workbookPr showInkAnnotation="0" autoCompressPictures="0"/><bookViews><workbookView xWindow="0" yWindow="0" windowWidth="25600" windowHeight="19020" tabRatio="500"/></bookViews><sheets><sheet name="" sheetId="1" r:id="rId1"/></sheets></workbook>',171 "xl/worksheets/sheet1.xml": '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"><sheetData/><mergeCells count="0"/></worksheet>',172 "xl/styles.xml": '<?xml version="1.0" encoding="UTF-8"?><styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac"><numFmts count="6"><numFmt numFmtId="164" formatCode="#,##0.00_- [$$-45C]"/><numFmt numFmtId="165" formatCode="&quot;£&quot;#,##0.00"/><numFmt numFmtId="166" formatCode="[$€-2] #,##0.00"/><numFmt numFmtId="167" formatCode="0.0%"/><numFmt numFmtId="168" formatCode="#,##0;(#,##0)"/><numFmt numFmtId="169" formatCode="#,##0.00;(#,##0.00)"/></numFmts><fonts count="5" x14ac:knownFonts="1"><font><sz val="11" /><name val="Calibri" /></font><font><sz val="11" /><name val="Calibri" /><color rgb="FFFFFFFF" /></font><font><sz val="11" /><name val="Calibri" /><b /></font><font><sz val="11" /><name val="Calibri" /><i /></font><font><sz val="11" /><name val="Calibri" /><u /></font></fonts><fills count="6"><fill><patternFill patternType="none" /></fill><fill><patternFill patternType="none" /></fill><fill><patternFill patternType="solid"><fgColor rgb="FFD9D9D9" /><bgColor indexed="64" /></patternFill></fill><fill><patternFill patternType="solid"><fgColor rgb="FFD99795" /><bgColor indexed="64" /></patternFill></fill><fill><patternFill patternType="solid"><fgColor rgb="ffc6efce" /><bgColor indexed="64" /></patternFill></fill><fill><patternFill patternType="solid"><fgColor rgb="ffc6cfef" /><bgColor indexed="64" /></patternFill></fill></fills><borders count="2"><border><left /><right /><top /><bottom /><diagonal /></border><border diagonalUp="false" diagonalDown="false"><left style="thin"><color auto="1" /></left><right style="thin"><color auto="1" /></right><top style="thin"><color auto="1" /></top><bottom style="thin"><color auto="1" /></bottom><diagonal /></border></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" /></cellStyleXfs><cellXfs count="67"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="1" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="2" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="3" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="4" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="0" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="1" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="2" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="3" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="4" fillId="2" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="0" fillId="3" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="1" fillId="3" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="2" fillId="3" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="3" fillId="3" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="4" fillId="3" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="0" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="1" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="2" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="3" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="4" fillId="4" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="0" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="1" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="2" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="3" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="4" fillId="5" borderId="0" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="0" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="1" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="2" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="3" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="4" fillId="0" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="0" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="1" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="2" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="3" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="4" fillId="2" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="0" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="1" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="2" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="3" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="4" fillId="3" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="0" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="1" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="2" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="3" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="4" fillId="4" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="0" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="1" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="2" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="3" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="4" fillId="5" borderId="1" applyFont="1" applyFill="1" applyBorder="1"/><xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1"><alignment horizontal="left"/></xf><xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1"><alignment horizontal="center"/></xf><xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1"><alignment horizontal="right"/></xf><xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1"><alignment horizontal="fill"/></xf><xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1"><alignment textRotation="90"/></xf><xf numFmtId="0" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyAlignment="1"><alignment wrapText="1"/></xf><xf numFmtId="9" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="164" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="165" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="166" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="167" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="168" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="169" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="3" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="4" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="1" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/><xf numFmtId="2" fontId="0" fillId="0" borderId="0" applyFont="1" applyFill="1" applyBorder="1" xfId="0" applyNumberFormat="1"/></cellXfs><cellStyles count="1"><cellStyle name="Normal" xfId="0" builtinId="0" /></cellStyles><dxfs count="0" /><tableStyles count="0" defaultTableStyle="TableStyleMedium9" defaultPivotStyle="PivotStyleMedium4" /></styleSheet>'173 },174 I = [{175 match: /^\-?\d+\.\d%$/,176 style: 60,177 fmt: function (a) {178 return a / 100179 }180 }, {181 match: /^\-?\d+\.?\d*%$/,182 style: 56,183 fmt: function (a) {184 return a / 100185 }186 }, {187 match: /^\-?\$[\d,]+.?\d*$/,188 style: 57189 }, {190 match: /^\-?£[\d,]+.?\d*$/,191 style: 58192 }, {193 match: /^\-?€[\d,]+.?\d*$/,194 style: 59195 }, {196 match: /^\-?\d+$/,197 style: 65198 }, {199 match: /^\-?\d+\.\d{2}$/,200 style: 66201 }, {202 match: /^\([\d,]+\)$/,203 style: 61,204 fmt: function (a) {205 return -1 * a.replace(/[\(\)]/g, "")206 }207 }, {208 match: /^\([\d,]+\.\d{2}\)$/,209 style: 62,210 fmt: function (a) {211 return -1 * a.replace(/[\(\)]/g, "")212 }213 }, {214 match: /^\-?[\d,]+$/,215 style: 63216 },217 {218 match: /^\-?[\d,]+\.\d{2}$/,219 style: 64220 }221 ];222 p.ext.buttons.copyHtml5 = {223 className: "buttons-copy buttons-html5",224 text: function (a) {225 return a.i18n("buttons.copy", "Copy")226 },227 action: function (a, b, d, c) {228 this.processing(!0);229 var f = this,230 a = G(b, c),231 h = b.buttons.exportInfo(c),232 g = F(c),233 i = a.str,234 d = e("<div/>").css({235 height: 1,236 width: 1,237 overflow: "hidden",238 position: "fixed",239 top: 0,240 left: 0241 });242 h.title && (i = h.title + g + g + i);243 h.messageTop && (i = h.messageTop + g + g + i);244 h.messageBottom && (i = i + g + g + h.messageBottom);245 c.customize && (i = c.customize(i, c));246 c = e("<textarea readonly/>").val(i).appendTo(d);247 if (l.queryCommandSupported("copy")) {248 d.appendTo(b.table().container());249 c[0].focus();250 c[0].select();251 try {252 var k = l.execCommand("copy");253 d.remove();254 if (k) {255 b.buttons.info(b.i18n("buttons.copyTitle", "Copy to clipboard"), b.i18n("buttons.copySuccess", {256 1: "Copied one row to clipboard",257 _: "Copied %d rows to clipboard"258 }, a.rows), 2E3);259 this.processing(!1);260 return261 }262 } catch (o) {}263 }264 k = e("<span>" + b.i18n("buttons.copyKeys", "Press <i>ctrl</i> or <i>⌘</i> + <i>C</i> to copy the table data<br>to your system clipboard.<br><br>To cancel, click this message or press escape.") +265 "</span>").append(d);266 b.buttons.info(b.i18n("buttons.copyTitle", "Copy to clipboard"), k, 0);267 c[0].focus();268 c[0].select();269 var j = e(k).closest(".dt-button-info"),270 n = function () {271 j.off("click.buttons-copy");272 e(l).off(".buttons-copy");273 b.buttons.info(!1)274 };275 j.on("click.buttons-copy", n);276 e(l).on("keydown.buttons-copy", function (a) {277 27 === a.keyCode && (n(), f.processing(!1))278 }).on("copy.buttons-copy cut.buttons-copy", function () {279 n();280 f.processing(!1)281 })282 },283 exportOptions: {},284 fieldSeparator: "\t",285 fieldBoundary: "",286 header: !0,287 footer: !1,288 title: "*",289 messageTop: "*",290 messageBottom: "*"291 };292 p.ext.buttons.csvHtml5 = {293 bom: !1,294 className: "buttons-csv buttons-html5",295 available: function () {296 return i.FileReader !== q && i.Blob297 },298 text: function (a) {299 return a.i18n("buttons.csv", "CSV")300 },301 action: function (a, b, d, c) {302 this.processing(!0);303 a = G(b, c).str;304 b = b.buttons.exportInfo(c);305 d = c.charset;306 c.customize && (a = c.customize(a, c));307 !1 !== d ? (d || (d = l.characterSet || l.charset), d && (d = ";charset=" + d)) : d = "";308 c.bom && (a = "" + a);309 r(new Blob([a], {310 type: "text/csv" + d311 }), b.filename, !0);312 this.processing(!1)313 },314 filename: "*",315 extension: ".csv",316 exportOptions: {},317 fieldSeparator: ",",318 fieldBoundary: '"',319 escapeChar: '"',320 charset: null,321 header: !0,322 footer: !1323 };324 p.ext.buttons.excelHtml5 = {325 className: "buttons-excel buttons-html5",326 available: function () {327 return i.FileReader !== q && (t || i.JSZip) !== q && !H() && x328 },329 text: function (a) {330 return a.i18n("buttons.excel", "Excel")331 },332 action: function (a, b, d, c) {333 this.processing(!0);334 var f = this,335 h = 0,336 a = function (a) {337 return e.parseXML(A[a])338 },339 g = a("xl/worksheets/sheet1.xml"),340 k = g.getElementsByTagName("sheetData")[0],341 a = {342 _rels: {343 ".rels": a("_rels/.rels")344 },345 xl: {346 _rels: {347 "workbook.xml.rels": a("xl/_rels/workbook.xml.rels")348 },349 "workbook.xml": a("xl/workbook.xml"),350 "styles.xml": a("xl/styles.xml"),351 worksheets: {352 "sheet1.xml": g353 }354 },355 "[Content_Types].xml": a("[Content_Types].xml")356 },357 d = b.buttons.exportData(c.exportOptions),358 l, p, j = function (a) {359 l = h + 1;360 p = o(g, "row", {361 attr: {362 r: l363 }364 });365 for (var b = 0, d = a.length; b < d; b++) {366 var i = y(b) + "" + l,367 f = null;368 if (null === a[b] || a[b] === q || "" === a[b])369 if (!0 === c.createEmptyCells) a[b] = "";370 else continue;371 a[b] = e.trim(a[b]);372 for (var j =373 0, n = I.length; j < n; j++) {374 var m = I[j];375 if (a[b].match && !a[b].match(/^0\d+/) && a[b].match(m.match)) {376 f = a[b].replace(/[^\d\.\-]/g, "");377 m.fmt && (f = m.fmt(f));378 f = o(g, "c", {379 attr: {380 r: i,381 s: m.style382 },383 children: [o(g, "v", {384 text: f385 })]386 });387 break388 }389 }390 f || ("number" === typeof a[b] || a[b].match && a[b].match(/^-?\d+(\.\d+)?$/) && !a[b].match(/^0\d+/) ? f = o(g, "c", {391 attr: {392 t: "n",393 r: i394 },395 children: [o(g, "v", {396 text: a[b]397 })]398 }) : (m = !a[b].replace ? a[b] : a[b].replace(/[\x00-\x09\x0B\x0C\x0E-\x1F\x7F-\x9F]/g, ""), f = o(g, "c", {399 attr: {400 t: "inlineStr",401 r: i402 },403 children: {404 row: o(g,405 "is", {406 children: {407 row: o(g, "t", {408 text: m409 })410 }411 })412 }413 })));414 p.appendChild(f)415 }416 k.appendChild(p);417 h++418 };419 e("sheets sheet", a.xl["workbook.xml"]).attr("name", N(c));420 c.customizeData && c.customizeData(d);421 var n = function (a, b) {422 var c = e("mergeCells", g);423 c[0].appendChild(o(g, "mergeCell", {424 attr: {425 ref: "A" + a + ":" + y(b) + a426 }427 }));428 c.attr("count", parseFloat(c.attr("count")) + 1);429 e("row:eq(" + (a - 1) + ") c", g).attr("s", "51")430 },431 m = b.buttons.exportInfo(c);432 m.title && (j([m.title], h), n(h, d.header.length - 1));433 m.messageTop && (j([m.messageTop], h), n(h, d.header.length -434 1));435 c.header && (j(d.header, h), e("row:last c", g).attr("s", "2"));436 for (var b = 0, s = d.body.length; b < s; b++) j(d.body[b], h);437 c.footer && d.footer && (j(d.footer, h), e("row:last c", g).attr("s", "2"));438 m.messageBottom && (j([m.messageBottom], h), n(h, d.header.length - 1));439 b = o(g, "cols");440 e("worksheet", g).prepend(b);441 j = 0;442 for (n = d.header.length; j < n; j++) b.appendChild(o(g, "col", {443 attr: {444 min: j + 1,445 max: j + 1,446 width: J(d, j),447 customWidth: 1448 }449 }));450 c.customize && c.customize(a);451 0 === e("mergeCells", g).children().length && e("mergeCells", g).remove();452 d = new(t ||453 i.JSZip);454 b = {455 type: "blob",456 mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"457 };458 z(d, a);459 d.generateAsync ? d.generateAsync(b).then(function (a) {460 r(a, m.filename);461 f.processing(false)462 }) : (r(d.generate(b), m.filename), this.processing(!1))463 },464 filename: "*",465 extension: ".xlsx",466 exportOptions: {},467 header: !0,468 footer: !1,469 title: "*",470 messageTop: "*",471 messageBottom: "*",472 createEmptyCells: !1473 };474 p.ext.buttons.pdfHtml5 = {475 className: "buttons-pdf buttons-html5",476 available: function () {477 return i.FileReader !== q && (s || i.pdfMake)478 },479 text: function (a) {480 return a.i18n("buttons.pdf", "PDF")481 },482 action: function (a, b, d, c) {483 this.processing(!0);484 a = b.buttons.exportData(c.exportOptions);485 b = b.buttons.exportInfo(c);486 d = [];487 c.header && d.push(e.map(a.header, function (a) {488 return {489 text: "string" === typeof a ? a : a + "",490 style: "tableHeader"491 }492 }));493 for (var f = 0, h = a.body.length; f < h; f++) d.push(e.map(a.body[f], function (a) {494 return {495 text: "string" === typeof a ? a : a + "",496 style: f % 2 ? "tableBodyEven" : "tableBodyOdd"497 }498 }));499 c.footer && a.footer && d.push(e.map(a.footer, function (a) {500 return {501 text: "string" ===502 typeof a ? a : a + "",503 style: "tableFooter"504 }505 }));506 a = {507 pageSize: c.pageSize,508 pageOrientation: c.orientation,509 content: [{510 table: {511 headerRows: 1,512 body: d513 },514 layout: "noBorders"515 }],516 styles: {517 tableHeader: {518 bold: !0,519 fontSize: 11,520 color: "white",521 fillColor: "#2d4154",522 alignment: "center"523 },524 tableBodyEven: {},525 tableBodyOdd: {526 fillColor: "#f3f3f3"527 },528 tableFooter: {529 bold: !0,530 fontSize: 11,531 color: "white",532 fillColor: "#2d4154"533 },534 title: {535 alignment: "center",536 fontSize: 15537 },538 message: {}539 },540 defaultStyle: {541 fontSize: 10542 }543 };544 b.messageTop && a.content.unshift({545 text: b.messageTop,546 style: "message",547 margin: [0, 0, 0, 12]548 });549 b.messageBottom && a.content.push({550 text: b.messageBottom,551 style: "message",552 margin: [0, 0, 0, 12]553 });554 b.title && a.content.unshift({555 text: b.title,556 style: "title",557 margin: [0, 0, 0, 12]558 });559 c.customize && c.customize(a, c);560 a = (s || i.pdfMake).createPdf(a);561 "open" === c.download && !H() ? a.open() : a.download(b.filename);562 this.processing(!1)563 },564 title: "*",565 filename: "*",566 extension: ".pdf",567 exportOptions: {},568 orientation: "portrait",569 pageSize: "A4",570 header: !0,571 footer: !1,572 messageTop: "*",573 messageBottom: "*",574 customize: null,575 download: "download"576 };577 return p.Buttons...

Full Screen

Full Screen

test_apply.py

Source:test_apply.py Github

copy

Full Screen

...26 parse_dates=[["date", "time"]],27 )28 df = df.set_index("date_time")29 expected = df.groupby(df.index.date).idxmax()30 result = df.groupby(df.index.date).apply(lambda x: x.idxmax())31 tm.assert_frame_equal(result, expected)32 # GH 578933 # don't auto coerce dates34 df = pd.read_csv(StringIO(s), header=None, names=["date", "time", "value"])35 exp_idx = pd.Index(36 ["2011.05.16", "2011.05.17", "2011.05.18"], dtype=object, name="date"37 )38 expected = Series(["00:00", "02:00", "02:00"], index=exp_idx)39 result = df.groupby("date").apply(lambda x: x["time"][x["value"].idxmax()])40 tm.assert_series_equal(result, expected)41def test_apply_trivial():42 # GH 2006643 # trivial apply: ignore input and return a constant dataframe.44 df = pd.DataFrame(45 {"key": ["a", "a", "b", "b", "a"], "data": [1.0, 2.0, 3.0, 4.0, 5.0]},46 columns=["key", "data"],47 )48 expected = pd.concat([df.iloc[1:], df.iloc[1:]], axis=1, keys=["float64", "object"])49 result = df.groupby([str(x) for x in df.dtypes], axis=1).apply(50 lambda x: df.iloc[1:]51 )52 tm.assert_frame_equal(result, expected)53@pytest.mark.xfail(54 reason="GH#20066; function passed into apply "55 "returns a DataFrame with the same index "56 "as the one to create GroupBy object."57)58def test_apply_trivial_fail():59 # GH 2006660 # trivial apply fails if the constant dataframe has the same index61 # with the one used to create GroupBy object.62 df = pd.DataFrame(63 {"key": ["a", "a", "b", "b", "a"], "data": [1.0, 2.0, 3.0, 4.0, 5.0]},64 columns=["key", "data"],65 )66 expected = pd.concat([df, df], axis=1, keys=["float64", "object"])67 result = df.groupby([str(x) for x in df.dtypes], axis=1).apply(lambda x: df)68 tm.assert_frame_equal(result, expected)69def test_fast_apply():70 # make sure that fast apply is correctly called71 # rather than raising any kind of error72 # otherwise the python path will be callsed73 # which slows things down74 N = 100075 labels = np.random.randint(0, 2000, size=N)76 labels2 = np.random.randint(0, 3, size=N)77 df = DataFrame(78 {79 "key": labels,80 "key2": labels2,81 "value1": np.random.randn(N),82 "value2": ["foo", "bar", "baz", "qux"] * (N // 4),83 }84 )85 def f(g):86 return 187 g = df.groupby(["key", "key2"])88 grouper = g.grouper89 splitter = grouper._get_splitter(g._selected_obj, axis=g.axis)90 group_keys = grouper._get_group_keys()91 values, mutated = splitter.fast_apply(f, group_keys)92 assert not mutated93@pytest.mark.parametrize(94 "df, group_names",95 [96 (DataFrame({"a": [1, 1, 1, 2, 3], "b": ["a", "a", "a", "b", "c"]}), [1, 2, 3]),97 (DataFrame({"a": [0, 0, 1, 1], "b": [0, 1, 0, 1]}), [0, 1]),98 (DataFrame({"a": [1]}), [1]),99 (DataFrame({"a": [1, 1, 1, 2, 2, 1, 1, 2], "b": range(8)}), [1, 2]),100 (DataFrame({"a": [1, 2, 3, 1, 2, 3], "two": [4, 5, 6, 7, 8, 9]}), [1, 2, 3]),101 (102 DataFrame(103 {104 "a": list("aaabbbcccc"),105 "B": [3, 4, 3, 6, 5, 2, 1, 9, 5, 4],106 "C": [4, 0, 2, 2, 2, 7, 8, 6, 2, 8],107 }108 ),109 ["a", "b", "c"],110 ),111 (DataFrame([[1, 2, 3], [2, 2, 3]], columns=["a", "b", "c"]), [1, 2]),112 ],113 ids=[114 "GH2936",115 "GH7739 & GH10519",116 "GH10519",117 "GH2656",118 "GH12155",119 "GH20084",120 "GH21417",121 ],122)123def test_group_apply_once_per_group(df, group_names):124 # GH2936, GH7739, GH10519, GH2656, GH12155, GH20084, GH21417125 # This test should ensure that a function is only evaluated126 # once per group. Previously the function has been evaluated twice127 # on the first group to check if the Cython index slider is safe to use128 # This test ensures that the side effect (append to list) is only triggered129 # once per group130 names = []131 # cannot parameterize over the functions since they need external132 # `names` to detect side effects133 def f_copy(group):134 # this takes the fast apply path135 names.append(group.name)136 return group.copy()137 def f_nocopy(group):138 # this takes the slow apply path139 names.append(group.name)140 return group141 def f_scalar(group):142 # GH7739, GH2656143 names.append(group.name)144 return 0145 def f_none(group):146 # GH10519, GH12155, GH21417147 names.append(group.name)148 return None149 def f_constant_df(group):150 # GH2936, GH20084151 names.append(group.name)152 return DataFrame({"a": [1], "b": [1]})153 for func in [f_copy, f_nocopy, f_scalar, f_none, f_constant_df]:154 del names[:]155 df.groupby("a").apply(func)156 assert names == group_names157def test_apply_with_mixed_dtype():158 # GH3480, apply with mixed dtype on axis=1 breaks in 0.11159 df = DataFrame(160 {161 "foo1": np.random.randn(6),162 "foo2": ["one", "two", "two", "three", "one", "two"],163 }164 )165 result = df.apply(lambda x: x, axis=1).dtypes166 expected = df.dtypes167 tm.assert_series_equal(result, expected)168 # GH 3610 incorrect dtype conversion with as_index=False169 df = DataFrame({"c1": [1, 2, 6, 6, 8]})170 df["c2"] = df.c1 / 2.0171 result1 = df.groupby("c2").mean().reset_index().c2172 result2 = df.groupby("c2", as_index=False).mean().c2173 tm.assert_series_equal(result1, result2)174def test_groupby_as_index_apply(df):175 # GH #4648 and #3417176 df = DataFrame(177 {178 "item_id": ["b", "b", "a", "c", "a", "b"],179 "user_id": [1, 2, 1, 1, 3, 1],180 "time": range(6),181 }182 )183 g_as = df.groupby("user_id", as_index=True)184 g_not_as = df.groupby("user_id", as_index=False)185 res_as = g_as.head(2).index186 res_not_as = g_not_as.head(2).index187 exp = Index([0, 1, 2, 4])188 tm.assert_index_equal(res_as, exp)189 tm.assert_index_equal(res_not_as, exp)190 res_as_apply = g_as.apply(lambda x: x.head(2)).index191 res_not_as_apply = g_not_as.apply(lambda x: x.head(2)).index192 # apply doesn't maintain the original ordering193 # changed in GH5610 as the as_index=False returns a MI here194 exp_not_as_apply = MultiIndex.from_tuples([(0, 0), (0, 2), (1, 1), (2, 4)])195 tp = [(1, 0), (1, 2), (2, 1), (3, 4)]196 exp_as_apply = MultiIndex.from_tuples(tp, names=["user_id", None])197 tm.assert_index_equal(res_as_apply, exp_as_apply)198 tm.assert_index_equal(res_not_as_apply, exp_not_as_apply)199 ind = Index(list("abcde"))200 df = DataFrame([[1, 2], [2, 3], [1, 4], [1, 5], [2, 6]], index=ind)201 res = df.groupby(0, as_index=False).apply(lambda x: x).index202 tm.assert_index_equal(res, ind)203def test_apply_concat_preserve_names(three_group):204 grouped = three_group.groupby(["A", "B"])205 def desc(group):206 result = group.describe()207 result.index.name = "stat"208 return result209 def desc2(group):210 result = group.describe()211 result.index.name = "stat"212 result = result[: len(group)]213 # weirdo214 return result215 def desc3(group):216 result = group.describe()217 # names are different218 result.index.name = f"stat_{len(group):d}"219 result = result[: len(group)]220 # weirdo221 return result222 result = grouped.apply(desc)223 assert result.index.names == ("A", "B", "stat")224 result2 = grouped.apply(desc2)225 assert result2.index.names == ("A", "B", "stat")226 result3 = grouped.apply(desc3)227 assert result3.index.names == ("A", "B", None)228def test_apply_series_to_frame():229 def f(piece):230 with np.errstate(invalid="ignore"):231 logged = np.log(piece)232 return DataFrame(233 {"value": piece, "demeaned": piece - piece.mean(), "logged": logged}234 )235 dr = bdate_range("1/1/2000", periods=100)236 ts = Series(np.random.randn(100), index=dr)237 grouped = ts.groupby(lambda x: x.month)238 result = grouped.apply(f)239 assert isinstance(result, DataFrame)240 tm.assert_index_equal(result.index, ts.index)241def test_apply_series_yield_constant(df):242 result = df.groupby(["A", "B"])["C"].apply(len)243 assert result.index.names[:2] == ("A", "B")244def test_apply_frame_yield_constant(df):245 # GH13568246 result = df.groupby(["A", "B"]).apply(len)247 assert isinstance(result, Series)248 assert result.name is None249 result = df.groupby(["A", "B"])[["C", "D"]].apply(len)250 assert isinstance(result, Series)251 assert result.name is None252def test_apply_frame_to_series(df):253 grouped = df.groupby(["A", "B"])254 result = grouped.apply(len)255 expected = grouped.count()["C"]256 tm.assert_index_equal(result.index, expected.index)257 tm.assert_numpy_array_equal(result.values, expected.values)258def test_apply_frame_concat_series():259 def trans(group):260 return group.groupby("B")["C"].sum().sort_values()[:2]261 def trans2(group):262 grouped = group.groupby(df.reindex(group.index)["B"])263 return grouped.sum().sort_values()[:2]264 df = DataFrame(265 {266 "A": np.random.randint(0, 5, 1000),267 "B": np.random.randint(0, 5, 1000),268 "C": np.random.randn(1000),269 }270 )271 result = df.groupby("A").apply(trans)272 exp = df.groupby("A")["C"].apply(trans2)273 tm.assert_series_equal(result, exp, check_names=False)274 assert result.name == "C"275def test_apply_transform(ts):276 grouped = ts.groupby(lambda x: x.month)277 result = grouped.apply(lambda x: x * 2)278 expected = grouped.transform(lambda x: x * 2)279 tm.assert_series_equal(result, expected)280def test_apply_multikey_corner(tsframe):281 grouped = tsframe.groupby([lambda x: x.year, lambda x: x.month])282 def f(group):283 return group.sort_values("A")[-5:]284 result = grouped.apply(f)285 for key, group in grouped:286 tm.assert_frame_equal(result.loc[key], f(group))287def test_apply_chunk_view():288 # Low level tinkering could be unsafe, make sure not289 df = DataFrame({"key": [1, 1, 1, 2, 2, 2, 3, 3, 3], "value": range(9)})290 result = df.groupby("key", group_keys=False).apply(lambda x: x[:2])291 expected = df.take([0, 1, 3, 4, 6, 7])292 tm.assert_frame_equal(result, expected)293def test_apply_no_name_column_conflict():294 df = DataFrame(295 {296 "name": [1, 1, 1, 1, 1, 1, 2, 2, 2, 2],297 "name2": [0, 0, 0, 1, 1, 1, 0, 0, 1, 1],298 "value": range(9, -1, -1),299 }300 )301 # it works! #2605302 grouped = df.groupby(["name", "name2"])303 grouped.apply(lambda x: x.sort_values("value", inplace=True))304def test_apply_typecast_fail():305 df = DataFrame(306 {307 "d": [1.0, 1.0, 1.0, 2.0, 2.0, 2.0],308 "c": np.tile(["a", "b", "c"], 2),309 "v": np.arange(1.0, 7.0),310 }311 )312 def f(group):313 v = group["v"]314 group["v2"] = (v - v.min()) / (v.max() - v.min())315 return group316 result = df.groupby("d").apply(f)317 expected = df.copy()318 expected["v2"] = np.tile([0.0, 0.5, 1], 2)319 tm.assert_frame_equal(result, expected)320def test_apply_multiindex_fail():321 index = MultiIndex.from_arrays([[0, 0, 0, 1, 1, 1], [1, 2, 3, 1, 2, 3]])322 df = DataFrame(323 {324 "d": [1.0, 1.0, 1.0, 2.0, 2.0, 2.0],325 "c": np.tile(["a", "b", "c"], 2),326 "v": np.arange(1.0, 7.0),327 },328 index=index,329 )330 def f(group):331 v = group["v"]332 group["v2"] = (v - v.min()) / (v.max() - v.min())333 return group334 result = df.groupby("d").apply(f)335 expected = df.copy()336 expected["v2"] = np.tile([0.0, 0.5, 1], 2)337 tm.assert_frame_equal(result, expected)338def test_apply_corner(tsframe):339 result = tsframe.groupby(lambda x: x.year).apply(lambda x: x * 2)340 expected = tsframe * 2341 tm.assert_frame_equal(result, expected)342def test_apply_without_copy():343 # GH 5545344 # returning a non-copy in an applied function fails345 data = DataFrame(346 {347 "id_field": [100, 100, 200, 300],348 "category": ["a", "b", "c", "c"],349 "value": [1, 2, 3, 4],350 }351 )352 def filt1(x):353 if x.shape[0] == 1:354 return x.copy()355 else:356 return x[x.category == "c"]357 def filt2(x):358 if x.shape[0] == 1:359 return x360 else:361 return x[x.category == "c"]362 expected = data.groupby("id_field").apply(filt1)363 result = data.groupby("id_field").apply(filt2)364 tm.assert_frame_equal(result, expected)365def test_apply_corner_cases():366 # #535, can't use sliding iterator367 N = 1000368 labels = np.random.randint(0, 100, size=N)369 df = DataFrame(370 {371 "key": labels,372 "value1": np.random.randn(N),373 "value2": ["foo", "bar", "baz", "qux"] * (N // 4),374 }375 )376 grouped = df.groupby("key")377 def f(g):378 g["value3"] = g["value1"] * 2379 return g380 result = grouped.apply(f)381 assert "value3" in result382def test_apply_numeric_coercion_when_datetime():383 # In the past, group-by/apply operations have been over-eager384 # in converting dtypes to numeric, in the presence of datetime385 # columns. Various GH issues were filed, the reproductions386 # for which are here.387 # GH 15670388 df = pd.DataFrame(389 {"Number": [1, 2], "Date": ["2017-03-02"] * 2, "Str": ["foo", "inf"]}390 )391 expected = df.groupby(["Number"]).apply(lambda x: x.iloc[0])392 df.Date = pd.to_datetime(df.Date)393 result = df.groupby(["Number"]).apply(lambda x: x.iloc[0])394 tm.assert_series_equal(result["Str"], expected["Str"])395 # GH 15421396 df = pd.DataFrame(397 {"A": [10, 20, 30], "B": ["foo", "3", "4"], "T": [pd.Timestamp("12:31:22")] * 3}398 )399 def get_B(g):400 return g.iloc[0][["B"]]401 result = df.groupby("A").apply(get_B)["B"]402 expected = df.B403 expected.index = df.A404 tm.assert_series_equal(result, expected)405 # GH 14423406 def predictions(tool):407 out = pd.Series(index=["p1", "p2", "useTime"], dtype=object)408 if "step1" in list(tool.State):409 out["p1"] = str(tool[tool.State == "step1"].Machine.values[0])410 if "step2" in list(tool.State):411 out["p2"] = str(tool[tool.State == "step2"].Machine.values[0])412 out["useTime"] = str(tool[tool.State == "step2"].oTime.values[0])413 return out414 df1 = pd.DataFrame(415 {416 "Key": ["B", "B", "A", "A"],417 "State": ["step1", "step2", "step1", "step2"],418 "oTime": ["", "2016-09-19 05:24:33", "", "2016-09-19 23:59:04"],419 "Machine": ["23", "36L", "36R", "36R"],420 }421 )422 df2 = df1.copy()423 df2.oTime = pd.to_datetime(df2.oTime)424 expected = df1.groupby("Key").apply(predictions).p1425 result = df2.groupby("Key").apply(predictions).p1426 tm.assert_series_equal(expected, result)427def test_apply_aggregating_timedelta_and_datetime():428 # Regression test for GH 15562429 # The following groupby caused ValueErrors and IndexErrors pre 0.20.0430 df = pd.DataFrame(431 {432 "clientid": ["A", "B", "C"],433 "datetime": [np.datetime64("2017-02-01 00:00:00")] * 3,434 }435 )436 df["time_delta_zero"] = df.datetime - df.datetime437 result = df.groupby("clientid").apply(438 lambda ddf: pd.Series(439 dict(clientid_age=ddf.time_delta_zero.min(), date=ddf.datetime.min())440 )441 )442 expected = pd.DataFrame(443 {444 "clientid": ["A", "B", "C"],445 "clientid_age": [np.timedelta64(0, "D")] * 3,446 "date": [np.datetime64("2017-02-01 00:00:00")] * 3,447 }448 ).set_index("clientid")449 tm.assert_frame_equal(result, expected)450def test_time_field_bug():451 # Test a fix for the following error related to GH issue 11324 When452 # non-key fields in a group-by dataframe contained time-based fields453 # that were not returned by the apply function, an exception would be454 # raised.455 df = pd.DataFrame({"a": 1, "b": [datetime.now() for nn in range(10)]})456 def func_with_no_date(batch):457 return pd.Series({"c": 2})458 def func_with_date(batch):459 return pd.Series({"b": datetime(2015, 1, 1), "c": 2})460 dfg_no_conversion = df.groupby(by=["a"]).apply(func_with_no_date)461 dfg_no_conversion_expected = pd.DataFrame({"c": 2}, index=[1])462 dfg_no_conversion_expected.index.name = "a"463 dfg_conversion = df.groupby(by=["a"]).apply(func_with_date)464 dfg_conversion_expected = pd.DataFrame(465 {"b": datetime(2015, 1, 1), "c": 2}, index=[1]466 )467 dfg_conversion_expected.index.name = "a"468 tm.assert_frame_equal(dfg_no_conversion, dfg_no_conversion_expected)469 tm.assert_frame_equal(dfg_conversion, dfg_conversion_expected)470def test_gb_apply_list_of_unequal_len_arrays():471 # GH1738472 df = DataFrame(473 {474 "group1": ["a", "a", "a", "b", "b", "b", "a", "a", "a", "b", "b", "b"],475 "group2": ["c", "c", "d", "d", "d", "e", "c", "c", "d", "d", "d", "e"],476 "weight": [1.1, 2, 3, 4, 5, 6, 2, 4, 6, 8, 1, 2],477 "value": [7.1, 8, 9, 10, 11, 12, 8, 7, 6, 5, 4, 3],478 }479 )480 df = df.set_index(["group1", "group2"])481 df_grouped = df.groupby(level=["group1", "group2"], sort=True)482 def noddy(value, weight):483 out = np.array(value * weight).repeat(3)484 return out485 # the kernel function returns arrays of unequal length486 # pandas sniffs the first one, sees it's an array and not487 # a list, and assumed the rest are of equal length488 # and so tries a vstack489 # don't die490 df_grouped.apply(lambda x: noddy(x.value, x.weight))491def test_groupby_apply_all_none():492 # Tests to make sure no errors if apply function returns all None493 # values. Issue 9684.494 test_df = DataFrame({"groups": [0, 0, 1, 1], "random_vars": [8, 7, 4, 5]})495 def test_func(x):496 pass497 result = test_df.groupby("groups").apply(test_func)498 expected = DataFrame()499 tm.assert_frame_equal(result, expected)500def test_groupby_apply_none_first():501 # GH 12824. Tests if apply returns None first.502 test_df1 = DataFrame({"groups": [1, 1, 1, 2], "vars": [0, 1, 2, 3]})503 test_df2 = DataFrame({"groups": [1, 2, 2, 2], "vars": [0, 1, 2, 3]})504 def test_func(x):505 if x.shape[0] < 2:506 return None507 return x.iloc[[0, -1]]508 result1 = test_df1.groupby("groups").apply(test_func)509 result2 = test_df2.groupby("groups").apply(test_func)510 index1 = MultiIndex.from_arrays([[1, 1], [0, 2]], names=["groups", None])511 index2 = MultiIndex.from_arrays([[2, 2], [1, 3]], names=["groups", None])512 expected1 = DataFrame({"groups": [1, 1], "vars": [0, 2]}, index=index1)513 expected2 = DataFrame({"groups": [2, 2], "vars": [1, 3]}, index=index2)514 tm.assert_frame_equal(result1, expected1)515 tm.assert_frame_equal(result2, expected2)516def test_groupby_apply_return_empty_chunk():517 # GH 22221: apply filter which returns some empty groups518 df = pd.DataFrame(dict(value=[0, 1], group=["filled", "empty"]))519 groups = df.groupby("group")520 result = groups.apply(lambda group: group[group.value != 1]["value"])521 expected = pd.Series(522 [0],523 name="value",524 index=MultiIndex.from_product(525 [["empty", "filled"], [0]], names=["group", None]526 ).drop("empty"),527 )528 tm.assert_series_equal(result, expected)529def test_apply_with_mixed_types():530 # gh-20949531 df = pd.DataFrame({"A": "a a b".split(), "B": [1, 2, 3], "C": [4, 6, 5]})532 g = df.groupby("A")533 result = g.transform(lambda x: x / x.sum())534 expected = pd.DataFrame({"B": [1 / 3.0, 2 / 3.0, 1], "C": [0.4, 0.6, 1.0]})535 tm.assert_frame_equal(result, expected)536 result = g.apply(lambda x: x / x.sum())537 tm.assert_frame_equal(result, expected)538def test_func_returns_object():539 # GH 28652540 df = DataFrame({"a": [1, 2]}, index=pd.Int64Index([1, 2]))541 result = df.groupby("a").apply(lambda g: g.index)542 expected = Series(543 [pd.Int64Index([1]), pd.Int64Index([2])], index=pd.Int64Index([1, 2], name="a")544 )545 tm.assert_series_equal(result, expected)546@pytest.mark.parametrize(547 "group_column_dtlike",548 [datetime.today(), datetime.today().date(), datetime.today().time()],549)550def test_apply_datetime_issue(group_column_dtlike):551 # GH-28247552 # groupby-apply throws an error if one of the columns in the DataFrame553 # is a datetime object and the column labels are different from554 # standard int values in range(len(num_columns))555 df = pd.DataFrame({"a": ["foo"], "b": [group_column_dtlike]})556 result = df.groupby("a").apply(lambda x: pd.Series(["spam"], index=[42]))557 expected = pd.DataFrame(558 ["spam"], Index(["foo"], dtype="object", name="a"), columns=[42]559 )560 tm.assert_frame_equal(result, expected)561def test_apply_series_return_dataframe_groups():562 # GH 10078563 tdf = DataFrame(564 {565 "day": {566 0: pd.Timestamp("2015-02-24 00:00:00"),567 1: pd.Timestamp("2015-02-24 00:00:00"),568 2: pd.Timestamp("2015-02-24 00:00:00"),569 3: pd.Timestamp("2015-02-24 00:00:00"),570 4: pd.Timestamp("2015-02-24 00:00:00"),571 },572 "userAgent": {573 0: "some UA string",574 1: "some UA string",575 2: "some UA string",576 3: "another UA string",577 4: "some UA string",578 },579 "userId": {580 0: "17661101",581 1: "17661101",582 2: "17661101",583 3: "17661101",584 4: "17661101",585 },586 }587 )588 def most_common_values(df):589 return Series({c: s.value_counts().index[0] for c, s in df.iteritems()})590 result = tdf.groupby("day").apply(most_common_values)["userId"]591 expected = pd.Series(592 ["17661101"], index=pd.DatetimeIndex(["2015-02-24"], name="day"), name="userId"593 )594 tm.assert_series_equal(result, expected)595@pytest.mark.parametrize("category", [False, True])596def test_apply_multi_level_name(category):597 # https://github.com/pandas-dev/pandas/issues/31068598 b = [1, 2] * 5599 if category:600 b = pd.Categorical(b, categories=[1, 2, 3])601 df = pd.DataFrame(602 {"A": np.arange(10), "B": b, "C": list(range(10)), "D": list(range(10))}603 ).set_index(["A", "B"])604 result = df.groupby("B").apply(lambda x: x.sum())605 expected = pd.DataFrame(606 {"C": [20, 25], "D": [20, 25]}, index=pd.Index([1, 2], name="B")607 )608 tm.assert_frame_equal(result, expected)609 assert df.index.names == ["A", "B"]610@pytest.mark.parametrize(611 "index",612 [613 pd.CategoricalIndex(list("abc")),614 pd.interval_range(0, 3),615 pd.period_range("2020", periods=3, freq="D"),616 pd.MultiIndex.from_tuples([("a", 0), ("a", 1), ("b", 0)]),617 ],618)619def test_apply_index_has_complex_internals(index):620 # GH 31248621 df = DataFrame({"group": [1, 1, 2], "value": [0, 1, 0]}, index=index)622 result = df.groupby("group").apply(lambda x: x)623 tm.assert_frame_equal(result, df)624@pytest.mark.parametrize(625 "function, expected_values",626 [627 (lambda x: x.index.to_list(), [[0, 1], [2, 3]]),628 (lambda x: set(x.index.to_list()), [{0, 1}, {2, 3}]),629 (lambda x: tuple(x.index.to_list()), [(0, 1), (2, 3)]),630 (631 lambda x: {n: i for (n, i) in enumerate(x.index.to_list())},632 [{0: 0, 1: 1}, {0: 2, 1: 3}],633 ),634 (635 lambda x: [{n: i} for (n, i) in enumerate(x.index.to_list())],636 [[{0: 0}, {1: 1}], [{0: 2}, {1: 3}]],637 ),638 ],639)640def test_apply_function_returns_non_pandas_non_scalar(function, expected_values):641 # GH 31441642 df = pd.DataFrame(["A", "A", "B", "B"], columns=["groups"])643 result = df.groupby("groups").apply(function)644 expected = pd.Series(expected_values, index=pd.Index(["A", "B"], name="groups"))...

Full Screen

Full Screen

dbobj.py

Source:dbobj.py Github

copy

Full Screen

...37 import collections38 MutableMapping = collections.MutableMapping39class DBEnv:40 def __init__(self, *args, **kwargs):41 self._cobj = apply(db.DBEnv, args, kwargs)42 def close(self, *args, **kwargs):43 return apply(self._cobj.close, args, kwargs)44 def open(self, *args, **kwargs):45 return apply(self._cobj.open, args, kwargs)46 def remove(self, *args, **kwargs):47 return apply(self._cobj.remove, args, kwargs)48 def set_shm_key(self, *args, **kwargs):49 return apply(self._cobj.set_shm_key, args, kwargs)50 def set_cachesize(self, *args, **kwargs):51 return apply(self._cobj.set_cachesize, args, kwargs)52 def set_data_dir(self, *args, **kwargs):53 return apply(self._cobj.set_data_dir, args, kwargs)54 def set_flags(self, *args, **kwargs):55 return apply(self._cobj.set_flags, args, kwargs)56 def set_lg_bsize(self, *args, **kwargs):57 return apply(self._cobj.set_lg_bsize, args, kwargs)58 def set_lg_dir(self, *args, **kwargs):59 return apply(self._cobj.set_lg_dir, args, kwargs)60 def set_lg_max(self, *args, **kwargs):61 return apply(self._cobj.set_lg_max, args, kwargs)62 def set_lk_detect(self, *args, **kwargs):63 return apply(self._cobj.set_lk_detect, args, kwargs)64 if db.version() < (4,5):65 def set_lk_max(self, *args, **kwargs):66 return apply(self._cobj.set_lk_max, args, kwargs)67 def set_lk_max_locks(self, *args, **kwargs):68 return apply(self._cobj.set_lk_max_locks, args, kwargs)69 def set_lk_max_lockers(self, *args, **kwargs):70 return apply(self._cobj.set_lk_max_lockers, args, kwargs)71 def set_lk_max_objects(self, *args, **kwargs):72 return apply(self._cobj.set_lk_max_objects, args, kwargs)73 def set_mp_mmapsize(self, *args, **kwargs):74 return apply(self._cobj.set_mp_mmapsize, args, kwargs)75 def set_timeout(self, *args, **kwargs):76 return apply(self._cobj.set_timeout, args, kwargs)77 def set_tmp_dir(self, *args, **kwargs):78 return apply(self._cobj.set_tmp_dir, args, kwargs)79 def txn_begin(self, *args, **kwargs):80 return apply(self._cobj.txn_begin, args, kwargs)81 def txn_checkpoint(self, *args, **kwargs):82 return apply(self._cobj.txn_checkpoint, args, kwargs)83 def txn_stat(self, *args, **kwargs):84 return apply(self._cobj.txn_stat, args, kwargs)85 def set_tx_max(self, *args, **kwargs):86 return apply(self._cobj.set_tx_max, args, kwargs)87 def set_tx_timestamp(self, *args, **kwargs):88 return apply(self._cobj.set_tx_timestamp, args, kwargs)89 def lock_detect(self, *args, **kwargs):90 return apply(self._cobj.lock_detect, args, kwargs)91 def lock_get(self, *args, **kwargs):92 return apply(self._cobj.lock_get, args, kwargs)93 def lock_id(self, *args, **kwargs):94 return apply(self._cobj.lock_id, args, kwargs)95 def lock_put(self, *args, **kwargs):96 return apply(self._cobj.lock_put, args, kwargs)97 def lock_stat(self, *args, **kwargs):98 return apply(self._cobj.lock_stat, args, kwargs)99 def log_archive(self, *args, **kwargs):100 return apply(self._cobj.log_archive, args, kwargs)101 def set_get_returns_none(self, *args, **kwargs):102 return apply(self._cobj.set_get_returns_none, args, kwargs)103 def log_stat(self, *args, **kwargs):104 return apply(self._cobj.log_stat, args, kwargs)105 if db.version() >= (4,1):106 def dbremove(self, *args, **kwargs):107 return apply(self._cobj.dbremove, args, kwargs)108 def dbrename(self, *args, **kwargs):109 return apply(self._cobj.dbrename, args, kwargs)110 def set_encrypt(self, *args, **kwargs):111 return apply(self._cobj.set_encrypt, args, kwargs)112 if db.version() >= (4,4):113 def lsn_reset(self, *args, **kwargs):114 return apply(self._cobj.lsn_reset, args, kwargs)115class DB(MutableMapping):116 def __init__(self, dbenv, *args, **kwargs):117 # give it the proper DBEnv C object that its expecting118 self._cobj = apply(db.DB, (dbenv._cobj,) + args, kwargs)119 # TODO are there other dict methods that need to be overridden?120 def __len__(self):121 return len(self._cobj)122 def __getitem__(self, arg):123 return self._cobj[arg]124 def __setitem__(self, key, value):125 self._cobj[key] = value126 def __delitem__(self, arg):127 del self._cobj[arg]128 if sys.version_info[0:2] >= (2, 6) :129 def __iter__(self) :130 return self._cobj.__iter__()131 def append(self, *args, **kwargs):132 return apply(self._cobj.append, args, kwargs)133 def associate(self, *args, **kwargs):134 return apply(self._cobj.associate, args, kwargs)135 def close(self, *args, **kwargs):136 return apply(self._cobj.close, args, kwargs)137 def consume(self, *args, **kwargs):138 return apply(self._cobj.consume, args, kwargs)139 def consume_wait(self, *args, **kwargs):140 return apply(self._cobj.consume_wait, args, kwargs)141 def cursor(self, *args, **kwargs):142 return apply(self._cobj.cursor, args, kwargs)143 def delete(self, *args, **kwargs):144 return apply(self._cobj.delete, args, kwargs)145 def fd(self, *args, **kwargs):146 return apply(self._cobj.fd, args, kwargs)147 def get(self, *args, **kwargs):148 return apply(self._cobj.get, args, kwargs)149 def pget(self, *args, **kwargs):150 return apply(self._cobj.pget, args, kwargs)151 def get_both(self, *args, **kwargs):152 return apply(self._cobj.get_both, args, kwargs)153 def get_byteswapped(self, *args, **kwargs):154 return apply(self._cobj.get_byteswapped, args, kwargs)155 def get_size(self, *args, **kwargs):156 return apply(self._cobj.get_size, args, kwargs)157 def get_type(self, *args, **kwargs):158 return apply(self._cobj.get_type, args, kwargs)159 def join(self, *args, **kwargs):160 return apply(self._cobj.join, args, kwargs)161 def key_range(self, *args, **kwargs):162 return apply(self._cobj.key_range, args, kwargs)163 def has_key(self, *args, **kwargs):164 return apply(self._cobj.has_key, args, kwargs)165 def items(self, *args, **kwargs):166 return apply(self._cobj.items, args, kwargs)167 def keys(self, *args, **kwargs):168 return apply(self._cobj.keys, args, kwargs)169 def open(self, *args, **kwargs):170 return apply(self._cobj.open, args, kwargs)171 def put(self, *args, **kwargs):172 return apply(self._cobj.put, args, kwargs)173 def remove(self, *args, **kwargs):174 return apply(self._cobj.remove, args, kwargs)175 def rename(self, *args, **kwargs):176 return apply(self._cobj.rename, args, kwargs)177 def set_bt_minkey(self, *args, **kwargs):178 return apply(self._cobj.set_bt_minkey, args, kwargs)179 def set_bt_compare(self, *args, **kwargs):180 return apply(self._cobj.set_bt_compare, args, kwargs)181 def set_cachesize(self, *args, **kwargs):182 return apply(self._cobj.set_cachesize, args, kwargs)183 def set_flags(self, *args, **kwargs):184 return apply(self._cobj.set_flags, args, kwargs)185 def set_h_ffactor(self, *args, **kwargs):186 return apply(self._cobj.set_h_ffactor, args, kwargs)187 def set_h_nelem(self, *args, **kwargs):188 return apply(self._cobj.set_h_nelem, args, kwargs)189 def set_lorder(self, *args, **kwargs):190 return apply(self._cobj.set_lorder, args, kwargs)191 def set_pagesize(self, *args, **kwargs):192 return apply(self._cobj.set_pagesize, args, kwargs)193 def set_re_delim(self, *args, **kwargs):194 return apply(self._cobj.set_re_delim, args, kwargs)195 def set_re_len(self, *args, **kwargs):196 return apply(self._cobj.set_re_len, args, kwargs)197 def set_re_pad(self, *args, **kwargs):198 return apply(self._cobj.set_re_pad, args, kwargs)199 def set_re_source(self, *args, **kwargs):200 return apply(self._cobj.set_re_source, args, kwargs)201 def set_q_extentsize(self, *args, **kwargs):202 return apply(self._cobj.set_q_extentsize, args, kwargs)203 def stat(self, *args, **kwargs):204 return apply(self._cobj.stat, args, kwargs)205 def sync(self, *args, **kwargs):206 return apply(self._cobj.sync, args, kwargs)207 def type(self, *args, **kwargs):208 return apply(self._cobj.type, args, kwargs)209 def upgrade(self, *args, **kwargs):210 return apply(self._cobj.upgrade, args, kwargs)211 def values(self, *args, **kwargs):212 return apply(self._cobj.values, args, kwargs)213 def verify(self, *args, **kwargs):214 return apply(self._cobj.verify, args, kwargs)215 def set_get_returns_none(self, *args, **kwargs):216 return apply(self._cobj.set_get_returns_none, args, kwargs)217 if db.version() >= (4,1):218 def set_encrypt(self, *args, **kwargs):219 return apply(self._cobj.set_encrypt, args, kwargs)220class DBSequence:221 def __init__(self, *args, **kwargs):222 self._cobj = apply(db.DBSequence, args, kwargs)223 def close(self, *args, **kwargs):224 return apply(self._cobj.close, args, kwargs)225 def get(self, *args, **kwargs):226 return apply(self._cobj.get, args, kwargs)227 def get_dbp(self, *args, **kwargs):228 return apply(self._cobj.get_dbp, args, kwargs)229 def get_key(self, *args, **kwargs):230 return apply(self._cobj.get_key, args, kwargs)231 def init_value(self, *args, **kwargs):232 return apply(self._cobj.init_value, args, kwargs)233 def open(self, *args, **kwargs):234 return apply(self._cobj.open, args, kwargs)235 def remove(self, *args, **kwargs):236 return apply(self._cobj.remove, args, kwargs)237 def stat(self, *args, **kwargs):238 return apply(self._cobj.stat, args, kwargs)239 def set_cachesize(self, *args, **kwargs):240 return apply(self._cobj.set_cachesize, args, kwargs)241 def set_flags(self, *args, **kwargs):242 return apply(self._cobj.set_flags, args, kwargs)243 def set_range(self, *args, **kwargs):244 return apply(self._cobj.set_range, args, kwargs)245 def get_cachesize(self, *args, **kwargs):246 return apply(self._cobj.get_cachesize, args, kwargs)247 def get_flags(self, *args, **kwargs):248 return apply(self._cobj.get_flags, args, kwargs)249 def get_range(self, *args, **kwargs):...

Full Screen

Full Screen

test_common.py

Source:test_common.py Github

copy

Full Screen

1import numpy as np2from agents.common import BoardPiece, NO_PLAYER3def test_initialize_game_state():4 from agents.common import initialize_game_state5 ret = initialize_game_state()6 assert isinstance(ret, np.ndarray)7 assert ret.dtype == BoardPiece8 assert ret.shape == (6, 7)9 assert np.all(ret == NO_PLAYER)10def test_apply_player_action():11 from agents.common import initialize_game_state12 from agents.common import apply_player_action13 board = initialize_game_state()14 board[0, 1] = BoardPiece(1)15 board[0, 2] = BoardPiece(2)16 board[1, 1] = BoardPiece(1)17 ret = apply_player_action(board, 2, BoardPiece(2), False)18 assert ret.dtype == BoardPiece19 assert ret.shape == (6, 7)20 assert isinstance(ret, np.ndarray)21 assert ret[1, 2] == BoardPiece(2)22 board = initialize_game_state()23 ret = apply_player_action(board, 2, BoardPiece(2), False)24 assert ret[0, 2] == BoardPiece(2)25 ret = apply_player_action(board, 2, BoardPiece(1), False)26 assert ret[1, 2] == BoardPiece(1)27 ret = apply_player_action(board, 3, BoardPiece(2), False)28 assert ret[0, 3] == BoardPiece(2)29 ret = apply_player_action(board, 3, BoardPiece(1), False)30 assert ret[1, 3] == BoardPiece(1)31 ret = apply_player_action(board, 2, BoardPiece(2), False)32 assert ret[2, 2] == BoardPiece(2)33 assert isinstance(ret, np.ndarray)34 assert ret.dtype == BoardPiece35 assert ret.shape == (6, 7)36def test_connected_four():37 from agents.common import initialize_game_state38 from agents.common import apply_player_action39 from agents.common import connected_four40 board = initialize_game_state()41 # TRUE TESTS42 # vertical43 apply_player_action(board, 2, BoardPiece(2), False)44 apply_player_action(board, 2, BoardPiece(1), False)45 apply_player_action(board, 3, BoardPiece(2), False)46 apply_player_action(board, 2, BoardPiece(1), False)47 apply_player_action(board, 3, BoardPiece(2), False)48 apply_player_action(board, 2, BoardPiece(1), False)49 apply_player_action(board, 3, BoardPiece(2), False)50 apply_player_action(board, 2, BoardPiece(1), False)51 ret = connected_four(board, BoardPiece(1))52 assert isinstance(ret, bool)53 assert ret == True54 # horizontal55 board = initialize_game_state()56 apply_player_action(board, 2, BoardPiece(1), False)57 apply_player_action(board, 2, BoardPiece(2), False)58 apply_player_action(board, 3, BoardPiece(1), False)59 apply_player_action(board, 2, BoardPiece(2), False)60 apply_player_action(board, 4, BoardPiece(1), False)61 apply_player_action(board, 2, BoardPiece(2), False)62 apply_player_action(board, 5, BoardPiece(1), False)63 ret = connected_four(board, 1, 5)64 assert isinstance(ret, bool)65 assert ret == True66 # left right diagonal67 board = initialize_game_state()68 apply_player_action(board, 0, BoardPiece(1), False)69 apply_player_action(board, 0, BoardPiece(2), False)70 apply_player_action(board, 0, BoardPiece(1), False)71 apply_player_action(board, 1, BoardPiece(2), False)72 apply_player_action(board, 1, BoardPiece(1), False)73 apply_player_action(board, 2, BoardPiece(2), False)74 apply_player_action(board, 5, BoardPiece(1), False)75 apply_player_action(board, 2, BoardPiece(2), False)76 apply_player_action(board, 2, BoardPiece(1), False)77 apply_player_action(board, 3, BoardPiece(2), False)78 apply_player_action(board, 4, BoardPiece(1), False)79 apply_player_action(board, 3, BoardPiece(2), False)80 apply_player_action(board, 4, BoardPiece(1), False)81 apply_player_action(board, 3, BoardPiece(2), False)82 apply_player_action(board, 3, BoardPiece(1), False)83 ret = connected_four(board, 1, 3)84 assert isinstance(ret, bool)85 assert ret == True86 # right left diagonal87 board = initialize_game_state()88 apply_player_action(board, 0, BoardPiece(1), False)89 apply_player_action(board, 0, BoardPiece(2), False)90 apply_player_action(board, 0, BoardPiece(1), False)91 apply_player_action(board, 1, BoardPiece(2), False)92 apply_player_action(board, 1, BoardPiece(1), False)93 apply_player_action(board, 2, BoardPiece(2), False)94 apply_player_action(board, 5, BoardPiece(1), False)95 apply_player_action(board, 2, BoardPiece(2), False)96 apply_player_action(board, 2, BoardPiece(1), False)97 apply_player_action(board, 3, BoardPiece(2), False)98 apply_player_action(board, 4, BoardPiece(1), False)99 apply_player_action(board, 3, BoardPiece(2), False)100 apply_player_action(board, 4, BoardPiece(1), False)101 apply_player_action(board, 1, BoardPiece(2), False)102 apply_player_action(board, 3, BoardPiece(1), False)103 apply_player_action(board, 0, BoardPiece(2), False)104 ret = connected_four(board, 2, 0)105 assert isinstance(ret, bool)106 assert ret == True107 # FALSE TESTS108 # vertical109 board = initialize_game_state()110 apply_player_action(board, 2, BoardPiece(2), False)111 apply_player_action(board, 2, BoardPiece(1), False)112 apply_player_action(board, 3, BoardPiece(2), False)113 apply_player_action(board, 2, BoardPiece(1), False)114 apply_player_action(board, 3, BoardPiece(2), False)115 apply_player_action(board, 2, BoardPiece(1), False)116 apply_player_action(board, 3, BoardPiece(2), False)117 ret = connected_four(board, BoardPiece(2), 3)118 assert ret == False119 # horizontal120 board = initialize_game_state()121 apply_player_action(board, 2, BoardPiece(1), False)122 apply_player_action(board, 2, BoardPiece(2), False)123 apply_player_action(board, 3, BoardPiece(1), False)124 apply_player_action(board, 2, BoardPiece(2), False)125 apply_player_action(board, 4, BoardPiece(1), False)126 apply_player_action(board, 2, BoardPiece(2), False)127 ret = connected_four(board, 2, 2)128 assert isinstance(ret, bool)129 assert ret == False130 # left right diagonal131 board = initialize_game_state()132 apply_player_action(board, 0, BoardPiece(1), False)133 apply_player_action(board, 0, BoardPiece(2), False)134 apply_player_action(board, 0, BoardPiece(1), False)135 apply_player_action(board, 1, BoardPiece(2), False)136 apply_player_action(board, 1, BoardPiece(1), False)137 apply_player_action(board, 2, BoardPiece(2), False)138 apply_player_action(board, 5, BoardPiece(1), False)139 apply_player_action(board, 2, BoardPiece(2), False)140 apply_player_action(board, 2, BoardPiece(1), False)141 apply_player_action(board, 3, BoardPiece(2), False)142 apply_player_action(board, 4, BoardPiece(1), False)143 apply_player_action(board, 3, BoardPiece(2), False)144 apply_player_action(board, 4, BoardPiece(1), False)145 ret = connected_four(board, BoardPiece(1), 4)146 assert ret == False147 # right left diagonal148 board = initialize_game_state()149 apply_player_action(board, 0, BoardPiece(1), False)150 apply_player_action(board, 0, BoardPiece(2), False)151 apply_player_action(board, 0, BoardPiece(1), False)152 apply_player_action(board, 1, BoardPiece(2), False)153 apply_player_action(board, 1, BoardPiece(1), False)154 apply_player_action(board, 2, BoardPiece(2), False)155 apply_player_action(board, 5, BoardPiece(1), False)156 apply_player_action(board, 2, BoardPiece(2), False)157 apply_player_action(board, 2, BoardPiece(1), False)158 apply_player_action(board, 3, BoardPiece(2), False)159 apply_player_action(board, 4, BoardPiece(1), False)160 apply_player_action(board, 3, BoardPiece(2), False)161 apply_player_action(board, 4, BoardPiece(1), False)162 apply_player_action(board, 1, BoardPiece(2), False)163 ret = connected_four(board, 2, 1)164 assert isinstance(ret, bool)165 assert ret == False166 # NO WIN TEST167 board = initialize_game_state()168 apply_player_action(board, 2, BoardPiece(2), False)169 apply_player_action(board, 2, BoardPiece(1), False)170 apply_player_action(board, 3, BoardPiece(2), False)171 apply_player_action(board, 2, BoardPiece(1), False)172 apply_player_action(board, 3, BoardPiece(2), False)173 apply_player_action(board, 2, BoardPiece(1), False)174 apply_player_action(board, 3, BoardPiece(2), False)175 ret = connected_four(board, BoardPiece(1))176 assert isinstance(ret, bool)177 assert ret == False178def test_check_end_state():179 from agents.common import check_end_state180 from agents.common import apply_player_action181 from agents.common import initialize_game_state182 from agents.common import GameState183 from agents.common import pretty_print_board184 # test 'is win'185 board = initialize_game_state()186 apply_player_action(board, 2, BoardPiece(1), False)187 apply_player_action(board, 2, BoardPiece(2), False)188 apply_player_action(board, 3, BoardPiece(1), False)189 apply_player_action(board, 2, BoardPiece(2), False)190 apply_player_action(board, 4, BoardPiece(1), False)191 apply_player_action(board, 2, BoardPiece(2), False)192 apply_player_action(board, 5, BoardPiece(1), False)193 ret = check_end_state(board, BoardPiece(1), 5)194 assert isinstance(ret, GameState)195 assert ret == GameState.IS_WIN196 # test still playing197 board = initialize_game_state()198 apply_player_action(board, 2, BoardPiece(2), True)199 apply_player_action(board, 3, BoardPiece(1), True)200 ret = check_end_state(board, 1, 3)201 assert ret == GameState.STILL_PLAYING202 # test is draw203 board[:, 0] = BoardPiece(1)204 board[:, 1:3] = BoardPiece(2)205 board[:, 3:5] = BoardPiece(1)206 board[:, 5:7] = BoardPiece(2)207 board[3:5, :] = BoardPiece(1)208 board[1, :] = BoardPiece(2)209 ret = check_end_state(board, 2, 5)210 assert ret == GameState.IS_DRAW211def test_pretty_print_board():212 from agents.common import pretty_print_board213 board = np.zeros((6, 7))214 board[0, 0:7] = [1, 2, 2, 1, 1, 1, 2]215 board[1, 0:7] = [2, 1, 2, 1, 2, 2, 1]216 board[2, 0:7] = [1, 2, 1, 2, 0, 0, 0]217 board[3, 0:7] = [2, 2, 1, 0, 0, 0, 0]218 board[4, 0:7] = [1, 1, 0, 0, 0, 0, 0]219 board[5, 0:7] = [2, 0, 0, 0, 0, 0, 0]220 boardStr = '|==============|\n' \221 '|O |\n' \222 '|X X |\n' \223 '|O O X |\n' \224 '|X O X O |\n' \225 '|O X O X O O X |\n' \226 '|X O O X X X O |\n' \227 '|==============|\n' \228 '|0 1 2 3 4 5 6 |'229 assert boardStr == pretty_print_board(board)230def test_string_to_board():231 from agents.common import string_to_board232 board = np.zeros((6, 7))233 board[0, 0:7] = [1, 2, 2, 1, 1, 1, 2]234 board[1, 0:7] = [2, 1, 2, 1, 2, 2, 1]235 board[2, 0:7] = [1, 2, 1, 2, 0, 0, 0]236 board[3, 0:7] = [2, 2, 1, 0, 0, 0, 0]237 board[4, 0:7] = [1, 1, 0, 0, 0, 0, 0]238 board[5, 0:7] = [2, 0, 0, 0, 0, 0, 0]239 boardStr = '|==============|\n' \240 '|O |\n' \241 '|X X |\n' \242 '|O O X |\n' \243 '|X O X O |\n' \244 '|O X O X O O X |\n' \245 '|X O O X X X O |\n' \246 '|==============|\n' \247 '|0 1 2 3 4 5 6 |'...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run localstack automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful