text:
Q: Python Regex String Extraction when the string is a number ranging from 0 to 9,999,999.99 and has either no commas or multiple commas Im looking for a way to extract this string our of this CSV list. Im thinking i need to change the , as they are giving me a issue but im not sure. the number at the end can rang from 0 to 9,999,999.00 and can have 0 commas or multiple
Transfer Out Pick - Total,EACH,42,552

CSV LIST:
    ['Actual Plan YOY Improvement,Main Processes Core Processes Line Items Unit Vol Hrs Rate Rate Hrs Δ to Plan (Hrs) % to Plan PY Volume (Base) PY Rate Hrs @ CY Rate Hrs @ PY Rate YOY %,Inbound Receive,Receive Dock,-,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,Each Receive - Small,EACH,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,Each Receive - Medium,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,Each Receive - Large,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,Each Receive - Heavy/Bulky,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,Each Receive - Total,EACH,0,0,0,0,0,0,0%,0.0,0,0,0,0%,Each To Bin - Small,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,Each To Bin - Medium,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,Each To Bin - Large,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,Each To Bin - Heavy/Bulky,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,Each To Bin - Total,EACH,0,0,0,0,0,0,0%,0.0,0,0,0,0%,Case Receive,Case,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,LP Receive,Case,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,Pallet Receive,Pallet,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,Receive Support,-,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,Receive - Total,EACH,0,0,0,0,0,0,0%,0.0,0,0,0,0%,Transfer In and Stow,Transfer In Decant,Case,16,412,248.45,66.06,52.84,310.6,62.14,125.01%,0.0,0,0,0,0%,Each Transfer In - Small,EACH,94,933,283.93,334.36,252.63,375.78,91.85,132.35%,0.0,0,0,0,0%,Each Transfer In - Medium,EACH,108,015,643.24,167.92,122.31,883.12,239.88,137.29%,0.0,0,0,0,0%,Each Transfer In - Large,EACH,952,8.18,116.35,107.17,8.88,0.7,108.57%,0.0,0,0,0,0%,Each Transfer In - Heavy/Bulky,EACH,0,0,0,196.02,0,0,0%,0.0,0,0,0,0%,Each Transfer In - Total,EACH,203,900,935.35,217.99,160.83,1,267.79,332.43,135.54%,0.0,0,0,0,0%,Case Transfer In,Case,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,Pallet Transfer In,Pallet,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,Transfer
In Support,-,203,900,160.17,1,273.01,1,138.5,179.1,18.92,111.81%,0.0,0,0,0,0%,Transfer In - Total,EACH,203,900,1,343.98,151.71,116.02,1,757.48,413.5,130.77%,0.0,0,0,0,0%,IB Prep,Cubiscan,EACH,42,0.42,100,10,000,0,-0.42,1%,0.0,0,0,0,0%,Sample Center,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,Prep Recorder - Small,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,Prep Recorder - Medium,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,Prep Recorder - Large,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,Prep Recorder - Heavy/Bulky,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,Prep Recorder - Total,EACH,0,0,0,0,0,0,0%,0.0,0,0,0,0%,Prep Support,-,42,0,0,10,000,0,0,0%,0.0,0,0,0,0%,Prep - Total,-,42,0.42,100,5,000,0.01,-0.41,2%,0.0,0,0,0,0%,Stow to Prime,Each Stow To Prime - Small,EACH,3,727,16.47,226.32,202.68,18.39,1.92,111.66%,0.0,0,0,0,0%,Each Stow To Prime - Medium,EACH,3,881,27.22,142.6,103.55,37.48,10.26,137.71%,0.0,0,0,0,0%,Each Stow To Prime - Large,EACH,53,0.49,107.8,102.08,0.52,0.03,105.6%,0.0,0,0,0,0%,Each Stow To Prime - Heavy/Bulky,EACH,0,0,0,183.89,0,0,0%,0.0,0,0,0,0%,Each Stow to Prime - Total,EACH,7,661,44.18,173.42,135.86,56.39,12.21,127.64%,0.0,0,0,0,0%,Case Stow to Prime,Case,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,Pallet Stow to Prime,Pallet,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,Stow to Prime Support,EACH,7,661,6.77,1,131.38,418.84,18.29,11.52,270.12%,0.0,0,0,0,0%,Stow to Prime - Total,EACH,7,661,50.95,150.37,102.59,74.68,23.73,146.58%,0.0,0,0,0,0%,RSR,Case Stow to Reserve,Case,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,Case Replenishment,CASE,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,Pallet Stow Reserve,Pallet,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,Pallet Replenishment,PALLET,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,RSR Support,-,535,759,34.04,15,740.64,29,431.41,18.2,-15.83,53.48%,0.0,0,0,0,0%,RSR - Total,-,535,759,34.04,15,740.64,29,431.41,18.2,-15.83,53.48%,0.0,0,0,0,0%,IB Lead/PA,IB Lead/PA,-,203,900,24.99,8,157.99,6,497.18,31.38,6.39,125.56%,0.0,0,0,0,0%,IB Defect,IB Problem Solve,-,203,900,146.27,1,394.04,1,127.9,180.78,34.51,123.6%,0.0,0,0,0,0%,TOTAL,IB Total,EACH,203,900,1,600.64,127.39,98.86,2,062.53,461.89,128.86%,0.0,0,0,0,0%,DA - Building to Building Transfer RC Stow,RC Case Stow,Case,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,RC Pallet Stow,Pallet,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,RC Pick,RC Pick - Library,Case,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,RC Pick - Pallet Rack,Case,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,RC Sort,RC Presort Cases,Case,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,RC Sort - Small,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,RC Sort - Medium,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,RC Sort - Large,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,RC Sort - Heavy/Bulky,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,RC Sort - Total,-,0,0,0,0,0,0,0%,0.0,0,0,0,0%,Transfer Out Pick,Transfer Out Pick - Small,EACH,18,982,60.66,312.93,272.1,69.76,9.1,115%,0.0,0,0,0,0%,Transfer Out Pick - Medium,EACH,22,538,81.44,276.75,243.05,92.73,11.29,113.87%,0.0,0,0,0,0%,Transfer Out Pick - Large,EACH,32,0.16,198.62,272.68,0.12,-0.04,72.84%,0.0,0,0,0,0%,Transfer Out Pick - Heavy/Bulky,EACH,0,0,0,153.8,0,0,0%,0.0,0,0,0,0%,Transfer Out Pick - Total,EACH,42,552,142.26,292.09,255.53,162.61,20.35,114.31%,0.0,0,0,0,0%,Transfer Out,Transfer Out,EACH,41,336,183.96,224.7,375.5,110.08,-73.88,59.84%,0.0,0,0,0,0%,Transfer Out Dock,Transfer Out Dock,-,41,336,46.44,890.06,171.68,240.77,194.33,518.44%,0.0,0,0,0,0%,TO Lead/PA,TO Lead/PA,-,41,336,0,0,5,021.96,8.23,8.23,0%,0.0,0,0,0,0%,TO Defect,TO Problem Solve,-,41,336,0,0,25,053,679,767.17,0,0,0%,0.0,0,0,0,0%,TOTAL,DA Bldg to Bldg Transfer TOTAL,-,41,336,372.66,110.92,79.23,521.7,149.03,139.99%,0.0,0,0,0,0%,Outbound Pick,Pick - Small,EACH,131,919,467.44,282.21,249.27,529.22,61.78,113.22%,0.0,0,0,0,0%,Pick - Medium,EACH,160,891,622.21,258.58,234.65,685.66,63.46,110.2%,0.0,0,0,0,0%,Pick - Large,EACH,1,157,4.96,233.48,222.62,5.2,0.24,104.88%,0.0,0,0,0,0%,Pick - Heavy/Bulky,EACH,0,0,0,574.79,0,0,0%,0.0,0,0,0,0%,Pick - Total,EACH,293,967,1,094.6,268.56,240.94,1,220.08,125.48,111.46%,0.0,0,0,0,0%,Pick Support,-,335,519,171.66,1,954.57,2,148.7,156.15,-15.51,90.97%,0.0,0,0,0,0%,Pick Total (Incl. Support),-,293,967,1,266.26,232.15,213.6,1,376.23,109.97,108.68%,0.0,0,0,0,0%,Sort,Batch Sort - Small,EACH,0,0.09,0,1,034.13,0,-0.09,0%,0.0,0,0,0,0%,Batch Sort - Medium,EACH,0,0.09,0,493.2,0,-0.09,0%,0.0,0,0,0,0%,Batch Sort - Large,EACH,0,0.09,0,2,462.8,0,-0.09,0%,0.0,0,0,0,0%,Batch Sort - Heavy/Bulky,EACH,0,0.09,0,10,001.7,0,-0.09,0%,0.0,0,0,0,0%,Batch Sort - Total,EACH,0,0.37,0,0,0,-0.37,0%,0.0,0,0,0,0%,Flow Sort - Small,EACH,49,922,175.61,284.27,275.86,180.97,5.35,103.05%,0.0,0,0,0,0%,Flow Sort - Medium,EACH,49,617,178.3,278.28,264.68,187.46,9.16,105.14%,0.0,0,0,0,0%,Flow Sort - Large,EACH,242,0.71,341.78,251.69,0.96,0.25,135.79%,0.0,0,0,0,0%,Flow Sort - Heavy/Bulky,EACH,0,0,0,480.35,0,0,0%,0.0,0,0,0,0%,Flow Sort - Total,EACH,99,781,354.62,281.37,270.12,369.39,14.77,104.16%,0.0,0,0,0,0%,Sort Support,-,99,781,11,9,071,4,845.63,20.59,9.59,187.2%,0.0,0,0,0,0%,Sort - Total,EACH,99,781,365.99,272.63,255.86,389.98,23.99,106.56%,0.0,0,0,0,0%,Pack,Chutings - Small,EACH,49,597,330.84,149.91,138.16,358.98,28.15,108.51%,0.0,0,0,0,0%,Chutings - Medium,EACH,48,953,288.1,169.91,152.02,322.02,33.91,111.77%,0.0,0,0,0,0%,Chutings - Large,EACH,243,1.95,124.46,142.61,1.7,-0.25,87.27%,0.0,0,0,0,0%,Chutings - Heavy/Bulky,EACH,0,0,0,427.8,0,0,0%,0.0,0,0,0,0%,Pack Chuting - Total,EACH,98,793,620.89,159.11,144.71,682.7,61.81,109.96%,0.0,0,0,0,0%,Auto Slam,Package,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,Pack - Autobox,EACH,8,071,15.45,522.43,451.96,17.86,2.41,115.59%,0.0,0,0,0,0%,Pack - Lev/Autofold,EACH,37,472,77.94,480.8,501.71,74.69,-3.25,95.83%,0.0,0,0,0,0%,Pack Singles - Small,EACH,18,384,150.38,122.25,84.04,218.75,68.38,145.47%,0.0,0,0,0,0%,Pack Singles - Medium,EACH,48,937,635.84,76.96,64.55,758.13,122.29,119.23%,0.0,0,0,0,0%,Pack Singles - Large,EACH,594,13.01,45.65,34.95,17,3.98,130.61%,0.0,0,0,0,0%,Pack Singles - Heavy/Bulky,EACH,0,0,0,277,913.74,0,0,0%,0.0,0,0,0,0%,Pack Singles - Total,EACH,67,915,799.23,84.98,68.33,993.87,194.65,124.35%,0.0,0,0,0,0%,Pack Multis - Small,EACH,32,037,195.01,164.28,135.14,237.07,42.05,121.56%,0.0,0,0,0,0%,Pack Multis - Medium,EACH,43,437,252.05,172.33,131.85,329.44,77.39,130.7%,0.0,0,0,0,0%,Pack Multis - Large,EACH,253,2.76,91.7,130.83,1.93,-0.83,70.09%,0.0,0,0,0,0%,Pack Multis - Heavy/Bulky,EACH,0,0,0,284.19,0,0,0%,0.0,0,0,0,0%,Pack Multis - Total,EACH,75,727,449.82,168.35,133.22,568.44,118.62,126.37%,0.0,0,0,0,0%,Pack Support,-,290,523,443.55,654.99,771.17,376.73,-66.82,84.93%,0.0,0,0,0,0%,Outbound Prep,Giftwrap,EACH,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,Partner Prep,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,Library Services,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,Custom Packaging,EACH,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,Pack and OB Prep Total,EACH,290,523,2,406.88,120.71,107.03,2,714.3,307.41,112.77%,0.0,0,0,0,0%,OB Lead/PA,OB Lead/PA,EACH,290,523,204.35,1,421.7,1,123.14,258.67,54.32,126.58%,0.0,0,0,0,0%,OB Defect,OB Problem Solve,EACH,290,523,202.71,1,433.23,1,082.81,268.3,65.6,132.36%,0.0,0,0,0,0%,Ship,Ship Dock,EACH,290,523,1,135.86,255.77,257.79,1,126.98,-8.89,99.22%,0.0,0,0,0,0%,TOTAL,OB TOTAL,EACH,290,523,5,582.05,52.05,47.36,6,134.46,552.41,109.9%,0.0,0,0,0,0%,Reverse Logistics C-Return,C-Returns Processed - Small,EACH,0,0,0,77.19,0,0,0%,0.0,0,0,0,0%,C-Returns Processed - Medium,EACH,0,0,0,68.94,0,0,0%,0.0,0,0,0,0%,C-Returns Processed - Large,EACH,0,0,0,32.36,0,0,0%,0.0,0,0,0,0%,C-Returns Processed - Heavy/Bulky,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,C-Return Processed - Total,-,0,0,0,0,0,0,0%,0.0,0,0,0,0%,C-Return Stow - Small,EACH,0,0,0,28.1,0,0,0%,0.0,0,0,0,0%,C-Return Stow - Medium,EACH,0,0,0,21.39,0,0,0%,0.0,0,0,0,0%,C-Return Stow - Large,EACH,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,C-Return Stow - Heavy/Bulky,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,C-Return Stow - Total,-,0,0,0,0,0,0,0%,0.0,0,0,0,0%,C-Return Support,-,0,0,0,56.19,0,0,0%,0.0,0,0,0,0%,Customer Returns - Total,-,0,0,0,0,0,0,0%,0.0,0,0,0,0%,V-Return,V-Return Pick - Small,EACH,0,0,0,326,0,0,0%,0.0,0,0,0,0%,V-Return Pick - Medium,EACH,0,0,0,272.41,0,0,0%,0.0,0,0,0,0%,V-Return Pick - Large,EACH,0,0,0,191.31,0,0,0%,0.0,0,0,0,0%,V-Return Pick - Heavy/Bulky,EACH,0,0,0,179.99,0,0,0%,0.0,0,0,0,0%,V-Return Pick - Total,EACH,0,0,0,0,0,0,0%,0.0,0,0,0,0%,V-Return Pack - Small,EACH,0,0,0,323.28,0,0,0%,0.0,0,0,0,0%,V-Return Pack - Medium,EACH,0,0,0,202.97,0,0,0%,0.0,0,0,0,0%,V-Return Pack - Large,EACH,0,0,0,173.68,0,0,0%,0.0,0,0,0,0%,V-Return Pack - Heavy/Bulky,EACH,0,0,0,32.86,0,0,0%,0.0,0,0,0,0%,V-Return Pack - Total,EACH,0,0,0,0,0,0,0%,0.0,0,0,0,0%,V-Return Support,-,0,0,0,447.92,0,0,0%,0.0,0,0,0,0%,Vendor Returns - Total,EACH,0,0,0,0,0,0,0%,0.0,0,0,0,0%,Warehouse Deals,WHD Grading,EACH,0,0,0,18.95,0,0,0%,0.0,0,0,0,0%,WHD Specialty Grading,EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,WHD Support,-,0,0,0,10.38,0,0,0%,0.0,0,0,0,0%,Warehouse Deals - Total,-,0,0,0,0,0,0,0%,0.0,0,0,0,0%,External Repairs,External Repair Prep,EACH,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,External Repair Support,-,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,External Repair - Total,-,0,0,0,0,0,0,0%,0.0,0,0,0,0%,Trade In,Trade In Grading,EACH,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,Trade In Support,-,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,Trade In - Total,-,0,0,0,0,0,0,0%,0.0,0,0,0,0%,Kindle Diagnostics,Kindle Diagnostics,EACH,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,TOTAL,REVERSE LOGISTICS TOTAL,-,0,0,0,0,0,0,0%,0.0,0,0,0,0%,On-Demand On Demand,Print On Demand,EACH,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,Disc On Demand,EACH,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,Create Your Own Ring (CYOR),EACH,0,0,0,10,001.7,0,0,0%,0.0,0,0,0,0%,Support Support,Admin/HR/IT,-,331,859,245.54,1,351.54,596.63,556.22,310.68,226.53%,0.0,0,0,0,0%,On Boarding,-,331,859,0,0,0,0,0,0%,0.0,0,0,0,0%,AR Support,-,331,859,0,0,0,0,0,0%,0.0,0,0,0,0%,Non_FC_Controllable,-,331,859,111.52,2,975.66,12,438.49,26.68,-84.84,23.92%,0.0,0,0,0,0%,IC/QA/CS,-,535,759,476.69,1,123.93,925.49,578.89,102.21,121.44%,0.0,0,0,0,0%,Facilities,-,331,859,135.91,2,441.82,2,765.49,120,-15.91,88.3%,0.0,0,0,0,0%,Transport AmTran,Amtran In,Package,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,Amtran Sortation,Package,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,Amtran Out,Package,0,0,0,10,000,0,0,0%,0.0,0,0,0,0%,  FC Summary FC Summary,Vendor Rec (incl. Stow+Prep+RSR),EACH,0,256.66,0,0,305.05,48.39,118.85%,0.0,0,0,0,0%,Transfer-In,EACH,203,900,1,343.98,151.71,116.02,1,757.48,413.5,130.77%,0.0,0,0,0,0%,Total Inbound,EACH,203,900,1,600.64,127.39,98.86,2,062.53,461.89,128.86%,0.0,0,0,0,0%,Outbound,EACH,290,523,5,582.05,52.05,47.36,6,134.46,552.41,109.9%,0.0,0,0,0,0%,Transfer-Out,EACH,41,336,372.66,110.92,79.23,521.7,149.03,139.99%,0.0,0,0,0,0%,Reverse Logistics,EACH,0,0,0,0,0,0,0%,0.0,0,0,0,0%,On Demand,EACH,0,0,0,0,0,0,0%,0.0,0,0,0,0%,Support,EACH,331,859,969.66,342.24,258.9,1,281.79,312.13,132.19%,0.0,0,0,0,0%,Transport,Package,0,0,0,0,0,0,0%,0.0,0,0,0,0%,THROUGHPUT,EACH,535,759,8,525.01,62.85,53.57,10,000.48,1,475.47,117.31%,0.0,0,0,0,0%,  RC Summary RC Summary,Inbound,EACH,203,900,1,600.64,127.39,98.86,2,062.53,461.89,128.86%,0.0,0,0,0,0%,DA,EACH,41,336,372.66,110.92,79.23,521.7,149.03,139.99%,0.0,0,0,0,0%,Reverse Logistics,EACH,0,0,0,0,0,0,0%,0.0,0,0,0,0%,Support,EACH,41,336,858.13,48.17,32.93,1,255.11,396.98,146.26%,0.0,0,0,0,0%,Transport,Package,0,0,0,0,0,0,0%,0.0,0,0,0,0%,THROUGHPUT,EACH,245,236,2,831.44,86.61,63.87,3,839.34,1,007.9,135.6%,0.0,0,0,0,0%']

A: This example should help you. Try to get the name of the csv file, you can use Pandas Library for that. Then use the example below to get only numbers out of the string:
import re

txt = "126 7428,3453ssds"

numbers = re.findall('[0-9]', txt)

print(numbers)


text:
Q: How to resolve Python Attribute Error-'str' object has no attribute 'balance_inventory' My code throws the following errors:
Error 1:

{'iPhone Model xy': 100, 'Xiaomi Model YA': 1000, 'Nokia Model Zs': 25} iPhone Model X
  AttributeError Traceback (most recent call last) <ipython-input-51-e83a253ecf45> in <module> 50 51 Test_Inventory_Add_Stock.setup_class() ---> 52 Test_Inventory_Add_Stock.test_add_new_stock_as_dict()

Error 2:

AttributeError: 'str' object has no attribute 'balance_inventory' on Test_Inventory_Add_Stock.test_add_new_stock_as_dict()

Can anyone please help me on how to resolve this error?
class InsufficientException(Exception):
  pass
class MobileInventory:

    def __init__(self, inventory=None):
        if inventory == None:
            balance_inventory = {}
        elif not isinstance(inventory, dict):
            raise TypeError("Input inventory must be a dictionary")
        elif not (set(map(type, inventory)) == {str}):
            raise ValueError("Mobile model name must be a string")
        elif [True for i in inventory.values() if (not isinstance(i, int) or i < 1)]:
            raise ValueError("No. of mobiles must be a positive integer")
        self.balance_inventory = inventory
class add_stock():

    def __init__(self, m, new_stock):
        if not isinstance(new_stock, dict):
            raise TypeError("Input stock must be a dictionary")
        elif not (set(map(type, new_stock)) == {str}):
            raise ValueError("Mobile model name must be a string")
        elif [True for i in new_stock.values() if (not isinstance(i, int) or i < 1)]:
            raise ValueError("No. of mobiles must be a positive integer")
        for key, value in new_stock.items():
            print(key)
            if key in m.balance_inventory.keys():
                x = m.balance_inventory[key] + value
                m.balance_inventory[key] = x
            else:
                m.balance_inventory.update({key: value})
class Test_Inventory_Add_Stock:

    def setup_class():
        m = MobileInventory({'iPhone Model xy': 100, 'Xiaomi Model YA': 1000, 'Nokia Model Zs': 25})
        print(m.balance_inventory)

    def test_add_new_stock_as_dict():
        o={'iPhone Model X': 50, 'Xiaomi Model Y': 2000, 'Nokia Model A': 10}
        add_stock( m, o)
Test_Inventory_Add_Stock.setup_class()
Test_Inventory_Add_Stock.test_add_new_stock_as_dict()

A:     global m
    m = MobileInventory({'iPhone Model xy': 100, 'Xiaomi Model YA': 1000, 'Nokia Model Zs': 25})

redpajama_set_name: RedPajamaStackExchange


text:
Q: Printing to file works on Linux but not on Windows? So I wrote this code and it works perfectly fine on Linux.

*

*Reading data from file

*Do whatever my code is supposed to do

*Write the solutions on a new file.

Here's the part of the code that is supposed to do that:
outFile = open( "input.txt", "w" )

for item in oplist:
     outFile.write(item + "\n")

outFile.close

It works perfectly fine on Linux but on windows in only creates the new output file but doesn't write anything into it.
Please help!

A: You are not closing the file; you are merely referring to the close method. Call it:
outFile.close()

Without closing the file buffers won't be flushed until Python exits.
A better way to handle file closing is to use the with statement:
with open( "input.txt", "w" ) as outFile:
    for item in oplist:
        outFile.write(item + "\n")

Now the file is closed automatically.


text:
Q: Replace HTML between two tags What I want to do is replace what is in between two HTML tags.
I'm using this as a reference but I'm still encountering problems:
REFERENCE
This is what I've tried:
el.getValue().replace(/<form.+<\/form>/, "

");

I need to replace all my form tags dynamically.

A: If you use jQuery, just retrieve the parent element of what you'd like to be replaced, and replace the content with the .html() function.
Ex:
var formParentElement = $('#formParentElement');
formParentElement.html("
my new content
");

If you don't use jQuery:
var formParentElement = document.getElementById("formParentElement");
formParentElement.innerHTML = "
my new content
";

The example assumes the parent element of your form has an ID with value "formParentElement".

A: Yeah. I found a solution.
el.getValue().replace(/<form[\s\S]*?<\/form>/, "

");

Explanation by @[James G]:
[\s\S]*? means [any character including space and line breaks]any number of times, and the ? makes the asterisk "not greedy," so it will stop (more quickly) when it finds </form>.
Reference


text:
Q: JavaScript Revealing Module pattern private variable state I have recently started working on a JavaScript project and coming from Java world things seem, not surprisingly, weird at times.
I was implementing a simple module (Using revealing module pattern, afaik) which would provide config based on initialisation but notice that after a "local" variable domain is assigned in init() function its value differs depending whether it is accessed via a "getter" function getDomain() or directly via domain variable as exposed via modules "public" API.
See the following stripped down code which demonstrates the issue.

var ConfigManager = (function() {

  var privateDomain = 'default';

  function init(dom) {
    privateDomain = dom;
  }

  function getDomain() {
    return privateDomain;
  }

  return {
    init: init,
    domain: privateDomain,
    getDomain: getDomain
  };

})();

console.log(ConfigManager.domain); // Prints 'default'
console.log(ConfigManager.getDomain()); // Prints 'default'

ConfigManager.init('new domain');

console.log(ConfigManager.domain); // Prints 'default' <-- What??
console.log(ConfigManager.getDomain()); // Prints 'new domain'

At this point I am very confused how a variable returned from a getter function can have a different value when it is accessed directly?
Than you in advance!

A: Since privateDomain is a String, you're not copying / returning the reference, but the value.
Therefore when you're changing the domain using the init function, it just updates privateDomain, since domain has no link to it other than being a copy.
Hope it helps! :)

A: It's because when domain is returned, it's value is still "default". It's how Javascript works, more info here: Javascript by reference vs. by value
But when you use the function "getDomain" you will get the updated value.
Also have a look at the get/set syntax: Getter


text:
Q: Changing SQL Agent Job Schedule time programmaticaly doesn't work I have an SQL Agent Job, that is supposed to be fired everyday at provided time. If I change the schedule time manualy from Management Studio, it works fine, but i need to change the time using stored procedure as below:
update s set
s.active_start_time = @time
from msdb..sysjobs j
left join msdb..sysjobschedules js on j.job_id = js.job_id
left join msdb..sysschedules s on js.schedule_id = s.schedule_id
where j.name = 'MyJobName'

And guess what? After running such procedure, when I check scheduled time in Management Studio, it's updated correctly, BUT obviously Job ignores that.
I even found out, that this Job keeps somewhere the old schedule time that was set manually, and run using that one - if I for example manually set time to 10:45 AM, and then quickly change time using procedure to 10:55 AM, even if schedule time inside Management Studio looks to be updated, Job still will run at 10:45...
Any thoughts what can be wrong?


text:
Q: How to check in excel if a cell doesn't contain a list of values let's say i have a cell in excel with Text, and i have another column of text values. I want to check if that cell contains any of the values in the column.
How to?
Thanks.

A: Let's say you want to check whether cell B1 contains any of the values in the column A
Then you could use
=COUNTIF(A:A,B1)

A: If I understand you correctly, this array-entered formula should do it, returning TRUE if a word in ColumnOfTextValues can be found in MyCell.
=OR(COUNTIF(MyCell,"*"&ColumnOfTextValues&"*"))

To array-enter a formula, after entering
the formula into the cell or formula bar, hold down
ctrlshift while hitting enter.  If you did this
correctly, Excel will place braces {...} around the formula.

A: Googled some more and found a solution
=IF(SUMPRODUCT(--ISNUMBER((SEARCH("*"&B1:B10,A1)))),TRUE,FALSE)
returns true if A1 contains any of the strings in B1 to B10


text:
Q: Block elements inside a flex container get squeezed. But why? I wonder why the 8 inline-block elements inside the flex div get squeezed and do not adhere to their setting (width: 50px).

div {
  display: flex;
  justify-content: center;
  border: 1px solid red;
  width: 150px;
  overflow: auto;
}

a {
  display: inline-block;
  background: orange;
  width: 50px;
  height: 50px;
  margin: 10px;
}

  12345678

A: The key here is adding "flex-shrink: 0;" and remove "justify-content: center;"

div
{
 display: flex;
 border: 1px solid red;
 width: 150px;
    overflow: auto;
}

a
{
 display: inline-block;
 background:orange;
 width: 50px;
 height: 50px;
 margin: 10px;
 flex-shrink: 0;
}

  12345678

http://jsfiddle.net/zogybegu/

A: Because its width is set. Just delete width: 150px;.

div {
           display: flex;
           justify-content: center;
           border: 1px solid red;
           overflow: auto;
        }

        a {
           display: inline-block;
           background:orange;
           width: 50px;
           height: 50px;
           margin: 10px;
        }

  12345678

This works if the space the flex div has is big enough for all the children. Otherwise the div adapts to the size, making the children smaller.


text:
Q: What is the relationship between device drivers and a filesystem Background
Hello.
I am trying to wrap my head around the relationship between a filesystem (ext2/3 etc), device drivers and device files.
I'll lay out my understanding of each term and then my questions.
Device Driver
As far as I understand, the device driver would be the kernel side code that handles the I/O and logic of accessing some device (mouse, flash memory, etc), and it needs to implement several functions (such as open, read, etc) and assigning them to some function pointers when registering the device.
Device File
The device file would be a file usually located in /dev which should be used as the interface to the device driver, through major and minor values assigned to that file.
Filesystem
I Don't think I fully understand this concept, a filesystem should handle I/O and general access to files stored physically on a drive, but that sounds like a device driver, so - would appreciate some more information here
Scenario
If, for example, I was to mount /dev/sdb1 which is my backup ssd to some mountpoint, say /mnt/temp - /dev/sdb1 would be the device file, and the filesystem type would be ext4.
Now when I cd to /mnt/temp and use ls, the open method implemented by the device driver should be called.
My request/questions

*

*Is my understanding of device driver and file correct? If not I would appreciate some more details

*How does the appropriate open function gets called in the scenario I discussed?

*How exactly does the filesystem type plays any role in file access if the device driver is the one implementing the access?

Thank you for your help.

A: This is a good question, but pretty meaty! :)
Re your question 2., here's some info about what open is/does. open is a libc call - it's a C function that POSIX systems have to implement. Basically every distro nowadays uses a release of libc called glibc (the GNU libc implementation), but especially on embedded devices with limited RAM or storage resources, you still sometimes see folks using other libc implementations. Here's the manpage for glibc open. open works by trying to open files at a given pathname - it talks to the filesystem. To open, differences in the way the filesystem is implemented underlying storage layer don't matter. So, the phrasing of your question 2 as written right now ("How does the appropriate open function gets called in the scenario I discussed?") is a little bit off-base: there's only one open function, not multiple ones implemented per filesystem.


text:
Q: How to set percentage in a determinate horizontal progress bar I want to make a custom progress bar, in which I can set percentage values dynamically by the program.

A: As the documentation says, you should use the method:

void setProgress (int progress)
Sets the current progress to the
  specified value. Does not do anything if the progress bar is in
  indeterminate mode.
This method will immediately update the visual position of the
  progress indicator. To animate the visual position to the target
  value, use setProgress(int, boolean)}.

So use:
progressbar.setProgress(yourProgressValue);


text:
Q: RESTful / Crud based approach to controlling an entity behavior that is typically implicit I am modifying a CakePHP application to have an API available on it. My intention is to try to keep keep the endpoints as close to being RESTful / Crud oriented as possible. Although I have a use case that that I am unsure of.
I have the following requests for adding and editing tasks:
PUT       /tasks
PATCH     /tasks/:id

One of the behaviors of task entity in the system I am working on is that they send emails to the effected users associated with the task, when a save or edit is performed. This allows the various parties surrounding the task to be updated on the status of the particular task.
However the the one issue is that in some uncommon cases the end user will need to be able to toggle if they want an email to be sent on the front end.
What is the proper RESTful / Crud oriented approach to flag the task endpoints to not fire the email in the API request?
There is no record of the email in the application's database and it is nice to have to functionality tied into the task life cycle hooks and called implicitly. So I am not crazy about doing something like creating an /emailTask set of endpoints. It seems like an optional flag in the task request would be cleaner, but might not be maintainable if we begin to have similar needs for other behaviors associated with tasks.
Thanks in advance for the help!

A:
PUT       /tasks

If you're intending to use this for adding tasks, use POST instead. PUT /tasks implies that you are overwriting all tasks.
As for side-effects, this to me feels like a decent use-case for a custom HTTP header. Perhaps something like Suppress-Notifications: ?1 ?
Why ?1 as a value? This is going to be the future default for new HTTP headers that specify a boolean:
https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-header-structure-15#section-4.1.9


text:
Q: Check if passed parameter is a type of class I want to call the following function:
fun <T> isCurrentActivity( t: Class<T>): Boolean {
    return (currentActivity != null) &&  (currentActivity is t)
}

if (isCurrentActivity(MainActivity::class.java)) {

}

But t is an unresolved reference. How can I fix that? I can't use an inline reified function because the function needs to be publicly available.

A: The problem is that JVM erase generic type, so type of parameter T is not accessible at runtime.
That's why in Java a popular pattern is passing instance of Class<T> as a param. It's not required in Kotlin, because in Kotlin we can define reified type and that type is accessible at runtime.
Example:
inline fun <reified T> isCurrentActivity(): Boolean {
    return (currentActivity != null) &&  (currentActivity is T)
}

fun example() {
    if (isCurrentActivity<MainActivity>()) {
        // it is!
    }
}

Requirements for marking T as reified is marking a function as inline. See more at docs: https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters
An example above is a "kotlin way to do that". If you would like to stay with "java like code" the mistake you do is that you try to check if a currentActivity is an instance of variable - what is not possible. Correct way would be:
fun <T> isCurrentActivity(t: Class<T>): Boolean {
    return (currentActivity != null) && currentActivity.javaClass == t
}

Please see @gidds comment about the check above.
But, I still recommend using reified type parameter, as it's a really nice way to check the type.


text:
Q: How to use the enumerate function on a txt file? I am trying to read the Hi.txt file that I previously created on the console but instead of just getting the values from it I'm trying to add the index value next to it using the enumerate function. (Let's assume that the text file has 3 elements in it).
with open('Hi.txt','r') as hello:
    x = hello.read()
    print(x)

From my understanding, this code will iterate through the elements in that txt file like so:
Dave
Jack
Mary

However, when I try something like this:
with open('Hi.txt','r') as hello:
    x = hello.read()
    for i,v in enumerate(x,1):
        print(i,v)

It prints out every character one by one.
Desired output:
1 Dave
2 Jack
3 Mary

A: You enumerate the file handle itself:
with open('/Hi.txt','r') as hello:
    for i,v in enumerate(hello,1):
        print(i,v, end="")

A: You can do something like this:
with open('Hi.txt','r') as hello:
    for i,v in enumerate(hello.readlines(), 1):
        print(i,v, end="")

This will iterate for all the lines in your file (assuming you have all the file items in separated lines).


text:
Q: Can I find out how many questions I have asked across all Stack Exchange networks? Is there a nice and easy way to find the above out without having to go through each one manually?

A: Someone could make an app for this using the API, go to stackapps.com and ask there.


text:
Q: Is there an interval notation for complex numbers? Just as $$\{x \in \mathbb{R}:  a \leq  x \leq b\}$$ can be written in the more-compact form $[a,b],$ is there an analogous notation for $$\{z \in \mathbb{C}:z=x+yi, x \in[a,b], y \in[c,d]\} \quad ?$$
Pictorially, the set of all  $z \in \mathbb{C}$ lying in the green area is the set that I'd like to express in a more concise form:

A: Well, Cartesian product could work here, $\{z\in\mathbb{C}:\Re(z)\in[a,b],\Im(z)\in[c,d]\}$ as $[a,b]\times[ic,id]$.
But I've never seen a standardized notation for something like this, except for circular regions, such as $|z+1|<4$.

A: During the Complex Analysis course I took we used
$$[z,w]:=\{(1-t)z+tw:t\in[0,1]\},\quad z,w\in\mathbb{C},$$
which coincides with normal intervals when $z,w\in\mathbb{R}$. But you should define this yourself, because people won't know what you mean if you don't.

A: You could write it like this:
$\{(x + yi) \in \mathbb{C}: x \in [a,b], \; y \in [c,d]\}$.
Alternatively, choose one of these:
$[a,b] \times i[c,d]$
$[a,b] \times [ic,id]$

A: A teacher of mine once used an "interval notation" for boxes in $\Bbb R^n$. If $\vec{a} = (a_1, \ldots, a_n)$ and $\vec{b} = (b_1, \cdots, b_n)$, then: $$]\vec{a}, \vec{b}[ = ]a_1, b_1[ \times \cdots \times ]a_n, b_n[ = \prod_{i = 1}^n ]a_i, b_i[$$
Maybe you can adapt it for what you need.

A: Maybe not the answer you're looking for, but you can include the picture and then write:

Let $X$ be a rectangle in the complex plane, as depicted.

A: Perhaps $\{z \in \mathbb{C}: \operatorname{Re}(z) \in [a,b], \; \operatorname{Im}(z) \in [c,d]\}$.
The complex numbers have no inherent order, so unless you invent something like $[[a+ci, b+di]]$ I know no more compact way to write this.

A: Maybe just define something as $[a,b]+[c,d]i$ ?

A: As far as I know there is no widely recognized standard notation. Define one in your paper/book/essay if you need it often.

A: Since $\mathbb C$ is just $\mathbb R^2$ with specific operations, the notation $[a,b]\times[c,d]$ obviously do the trick.


text:
Q: How do I pinpoint why wifi access is dropping I am in a public building (ie. library) with wifi. I am trying to to pinpoint why a wifi signal keeps dropping...or find a why to work around it. My boss often uses the wifi and recently she has encountered problems with the wifi just dropping off and internet not loading.
I have determined that it is issues with the wifi signal, and not her computer that has caused the problem.
While surfing the internet on a laptop I also had Wifi Analyzer app open on my tablet. Dropped internet page loads coincided with signal drops on the WA app. I then noticed there were two different signals from the router (different MAC addresses) and found a link (Connect to Wi-Fi access point with specific MAC address) on how to get her computer to access the slightly slower but much more stable MAC address signal.
I also saw that there were other wifi signals nearby in the same range dropping in and out.
Besides having a dedicated landline....why other things can I do to help troubleshoot this issue? Anything else I can tweak? I'm an enduser and I know there are ton of variables on this problem.
THanks for your help! :)


text:
Q: display product price with exclusive of tax in magento 2 I want to get product price (exclusive of tax) in catalog pages in Magento 2
vendor\magento\module-catalog\view\base\templates\product\price\amount\default.phtml

I override this file for custom text to my theme.

I override that file but I want to get the product price (Exclusive
  of Tax) in Magento 2

how I can do this??
I don't know

A: There is an admin configuration to display the product prices,
Store -> configuration -> Sales -> Price Display Settings -> Display Product Prices In Catalog == Including and Excluding Tax


text:
Q: How to create a new column in a dataframe depending on other columns values I have a dataset about the years that different subjects took a certain treatment. I need to obtain a column that sets the first year of treatment and 0 if the subject has never been treated.
Let's say I have this dataset:
subject <- c(A, A, A, A, A, B, B, B, B, B, C, C, C, C, C)
year <- c(2000, 2001, 2002, 2003, 2004, 2000, 2001, 2002, 2003, 2004, 2000, 2001, 2002, 2003, 2004)
treat <- c(0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0)
df1 <- data.frame(subject, year, treat)

I want to obtain this:
subject <- c(A, A, A, A, A, B, B, B, B, B, C, C, C, C, C)
year <- c(2000, 2001, 2002, 2003, 2004, 2000, 2001, 2002, 2003, 2004, 2000, 2001, 2002, 2003, 2004)
treat <- c(0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0)
first_treat <- c(2003, 2003, 2003, 2003, 2003, 2001, 2001, 2001, 2001, 2001, 0, 0, 0, 0, 0)
df1 <- data.frame(subject, year, treat, first_treat)

In my original dataset I have mulriple subjects, so I would like to obtain a code to get this done without the need to mention rows or column values.
Thanks!

A: We can do a group by approach - grouped by 'subject', create a logical vector with treat, subset the 'year' and extract the first element ([1])
library(dplyr)
df1 <- df1 %>%
  group_by(subject) %>%
  mutate(first_treat = year[treat == 1][1]) %>%
  ungroup

-output
df1
# A tibble: 15 × 4
   subject  year treat first_treat
   <chr>   <dbl> <dbl>       <dbl>
 1 a        2000     0        2003
 2 a        2001     0        2003
 3 a        2002     0        2003
 4 a        2003     1        2003
 5 a        2004     1        2003
 6 b        2000     0        2001
 7 b        2001     1        2001
 8 b        2002     1        2001
 9 b        2003     1        2001
10 b        2004     1        2001
11 c        2000     0          NA
12 c        2001     0          NA
13 c        2002     0          NA
14 c        2003     0          NA
15 c        2004     0          NA

If we want to return no year case as 0, an option is with coalesce
df1 %>%
  group_by(subject) %>%
  mutate(first_treat = coalesce(year[treat == 1][1], 0)) %>%
  ungroup
# A tibble: 15 × 4
   subject  year treat first_treat
   <chr>   <dbl> <dbl>       <dbl>
 1 a        2000     0        2003
 2 a        2001     0        2003
 3 a        2002     0        2003
 4 a        2003     1        2003
 5 a        2004     1        2003
 6 b        2000     0        2001
 7 b        2001     1        2001
 8 b        2002     1        2001
 9 b        2003     1        2001
10 b        2004     1        2001
11 c        2000     0           0
12 c        2001     0           0
13 c        2002     0           0
14 c        2003     0           0
15 c        2004     0           0

A: Here is an option with ifelse:
library(dplyr)

df1 %>%
  group_by(subject) %>%
  mutate(first_treat = ifelse(1 %in% treat, year[treat==1], 0))

subject  year treat first_treat
   <chr>   <dbl> <dbl>       <dbl>
 1 A        2000     0        2003
 2 A        2001     0        2003
 3 A        2002     0        2003
 4 A        2003     1        2003
 5 A        2004     1        2003
 6 B        2000     0        2001
 7 B        2001     1        2001
 8 B        2002     1        2001
 9 B        2003     1        2001
10 B        2004     1        2001
11 C        2000     0           0
12 C        2001     0           0
13 C        2002     0           0
14 C        2003     0           0
15 C        2004     0           0


text:
Q: How to prevent Button enable or disable from view source I have two button on page first submit and other save but one there is one condition if admin log in Save button shows and if client log in submit button show. But bug is any one who log in can easily change disable to enable or enable to disable from view source and click the button
@{
  if((Utility.GetUserRoleFromSession().ToString().ToLower().Equals(UserRole.Client.ToString().ToLower())
  {
    <input type="button" value="Submit" title="submit" class="blueBtn" id="btnSubmit" />
  }
  if (Utility.GetUserRoleFromSession().ToLower().Equals(UserRole.Admin.ToString().ToLower())
  {
    <input type="button" value="Submit" id="btnSubmitEE" class="btnSubmitEE blueBtn" />
  }
}

A: Make the button visible = false according to user. If button is invisible, then it will not appear in the viewsource.

A: Make the button invisible to ensure that the button is not emitted to the rendered HTML.
As a second line of defense, put logic into the code-behind to verify that the user should be able to click the button before actually performing the logic on the server-side. This is analogous to performing both client-side validation and server-side validation, because the user can turn off JavaScript on the client-side, at that point server-side validation is all that is executed.

Note: Bottom line is the server-side should NEVER trust anything the client provides to it.


text:
Q: How to get the entire content of a variable in the debug watch window of visual studio
If i right click and copy i only get half text:
-       text    0x00000000000f20d0 L"_BinRun.IMAGE_DOS_HEADER := \"\t\tWORD   e_magic;\n\t\tWORD   e_cblp;\n\t\tWORD   e_cp;\n\t\tWORD   e_crlc;\n\t\tWORD   e_cparhdr;\n\t\tWORD   e_minalloc;\n\t\tWORD   e_maxalloc;\n\t\tWORD   e_ss;\n\t\tWORD   e_sp;\n\t\tWORD   e_c...  wchar_t *

Trying to get the entire content as a literal string including \"\t\t\n\ etc.
Im using c++ in my project and vstudio2019.

A: You can't. The string is too long to display directly in the debugger watch window. Use the String Visualizer by clicking the magnifying glass to the right of the variable. That's what it's for and then copy it from there:
(Emphasis mine)

While you are debugging in Visual Studio, you can view strings with the built-in string visualizer. The string visualizer shows strings that are too long for a data tip or debugger window.


text:
Q: Above and Below Display Arrangement in El Capitan Now with more El Capitan, and a change of screen layout.  Apple seems to be deliberately mocking me!
I have a laptop running Yosemite El Capitan with an external monitor sitting above next to the laptops display.  When I am logged in I have the display arrangement mimicking the physical above and below side by side layout.  This works and is good.
However when I am logged out the Yosemite El Capitan login screen reverts to an side by side above and below arrangement.
I would like Yosemite El Capitan to keep the side by side arrangement even when I am logged out, but the display arrangement in the System Preferences is per logged in account.
So what would I do to set the arrangement when there is no logged in account?

A: I think I may have just solved it.  I have two accounts on this Mac, my Admin account and my daily use account.  The admin account didn't have the same screen orientation as the the daily use account, and on the login screen the admin account was listed first.  I suspect that when no accounts are logged in that OS X grabs the screen configuration of the first account that it finds - which happened to be the admin account in my case.


text:
Q: maximal irreducble subgroups of $SL(2,q)$ If $H$ is a maximal solvable irreducible subgroup of $GL(2,q)$ then intersection $H \cap SL(2,q)$ is maximal solvable irreducible subgroup of $SL(2,q)$. Why is it true?
Maybe this is not true, but is there any counterexample? (I cannot comment.)


text:
Q: list view with change width of row when scroll like Carousel view android I am trying to achieved animated list view.As show in below image when list view item fully visible that time change width of fully visible item other wise its width remain default width as given.Here blue color item width is small when its not fully visible but when green color item come in middle of screen then its width goes to full mode with animation.How can i achieved this type of animation in list view ?
change size of up coming item with animation for list item.

A: Try with the below code... and make the changes to suite you.
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.animation.Transformation;
import android.widget.ListView;

public class MyListView extends ListView {
    private final Transformation mTransformation;

    public MyListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        if (!isInEditMode()) {
            setStaticTransformationsEnabled(true);
            mTransformation = new Transformation();
            mTransformation.setTransformationType(Transformation.TYPE_MATRIX);
        } else {
            mTransformation = null;
        }
    }

    @Override
    protected boolean getChildStaticTransformation(View child, Transformation t) {
        mTransformation.getMatrix().reset();
        final int childTop = Math.max(0,child.getTop());
        final int parentHeight = getHeight();
//      Log.d("details1","childTop : "+childTop+" , parentHeight : "+parentHeight );
        final float scale = (float)(parentHeight-(childTop/2))/getHeight();
//      Log.d("details2", "parentHeight-(childTop/2) : "+ (parentHeight-(childTop/2)) );
//      Log.d("details3", "getHeight() : "+getHeight());
//      Log.d("scale",scale+"");
        final float px = child.getLeft() + (child.getWidth()) / 2;
        final float py = (child.getTop() + (child.getHeight()) / 2);
//      Log.d("details4", "child.getLeft() : "+child.getLeft()+ ",  child.getWidth(): "+child.getWidth()+" , child.getTop(): "+child.getTop()+" , child.getHeight()"+child.getHeight());
//      Log.d("px py", px +" , "+py);
//      Log.e("end", "end");
        mTransformation.getMatrix().preScale(scale, scale);

        t.compose(mTransformation);
        return true;
    }

}


text:
Q: Simple derangement algorithm (secret santa)
In combinatorial mathematics, a derangement is a permutation of the
elements of a set, such that no element appears in its original
position. - from Wikipedia

A real example might be a secret santa draw where each person is randomly assigned another person who they have to buy a present, and everyone should be assigned only once to someone (but not themselves).
Anyway, I saw a lot of algorithms that just try random combinations until no "collisions" occur. My question is can we use a trivial solution where we map each element to the next, and the last one to the first:
$$(a_1, a_2,...a_n) \implies (a_2, a_3, ..., a_n, a_1) $$ However, my idea is to first shuffle the elements or take a permutation, and then map them as previously explained.
Example:

*

*Take ANY permutation, collisions 3 and 4 are fine

$$
(1, 2, 3, 4) \implies (2, 1, 3, 4)
$$

*And then we apply the "trivial" mapping:

$$
(2, 1, 3, 4) \implies (1, 3, 4, 2)
$$

*Reverse shuffle to finally get:

$$
(1, 2, 3, 4) \implies (3, 1, 4, 2)
$$
Wouldn't this work faster then just "guessing", since we take any random permutation without discarding it? Is there any bias?


text:
Q: How to find the outliers from the data set and plot using Z score Data set is below
store id,revenue ,profit
101,779183,281257
101,144829,838451
101,766465,757565
101,353297,261071
101,1615461,275760
102,246731,949229
102,951518,301016
102,444669,430583

Code is below
import pandas as pd
dummies1 = dummies[['storeid', 'revenue', 'profit']]
cols = list(dummies1.columns)
cols.remove('storeid')
dummies1[cols]
# code to find the z score
for col in cols:
    col_zscore = col + '_zscore'
    dummies1[col_zscore] = (dummies1[col] - dummies1[col].mean())/dummies1[col].std(ddof=0)

Here I need to scatter-plot, box plot with outliers, How to to do
How to find the outliers is below ?
let say threshold is 3 means np.abs(z_score) > threshold will consider as outlier.

A: Slicing the data based on the z-score will you you the data to plot.  If you just want to find where one variable is an outlier you can do (for example):
THRESHOLD = 1.5 #nothing > 3 in your example

to_plot = dummies1[(np.abs(dummies1['revenue_zscore']) > THRESHOLD)]

Or if either column can be an outlier, you can do:
to_plot = dummies1[(np.abs(dummies1['revenue_zscore']) > THRESHOLD) |
                   (np.abs(dummies1['profit_zscore']) > THRESHOLD)]

You weren't very specific about the plot, but here's an example taking advantage of this (using ~ to reverse the detection of outliers for normal points):
fig, ax = plt.subplots(figsize=(7,5))
non_outliers = dummies1[~((np.abs(dummies1['revenue_zscore']) > THRESHOLD) |
                        (np.abs(dummies1['profit_zscore']) > THRESHOLD))]
outliers = dummies1[((np.abs(dummies1['revenue_zscore']) > THRESHOLD) |
                    (np.abs(dummies1['profit_zscore']) > THRESHOLD))]

ax.scatter(non_outliers['revenue'],non_outliers['profit'])
ax.scatter(outliers['revenue'],outliers['profit'], color='red', marker='x')
ax.set_ylabel('Profit')
ax.set_xlabel('Revenue')


text:
Q: JSF Templating with russian I have the following template:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<h:head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>
        <ui:insert name="title" />
    </title>
</h:head>
<h:body>

Some header

        <ui:insert name="content" />

Some Footer

</h:body>

and the following client template:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
    xmlns:ui="http://java.sun.com/jsf/facelets"
    template="templates/template.xhtml">
    <ui:define name="title">
        English Online
    </ui:define>
    <ui:define name="content">

Кириллический шрифт

    </ui:define>
</ui:composition>

Now the problem is:
When I invoke the master template from the composite with the Cyrillic font in "h1"-tag, the browswer gives out:
com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: Invalid byte 2 of 2-byte UTF-8 sequence.

Even though I use the Cyrillic font in the master-client template it is ok. And when the client template h1-tag contains English it also works.
How can I fight this problem?

A: That can happen if those files are not saved as UTF-8. The answer depends on the editor used to save the files. If it's for example Eclipse (your question history hints that you're using it or are at least familiar with it), then you need to change Window > Preferences > General > Workspace > Text file encoding to UTF-8.

After making this change, edit and re-save the file(s).
See also:

*

*Unicode - How to get the characters right?


text:
Q: SQL Agent PowerShell job runs in ISE but not in SQL Servere My PowerShell script uses WinSCP to download files.  It writes a message to a sql server table containing the number of files downloaded.  When run within ISE it's fine.  When run as a sql agent job it fails with error msg 'You cannot call a method on a null-valued expression.'  This error is generated by the variable that the file count is assigned to.  The variable is $fileCount.
The code is below.  See variable $fileCount.  I suspect that the beginning $ in the variable name is causing sql to misinterpret the variable in some way but I'm not sure.  Any help is appreciated.
# Step 1 - Powershell script to download xml files to local folder.

param (
    $remotepath = "./",
    $mask = "*.xml",
    $destination = "D:\Files\Downloaded"
)

try
{
    # Load WinSCP .NET Assembly
    Add-Type -Path "c:\Program Files (x86)\WinSCP\WinSCPnet.dll"

    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = "hostname"
        UserName = "user"
        Password = 'password'
        SshHostKeyFingerprint = "fingerprint"
    }

    $session = New-Object WinSCP.Session

    $fileCount = 0
    $elements = 0
    $errOut = $null

    try
    {
        $session.Open($sessionOptions)
        $directory = $session.EnumerateRemoteFiles($remotepath, $mask, [WinSCP.EnumerationOptions]::None)
        $elements = $directory.count
        **$fileCount = $elements.count**

        $transferOptions = New-Object WinSCP.TransferOptions
        $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary
        $transferResult = $session.GetFiles($remotepath, $destination, $False, $transferOptions)
        $transferResult.Check()
     } # end try

    finally
    {
        $session.Dispose()
    }

} # end try

catch
{
        $errOut = ($_.Exception.Message)
}

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "ConnectionString;"
$SqlCommand = New-Object System.Data.SqlClient.SqlCommand
$SqlCommand.CommandText = "EXEC Stored_Proc @chvMessage, @chvFileIndex, @chvRecordCount"
$SqlCommand.Connection = $SqlConnection
$SqlCommand.Parameters.Add("@chvMessage", [system.data.SqlDbType]::nvarchar) | Out-Null
$SqlCommand.Parameters['@chvMessage'].Direction = [system.data.ParameterDirection]::Input
$SqlCommand.Parameters.Add("@chvFileIndex", [system.data.SqlDbType]::nvarchar) | Out-Null
$SqlCommand.Parameters['@chvFileIndex'].Direction = [system.data.ParameterDirection]::Input
$SqlCommand.Parameters.Add("@chvRecordCount", [system.data.SqlDbType]::nvarchar) | Out-Null
$SqlCommand.Parameters['@chvRecordCount'].Direction = [system.data.ParameterDirection]::Input

$SqlConnection.Open()
if ($errOut -ne $null)
{
    $SqlCommand.Parameters['@chvMessage'].Value = $errOut
}

if ($errOut -eq $null)
{
    $SqlCommand.Parameters['@chvMessage'].Value =  "**** " + $fileCount.toString() + " FILES DOWNLOADED"
}

$SqlCommand.Parameters['@chvFileIndex'].Value = ''

$SqlCommand.Parameters['@chvRecordCount'].Value = ""
$SqlCommand.ExecuteNonQuery() | Out-Null
$SqlConnection.Close()


text:
Q: R Omit Variable Label Not Correct I'm running a multivariate regression in R with 5 separate OLS regressions in a single model.
set.seed(1)

SampleData <- data.frame(X = sample(1:10), X1 = sample(1:10),
X2=sample(1:10), X3=sample(1:10), X4=sample(1:10), Y=sample(c("yes", "no"),
10, replace = TRUE))

OLS1 <- lm(X~X1, data=SampleData)
OLS2 <- lm(X~X1+X2, data=SampleData)
OLS3 <- lm(X~X1+X2+X3, data=SampleData)
OLS4 <- lm(X~X1+X2+X3+Y, data=SampleData)
OLS5 <- lm(X~X1+X2+X3+Y+X4, data=SampleData)

library(stargazer)
stargazer(OLS1, OLS2, OLS3, OLS4, OLS5,
    type="text", omit="X4", omit.labels="X4 Omitted?")

For the last column (5) in the stargazer output, I include variable year and omit from model.
omit="year",
omit.labels="Year Omitted?"

However, each column of the "X4 Omitted?" row reads "No" in the model, while I want columns 1-4 to indicate "Yes" and column 5 to indicate "No":

I had thought omit.labels would identify this in the model and can't seem to find a formula to fix. Appreciate any help, thanks.


text:
Q: C++ Templates - The Complete Guide: Wording of footnote about decltype and return type The 2nd edition of C++ Templates - The Complete Guide features the following footnote at page 436 (my bold):

Except that decltype(call-expression) does not require a nonreference, non-void return type to be complete, unlike call expressions in other contexts. Using decltype(std::declval<T>().begin(), 0) instead does add the requirement that the return type of the call is complete, because the returned value is no longer the result of the decltype operand.

The footnote refers to the fact that decltype(std::declval<T>().begin()) is used (ineffectively, based on the footnote) to test whether it is valid to call .begin() on a T. The code that uses it is the following (with some pieces of text around it for clarity:

the trick is to formulate the expression that checks whether we can call begin() inside a decltype expression for the default value of an additional function template parameter:
#include <utility>      // for declval
#include <type_traits>  // for true_type, false_type, and void_t
// primary template:
template<typename, typename = std::void_t<>>
struct HasBeginT : std::false_type {};
// partial specialization (may be SFINAE'd away):
template<typename T>
struct HasBeginT<T, std::void_t<decltype(std::declval<T>().begin())>>
  : std::true_type {
};

Here, we use decltype(std::declval<T>().begin()) to test whether, given a value/object of type T (using std::declval to avoid any constructor being required), calling a member begin() is valid.

From this previous question of mine, I've understood that since operator, can be overloaded, the role of the , 0 is to trigger the otherwise absent overload resolution, which in turn needs the type of std::declval<T>().begin() to be complete.
However, the text from the book (see the part highlighted in bold above), doesn't mention operator,, nor overload resolution. Is that just bad wording? Or maybe it's just the same matter looked from a different perspective? Or what?

A: It seems the author forgot or disregarded the possibility of , being overloaded. The whole technique is defective in this regard, not just the wording.
So if begin() is valid and returns a complete type, but , is overloaded and can't be called for some reason, you'll get a false negative.
A more robust solution would be decltype(void(std::declval<T>().begin())).


text:
Q: Can I temporarily use normal resistor in place of fusible resistor I have SMPS that uses 10 ohm 1W fusible resistor. I have located a fusible resistor in Amazon and its gonna take a while to deliver.
I would like to know if I can temporarily use 10 ohm resistor for now in its place or is it too much of a stretch?

A: The fusable resistor differs from a normal resistor in that the fusing characteristics are specified and civilised .On high energy stuff like your single phase mains or forklift batteries random resistors can do bad things like Explode or go on fire and not self extinglush or release foul gas .Remember that you are poking Kw into your 1 watt resistor if there is a short in your SMPS . Unless you know what you are doing stick to the correct part .It may blow open circuit if your SMPS is faulty .

A: Real engineers do things like this all the time. The key is to ask yourself what could go wrong, and what would be the consequences? Then you ask yourself what can you do to make sure the worst consequences don't take place? If it seems like I am equivocating that is because I don't know you and what experiences you have had.
Every time you energize a device that is in some way questionable, you should be prepared to observe it for some time until you are sure it is working properly. Also, and this is really important:
You have to be able to de-energize the device without risking injury yourself.
This does not have to be complicated. It can just be the simple precaution of powering the device from an outlet that is accessible and distant from the device. Or, it could be a switched outlet, where the switch is safely distant.
Also, you need to make sure that you have a safe exit path if it catches on fire.
So if it should start to smoke extensively or burn, you first de-energize the device, then you flee the room and wait to go back in until the smoke has cleared (if necessary). It may also be a good idea to have a fire extinguisher handy so you can put out a fire if needed.
Finally, do not leave the energized device unattended.
Eventually you may come to the conclusion that it is working properly and maybe then you will feel safe to leave it energized unattended. But don't become distracted before that happens and leave it. Always de-energize the device if you have to walk away.
So, you plug it in, and if things go badly, you just unplug it and walk out of the room. Or switch off a breaker and walk out. If it goes really badly and the device ignites a more general fire, then you could use a fire extinguisher (after de-energizing the device).
An example of a bad idea would be plugging it in in such a way that you have to lean over the device to reach the plug. In this case, if it should catch on fire, you will have to lean over it to unplug it. Don't do that!
Another example of poor practice would be working around highly flammable materials. If there are flammable solvents around (Isopropyl alcohol? Acetone?), well, you probably should not energize questionable devices then. Curtains hanging down over the device? Move the device somewhere else, or move the curtains out of the way.
To me, these things are common sense. I hesitate to recommend to a stranger on the internet that they energize a questionable device because I don't know if these things are common sense to other people. Also, none of these precautions need to be elaborate. It is just basic stuff.
I am not trying to talk you out of doing it. It seems like a reasonable thing to do. But reasonable for me may not be the same as reasonable for you.


text:
Q: How do I get the id of a mentioned user in a discord.py message? I'm making a discord bot with discord.py. How do I get the ID of a user mentioned in a message?
For example, if someone types  Hello @user
The bot would detect the @user and find the id of that user.

A: The message object has a message.mentions field that is an array of type Member. Members have an id field which is equivalent to User.id. To get the id of a mentioned member:
message.mentions[0].id

If no one's been mentioned, the array will be empty. It's also worth noting that it's not in any particular order, so if multiple users have been mentioned the first index won't necessarily correspond to the first mention.


text:
Q: Investigation On I have a question about the mysterious usage of the preposition "on" here:

Time Orders Investigation On Accuracy Of CNN Report

Would "investigation of" be better than "investigation on"?  Could it be that the author used "on" because he wanted to avoid the usage of two "of"s in succession?

A: Typically investigation is followed by of or less commonly into.  On is used even less often, though I have seen it before.  I think that the headline would read more naturally with "Investigation Of Accuracy Of CNN" or better, to avoid the double "of", as you suggest, "Investigation Into Accuracy Of CNN."
A Google ngram of the three phrases shows "of" being used roughly ten times more than "into," which is used roughly five times more than "on."
As with any words or phrases, these three phrases aren't exactly identical, but I can't find any hard and fast rule for their usage.  The only one that I was able to think of is that when criminal investigations are being discussed, "investigation into" is typically used.

The police have started an investigation into the murder of John Smith.

A: In American English, "investigation on" usually occurs in the context of exposé TV journalism (e.g. 60 Minutes and 20/20), where the word "investigation" is used more or less as a synonym for "investigative piece" or "exposé" -- hence the "on".
The journalists complete an investigation of something, and then urge the audience to stay tuned for the upcoming investigation (i.e. the segment based on their sleuthing) on something.
For example: http://www.kwch.com/news/local-news/homeowners-respond-to-60-minutes-investigation-on-flooring/31577558


text:
Q: Can't get EF Code First to work in MVC 4 I create a new MVC 4 Internet Application in VS 2010. I created an "Item" model, and an "ItemContext" class:
public class Item
{
    public int ItemID { get; set; }
    public string Name { get; set; }
}

public class ItemContext : DbContext
{
    public DbSet<Item> Items { get; set; }
}

I built the project, then right clicked the "Controllers" folder, and attempted to add a new controller:

when I try to add it, I get the following error, which I do not understand:

I'm having bigger issues with this, but I thought I'd try boiling it down as simple as I could and see what I got. What steps am I missing? The "Internet Application" project has a connection string already, and it's got some membership related stuff as well.
Update This is the connection string the project creates:
<add name="DefaultConnection"
     connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\aspnet.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True"
     providerName="System.Data.SqlClient" />

A: Change the connection string name to ItemContext.

A: Here is another way of doing it without need to rename connection. DefaultConnection may be any of yours connections.
public class ItemsContext : DbContext
{
    public ItemsContext()
    : base("DefaultConnection")
    {
    }

    public DbSet<Item> Items { get; set; }
}

This approach gives you the benefit to avoid having new connection name for each new Model set.


text:
Q: use C++ to create a calculator I want to use C++ to make a calculator, so that I can enter an expression and calculate the result.
For example,
input
(5.2+4)*ln3.4+sin3
output
11.39985
The problem is that I don't know how to separate the number and the operator from the string. For the length of the operands and numbers are different.
Is there any good way?

A: Use a library such as exprtk.
I'm going to assume that you're a total noob which leads me to advise you to always Google for a library that solves your problem.

A: That's actually a much harder problem than it seems at first, and I say that from experience.
If you want an example of how to do it completely from scratch, here is a question where I posted an example I was working on. It is certainly not complete, but links to a great Java article (actually, probably the best article) on Pratt parses, which in my opinion is the best way to parse expressions. My question was on my attempt to port the Java code found there to C++. You can see a problem I ran into there.
You will also need to know some theory on lexers, and learn how to create tokens, which I don't ask about there.
The point is, you have a lot of research ahead of you, if you want to start from scratch, or even if you want to just know the theory of what's going on, but I certainly encourage you to try it if you don't have a deadline for it.

A: I programmed the calculator using function ,loops, switch case.
it can also be programmed with using if else statement but then it will be a simple one. I had made it like a real calculator it can take unlimited argument, while the other takes only 2 numbers as argument.
#include <iostream>
#include <conio.h>
using namespace std;

int add()
{
    int total, a, sum = 0;
    cout << "how much number you want to calculate :";
    cin >> total;

    for (int i = 1; i <= total; i++)
    {
        cout << "enter number " << i << "for +" << endl;
        cin >> a;
        sum = sum + a;
    }
    cout << "total addition is:" << sum;
    return 0;
}
int subtract()
{
    int sub = 0, a, b[20], total;
    cout << "how much number you want to calculate :";
    cin >> total;
    cout << "enter number 1 for - : \n";
    cin >> a;
    a = -a;
    for (int i = 1; i < total; i++)
    {
        cout << "enter number " << i << "for - :" << endl;
        cin >> b[i];
        sub = sub - a - b[i];
        a = 0;
    }
    cout << "HENCE THE SUBTRACT IS :" << sub;
}
int divide()
{
    float h;
    float a;
    float b;
    cout << "enter number 1 : ";
    cin >> a;

    cout << "enter number 2 : ";
    cin >> b;

    h = a / b;
    cout << "division is :" << h;
}
int multiply()
{
    int a[20];
    int total, multi = 1;
    cout << "how much number you want to multiply\n";
    cin >> total;
    for (int i = 0; i < total; i++)
    {
        cout << "enter number to multiply\n";
        cin >> a[i];
        multi = multi * a[i];
    }

    cout << "multiplicaion is : " << multi;
}
int main()
{
    int num1[20], num2[20];
    char sign;
    cout << "chouse a sign"
            "\npress this for executing the action +"
            "\npress this for executing the action -"
            "\npress this for executing the action X"
            "\npress this for executing the action /\n";
    cin >> sign;

    switch (sign)
    {
    case '+':
        add();
        break;

    case '-':
        subtract();
        break;

    case '*':
        multiply();
        break;

    case '/':
        divide();
        break;

    default:
        cout << "chouse something";
        break;
    }

    return 0;
}


text:
Q: Cannot resolve method 'openFile(java.lang.String)' import java.io.File;
import java.util.Scanner
import java.io.FileNotFoundException;

public class hello {
    public static void main (String [] args){
        File file = new File("example.txt");

        try {
            openFile("example.txt");
       } catch (FileNotFoundException exception){

            System.out.println("Cannot find that file");

        }

    }
}

java : cannot find symbol
symbol : method openFile(java.lang.String)
Cannot resolve method 'openFile(java.lang.String)'
EDİTED (thanks for our helps)
    import java.io.File;
    import java.io.FileNotFoundException;

    public class hello {
            public static void main(String [] args) {

try{
    File file = new File("example.txt");
    Scanner scanner = new Scanner(file);

    System.out.println("opened");
}
catch (FileNotFoundException exception){
        System.out.println("Cannot find that file");
      }
    }
  }

A: Ok, I'm going to assume a few things here. Given that its a text file and you're trying to open it, I'm guessing you're trying to read it,if not then edit your question.
You need a bufferedReader, you can probably find an implementation for your specific case but the basics are:

*

*create a buffered reader (called "reader" for example)

*Use the following line:
reader = new BufferedReader(new FileReader(file));

Where file is the path to the .txt file.

*Then to read do use
reader.readLine());

Put a while loop around this where the condition is that reader.readLine is not null
and also put a try/catch around it.
Hope this helps, I'm making a few assumptions but reading a .txt file is quite common and it looks like that's what you're trying to do.


text:
Q: Malloc to struct; segmentation fault So I defined my struct outside of any function:
typedef struct limb{
    char c;
    struct limb *child;
    int x;
    int y;
}limb;

And tried to allocate memory to it:
limb *body;
body = malloc(sizeof(limb));
body->child = malloc(sizeof(limb));

But it gives me segmentation fault.
Any help will be appreciated.
gdb:
Program received signal SIGSEGV, Segmentation fault.
0x0000000000409162 in wsyncdown ()
(gdb) x 0x0000000000409162
0x409162 <wsyncdown+18>:    0x406f8b48

Whole code (hope it helps):
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ncurses.h>

int max_x, max_y;

void welcome_screen();
void terrain();

typedef struct limb{
    char c;
    struct limb *child;
    int x;
    int y;
}limb;

int main()
{
    welcome_screen();
    terrain();
    return 0;
}
void terrain()
{
    WINDOW *terrain;
    int startx, starty, width, height;
    keypad(stdscr, TRUE);
    wrefresh(terrain);
    height = 60;
    width = 100;
    starty = (LINES - height) / 2;
    startx = (COLS - width) / 2;
    terrain = newwin(height, width, starty, startx);
    wborder(terrain, '|', '|', '-', '-', '+', '+', '+', '+');
    wrefresh(terrain);
    limb *body;
    if(!(body = malloc(sizeof(limb)))){
        printw("SEGMENTATION FAULT");
        getch();
    }
    /*body->child = malloc(sizeof(limb));*/

    while(1);
    endwin();
}

A: This causes undefined behaviour:
WINDOW *terrain;
// ...
wrefresh(terrain);

because you use an uninitialized variable. Take out the wrefresh(terrain) line. To avoid this sort of error you could delay declaring variables until you are ready to initialize them:
// ...
WINDOW *terrain = newwin(height, width, starty, startx);


text:
Q: AngularJS, RequireJS and Karma issue Apologies in advance for the long post. I have been stuck with this for the last couple of days. Basically, I have an AngularJS project with RequireJS setup which works fine. I am trying to write unit tests using the Angular, Require, Karma (Jasmine) combo. The error am getting is:
Error: [ng:areq] Argument 'fn' is not a function, got Object
http://errors.angularjs.org/1.2.9/ng/areq?p0=fn&p1=not%20a%20function%2C%20got%20Object
at D:/workspace/ecart-oauth/src/main/webapp/app/lib/angular/angular.js:78:12
at assertArg (D:/workspace/ecart-oauth/src/main/webapp/app/lib/angular/angular.js:1363:11)
at assertArgFn (D:/workspace/ecart-oauth/src/main/webapp/app/lib/angular/angular.js:1373:3)
at annotate (D:/workspace/ecart-oauth/src/main/webapp/app/lib/angular/angular.js:3019:5)
at invoke (D:/workspace/ecart-oauth/src/main/webapp/app/lib/angular/angular.js:3687:21)
at Object.instantiate (D:/workspace/ecart-oauth/src/main/webapp/app/lib/angular/angular.js:3721:23)
at D:/workspace/ecart-oauth/src/main/webapp/app/lib/angular/angular.js:6772:28
at null.<anonymous> (D:/workspace/ecart-oauth/src/main/webapp/test/spec/TestAppSetupSpec.js:11:24)
at Object.invoke (D:/workspace/ecart-oauth/src/main/webapp/app/lib/angular/angular.js:3710:17)
at workFn (D:/workspace/ecart-oauth/src/main/webapp/app/lib/angular/angular-mocks.js:2149:20)
Error: Declaration Location
at window.inject.angular.mock.inject (D:/workspace/ecart-oauth/src/main/webapp/app/lib/angular/angular-mocks.js:2134:2

at null.<anonymous> (D:/workspace/ecart-oauth/src/main/webapp/test/spec/TestAppSetupSpec.js:9:20)
at D:/workspace/ecart-oauth/src/main/webapp/test/spec/TestAppSetupSpec.js:4:5
....

This is the folder structure:
ROOT
|_app
|   |_js
|   |    |_controllers
|   |         |_SimpleController.js
|   |_app.js, main.js
|
|_test
|     |_spec
|           |_mockApp.js
|           |_TestAppSetupSpec.js
|
|__karma.conf.js
|_ test-main.js

Here are the relevant sections of the files:
SimpleController.js:
define(["app"], function( app ) {

return angular.module("simpleApp").controller("SimpleController", ["$scope",
    function($scope) {
       $scope.msg = "Hello ";
    }
]);
});

karma.conf.js
....
  // list of files / patterns to load in the browser
files: [

  {pattern: 'app/lib/**/*.js', included: false},
  {pattern: 'app/js/controllers/*.js', included: false},
  {pattern: 'app/js/**/*.js', included: false},
  {pattern: 'app/js/services/*.js', included: false},
  {pattern: 'test/spec/*Spec.js', included: false},
  {pattern: 'test/spec/mockApp.js', included: false},
  'test-main.js',
],

// list of files to exclude
exclude: [
  'app/js/main.js', 'app/js/app.js'    ],
....

test-main.js
var tests = [];
for (var file in window.__karma__.files) {
if (window.__karma__.files.hasOwnProperty(file)) {
if (/Spec\.js$/.test(file)) {
  tests.push(file);
}
}
}

require.config({
// Karma serves files under /base, which is the basePath from your config file
baseUrl: '/base/app/js',

paths: {
    "angular" : "../lib/angular/angular",
    "angular-resource" : "../lib/angular/angular-resource",
    "angular-route" : "../lib/angular/angular-route",
    "angular-storage" : "../lib/angular-local-storage",
    "bootstrap-tooltip" : "../lib/bootstrap-tooltip",
    "bootstrap-popover" : "../lib/bootstrap-popover",
    "bootstrap" : "../lib/bootstrap.min",
    "ui-bootstrap-tpls" : "../lib/ui-bootstrap-tpls-0.11.0",
    "dirPagination" : "../lib/dirPagination",
    "translate" : "../lib/angular-translate.min",
    "translationsEN" : "../js/locale/en/translations_en",
    "translationsDE" : "../js/locale/de/translations_de",
    "jQuery" : "../lib/jquery-1.9.0",
    "angular-mocks" : "../lib/angular/angular-mocks",
    "app" : "../../test/spec/mockApp",
    "SimpleController" : "controllers/SimpleController"
},
shim: {

    "jQuery" :{
        exports : 'jQuery'
    },

    "angular" : {
        deps: ["jQuery"],
        exports: 'angular'
    },

    "angular-resource": {
            deps: ["angular"],
            exports : 'ngResource'
    },

    "app" : {
         exports : 'app'
    },

    "SimpleController" : {
        deps : ["app"],
        exports : 'SimpleController'
    },

    "angular-mocks" : {

       deps : ["angular"],
       exports : 'angular-mocks'
     },

    "angular-route": {
      deps: ["angular"],
      exports : 'ngRoute'
  },
  "angular-storage": {
      deps: ["angular"],
      exports : 'angular-storage'
  },
  "bootstrap": {
     deps: ["jQuery"],
        exports : 'bootstrap'

   },
  "bootstrap-tooltip": {
     exports : 'bootstrap-tooltip',
     deps : ["jQuery"]
  },
  "bootstrap-popover": {
      exports : 'bootstrap-popover',
      deps : ["jQuery"]
  },

  "ui-bootstrap-tpls": {
    deps : ["jQuery", "angular", "bootstrap", "bootstrap-tooltip", "bootstrap-popover"],
    exports : 'ui-bootstrap-tpls'
  },
  "dirPagination": {
    deps : ["angular"],
      exports : 'dirPagination'
  },
  "translate": {
    deps : ["angular", "translationsEN", "translationsDE"],
      exports : 'translate'
  }

},
// dynamically load all test files
deps: tests,

// we have to kickoff jasmine, as it is asynchronous
callback: window.__karma__.start
});

mockApp.js :
define(["angular"], function(){
    var app = angular.module('simpleApp',[]);
    return app;

});

TestAppSetupSpec.js :
define([ 'angular', 'angular-mocks','SimpleController'], function (
     angular, angularMocks, SimpleController
    ) {
describe('App module tests', function () {
    var module, $rootScope, scope, AppCtrl;

    beforeEach(angular.module("simpleApp"));

    beforeEach(inject(function ($rootScope, $controller) {
        scope = $rootScope.$new();
        AppCtrl =  $controller("SimpleController", {
                '$scope': scope
        });

    }));

    it("App Controller should be defined", function(){

        expect(AppCtrl).not.toBe(null);
    });

});
});

I tried using "SampleController" as suggested, but now I get:
Chrome 37.0.2062 (Windows 7): Executed 2 of 2 (1 FAILED) (0.026 secs / 0.023 secs)
INFO [watcher]: Changed file "d:/workspace/ecart-   oauth/src/main/webapp/test/spec/TestAppSetupSpec.js".
Chrome 37.0.2062 (Windows 7) App module tests App Controller should be defined FAILED
    TypeError: undefined is not a function
    Error: [ng:areq] Argument 'SimpleController' is not a function, got undefined
    http://errors.angularjs.org/1.2.9/ng/areq?  p0=SimpleController&p1=not%20a%20function%2C%20got%20undefined
        at d:/workspace/ecart-oauth/src/main/webapp/app/lib/angular/angular.js:78:12
        at assertArg (d:/workspace/ecart-oauth/src/main/webapp/app/lib/angular/angular.js:1363:11)
        at assertArgFn (d:/workspace/ecart-oauth/src/main/webapp/app/lib/angular/angular.js:1373:3)
        at d:/workspace/ecart-oauth/src/main/webapp/app/lib/angular/angular.js:6769:9
        at null.<anonymous> (d:/workspace/ecart-oauth/src/main/webapp/test/spec/TestAppSetupSpec.js:12:26)
        at Object.invoke (d:/workspace/ecart-oauth/src/main/webapp/app/lib/angular/angular.js:3710:17)
        at workFn (d:/workspace/ecart-oauth/src/main/webapp/app/lib/angular/angular-mocks.js:2149:20)
    Error: Declaration Location
        at window.inject.angular.mock.inject (d:/workspace/ecart-oauth/src/main/webapp/app/lib/angular/angular-mocks.js:2134:2
5)
        at null.<anonymous> (d:/workspace/ecart-oauth/src/main/webapp/test/spec/TestAppSetupSpec.js:9:20)
        at d:/workspace/ecart-oauth/src/main/webapp/test/spec/TestAppSetupSpec.js:4:5

What am I missing?
Any help is much appreciated.

A: I finally got this working - but for the life of me, I still can't understand why it works even though I have a faint idea. Posting it for any future lost souls.
I had to write the SimpleController like :
define(["app"], function(app) {

var SimpleController =
    function($scope) {
        $scope.sayHello = function() {
            return "Hello";
        }
    }

SimpleController.$inject = ['$scope'];

app.controller('SimpleController', SimpleController);

return SimpleController;  //NOTE: not returning app.controller(..) which returns an object.
 });

The test case now looks like:
define([ 'angular', 'angular-mocks', 'controllers/SimpleController'], function (
     angular, angularMocks, SimpleController
    ) {
describe('App module tests -->', function () {
    var  scope, SimpleCtrl;

    beforeEach(
            function(){
             angular.module("simpleApp");
            }

    );

    beforeEach(inject(function($rootScope, $controller){

        scope = $rootScope.$new();

        SimpleCtrl =  $controller(SimpleController, {
             '$scope': scope
         });
    })

    );

    it("App Controller should be defined", function(){

        expect(SimpleCtrl).not.toBe(null);
    });

    it("The controller should have a sayHello method that says Hello", function(){

        expect(scope.sayHello).toMatch('Hello');

    });

});
});

Also, no path or shim declarations for SimpleController are required. Its looked up in the test class using 'controllers/SimpleController' - the file resides in the 'app/controllers' subfolder.

A: You have mixed things up a bit:
SimpleController.js (I guess SampleController.js above is a typo) returns the Angular module named "simpleApp" (which is an object). In this module, there is a controller called "SimpleController". The correct usage in the test script would be:
AppCtrl =  $controller("SimpleController", { // NOTE THE QUOTES!!!
    '$scope': scope
});

This is why Angular is complaining that an object was found where a function was expected.


text:
Q: How add hash-key in form field I have a model attribute 'options', and I want record to it a hash with a few parameters.For example:
options:
    name: 'username'
    address: 'useraddress'
    age: 'userage'

To do this, I use serialize
  serialize :options, Hash

how to make the right form for this to work
how make it?
sorry for my bad English

A: In model use
 serialize :options

and when you save your options to db do it like:
object.options = {name: 'username', address: 'useraddress', age: 'userage'}
object.save # in database it will save hash as string, but serialize it.

When you read options from db,
opt = User.first.options # ou will get Hash object
# opt = {name: 'username', address: 'useraddress', age: 'userage'}
# opt is now a Ruby Hash object

In your view, you have to add 3 input fields
<input type='text' name='user[options_name]'>
<input type='text' name='user[options_address]'>
<input type='text' name='user[options_age]'>

In your controller you will have
params[:user][:options_name], params[:user][:options_address], params[:user][:options_age]

Use these 3 variables to set the value of your options field, but set it as Hash

A: solved this problem like this
view with form
= form_for @user do |f|
  = f.fields_for :options do |o|
    = o.text_field :username, class: "form-control", placeholder: "Name"
    = o.text_field :useraddress, class: "form-control", placeholder: "Say your price"
    = o.text_field :useraddress, class: "form-control", placeholder: "Enter your address"

permit params in controller
def user_params
  params.require(:user).permit(:email, options: [:name, :price, :address])
end


text:
Q: Want to show a password toggle/visible button in my android app I have a login activity for my android app. Because of testing I typed in my password very often and sometimes I was not sure if its the right password so I need to delete it completely and typed it in again. I think this is not design! I've searched a little bit and found out that there is a function called app:passwordToggleEnabled="true". I have tried it but it throws an error.
My code:

<EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:layout_marginTop="24dp"
        android:id="@+id/loginPassword"
        android:layout_below="@+id/loginEmail"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:hint="Passwort"
        android:selectAllOnFocus="false"
        android:textSize="18sp"
        android:textColorLink="#63c3c3"
        android:textColorHighlight="#63c3c3"
        android:textCursorDrawable="@null"
        android:backgroundTint="#63c3c3"
        android:passwordToggleEnabled="true" //HERE!
        android:cursorVisible="true" />

But I got an error..
Error:(14) No resource identifier found for attribute 'passwordToggleEnabled' in package 'android'

Thanks for helping me :)

A: You need TextInputLayout and TextInputEditText
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:passwordToggleContentDescription="description"
    app:passwordToggleEnabled="true"
    app:passwordToggleTint="@color/colorAccent">

    <android.support.design.widget.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Password"
        android:inputType="textPassword"/>

</android.support.design.widget.TextInputLayout>
</LinearLayout>

A: You need to use a TextInputLayout, not an EditText.  EditText is a simpler UI element with fewer features.  TextInputLayout includes an EditText and various other views.

A: use this library it works fine for this purpose:
compile 'com.android.support:design:24.1.1'

Example:
<android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/txtUsername"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:drawableLeft="@drawable/user"
            android:drawableTint="#FF4081"
            android:hint="User Name"
            android:inputType="textEmailAddress"
            android:maxLines="1" />
    </android.support.design.widget.TextInputLayout>


text:
Q: How I can import a matrix without delimiters to python? I have a .geno file, what is basically a matrix with 0-1-2-9 numbers. I try to import it for further analysis to python. It looks like this:
0      1010111011011020001111111010011100012020110011...
1      1211101021010220201112100010110111111020120001...
2      0111110111211112211110111212212121210201111212...
3      2212222121222110111221222110111111222211222211...
4      0000000000000000100010000000000010100000010000...

It's basically a matrix with 2054 columns with a lot of rows, but without delimiters. With pandas I can import it with:
full_geno = pd.read_csv('22_chr.geno')

But It will be just one column. With numpy it said all the values are inf. What could be the solution for this?

A: this solved my problem :)
   len = [1]*2054
   full_geno = pd.read_fwf("22_chr.geno", widths=len, header=None)


text:
Q: How am I supposed to pass the time? In the game, there are number of events that only occur during specific time slots. For example, at one point there was a town meeting scheduled between 15:00 and 17:00. In this instance, when I was notified of this event, it was around 09:00. So I had some time to kill.
To pass the time naturally, you have a few options. You can run around town, whittling your time away on side-quests, but there are only so many. You can take a nap, but the naps are broken up into 3-hour incremental chunks. You can just let the in-game clock run up, but waiting for an in-game hour to pass seems to take about 20 minutes of real time.
It seems apparent then that there must be some sort of way to conveniently "wait" à la Fallout 3, Skyrim, etc. Otherwise, lining up a specific time in the game would be an extremely tedious affair. I'm obviously missing something.
How do you pass time quickly in Deadly Premonition?

A: You can pass the time by smoking a pack of cigarettes for as long as you like, similar to the wait function in Fallout 3.
However, make sure you eat/drink coffee before starting on a pack or the game will automatically terminate the smoking scene and warn you that you need to get something to eat/some sleep first. The game will also interrupt the smoking when it's midnight because:

 the zombies of the Other World just love hanging out at this time of the day.


text:
Q: Android annotation at runtime I want to annotate a list of classes with a custom annotation, which I need at runtime.
My annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface CustomAnnotation {
    String value() default "defaultValue";
}

My custom class is:
@CustomAnnotation
public class MyClass {
}

Now, I want to read the annotation from a class name, which I has as string. Code is without error handling (for easy handling):
String className = "com.example.MyClass";
Class clazz = Class.forName(className);
Annotation[] annotation = clazz.getAnnotation(); // is empty

Why is clazz.getAnnotation() empty? Has someone an idea?

A: Just tested your code - it works for me.
Only need to call getAnnotations()
The issue is definitely out of code you posted.


text:
Q: Slower delete performance in MySQL8 compared to MySQL5.7 I'm looking for some insights into why deletes from a fairly simple table seem to be much slower in MySQL8 than in MySQL5.7
Apologies in advance if this is a little fluffy at this stage and I've anonymised the table/column names.
We have a table:
CREATE TABLE things
(
  thing_id  BIGINT AUTO_INCREMENT,
  other_id  BIGINT, -- parent id from another table
  type      INT,
  timestamp BIGINT,
  creator   INT,

  PRIMARY KEY (thing_id),
  KEY (other_id,timestamp),
  KEY (timestamp,type),
  KEY (type,timestamp)
)
  CHARACTER SET "UTF8MB3"
  ENGINE = InnoDb;

...which accumulates a lot of rows (typically millions) and periodically we prune it down to remove old entries. It has a complicated relationship with ids in other tables so we can't prune it based purely on timestamp unfortunately so everything has to be done by ids.
When we do the prune, a working table old_things is built to contain all of the ids of the things to be deleted:
CREATE TABLE old_things (thing_id BIGINT primary key);

...and then we delete in looping batches from the things table using a JOIN with old_things and a BETWEEN range of ids (calculated on each loop using max/min of a query with LIMIT - usually 1000 rows):
DELETE IGNORE th.* FROM things th JOIN old_things t USING (thing_id) WHERE t.thing_id BETWEEN from_thing_id AND to_thing_id;

We're seeing, from slow query performance analysis, that this DELETE command above is taking typically 75% longer in MySQL 8.0.31 than it is in MySQL 5.7.36
For example, a run in which that DELETE query is performed ~33K times (deleting 1000 rows each time) results in 44s total execution time in MySQL 5.7.36 and 77s MySQL 8.0.31
I appreciate I haven't talked about mysql configuration but we've done our best to give the two databases identical settings on identical hardware and we are not using binary logging/replication - this is a standalone mysql instance.
Are there any obvious first ports of call to investigate?
I was wondering if it was something to do with the numerous compound indexes on that table - if I strip away the indexes on the things table and have only a single index (on other_id) then the ~33K execution time in MySQL 8.0.31 drops dramatically to ~10s.
To support this theory we have an accompanying table that has typically the same rowcount but with many more large columns but with only one index (on other_id) and deletes from that table using the same method above are actually showing as faster in MySQL8 than MySQL5.7 (51s vs 58s for 33K executions of that query with 1000 rows deleted each time).
Those numerous compound indexes were put in place to support various queries involving the "things" table but some may be legacy and up for review/removal.
Thank you in advance for any responses.
Neil


text:
Q: How to use a built-in in another built-in for Open policy agent Is there a way to call a built-in (like io.jwt.decode_verify(string, constraints)) in a new built-in that I wanted to create?
Or is there a way to call OPA's internal package's method?

A: You should be able to use the exported built-ins from the topdown.GetBuiltin functions. In the example below the base64.encode function is called from the my_custom custom built-in:
    rego.RegisterBuiltin2(
        &rego.Function{
            Name:    "my_custom",
            Decl:    types.NewFunction(types.Args(types.S), types.A),
        },
        func(bctx rego.BuiltinContext, a, b *ast.Term) (*ast.Term, error) {
            b64encode := topdown.GetBuiltin("base64.encode")
            if b64encode == nil {
                panic("base64.encode missing")
            }

            var res *ast.Term
            if err := b64encode(bctx, []*ast.Term{a}, func(encoded *ast.Term) error {
                res = encoded
                return nil
            }); err != nil {
                return nil, err
            }

            return res, nil
        },
    )


text:
Q: Accessing minishift from outside I am testing gitlab integration with minishift and for the same i need the IP that will act as the IP for the external systems. Machine IP is not working.
Is there a way with which I can access minishift from external systems. Thanks in advance.

A:
I am testing gitlab integration with minishift and for the same i need the IP that will act as the IP for the external systems

I am not sure what exactly you understand with GitLab integration, but I assume you have some codebase in GitLab and you also have a build config in OpenShift/Minishift. Now you want to trigger a build within Minishift as part of a push to GitLab using a webhook (if these assumptions are not correct, please clarify your question).
Anyways, as pointed out in some of the comments, Minishift is a local development tool. It's network is not intended to be shared to the outside world. In most cases (depdending on the hypervisor your are using), the created network interface is host local only.
Provided you want to test webhooks, I would recommend to try ngrok which creates secure tunnels to your localhost. Once you have ngrok installed, you can start a tunnel like this:
ngrok tcp `minishift ip`:8443

You will get a forwarding TCP connection. Something like tcp://0.tcp.ngrok.io:11656. Now you can use https://0.tcp.ngrok.io:11656/<remainder of webhook URL> as the URL to configure in GitLab.
I hope this helps.


text:
Q: How can I extract only the name of the defined function from a function like macro in C? Let's say I want to have 2 modules, which are loosely coupled.
The first module is depending on the interface of the other module.
I would like to decouple them by introducing defines for the interfaces.
In module1_cfg.h
#define FUNC1_MODULE2(x) Func1_module2_impl(x)

In module1.c I would use this define to access the other module.
if(TRUE != FUNC1_MODULE2(arg))
{
    //do something
}

In module2.c then I would implement this function:
BOOL Func1_module2_impl(uint8_t i)
{
   //do something
}

This decoupling strategy works really well until I would like to write Unit Tests for module1.
If I want to write my Unit Tests with Hippomocks they would look like this:
void test_func1_module2_ok()
{
    MockRepository mocks;
    mocks.ExpectCallFunc(Func2_module2_impl).Return(TRUE);
    ...
}

But now my unit tests for module1 are depending on module2.
Would there be a possibility to use the introduced function like macro (FUNC1_MODULE2) in the unit test, but with some macro magic omit the parenthesis, so I can pass the defined function pointer to hippomocks?
I would like to stick to function like macros and avoid object macros in the real code to redefine functions, but would use any tricks necessary in the unit test to get rid of the parenthesis.
Thank you for your help!


text:
Q: How to XCode test a string I have to set up test cases for an assignment. I know to use STAssertEquals for numbers but I am unsure how to test the following method that returns a string.
-(NSString *) description
{
    NSLog(@"\n \n Account information for %@ \n Balance is $%g dollars \n Number of transacrions are: %d \n\n\n\n", [self owner],[self balance], [self numberOfTransactions]);

Would I use STAssertsTrue?? If so how would I apply it to the code above?

A: If you know the expected string result, use STAssertEqualObjects.
Since string is an NSObject, you can use STAssertEqualObjects, and it will delegate the check to the NSString implementation of object equality.


text:
Q: Is this combination of forms correct? I ran into this particular sentence today:

They shouldn't work more than they are now.

Though, I'd expect this sentence to be expressed as:

They shouldn't work more than they work now.

or:

They shouldn't be working more than they are now.

Is my conception of English wrong on that particular point or is the former sentence incorrect?

A: A problem with that first sentence is that are does not belong with that form of work.  Substitute do and that sentence becomes acceptable: "They shouldn't work more than they do now.'


text:
Q: Catching iframe readystatechange event on the same origin URL On a web page, I tried to create a URL bar for a IFrame element(on the page) which URL is on the same origin.
I could catch 'load' event on iframe, but some page like phpmyadmin does not fire load event but fire Ready State Change event.
I tried to cache "readystatechange" event like below:

var newFrame = document.createElement("iframe");
newFrame.setAttribute("src", url);
...
newFrame.addEventListener('load', function(){
    newFrame.contentDocument.addEventListener('readystatechange', function(ev){
        console.log('readystatechange', ev);
    });
});

But, this does not work. I cannot catch the "readystatechange" event.
Is there any way to catch the "readystatechange" event of the iframe ?


text:
Q: In bootstrap, how to split page into 2 columns, and left part has a fixed width I am new to bootstrap and css. I want to split whole page into 2 parts, left part looks like a sidebar which has fixed width and doesn't respond to browser window sizing.
Now I am using grid system:
.row
   .col-xs-4  //left part
       .row
       .row
       .row
       .row
   .col-xs-8  //right part
       .row
       .row

However since grid system is responsive so when I resize browser window, left part's width also changes.

A: I'd suggest keeping the left menu out of the Bootstrap grid system and using pure CSS to do it.


text:
Q: A parameter is missing for correct numpy percentiles? I'm using numpy to calculate percentiles for an array. I found that numpy gives me the right answer for the 50th percentile but not for the 25th or 75th (correct answers 12 and 19.5 respectively). Is there some parameter I'm missing to note?
import numpy as np

c = [10, 14, 16, 19, 20]

print(np.percentile(c, 25))

print(np.percentile(c, 50))

print(np.percentile(c, 75))

A: The 25th and 75th percentile of [10, 14, 16, 19, 20] are 14 and 19, so it's returning the right answer.
In case you want to specify the interpolation method to use when the desired percentile lies between two data points, you can check out the interpolation arguments in the documentation.
Hope this helps!