input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
get data from a ngrepeated div to another div on click <pre><code><div ng-app="appPage" ng-controller="appController">
<div class="nav">
<h1 class="logo">Todlio</h1>
<a href="setting.html"><i class="icon setting" style="color:#fff;font-size:1.8em;;position:absolute;top:11px;right:12px;"/></i></a>
</div>
<div class="todo">
<div class="todo_column">
<div style="font-weight700;text-align:center; margin:20px;">
<a href="#/add" ng-click="addTodo()" class="ui basic button">
<i class="add square icon"></i>
Add
</a>
</div>
<ul>
<a href="#/"><li ng-href="#/" ng-click="detail($index)" ng-repeat="todo in todos">
<h3 ng-model="title">{{ todo.title }}</h3>
<h6>{{ todo.note_date }}</h6>
</li></a>
</ul>
</div>
<div class="todo_full">
<div class="todo_title" ng-scope="todo in todos">
<span><h1>{{ title }}</h1></span>
<span class="check">
<i style="font-size:2em;" class="square outline icon"></i>
<a href="#/edit"><i class="write icon" style="font-size:1.8em;"></i></a>
</span>
</div>
<h4>Note:</h4>
<p class="todo_note">{{ note }}
</p>
</div>
</div>
</div>
</code></pre>
<p>Controller</p>
<pre><code> app.controller("appController", function ($scope) {
$scope.todos = [
{title: "Call Vaibhav", note: "", note_date: ""},
{title: "Grocery", note: "Lemons, Apple and Coffee", note_date: ""},
{title: "Website design for Stallioners", note: "UI/UX on xyz@mail.com", note_date: ""},
{title: "Fill MCA form", note: "First search for all the colleges", note_date: "" }
];
$scope.detail = function(x){
$scope.todos.title = $scope.title;
$scope.todos.note = $scope.note;
};
</code></pre>
<p>I want to get the clicked list item title and the note attached to it to the different div below
Can anybody please help. Its a todo app the left half has the list to todos and the right half has a note attached to it or anything checked or not.</p>
| <p>There are a few ways to do this. One easy way is as follows:</p>
<ol>
<li>Define a $scope variable with a name like $scope.currentTodo.</li>
<li>In the repeat loop, the ng-click would set $scope.currentTodo=todo</li>
<li>This current variable will hold the todo object so you can use {{ $scope.currentTodo.title }} in place of {{title}}</li>
<li>Ditch the ng-scope</li>
</ol>
|
Loading Files From A Local Folder <p>I have been working on a HTML/JavaScript program which requires to be downloaded on to you local computer. I am wanting the program to load .mp3 files form the users music folder and display it. How can I do this locally without PHP. </p>
| <p><strong>For security reasons,</strong></p>
<p>All the popular browsers <strong>does not let you load files from the local computer</strong> by default, unless the user select the file (or drag and drop it) on the browser (html5 example <a href="https://www.html5rocks.com/en/tutorials/file/dndfiles/" rel="nofollow">here</a>).</p>
<p>Also, the browsers do not let you see a folder's content so that you know the files inside it.</p>
<p>In order to have full access to the file system with javascript, you need something else.</p>
<p><strong>Web App as a computer app</strong></p>
<p>For now, the best way to build a computer application using Web technologies (HTML, Javascript, CSS), is either <a href="http://nwjs.io/" rel="nofollow">NW.js</a> or <a href="http://electron.atom.io/" rel="nofollow">Electron</a></p>
<hr>
<p><strong>NW.js</strong></p>
<p>From their <a href="https://github.com/nwjs/nw.js" rel="nofollow">github</a></p>
<blockquote>
<p>NW.js is an app runtime based on Chromium and node.js. You can write native apps in HTML and JavaScript with NW.js. It also lets you call Node.js modules directly from the DOM and enables a new way of writing native applications with all Web technologies.</p>
</blockquote>
<p>You can start by building your code as a NW.js app (<a href="https://github.com/nwjs/nw.js/blob/nw18/docs/For%20Users/Getting%20Started.md" rel="nofollow">Getting started</a> doc on their github)</p>
<hr>
<p><strong>Electron</strong></p>
<p>Form their <a href="http://electron.atom.io/" rel="nofollow">page</a></p>
<blockquote>
<p>If you can build a website, you can build a desktop app. Electron is a framework for creating native applications with web technologies like JavaScript, HTML, and CSS. It takes care of the hard parts so you can focus on the core of your application.</p>
</blockquote>
<hr>
<p><strong>Node.js</strong></p>
<p>You can use Node.js 's API for file system access (<a href="https://nodejs.org/api/fs.html" rel="nofollow">fs</a> doc)</p>
|
Adding search function to the AlternateID on the Sales Order Line Grid <p>I want to add a pxselector to the AlternateID field on the Sales Order Line grid to search multiple alternate id's for a single item for the customer identified on the SOHeader. I added the following code:</p>
<pre><code>namespace PX.Objects.SO {
public class SOOrderEntry_Extension:PXGraphExtension<SOOrderEntry> {
#region Event Handlers
[PXMergeAttributes(Method = MergeMethod.Merge)]
[PXSelector(typeof(Search<INItemXRef.alternateID,
Where<INItemXRef.inventoryID, Equal<Current<SOLine.inventoryID>>,
And<INItemXRef.bAccountID, Equal<Current<SOOrder.customerID>>>>>),
typeof(INItemXRef.alternateID),
typeof(INItemXRef.inventoryID),
typeof(INItemXRef.bAccountID)
)]
public void SOLine_AlternateID_CacheAttributeCacheAttached() {}
#endregion
}
}
</code></pre>
<p>I also deleted the text control from the Transactions grid and re-added it as a selector.</p>
<p>My selector shows up on the AlternateID field on as expected but when the selector is clicked the error <code>"Error #107: View doesn't exist"</code> is displayed.
This was an example Ruslan from Acumatica went over with us at Framework training last week in Ohio, but I obviously missed a step. Any help would be appreciated.</p>
| <p>George, you put a wrong name for your event handler and that causes the error. Try replacing your handler with the code snippet below:</p>
<pre><code>[PXMergeAttributes(Method = MergeMethod.Merge)]
[PXSelector(typeof(Search<INItemXRef.alternateID>),
typeof(INItemXRef.alternateID),
typeof(INItemXRef.inventoryID),
typeof(INItemXRef.bAccountID))]
public void SOLine_AlternateID_CacheAttached(PXCache sender)
{
}
</code></pre>
|
How to add "Open in app" link on my website <p>I have added support for deep links to my android app and have added the appropriate intent filters. If I click on a weblink in a browser and I support that url, a chooser will been shown with my app listed. </p>
<p>But what I want now is add a html link to my website so when the users clicks in it, it opens my app (with the url sent) without showing the chooser. But if the user doesn't have the app installed then it should open the app PlayStore page. </p>
<p>Please do you know how I could do that?</p>
| <p>you should Try to open it like myapp://returnApp/?status=1 (add trailing slash character). This is happens because path parameter is defined with default value of /.</p>
<p>Unfortunately, you can't match exactly for empty string. As documentation states:</p>
<pre><code>Note : - The path part of a URI which must begin with a /.
</code></pre>
<p>you really in need to start app with exactly url myapp://returnApp?status=1 you can add android:pathPattern=".*" parameter to your data clause like</p>
<pre><code> <intent-filter>
<data android:host="returnApp" android:scheme="myapp" android:pathPattern=".*"></data>
</intent-filter>
</code></pre>
<p>Intent filter with data android:pathPattern=".*" will match for any paths including empty one.</p>
|
Exceptions in Java - Try/ Catch <p>I'm learning Java and I have this program that tells the sign depending on the day and month the user writes. The program works as it is, but if the user enters a day like 90 or so, the program doesnt evaluate that "error". Can I correct this with a try/catch? If so, how do I write it? Here's the code (a piece of it), thanks in advance</p>
<pre><code> import java.util.Scanner;
public class Signo{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int day, month;
System.out.println("Day Input:");
day=in.nextInt();
System.out.println("Month Input:");
month=in.nextInt();
int result=getSign(day,month);
}
private static int getSign(int day, int month){
switch(month){
case 1:
if(month==1 && day>=20){
System.out.println("Your sign is Aquarius");
}else{
System.out.println("Your sign is Capricorn");
}
break;
//etc
}
return day;
}
}
</code></pre>
| <p>It's pretty simple, really...</p>
<pre><code>try
{
//statements that may cause an exception
}
catch (exception(type) e(object))â
{
//error handling code
}
</code></pre>
<p>That's all you really need right there. Just put your code that you think might break in the appropriate spot.</p>
<p>Though, having read the comment, I agree that this is overkill for what you're doing.</p>
<p>You just need to set a condition for a While loop:</p>
<pre><code>boolean goodAnswer = false;
while goodAnswer == false{
System.out.println("Day Input:");
day=in.nextInt();
if (day<31) { goodAnswer=true; }
}
</code></pre>
<p>A routine like this will effectively keep on asking for an integer until it gets one it likes. Only then will it leave the loop. This is a fairly common approach for this sort of thing.</p>
|
Oracle group by to get a record based on the length <p>I have this data after grouping by in table, so we can see code is repeated
twice as there are different names associated with it. </p>
<p>But I want whenever the max length is more then get that name, otherwise, get short name,</p>
<p>so for </p>
<ul>
<li><code>cs161</code> I need <code>Craig L Smith</code></li>
<li><code>cs226</code> I need <code>C_SCHLASINGER</code></li>
</ul>
<p>Query that I used to get the below data is </p>
<pre><code>Select code, name, max(length(name))
from acct
where code in ('CS226', 'CS161')
group by code,name
</code></pre>
<p>and result is:</p>
<pre><code>CODE MAX(LENGTH(T1.NAME)) NAME
CS161 7 C SMITH
CS226 13 C SCHLASINGER
CS161 13 CRAIG L SMITH
</code></pre>
<p>Any help highly appreciated</p>
| <p>Simply change your query to:</p>
<pre><code>select code, max(name) from acct
where
code in('CS226','CS161')
group by code
</code></pre>
|
How can I set length of array to field value in the same class? <p>I made the the field value maxSeats as to represent the number of max seat that will be in the main class like this.
Main Class: </p>
<pre><code>public static void main(String[] args) {
Student a = new Student("Abigail", 1, 5);
Student b = new Student("Benny", 1, 6);
Student c = new Student("Charles", 1, 10);
Student d = new Student("Denise", 2, 12);
Student e = new Student("Eleanor", 2, 9);
Student f = new Student("Fred", 2, 5);
SchoolBus sb1 = new SchoolBus(3, 1);
SchoolBus sb2 = new SchoolBus(3, 2);
sb1.getRemainSeat();
sb1.addStudent("Benny", 1, 6);
}
</code></pre>
<p>Other class:</p>
<pre><code>private int maxSeats;
private int routeNum;
String[] studentArray = new String[3];
public SchoolBus(int mS, int rN){
mS = maxSeats;
rN = routeNum;
}
</code></pre>
<p>And I want the field studentArray to have the length of the maxSeats, but it seems that this sets the length of array to 0, and I get outofboudary error. Is there any way to properly set the length of array to the field value in the same class?</p>
| <p>1) You need to create your array after you define the value of the variable <code>maxSeats</code>.</p>
<p>2) You're setting the values in your constructor backwards.</p>
<p>Try this:</p>
<pre><code>private int maxSeats;
private int routeNum;
String[] studentArray;
public SchoolBus(int mS, int rN){
maxSeats = mS;
routeNum = rN;
studentArray = new String[maxSeats]; //Define an array of length [maxSeats]
}
</code></pre>
|
Fastest way to parse all Excel formulas using Python 3.5 <p>As part of a bigger set of tests I need to extract all the formulas within an uploaded Excel workbook. I then need to parse each formula into its respective range references and dump those references into a simple database. For example, if Cell A1 has a formula =B1 + C1 then my database would record B1 and C1 as referenced cells.</p>
<p>Currently I read formulas one at a time using openpyxl and then parse them. This is fine for smaller workbooks, but for large workbooks it can be very slow. It feels entirely inefficient.</p>
<p>Could pandas or a similar module extract Excel formulas faster? Or is there perhaps a better way to extract all workbook formulas than reading it one cell at a time?</p>
<p>Any advice would be highly appreciated.</p>
| <p>What do you mean by "extracting the formulae faster"? They are stored with each cell so you have to go cell by cell. When it comes to parsing, openpyxl includes a tokeniser which you might find useful. In theory this would allow you to read the worksheet XML files directly and only parse the nodes with formulae in them. However, you'd also have to handle the "shared formulae" that some applications use. openpyxl automatically converts such formulae into per-cell ones.</p>
<p>Internally Pandas relies on xlrd to read the files, so the ETL of getting the stuff into Pandas won't be faster than working directly with worksheet objects.</p>
|
Hash not inserting into database <p>I am trying to insert array into data base. I can see the array (status"=>{"group_one"=>"One", "group_two"=>"One"}) in the parameters but while inserting inot db, it is being ommitted.</p>
<p>My console displays the following:</p>
<pre><code>Parameters: {"utf8"=>"â",
"authenticity_token"=>"JgCBl8vcDAP9AUGaylk34om4mbKkxHCgM+GuAfxTL3sywaJkmvKL3pyS2C44MAkzMZ6AK+CUVv/Vmg9aUQYrZw==",
"irb"=>{"proposalno"=>"", "otherapptype"=>"", "titleofproject"=>"",
"date1"=>"", "date2"=>"", "date3"=>"", "fundingdetails"=>"",
"fund"=>"No internal funds or external funds are requested",
"datetobegindc"=>"", "rationale"=>"", "abstract"=>"",
"noofsub"=>"0", "natureofassociation"=>"",
"subjectselection"=>"", "confidentiality"=>"",
"howwhereconsent"=>"", "methodproceduresubjectparti"=>"",
"childrenpermission"=>"", "infowithheld"=>"",
"riskbenefitratio"=>"", "minimizingrisk"=>""},
"status"=>{"group_one"=>"One", "group_two"=>"One"},
"responsibility"=>{"nameoffac"=>"", "nameofinv"=>"",
"deptoffac"=>"", "deptofinv"=>"", "addoffac"=>"",
"addofinv"=>"", "phoneoffac"=>"", "phoneofinv"=>"",
"emailoffac"=>"", "emailofinv"=>""}, "commit"=>"SUBMIT MY DETAILS"}
(0.2ms) begin transaction
SQL (2.9ms) INSERT INTO "irbs" ("proposalno", "titleofproject",
"date1", "date2", "date3", "fund", "fundingdetails", "datetobegindc",
"rationale", "abstract", "noofsub", "natureofassociation",
"subjectselection", "confidentiality", "howwhereconsent",
"methodproceduresubjectparti", "childrenpermission", "infowithheld",
"riskbenefitratio", "minimizingrisk", "otherapptype", "created_at",
"updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?) [["proposalno", ""], ["titleofproject", ""],
["date1", ""], ["date2", ""], ["date3", ""],
["fund", "No internal funds or external funds are requested"],
["fundingdetails", ""], ["datetobegindc", ""], ["rationale", ""],
["abstract", ""], ["noofsub", "0"], ["natureofassociation", ""],
["subjectselection", ""], ["confidentiality", ""],
["howwhereconsent", ""], ["methodproceduresubjectparti", ""],
["childrenpermission", ""], ["infowithheld", ""],
["riskbenefitratio", ""], ["minimizingrisk", ""],
["otherapptype", ""], ["created_at", 2016-10-18 19:48:35 UTC],
["updated_at", 2016-10-18 19:48:35 UTC]]
</code></pre>
<p>Here is my controller:</p>
<pre><code>class IrbsController < ApplicationController
def new
@irb = Irb.new
end
def create
@irb = Irb.new(irb_params)
if @irb.save
#RegistrationMailer.signup_confirmation(@registration).deliver
#log_in @user
flash[:success] = "Your details have been registered. A confirmation email has been sent."
redirect_to root_url
else
render 'new'
end
end
def index
end
def edit
end
def show
end
private
def irb_params
params.require(:irb).permit(:proposalno, :apptype, :titleofproject, :acc1, :date1, :acc2, :date2, :acc3, :date3, :projtype, :fund, :fundingdetails, :datetobegindc, :statusofprininv, :typeofreview, :rationale, :abstract, :noofsub, :assowithsub, :natureofassociation, :subjectselection, :ressubcomp, :adforresparti, :confidentiality, :voluntaryparticipation, :howwhereconsent, :methodproceduresubjectparti, :childrenpermission, :infowithheld, :risk, :riskbenefitratio, :minimizingrisk, :otherapptype, status:[])
end
end
</code></pre>
<p>Here is the migration:</p>
<pre><code>class CreateIrbs < ActiveRecord::Migration[5.0]
def change
create_table :irbs do |t|
t.string :proposalno
t.text :status
t.string :responsibility
t.string :apptype
t.string :titleofproject
t.string :acc1
t.string :date1
t.string :acc2
t.string :date2
t.string :acc3
t.string :date3
t.string :projtype
t.string :fund
t.string :fundingdetails
t.string :datetobegindc
t.string :statusofprininv
t.string :typeofreview
t.string :rationale
t.string :abstract
t.string :poputype
t.string :noofsub
t.string :assowithsub
t.string :natureofassociation
t.string :subjectselection
t.string :ressubcomp
t.string :adforresparti
t.string :confidentiality
t.string :voluntaryparticipation
t.string :howwhereconsent
t.string :methodproceduresubjectparti
t.string :childrenpermission
t.string :infowithheld
t.string :risk
t.string :riskbenefitratio
t.string :minimizingrisk
t.string :otherapptype
t.timestamps
end
end
end
</code></pre>
<p>Model code:</p>
<pre><code>class Irb < ApplicationRecord
serialize :status
end
</code></pre>
| <p>Perhaps you should try changing your datatype from <code>string</code> to <code>text</code></p>
<p><a href="http://stackoverflow.com/questions/6694432/using-rails-serialize-to-save-hash-to-database">Using Rails serialize to save hash to database</a></p>
|
Why is some of the colorization of cells not occurring, and is there a connection between that and the "Cannot perform runtime binding" err msg? <p>I'm getting the following err msg:</p>
<p><a href="https://i.stack.imgur.com/xC3gQ.png" rel="nofollow"><img src="https://i.stack.imgur.com/xC3gQ.png" alt="enter image description here"></a></p>
<p>This is occurring in this code:</p>
<pre><code>private bool GetContractForDescription(string desc)
{
int DESCRIPTION_COL_NUM = 2;
int CONTRACT_COL_NUM = 7;
bool contractVal = false;
int rowsUsed = _xlBook.Worksheets["PivotData"].UsedRange.Rows.Count;
int colsUsed = _xlBook.Worksheets["PivotData"].UsedRange.Columns.Count;
string colsUsedAsAlpha
ReportRunnerConstsAndUtils.GetExcelColumnName(colsUsed);
string endRange = string.Format("{0}{1}", colsUsedAsAlpha, rowsUsed);
Range sourceData = _xlBook.Worksheets["PivotData"].Range[string.Format("A2:{0}", endRange)];
// This is blowing up for some reason, so look for more detail on why
string currentDesc = string.Empty;
try
{
for (int i = 1; i <= rowsUsed; i++)
{
var dynamicCell = (Range)sourceData.Cells[i, DESCRIPTION_COL_NUM];
currentDesc = dynamicCell.Value2.ToString();
if (currentDesc.Equals(desc))
{
var dynamicContractCell = (Range)sourceData.Cells[i, CONTRACT_COL_NUM];
contractVal = (bool)dynamicContractCell.Value2;
break;
}
}
return contractVal;
}
catch (Exception ex)
{
MessageBox.Show(string.Format("currentDesc is {0}; exception is {1}", currentDesc, ex.Message));
}
return false;
}
</code></pre>
<p>And weirder yet, a range of rows/cols that I colorize under a particular circumstance has a "hole cut out of it" where it is not being colored.</p>
<p>Here is the source data in question (the middle row (156), with the "TRUE" value in the last column, is the key one):</p>
<p><a href="https://i.stack.imgur.com/RoyKM.png" rel="nofollow"><img src="https://i.stack.imgur.com/RoyKM.png" alt="enter image description here"></a></p>
<p>Here is how that data is rendered on the pivottable (the middle block of data, rows 293-297, being key):</p>
<p><a href="https://i.stack.imgur.com/zU5HW.png" rel="nofollow"><img src="https://i.stack.imgur.com/zU5HW.png" alt="enter image description here"></a></p>
<p>Here is the code I use to pivotize the source data:</p>
<pre><code>private void AddPivotTable()
{
int FIRST_DESCRIPTION_ROW = 8;
int LINES_BETWEEN_DESCRIPTION_VALS = 5;
var pch = _xlBook.PivotCaches();
int rowsUsed = _xlBook.Worksheets["PivotData"].UsedRange.Rows.Count;
int colsUsed
_xlBook.Worksheets["PivotData"].UsedRange.Columns.Count;
string colsUsedAsAlpha
ReportRunnerConstsAndUtils.GetExcelColumnName(colsUsed);
string endRange = string.Format("{0}{1}", colsUsedAsAlph
rowsUsed);
Range sourceData
_xlBook.Worksheets["PivotData"].Range[string.Format("A1:{0}", endRange)];
PivotCache pc = pch.Create(XlPivotTableSourceType.xlDatabas
sourceData);
PivotTable pvt = pc.CreatePivotTable(_xlPivotTableSheet.Range["A6"
"PivotTable");
pvt.MergeLabels = true;
pvt.PivotFields("Description").Orientation
XlPivotFieldOrientation.xlRowField;
var monthField = pvt.PivotFields("MonthYr");
monthField.Orientation = XlPivotFieldOrientation.xlColumnField;
monthField.NumberFormat = "mmm yyyy";
monthField.DataRange.Interior.Color
ColorTranslator.ToOle(Color.LightBlue);
pvt.CompactLayoutColumnHeader = "Months";
pvt.CompactLayoutRowHeader = "Description";
pvt.AddDataField(pvt.PivotFields("TotalQty"), "Total Packages
XlConsolidationFunction.xlSum).NumberFormat = "###,##0";
pvt.AddDataField(pvt.PivotFields("TotalSales"), "Total Purchases
XlConsolidationFunction.xlSum).NumberFormat = "$#,##0";
PivotField avg = pvt.CalculatedFields().Add("Average Price
"=TotalSales/TotalQty", true);
avg.Orientation = XlPivotFieldOrientation.xlDataField;
// TODO: This calculation needs to change (it needs to actually
made a calculation, rather than just the TotalSales val)
pvt.CalculatedFields()._Add("PercentOfTotal", "=TotalSales");
pvt.AddDataField(pvt.PivotFields("PercentOfTotal"), "% of Total
Type.Missing).NumberFormat = "###.##";
. . .
</code></pre>
<p>...and here is the code to color the item in question:</p>
<pre><code>for (m = 1; m <= dataCnt + 1; m++)
{
string descVal = cellRng.Value2.ToString();
bool isContractItem = GetContractForDescription(descVal);
if (isContractItem)
{
mcellRng = _xlPivotTableSheet.Range[
_xlPivotTableSheet.Cells[rowcnt, 1],
_xlPivotTableSheet.Cells[rowcnt + 4, _grandTotalsColumn-1]];
mcellRng.Interior.Color = ColorTranslator.ToOle(CONTRACT_ITEM_COLOR);
mcellRng.EntireRow.RowHeight = 15;
}
. . .
</code></pre>
<p>I don't see how the colorization code (directly above) can only partially work - as seen in the second screenshot, with the first several cells in the B column being white instead of yellow, as the rest of the range is. It's as if there's
something "poison" in this data that's preventing it from being colorized.</p>
<p>If I generate fewer columns (by using a different date range to run the report) it runs without the err msg (but still has the "hole" in the range in question).</p>
<p>If I just generate two months, it's fine; but if I try six (the "problem" record exists in either case) the exception is thrown...?!?</p>
<h2>UPDATE</h2>
<p>When I comment out the entire while loop, it runs without the error, but of course I then do not get the ContractItems colorized.</p>
<p>The problematic while loop is:</p>
<pre><code>while ((cellRng.Value2 != null) && cellRng.Value2.ToString() != "Total Total Packages")
{
cellRng.RowHeight = 25;
for (m = 1; m <= pivotTableRowCount; m++)
{
string descVal = cellRng.Value2.ToString();
bool isContractItem = GetContractForDescription(descVal);
if (isContractItem)
{
mcellRng = _xlPivotTableSheet.Range[
_xlPivotTableSheet.Cells[rowCounter, 1],
_xlPivotTableSheet.Cells[rowCounter + 4, _grandTotalsColumn - 1]];
mcellRng.Interior.Color = ColorTranslator.ToOle(CONTRACT_ITEM_COLOR);
mcellRng.EntireRow.RowHeight = 15;
}
rowCounter = rowCounter + LINES_BETWEEN_DESCRIPTION_VALS;
cellRng = (Range)_xlPivotTableSheet.Cells[rowCounter, 1];
}
}
</code></pre>
<p>What in here could be causing that err msg?</p>
<p>It's not the GetContractForDescription() method that is causing the problem, because ignoring it like so:</p>
<pre><code>bool isContractItem = false; //GetContractForDescription(descVal);
</code></pre>
<p>...does not prevent the err msg.</p>
<h2>UPDATE 2</h2>
<p>Since my head is mushy from banging it against my wallpaper for so long, I decided to "go back to the coding board" and begin fresh. I now have this code for determining which items are contracted:</p>
<pre><code>List<String> contractItemDescs = GetContractItemDescriptions();
MessageBox.Show(contractItemDescs.Count.ToString());
. . .
private List<string> GetContractItemDescriptions()
{
int FIRST_PIVOTDATA_DATA_ROW = 2;
int DESCRIPTION_COLUMN = 2;
int CONTRACT_COLUMN = 7;
List<string> descriptionsOfContractedItems = new List<string>();
int pivotDataRowCount = _xlBook.Worksheets["PivotData"].UsedRange.Rows.Count;
// Loop through the data sheet, adding the Descriptions for all Contract Items to the generic list
for (int i = FIRST_PIVOTDATA_DATA_ROW; i <= pivotDataRowCount; i++)
{
Range contractItemCell = _xlPivotDataSheet.Cells[i, CONTRACT_COLUMN];
//if (contractItemCell.Value2.ToString() == "TRUE") <= seems to be the same logic as below, but this doesn't work, whereas the below code does...?!?
if (contractItemCell.Value2.ToString().ToUpper() != "FALSE")
{
Range descriptionCell = _xlPivotDataSheet.Cells[i, DESCRIPTION_COLUMN];
String desc = descriptionCell.Value2.ToString();
descriptionsOfContractedItems.Add(desc);
}
}
return descriptionsOfContractedItems;
}
</code></pre>
<p>This is working correctly - the messagebox is showing me the valid count. Note, though, the commented out "if" statement. Using that, I was getting nothing added to the list; with the seeming analogue that I now use, I get the correct/expected behavior, though, I don't know why.</p>
| <p>I don't rightly know why the previous code didn't work, but my guess is that the logic was just generally too discombobulated. I refactored and simplified it (rather than trying to adapt some existing code written by someone else, I started afresh and did it "my way") and it now works just fine. The new code is:</p>
<pre><code>private static readonly Color CONTRACT_ITEM_COLOR = Color.FromArgb(255, 255, 204);
. . .
private void AddPivotTable()
{
. . .
List<String> contractItemDescs = GetContractItemDescriptions();
ColorizeContractItemBlocks(contractItemDescs);
. . .
}
private List<string> GetContractItemDescriptions()
{
int FIRST_PIVOTDATA_DATA_ROW = 2;
int DESCRIPTION_COLUMN = 2;
int CONTRACT_COLUMN = 7;
List<string> descriptionsOfContractedItems = new List<string>();
int pivotDataRowCount = _xlBook.Worksheets["PivotData"].UsedRange.Rows.Count;
// Loop through the data sheet, adding the Descriptions for all Contract Items to the generic list
for (int i = FIRST_PIVOTDATA_DATA_ROW; i <= pivotDataRowCount; i++)
{
Range contractItemCell = _xlPivotDataSheet.Cells[i, CONTRACT_COLUMN];
if (contractItemCell.Value2.ToString().ToUpper() != "FALSE")
{
Range descriptionCell = _xlPivotDataSheet.Cells[i, DESCRIPTION_COLUMN];
String desc = descriptionCell.Value2.ToString();
descriptionsOfContractedItems.Add(desc);
}
}
return descriptionsOfContractedItems;
}
private void ColorizeContractItemBlocks(List<string> contractItemDescs)
{
int FIRST_DESCRIPTION_ROW = 8;
int DESCRIPTION_COL = 1;
int ROWS_BETWEEN_DESCRIPTIONS = 5;
int rowsUsed = _xlBook.Worksheets["PivotTable"].UsedRange.Rows.Count;
int colsUsed = _xlBook.Worksheets["PivotTable"].UsedRange.Columns.Count;
int currentRowBeingExamined = FIRST_DESCRIPTION_ROW;
while (currentRowBeingExamined < rowsUsed)
{
Range descriptionCell = _xlPivotTableSheet.Cells[currentRowBeingExamined, DESCRIPTION_COL];
String desc = descriptionCell.Value2.ToString();
if (contractItemDescs.Contains(desc))
{
Range rangeToColorize = _xlPivotTableSheet.Range[
_xlPivotTableSheet.Cells[currentRowBeingExamined, 1],
_xlPivotTableSheet.Cells[currentRowBeingExamined + 4, colsUsed]];
rangeToColorize.Interior.Color = ColorTranslator.ToOle(CONTRACT_ITEM_COLOR);
}
currentRowBeingExamined = currentRowBeingExamined + ROWS_BETWEEN_DESCRIPTIONS;
}
}
</code></pre>
|
How to clear "warning message" after selecting file? <p>Please follow the instructions below:</p>
<p><strong>My View:</strong></p>
<pre><code><div class="col-xs-6">
@Html.LabelFor(model => model.File)
<br />
@Html.TextBoxFor(model => model.File, new { @class = "form-control", @type = "file" })
<div id="ErrorFile"></div>
<br />
</div>
</code></pre>
<p><strong>My Javascript:</strong></p>
<pre><code>$.ajax({
success: function (response) {
if (response.ErrorFile) {
$("#ErrorFile").html('<span class="text-danger field-validation-error" data-valmsg-replace="true"><span class="">* Required field.</span></span>');
}
}
});
</code></pre>
<p>After selected a file, the message should disappear. It continues to show.</p>
<p>How can I hide or clean "id = File Error" after file selected?</p>
| <p>I think you are looking for something like this:</p>
<pre><code>$.ajax({
success: function (response) {
if (response.ErrorFile) {
$("#ErrorFile").html('<span class="text-danger field-validation-error" data-valmsg-replace="true"><span class="">* Required field.</span></span>');
} else {
$("#ErrorFile").html('');
}
}
});
</code></pre>
|
Unable to nest loops in jmeter test plan <p>I have a JMeter test plan to do the following: </p>
<ul>
<li>Reads a list of domain URLs from a CSV</li>
<li>visit each </li>
<li>extract main menu items from each domain</li>
<li>loop on each menu item
<ul>
<li>visit the menu item </li>
</ul></li>
</ul>
<p>I have a debug sampler and I am able to successfully run the thread group and successfully extract menu items but it fails to go into the last loop.</p>
<p><a href="https://i.stack.imgur.com/IdotT.png" rel="nofollow"><img src="https://i.stack.imgur.com/IdotT.png" alt="enter image description here"></a> </p>
| <p>Found the answer. had to check the <code>use "-" before number</code> checkbox in the loop through Non-admin links section as shown in the picture below.
<a href="https://i.stack.imgur.com/Ox6LT.png" rel="nofollow"><img src="https://i.stack.imgur.com/Ox6LT.png" alt="enter image description here"></a></p>
|
How to remove duplicates of a string from another string in Java? <p>So I need to remove duplicates of a specific string from another string in Java, a few examples:</p>
<pre><code>'test12312312312' -> Remove duplicates of '123', output -> 'test12312'
'my sentence-!!!!!!!!!' -> Remove duplicates of '!!' , output -> 'my sentence-!!!'
'3rd ?!?!?!abd%3!?!?!??'-> Remove duplicates of '!?' , output -> '3rd ?!?!abd%3?'
</code></pre>
<p>Hopefully those examples make this clear. e.g. you pass a function any two strings, and it removes all duplicates of the first one from the second. For example it might look like:</p>
<pre><code>String removeDuplicates(String checkString, String message) {
//Return 'message' with duplicates of 'checkString' removed
}
</code></pre>
<p>I've seen various implementations of this for removing all instances of the string, or removing duplicates of a specific character - but none that keep the first occurance of a string. Any ideas?</p>
| <p>With <code>String#replace</code>:</p>
<pre><code>String needle = /* search string */;
String base = /* input string */;
int firstLoc = base.indexOf(needle);
if (firstLoc > 0) {
int cutoff = firstLoc + needle.length();
return base.substring(0, cutoff) + base.substring(cutoff).replace(needle, "");
}
return base;
</code></pre>
<p>Outside of that, you can iterate through the string, and if the first character of your search string matches the current character you are at, see if the remainder makes up the string in total. If it does, then just skip ahead. You're essentially just rebuilding the string:</p>
<pre><code>//Precondition: needle not empty, vars not null, etc
StringBuilder back = new StringBuilder();
String needle = /* search string */;
String base = /* input string */;
boolean first = true;
for (int i = 0; i < base.length(); i++) {
char c = base.charAt(i);
if (c == needle.charAt(0)
&& base.substring(i, Math.min(base.length(), i + needle.length())).equals(needle)) {
if (first) {
first = false;
} else {
i += needle.length() - 1;
continue;
}
}
back.append(c);
}
return back.toString();
</code></pre>
|
Forcing Riak to store data on distinct physical servers <p>I'm concerned by this note in Riak's documentation:</p>
<blockquote>
<p>N=3 simply means that three copies of each piece of data will be stored in the cluster. That is, three different partitions/vnodes will receive copies of the data. <strong>There are no guarantees that the three replicas will go to three separate physical nodes</strong>; however, the built-in functions for determining where replicas go attempts to distribute the data evenly.</p>
</blockquote>
<p><a href="https://docs.basho.com/riak/kv/2.1.3/learn/concepts/replication/#so-what-does-n-3-really-mean" rel="nofollow">https://docs.basho.com/riak/kv/2.1.3/learn/concepts/replication/#so-what-does-n-3-really-mean</a></p>
<p>I have a cluster of 6 physical servers with N=3. I want to be 100% sure that total loss of some number of nodes (1 or 2) will not lose any data. As I understand the caveat above, Riak cannot guarantee that. It appears that there is some (admittedly low) portion of my data that could have all 3 copies stored on the same <em>physical server</em>. </p>
<p>In practice, this means that for a sufficiently large data set I'm guaranteed to completely lose records if I have a catastrophic failure on a single node (gremlins eat/degauss the drive or something). </p>
<p>Is there a Riak configuration that avoids this concern? </p>
<p>Unfortunate confounding reality: I'm on an old version of Riak (1.4.12).</p>
| <p>There is no configuration that avoids the minuscule possibility that a partition might have 2 or more copies on one physical node (although having 5+ nodes in your cluster makes it extremely unlikely that a single node with have more than 2 copies of a partition). With your 6 node cluster it is extremely unlikely that you would have 3 copies of a partition on one physical node.</p>
<p>The riak-admin command line tool can help you explore your partitions/vnodes. Running <code>riak-admin vnode-status</code> (<a href="http://docs.basho.com/riak/kv/2.1.4/using/admin/riak-admin/#vnode-status" rel="nofollow">http://docs.basho.com/riak/kv/2.1.4/using/admin/riak-admin/#vnode-status</a>) on each node for example will output the status of all vnodes the are running on the local node the command is run on. If you run it on every node in your cluster you confirm whether or not your data is distributed in a satisfactory way.</p>
|
Batch, trying to set a variable to a value that is the characters from x to x+5, missing operand? <pre><code> :modify
set xa=x+5
set /a m1=%l1:~%x%,%xa%%
set /a m2=%l2:~%x%,%xa%%
set /a m3=%l3:~%x%,%xa%%
set /a m4=%l4:~%x%,%xa%%
set /a m5=%l5:~%x%,%xa%%
goto main
</code></pre>
<p>x was set to 0 previously
what am i doing wrong?
i get Missing operand 5 times...</p>
<p><em>edit</em> copied code from pastebin:</p>
<pre><code>@echo off
set /a x=0
< batchmap.txt (
set /p l1=
set /p l2=
set /p l3=
set /p l4=
set /p l5=
)
goto modify
:modify
set xa=x+5
set /a m1=%l1:~%x%,%xa%%
set /a m2=%l2:~%x%,%xa%%
set /a m3=%l3:~%x%,%xa%%
set /a m4=%l4:~%x%,%xa%%
set /a m5=%l5:~%x%,%xa%%
goto main
:main
echo %m1%
echo %m2%
echo %m3%
echo %m4%
echo %m5%
echo i really hope it doesnt say Echo is OFF.
echo or the wrong thing
echo oh well, x is %x%
echo continue?
pause >nul
set /a x=x+1
goto :modify
</code></pre>
| <p>You have to use the <code>delayedexpansion</code> to make the substitution.</p>
<p>and <code>set /a</code> is used to make some Aritmetical operation that's why you get the operand error.</p>
<pre><code> setlocal enabledelayedexpansion
:modify
set /a xa=x+5
set m1=!l1:~%x%,%xa%!
set m2=!l2:~%x%,%xa%!
set m3=!l3:~%x%,%xa%!
set m4=!l4:~%x%,%xa%!
set m5=!l5:~%x%,%xa%!
goto main
</code></pre>
|
Is there a multiplication analogue to Integer::sum? <p>Since Java 8, the <code>Integer</code> class has a static <code>sum</code> method that adds two integers:</p>
<pre><code>public static int sum(int a, int b) {
return a + b;
}
</code></pre>
<p>I can pass this method to higher-order functions via <code>Integer::sum</code> which I find more readable than <code>(a, b) -> a + b</code>.</p>
<p>Is there a similar static method for multiplication, so I don't have to write <code>(a, b) -> a * b</code>? I couldn't find one in the <code>Integer</code> class.</p>
| <p><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/Math.html#multiplyExact-int-int-" rel="nofollow"><code>Math::multiplyExact</code></a></p>
<blockquote>
<p><code>static int multiplyExact(int x, int y)</code></p>
<p>Returns the product of the arguments, throwing an exception if the result overflows an int.</p>
</blockquote>
|
ONLYOFFICE and mime-types assosiasions <p>I`m using Elementary Os Loki and wanted to use ONLYOFFICE.
I tried installing the last deb file from official site and tried to use the repo(no change). The problem is that when the package installs it doesn`t register itself to allow opening the file from filemanager or terminal(desktopeditors -f example.doc or smth).
I found whole dir in the official repo where I think all logic is handled.</p>
<p>(<a href="https://github.com/ONLYOFFICE/desktop-apps/tree/master/win-linux/package/linux/qt-installer/packages/onlyoffice/data" rel="nofollow">https://github.com/ONLYOFFICE/desktop-apps/tree/master/win-linux/package/linux/qt-installer/packages/onlyoffice/data</a>)</p>
<p>I also tried to fix by changing file in /usr/share/applications - defaults.list and desktopeditors.desktop.</p>
<p>Please fix this or give a nice explaination if it a feature.
The only way to open a file is to use internal file chooser dialog or to drag&drop a file on the window.</p>
| <p>It is a bug in onlyoffice-desktopeditors. We will fix it soon. You can set file associations: open context menu of the file, choose "open with" -> "other applications". Then find 'desktopeditors' in recommended applications, select this and press 'Set as default' button.
After this you will be able to open files from file manager in ONLYOFFICE.</p>
|
How can I publish a beta in Google Play while my app is still in Timed publishing? <p>I have an app that's close to launch. In prep for this, I've put it into production with "Timed publishing". It's ready to go, all I have to do now is click "Go Live".</p>
<p>However, I have a bug fix and I want to put out a beta for it now, before I'm ready to release the app to the world at large.</p>
<p>I've managed to upload the beta, but how can I release it to my beta testers through the store. Previously when I've played with Timed publishing, it didn't actually go out to the Beta testers until I clicked "Go Live".</p>
<p>I don't want to do that, because I'm not ready for my app to be made public at all, and I'm afraid it will go anyway.</p>
<p>I've tried switching to Advanced mode and Deactivating the version in production right now; however, it won't let me save. It complains <code>The application could not be saved. Please check the form for errors.</code> But don't see anything on the form that looks like an error.</p>
<p>How can I do this, or what should I be looking for to find the error?</p>
| <p>Right now I'm facing the same problem, but I think it's not possible to publish a beta if timed publishing is enabled without going live.</p>
<p>Here is the reference about this topic I found in Google support:</p>
<p><a href="https://i.stack.imgur.com/4mhUy.png" rel="nofollow"><img src="https://i.stack.imgur.com/4mhUy.png" alt="Timed publishing"></a>
Reference link: <a href="https://support.google.com/googleplay/android-developer/answer/6334282?hl=en&ref_topic=7072031" rel="nofollow">https://support.google.com/googleplay/android-developer/answer/6334282?hl=en&ref_topic=7072031</a></p>
|
ng-lightning with angular2+systemjs and NgModule <p>I tried to use ng-lightning (0.24.0) with angular2 (2.0.2) and systemjs module loader. The bundle loading is okay I think but when I try to call an ng-lightning template in an ngModule I've got template parse error. From a single component it is workink but inside an ngModule doesn't.</p>
<p>My package.json</p>
<pre><code>"dependencies": {
"@angular/common": "~2.0.2",
"@angular/compiler": "~2.0.2",
"@angular/core": "~2.0.2",
"@angular/http": "~2.0.2",
"@angular/forms": "~2.0.2",
"@angular/platform-browser": "~2.0.2",
"@angular/platform-browser-dynamic": "~2.0.2",
"@angular/router": "~3.0.2",
"@angular/upgrade": "~2.0.2",
"reflect-metadata": "^0.1.8",
"rxjs": "5.0.0-beta.12",
"systemjs": "0.19.39",
"zone.js": "^0.6.25",
"core-js": "^2.4.1",
"@salesforce-ux/design-system": "^2.1.2",
"ng-lightning": "0.24.0",
"tether": "^1.2.4",
},
</code></pre>
<p>app.module.ts</p>
<pre><code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule, JsonpModule } from '@angular/http';
import { NglModule } from 'ng-lightning/ng-lightning'
import { AppRoutingModule } from './app.routing';
import { AppComponent } from './app.component';
import { TestModule } from './test/test.module';
@NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
JsonpModule,
NglModule.forRoot(),
TestModule,
AppRoutingModule
],
declarations: [
AppComponent,
],
bootstrap: [ AppComponent ]
})
export class AppModule { }
</code></pre>
<p>And in TestModule there is a test component and in the test component template theres the template tag.</p>
<p>test.module.ts</p>
<pre><code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { TestComponent } from './test.component';
import { TestRoutingModule } from './test.routing';
@NgModule({
imports: [ CommonModule, FormsModule, TestRoutingModule ],
declarations: [ TestComponent ],
exports: [ ],
providers: [ ]
})
export class TestModule { }
</code></pre>
<p>test.component.ts</p>
<pre><code>import { Component } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'testcomp',
template: '<ngl-badge></ngl-badge>'
})
export class TestComponent {}
</code></pre>
<p>I've got this error:</p>
<pre><code>zone.js:355 Unhandled Promise rejection: Template parse errors:
'my-app' is not a known element:
1. If 'my-app' is an Angular component, then verify that it is part of this module.
2. If 'my-app' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("
<body>
<div class="slds">
[ERROR ->]<my-app>
<div class="slds-grid slds-grid--align-center">
<div class="slds-col">
"): TestComponent@21:4 ; Zone: <root> ; Task: Promise.then ; Value: Error: Template parse errors:(â¦) Error: Template parse errors:
</code></pre>
<p> is the main app component template. When I delete tag from my test component template the app works fine. What is the problem? ng-lightning.umd.js loaded correctly as I see in network tab and no error after tsc compiling. So I don't understand.</p>
| <p><code>Angular</code> is built with modularity in mind: this means that each Module should declare or import every component, directive and pipe that it wants to use.</p>
<p>For the parser to recognize a component, it <em>must</em> have been declared in the current module, or exported by another module that the current module imports. This is why -- for instance -- you had to import <code>FormsModule</code> in both of your modules in the OP.</p>
<p>Thus you get parsing errors when you try to use <code>ngl-badge</code> in <code>TestComponent</code> because you haven't told <code>Angular</code> that you intend to use <code>ngl-badge</code> when you created <code>TestModule</code></p>
<p>Basically, just import what you need into <code>TestModule</code></p>
<pre><code>@NgModule({
imports: [ CommonModule, FormsModule,
TestRoutingModule, NglModule.forChild() ],
declarations: [ TestComponent ],
exports: [ ],
providers: [ ]
})
export class TestModule { }
</code></pre>
<p>I'm not familiar with <code>ng-lightning</code>, so I'm just making an educated guess that <code>NglModule.forChild()</code> is what you want to import. It may simply be <code>NglModule</code></p>
|
React native: How to combine external and inline styles? <p>This is a part of a _renderRow-function. I have some basic styles for a button, and also a style that is read from a variable on the row. In this example it's '#f00' but it could be a variable, like thisColor. How can I combine an external style with an inline style? </p>
<p>Something like this, but this doesn't work:</p>
<pre><code><TouchableHighlight style={[styles.button]{ backgroundColor: '#f00'}}
</code></pre>
<p>Or do I have to nest it with a container inside the TouchableHightlight and put the inline style on that element instead?</p>
| <p>Can use the spread syntax:</p>
<pre><code><TouchableHighlight style={{ ...styles.button, backgroundColor: '#f00'}}
</code></pre>
|
Unable to save Selected File to directory when not on the development server <p>When I am on the development server testing, the following code will save the document in the directory I want it to be in... But when I test it on another computer from the network, the file will not save to the directory. The Directory has "Everyone" Full access but still has this problem.</p>
<pre><code>Protected Sub btnSCSoldSheets_Click(sender As Object, e As EventArgs) Handles btnSCSoldSheets.Click
If fuSCSold.FileName = Nothing Then
Exit Sub
Else
Dim fileName As String = Path.GetFileName(fuSCSold.PostedFile.FileName)
fuSCSold.PostedFile.SaveAs(Server.MapPath("~/ISI/ScoreCard/ScoreCardFiles/") + fileName)
lblFileNameSCSold.Text = fileName
generateExcelSheets()
End If
End Sub
</code></pre>
| <p>I figured it out... So silly on my part. </p>
<p>When I copied the website from development to production, I didn't change the physical directory to match what was in production. </p>
|
Error accessing Swift dictionary value <p>I'm using a provided value to access an array value from a dictionary:</p>
<pre><code>print("thisFrom "+thisFrom)
print(values[thisFrom])
let ingredientArr = values[thisFrom] as! [String: Float]
</code></pre>
<p>But this is the output:</p>
<pre><code>thisFrom cup
Optional(["butter": 226.80000000000001, "caster sugar": 225.00730999999999, "granulated sugar": 200.0, "tbsp": 16.0, "ml": 236.58823649999999, "flour": 125.0, "tsp": 48.0, "icing sugar": 125.0])
fatal error: unexpectedly found nil while unwrapping an Optional value
</code></pre>
<p>I don't understand how it can be returning <code>nil</code> , when the <code>print</code> lines show the value and resulting array are valid.</p>
<p>I'm using Swift 3.</p>
| <p><code>values[thisFrom]</code> is not of the type <code>[String: Float]</code>. It is <code>[String: Double]</code> instead.</p>
<p>Why?</p>
<p>Let's have a look at the value for the key "butter": It is a <a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID321" rel="nofollow">floating-point</a> number with a precision of more than 6 decimal digits. So it can't be <code>Float</code>. That's why the force-cast fails.</p>
|
TypeError: not enough arguments for format string - Python SQL connection while using %Y-%m <pre><code>with engine.connect() as con:
rs = con.execute("""
SELECT datediff(STR_TO_DATE(CONCAT(year,'-',month,'-',day), '%Y-%m-%d') , current_date())
from TABLE
WHERE datediff(STR_TO_DATE(CONCAT(year,'-',month,'-',day), '%Y-%m-%d') , current_date()) < 900
group by STR_TO_DATE(CONCAT(year,'-',month,'-',day), '%Y-%m-%d');
""")
</code></pre>
<p>I feel the compiler is getting confused with '%Y-%m-%d', I might be wrong. Could someone help me on how to avoid this error:</p>
<blockquote>
<p>Type Error:not enough arguments for format string</p>
</blockquote>
| <p>It sees your <code>%</code> signs and thinks you want to format the string. I believe you should be able to replace them with <code>%%</code> to indicate that you want the character, not a format substitution.</p>
|
MATLAB: Moving Integrator (Sum) Window with Varying Size, Based on a Condition <p>I'd like to define the start and end indices of a moving integrator (sum) window based on the cumulative sum of the values of <code>array</code>. Each window should have a cumulative sum of less than or equal to a threshold. </p>
<p>The <code>end_index</code> of this window is uniformly moving forward by 1 for the future windows, however the <code>start_index</code> is dependent on the values of <code>array</code>. <code>start_index</code> could move forward, stay the same or backwards (negative values), hence the size of this moving window is not fixed. </p>
<p>For example:</p>
<p><code>array = [ 1 0 2 1 1 2 0 0 1 2 0 1 0 1 1]</code>;</p>
<p>With the <code>start_index = 1</code>, the cumulative sum of <code>array</code> will be 5 at <code>end_index = 5</code>, for the first window. </p>
<p>Now for the next window, the <code>end_index</code> is moved forward by 1 such that the new <code>end_index = 6</code>. I'd like to know how I could find the new <code>start_index</code> by back calculating the cumulative sum from the new <code>end_index</code> so that <code>cumsum</code> is less than or equal to 5 for the new window as well. In this case, the new <code>start_index = 4</code>. </p>
<p>Any suggestions on how it could be done? </p>
<p>Thanks.</p>
| <p>The idea is that if we want to get cumulative sum from an starting index <code>k</code> there is no need again to compute cumsum. Instead only cumsum computed onec, and disired cumulative sum is difference of original cumulative sum and <code>k-1</code>th element of original cumulative sum</p>
<pre><code>original_Summ = [1 1 3 4 5 7 7 7 8 10 10 11 11 12 13]
k=3
new_Summ = original_Summ - original_Summ(k-1)
</code></pre>
<p>Note: following implementation may cause memory limits if size of <code>array</code> is lage. Instead each cmp and cmp1 sould be compted in each iteration.</p>
<pre><code>array = [ 1 0 2 1 1 2 0 0 1 2 0 1 0 1 1 ];
%forward cumsum
fwd = cumsum(array);
%backward cumsum
bkw = cumsum(array(end:-1:1));%cumsum(array,'reverse')
%difference of cumulative sum with all starting indices
cmp = bsxfun(@minus,fwd,[0 fwd(1:end-1)].');%in matlab r2016b cmp= fwd-[0 fwd(1:end-1)].'
cmp1= bsxfun(@minus,bkw,[0 bkw(1:end-1)].');%in matlab r2016b cmp1=bkw-[0 bkw(1:end-1)].'
%find last indices of elements that are <=5
[r, c] = find(cmp <=5);
idx = accumarray(r,c,[],@max);
[r1, c1] = find(cmp1 <=5);
idx1 = accumarray(r1,c1,[],@max);
idx1 =flipud(numel(array) + 1-idx1);
%loop to find indices from previous indices
si = 1;
index={};
while true
ei = idx(si);
if ei == numel(array)
break;
end
index {end+1} = [si,ei];
ei = ei+1;
si = idx1(ei);
index {end+1} = [si,ei];
end
disp(index)
</code></pre>
|
Shortest possible JS code to get ids of all elements of a given tag <p>I want to gather all the ids on a page for <code>foobar</code> elements into a comma-delimited string. For example:</p>
<pre><code><div>
<foobar id="456"></foobar>
<foobar id="aaa"></foobar>
<foobar id="987"></foobar>
<div>
</code></pre>
<p>Should give <code>"456,aaa,987"</code></p>
<p>The <code>foobar</code> elements will not ever be nested, if that matters.</p>
<p>My current solution is</p>
<pre><code>[].slice.call(document.getElementsByTagName("foobar")).map(function(a){return a.id}).join(","))
</code></pre>
<p><strong>Is there a way to do this in pure JS with an even shorter (post-minification) statement?</strong></p>
<p><em>Edit: In ES5 (aka "plain" javascript)</em></p>
<p><em>Edit 2:</em> I was able to shave off a few characters with:</p>
<pre><code>[].map.call(document.getElementsByTagName("foobar"),function(a){return a.id}).join();
</code></pre>
| <p>With ES5 I belive there is not much that can be done, however note that the default argument value for the <code>join</code> function is ',' so you can skip that and it will end up like: </p>
<pre><code>[].slice.call(document.getElementsByTagName("foobar")).map(function(a){return a.id}).join()
</code></pre>
<hr>
<p>With ES6 you can convert array-likes to arrays using <em>Array.from</em>, also you could use a lambda expression to shorten it even more.</p>
<p>So it will end up like:</p>
<pre><code>Array.from(document.getElementsByTagName("div")).map(a => a.id).join()
</code></pre>
|
Rails 4: Turn complicated filter into a scope <p>I have a many-to-many / has-many-through relationship in my connecting my recipe model to my tag model such that:</p>
<pre><code>class Tag < ActiveRecord::Base
has_many :taggings
has_many :recipes, through: :taggings
end
class Tagging < ActiveRecord::Base
belongs_to :tag
belongs_to :recipe
end
class Recipe < ActiveRecord::Base
has_many :taggings
has_many :tags, through: :taggings
end
</code></pre>
<p>...is there any way to filter for recipes with the same tag through a scope? I'm new to scopes, but I find them much more useful than methods, and I can only achieve searching and filtering by tag name through a method.</p>
<p>For example this will get me all recipes tagged with a given name:</p>
<pre><code>def self.tagged_with(name)
Tag.find_by_name!(name).recipes
end
</code></pre>
| <p>You can basically convert most association-method-chains (though not all*) into a scope</p>
<p>eg I'd try this (note: not tested for bugs) and see how it turned out</p>
<pre><code>scope :tagged_with, ->(name) { find_by_name!(name).recipes }
</code></pre>
<p>If that doesn't work, I'd try something like:</p>
<pre><code>scope :tagged_with, ->(name) { where(:name => name).first.recipes }
</code></pre>
<p>[*] The big issue with using scopes over method-chaining is that <code>find</code>/<code>first</code> can sometimes do weird things if it doesn't find one... the code in Rails literally defaults to the <code>all</code> scope in some cases (this is really weird behaviour that I think shouldn't happen) so for scopes that find just a single item, I will often not bother with a scope and use a class-method as you have originally.</p>
|
Javascript setInterval doesn't work <p>I have this code that has to be a tree with random signs. I put setInterval to change the signs every second, but nothing happens and I don't get even any error.
Someone please tell me where I made a mistake, or more :).</p>
<p>OLD VERSION</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>'use strict';
window.onload = intervalSetup;
var arraySigns = ["*", "^", "&", "#"];
function intervalSetup() {
setInterval(function() {
theTree();
}, 1000);
}
function theTree() {
var x = 8;
for (var i=0; i<x; i++) {
for (var j=x-1; j>i; j--) {
document.write("&nbsp;&nbsp;");
}
for (var k=0; k<=(i*2); k++) {
document.write(arraySigns[Math.floor(Math.random() * arraySigns.length)]);
}
document.write("<br>")
}
for (var i=0; i<2; i++) {
for (var j=0; j<(x*2)-3; j++) {
document.write("&nbsp;");
}
document.write("**<br>");
}
}</code></pre>
</div>
</div>
</p>
<p>NEW VERSION (after reading the comments) </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>window.onload = intervalSetup;
var arraySigns = ["*", "^", "&", "#"];
var getTop = document.getElementById("top");
var getTree = document.getElementById("tree");
function intervalSetup() {
setInterval(function() {
theTree();
}, 1000);
}
function theTree() {
var x = 8;
getTree.innerHTML = ''
for (var i=0; i<x; i++) {
for (var j=x-1; j>i; j--) {
getTree.innerHTML += "&nbsp;&nbsp;";
}
for (var k=0; k<=(i*2); k++) {
getTree.innerHTML += arraySigns[Math.floor(Math.random() * arraySigns.length)];
}
getTree.innerHTML += "<br>";
}
for (var i=0; i<2; i++) {
for (var j=0; j<(x*2)-3; j++) {
getTree.innerHTML += "&nbsp;";
}
getTree.innerHTML += "**<br>";
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="tree"></div></code></pre>
</div>
</div>
</p>
| <p>I tested the code on Google Chrome and it worked correctly.</p>
<p>Only had an <code>undefined</code> error in <code>arraySigns</code>.</p>
<p><a href="https://i.stack.imgur.com/ls1qJ.png" rel="nofollow"><img src="https://i.stack.imgur.com/ls1qJ.png" alt="Image generate tree"></a></p>
|
How do you expand all objects in the console view of chrome? <p>Is there a short cut for me to expand all these objects? I have attached a photo of what i would like to expand below. Any help would be amazing.</p>
<p><a href="https://i.stack.imgur.com/dwnu2.png" rel="nofollow"><img src="https://i.stack.imgur.com/dwnu2.png" alt="enter image description here"></a></p>
| <ol>
<li>Switch devtools to detached/floating window by clicking its Settings button, dock side: undock.</li>
<li>Press <kbd>Ctrl</kbd>-<kbd>Shift</kbd>-<kbd>i</kbd> inside the devtools window to open devtools for the devtools.</li>
<li><p>Paste and execute the following code in the newly opened devtools window:</p>
<blockquote>
<p><code>$$('.console-view-object-properties-section').forEach(e => e._section._objectTreeElement.expandRecursively())</code></p>
</blockquote></li>
<li><p>Switch to the original devtools window.</p></li>
</ol>
<p>You may want to save the code as a snippet in Sources panel to quickly execute it later.</p>
<p><sup>Based on <a href="https://cs.chromium.org/chromium/src/third_party/WebKit/Source/devtools/front_end/ui/treeoutline.js?q=expandRecursively+-file:test&sq=package:chromium&dr=C&l=781" rel="nofollow">chromium source code</a> for the devtools.</sup></p>
|
Firebase Authentication is not working for me <p>In documentation for Auth with Facebook says: </p>
<blockquote>
<p>Make sure your OAuth redirect URI (e.g. my-app-12345.firebaseapp.com/__/auth/handler) is listed as one of your OAuth redirect URIs in your Facebook app's settings page on the Facebook for Developers site in the Product Settings > Facebook Login config.. </p>
</blockquote>
<p>But when I try it with my link - it not redirect at all (<a href="https://someproject-8fda3.firebaseapp.com/__/auth/handler" rel="nofollow">https://someproject-8fda3.firebaseapp.com/__/auth/handler</a>). In console Auth with FB is switched on. But I still don't understand why it's not working (with google auth - same problem).</p>
| <p>I'm not sure what you're trying to do, but if you have app and do want to use firebase functionality to authenticate the user with facebook you have to install FBSDK and implement it in your code.</p>
|
How to perform CRUD operations on a Heroku DB from a Heroku Java Web app <p>I have a simple Java web app deployed in Heroku at <a href="https://wallpostapi.herokuapp.com/" rel="nofollow">this link</a> and I've also attached a Heroku <code>hobby-dev</code> <strong>POSTGRES</strong> database to it. </p>
<p>I'm trying to implement RESTful web services in my web app and I want it to perform simple CRUD operations on the Heroku DB based on the type of request it receives. I found a tutorial on Heroku developer's site on how RESTful APIs could be built using MEAN stack and Node.js and how Heroku DB could be accessed, but nothing on how the same could be done in Java web app.</p>
<p>Can anyone please help me implement RESTful web services in my Heroku-Java Web app that would communicate with Heroku database?</p>
<p>Thank you for your time!</p>
| <p>Use JDBC to connect to the database and you can easily perform crud operations.</p>
<p>For ex:</p>
<p>private static Connection getConnection() throws URISyntaxException,SQLException{</p>
<pre><code>URI dbUri = new URI(System.getenv("DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath();
return DriverManager.getConnection(dbUrl, username, password);
</code></pre>
<p>}</p>
|
Passing and copying arrays? <p>I am trying to create two Arrays in main then call a method where the values of the first array(which I randomized) are copied to the second array,I am getting stuck at calling the method and passing. I am lost on how to call and pass arrays
any help would be appreciated. </p>
<pre><code>class C9hw5
{
public static void main(String[] args)
{
int[] ar = new int[10]; // random array
int[] at = new int[10]; // array two
Random r = new Random();
for(int i = 0; i < ar.length; i++) // initializing it to random
ar[i] = r.nextInt();
System.out.println("The random array displays");
for(int i = 0; i < ar.length; i++)
System.out.println( ar[i]);
copyArray();
}
public static void copyArray(int ar[], int at[])
{
for (int i = 0; i < at.length; i++)
at[i] = ar[i];
}
}
}
</code></pre>
| <p>You didn't passed your arrays to the method, replace <code>copyArray();</code> by <code>copyArray(ar, at);</code>.</p>
|
Retrieve table data based on specific condition in Teradata <p>I have a table with below data:</p>
<pre><code>emp_id | emp_sal | emp_grp
1 5 HMCCR
1 10 HMCPR
1 20 HMCPR
1 30 HMCPR
1 40 HMCRR
2 40 HMCRR
2 50 HMCCR
</code></pre>
<p>I need to write sql in Teradata where i need to find min(emp_sal) for each group of emp_id.If one or more rows of emp_id has emp_grp='HMCPR' then retain only those rows and take min of emp_sal. Do not do anything when none of the rows have emp_grp='HMCPR' and take min of emp_sal from that group. </p>
<p>Apologize, if you are confused. Based on above condition my output should look like this:</p>
<pre><code>emp_id | emp_sal | emp_grp
1 10 HMCPR
2 40 HMCRR
</code></pre>
<p>I tried below query but it gives min(emp_sal) for each group as i used group by emp_id, emp_grp</p>
<pre><code>sel
emp_id,
case when emp_grp='HMCPR' then min(emp_sal)
else min(emp_sal) end emp_sal, emp_grp
from db_wrk.emp_sin
group by emp_id, emp_grp
</code></pre>
<p>Can anyone help me to get expected result in teradata.</p>
| <p>You can use <code>row_number</code> with some logic to get the emp_grp HMCPR to be ordered first if it exists.</p>
<pre><code>select emp_id,emp_sal,emp_grp
from (
select e.*,
row_number() over(partition by emp_id
order by case when emp_grp = 'HMCPR' then 0 else 1 end,emp_sal) as rn
from db_wrk.emp_sin e
) t
where rn = 1
</code></pre>
|
How to use AppenderSkeleton, Logger and LoggingEvent in Log4j_2.x <p>I am new to using log4j. My current task involves migrating log4j 1.2 to log4j 2.6. We use slf4j version 2.x of log4j. I have updated jar files to required versions.
I am getting following error in finding symbols AppenderSkeleton, Logger and LoggingEvent.
How can I use these classes in log4j 2.x or is there any alternative if these classes are deprecated?</p>
| <p>Depending on your current usage: have you customized Log4j 1 components, or is your application simply calling the Log4j 1 library?</p>
<p>If no customization you can continue to use the SLF4J API or even the Log4j 1 API (using the log4j-1.2-api module). </p>
<p>If you have custom Log4j 1 components you need to take a closer look. It's possible that the desired behavior has been implemented in Log4j 2 so the customization is no longer required. If you do still need it, then I would not extend Logger or LogEvent. Extend AbstractAppender if you want to create a custom appender. </p>
<p>Let the Log4j community know of your requirements so they can steer you in the right direction. </p>
|
get, access and modify element values for an numpy array <p>I once saw the following code segment</p>
<pre><code>import numpy as np
nx=3
ny=3
label = np.ones((nx, ny))
mask=np.zeros((nx,ny),dtype=np.bool)
label[mask]=0
</code></pre>
<p>The <code>mask</code> generated is a bool array</p>
<pre><code>[[False False False]
[False False False]
[False False False]]
</code></pre>
<p>If I would like to assign some elements in mask to other values, for instance, I have been trying to use <code>mask[2,1]="True"</code>, but it did not work without changing the corrsponding entry as I expected. What's the correct way to get access and change the value for an numpy array. In addition, what does <code>label[mask]=0</code> do? It seems to me that it tries to use each mask entry value to assign the corrsponding label entry value.</p>
| <p>Here is a code snippet with some comments that might help you make sense of this. I would suggest you look into the link that @Divakar provided and look into <a href="https://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html#boolean-or-mask-index-arrays" rel="nofollow">boolean-indexing</a>. </p>
<pre><code># a two dimensional array with random values
arr = np.random.random((5, 5))
# assign mask to a two dimensional array (same shape as arr)
# that has True for every element where the corresponding
# element in arr is greater than 0.5
mask = arr > 0.5
# assign all the elements in arr that are greater than 0.5 to 0
arr[mask] = 0
# the above can be more concisely written as:
arr[arr>0.5] = 0
# you can change the mask any way you want
# here I invert the mask
inv_mask = np.invert(mask)
# assign all the values in arr less than 0.5 to 1
arr[inv_mask] = 1
</code></pre>
|
How to assign a value to more than one element of an array using loops? <p>I'm trying to write a program that makes each month of the year an array. Each month has different charges, some occur every month, some only occur every few months. We have to write this program using only loops, so I'm wondering how I can assign a certain value to multiple months (for example, + $200 for January and June) using only 1 "for" statement. </p>
<p>Below is the code I have so far dealing with this array:</p>
<pre><code>//This line creates an array for 12 months and a variable called "month"
Double[] yearlyExpenses = new Double[12];
int month;
//These lines assign values to the correct months using loops
for (month = 0; month < yearlyExpenses.length; month++) {
yearlyExpenses[month] = rent + miscExpenses;
}
for (month = 0; month == 0 & 5; month++) {
yearlyExpenses[month] = yearlyExpenses[month] + 200;
}
</code></pre>
<p>You can see that the second "for" statement is where I'm trying to assign the value to the two months. </p>
<p>The code works fine if I were to just say "month == 0", but when I try to include a different month using "&" or "&&" or anything of the sort, I get a compiling error.</p>
<p>Sorry if this is a dumb question, I'm fairly new to Java. Thanks in advance!</p>
| <p>Your second loop wouldn't work like you expect, instead perform the math in your first loop. Something like,</p>
<pre><code>for (month = 0; month < yearlyExpenses.length; month++) {
yearlyExpenses[month] = rent + miscExpenses;
if (month == 0 || month == 5) {
yearlyExpenses[month] = yearlyExpenses[month] + 200;
}
}
</code></pre>
|
Why does my custom UICollectionViewLayout throw an error when adding space between cells? <p>I'm making a custom <code>UICollectionViewLayout</code> class for practice, essentially trying to reproduce the horizontal flow layout where cells are laid out horizontally infinitely.</p>
<p>Everything was working perfectly with my <code>prepare()</code> and <code>layoutAttributesForElements()</code> functions looking like this:</p>
<pre><code>override func prepare() {
cache.removeAll(keepingCapacity: false)
var frame = CGRect.zero
for item in 0..<numberOfItems {
let indexPath = IndexPath(item: item, section: 0)
let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
frame = CGRect(x: CGFloat(item) * width + CGFloat(item) * spacing, y: 0, width: width, height: height)
attributes.frame = frame
cache.append(attributes)
}
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
for attributes in cache {
if attributes.frame.intersects(rect) {
layoutAttributes.append(attributes)
}
}
return layoutAttributes
}
</code></pre>
<p>The problem arises when I try to add an inset of value <code>spacing</code> to the x coordinate in following line in <code>prepare()</code> so that the first cell in the collection view has a leftwards inset:</p>
<pre><code>frame = CGRect(x: CGFloat(item) * width + CGFloat(item) * spacing, y: 0, width: width, height: height)
</code></pre>
<p>As soon as I do, everything looks well and good until I try swiping through the collection view. The following exception is thrown:</p>
<pre><code>*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no UICollectionViewLayoutAttributes instance for -layoutAttributesForItemAtIndexPath: <NSIndexPath: 0x618000036060> {length = 2, path = 0 - 3}'
</code></pre>
<p>Would someone please explain why this is happening? Is there an alternative way of achieving the layout?</p>
| <p>Found the solution! Apparently overriding <code>layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes?</code> fixes the issue! But I have no idea why.</p>
|
Cannot assign to property: âinputAccessoryViewâ is a get-only property <p>Within my swift app, I am trying to hide the inputAccessoryView that shows when a user taps a textfield inside of a webview.</p>
<p>Here is the code attempting to do that:</p>
<pre><code> func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue() {
var keyboardView = UIApplication.sharedApplication().windows.last!.subviews.first!
keyboardView.inputAccessoryView = nil
}
}
</code></pre>
<p>But I am getting this error:</p>
<pre><code>Cannot assign to property: âinputAccessoryViewâ is a get-only property
</code></pre>
<p>Is there a better way to do this? Any ideas on how to get this to work?</p>
| <p>I think the error is due to the way the keyboardView is declared.</p>
<p>When I create my own UIView and assign it as the inputView for a first responder, I can then assign (or set to nil) the first responder's inputAccessoryView.</p>
<p>I assume you are trying to remove an existing accessory view, as Apple says that the default value is nil. I found this workaround for iOS 7, maybe this still works? Somebody subclassed a UIWebDocumentView and then put in an implementation of inputAccessoryView that returns nil. It's in Obj-C, but it looks promising:</p>
<p><strong><a href="http://stackoverflow.com/questions/19033292/ios-7-uiwebview-keyboard-issue/19042279#19042279">iOS 7 UIWebView keyboard issue</a></strong></p>
|
Cannot connect to SQL server from python using Active Directory Authentication <p>I am using pymssql library to connect python to Sql Server. I can connect using windows/sql server authentication. I want to connect using Active Directory Authentication. </p>
<p>Tried the below connection string. But it fails with error : </p>
<pre><code>unexpected keyword authentication
conn = pymssql.connect(server='adventureworks.database.windows.net', authentication = 'Active Directory Password',user='username@server.com',password='Enterpasswordhere', database='dbo')
</code></pre>
| <p><a href="http://pymssql.org/en/latest/ref/pymssql.html#functions" rel="nofollow">Note that pymssql.connect does not have an 'authentication' parameter</a>. You are passing it that as a named arg, which is invalid, and the reason you see your error.</p>
<p>See <a href="http://pymssql.org/en/latest/pymssql_examples.html#connecting-using-windows-authentication" rel="nofollow">this example</a> for connecting using windows authentication:</p>
<pre><code>conn = pymssql.connect(
host=r'dbhostname\myinstance',
user=r'companydomain\username',
password=PASSWORD,
database='DatabaseOfInterest'
)
</code></pre>
|
Type 'void' is not assignable to type 'any[]' <p>I am getting error at following line of the constructor code</p>
<pre><code>this.data = this.getRisks(); .
</code></pre>
<p>The error is </p>
<blockquote>
<p>Type 'void' is not assignable to type 'any[]'.</p>
</blockquote>
<p>Could somebody tell me how do i assign it .</p>
<pre><code>import { Component, OnInit } from '@angular/core';
import { Risk } from './risk';
import { RiskService } from './risk.service';
import { GridModule, GridDataResult, PageChangeEvent } from '@progress/kendo-angular-grid';
@Component({
moduleId: module.id,
selector: 'rm-risks',
templateUrl: '/app/risk-list.component.html',
providers: [RiskService]
})
export class RiskListComponent implements OnInit {
private gridView: GridDataResult;
private data: any[];
private pageSize: number = 50;
private skip: number = 0;
title = 'Risk List';
risks: Risk[];
constructor(private _riskService: RiskService) {
this.data = this.getRisks();
this.loadRisks();
}
protected pageChange(event: PageChangeEvent): void {
this.skip = event.skip;
this.loadRisks();
}
private loadRisks(): void {
this.gridView = {
data: this.data.slice(this.skip, this.skip + this.pageSize),
total: this.data.length
};
}
getRisks(): void {
this._riskService.getRisks().then(risks => this.risks = risks);
}
ngOnInit(): void {
this.getRisks();
}
};
</code></pre>
<p><strong>risk.service.ts</strong></p>
<pre><code>import { Injectable } from '@angular/core';
import { Risk } from './risk';
import { Risks } from './mock-risk';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/from';
@Injectable()
export class RiskService {
getRisks(): Promise<Risk[]> {
return Promise.resolve(Risks);
}
}
</code></pre>
| <p>Since <code>getRisks()</code> doesn't return anything, simply call it and it will set <code>this.data</code></p>
<pre><code>constructor(private _riskService: RiskService) {
this.getRisks();
this.loadRisks();
}
</code></pre>
<p>You can set <code>this.data = []</code> if you need it to be defined before data is available.</p>
|
output truncated when writing to a file in python <p>i have unusual problem, i'm using Anaconda and my python code runs really good the output on the screen is perfect, however, after each print i put file.write to write my result in my file as well but not all output is written there every time it truncates the output in different positions which doesn't make sense. the file was opened in 'w' mode. my code is really long like 400 line of code so its not possible to paste it here.
i tried to close the console after each run and restart it but it doesn't always work i had a correct file output like just twice in 10 run tries.
can any one tell me why is this happening ...your time is highly appreciated </p>
<pre><code>file.write("\n \n")
current=EventQueue.head
for i in range(0,EventQueue.size()):
print "*" *70
file.write("\n In Time %s " %str(current.index))
file.write(str(current.data))
print "In Time ",current.index , " ",current.data
current=current.next
print "*" *70
file.close
</code></pre>
<p>when the size is equal to 25 there would be like only 16 or 19 output written in the file</p>
| <p>i just added the parenthesses to the file.close it fixed the problem ... thanks and sorry for the </p>
|
Artifactory delete all artifacts older than 6 months <p>How would you delete all artifacts that match a pattern (e.g older than 6 months old) from artifactory? </p>
<p>Using either curl, or the go library</p>
| <p>The jfrog cli takes a spec file to search for artifacts. See here for <a href="https://www.jfrog.com/confluence/display/CLI/CLI+for+JFrog+Artifactory#CLIforJFrogArtifactory-UsingFileSpecs" rel="nofollow">information on jfrog spec files</a></p>
<p>The jfrog cli <a href="https://www.jfrog.com/confluence/display/CLI/CLI+for+JFrog+Artifactory#CLIforJFrogArtifactory-UsingFileSpecs" rel="nofollow">documentation is available here</a>: </p>
<p>Create an aql search query to find just the artifacts you want: </p>
<p>If your aql search syntax were like: </p>
<p>/tmp/foo.query</p>
<pre><code>items.find(
{
"repo":"foobar",
"modified" : { "$lt" : "2016-10-18T21:26:52.000Z" }
}
)
</code></pre>
<p>And you could <em>find</em> the artifacts like so:</p>
<pre><code>curl -X PUT -u admin:<api_key> https://us-artifactory.netdocuments.com/artifactory/api/search/aql -T foo.query
</code></pre>
<p>Then the spec file would be</p>
<p>/tmp/foo.spec</p>
<pre><code>{
"files": [
{
"aql": {
"items.find": {
"repo": "foobar",
"$or": [
{
"$and": [
{
"modified": { "$lt": "2016-10-18T21:26:52.000Z"}
}
]
}
]
}
}
}
]
}
</code></pre>
<p>And you would use the golang library like so: </p>
<pre><code>jfrog rt del --spec /tmp/foo.spec --dry-run
</code></pre>
<p>Instead of modified, you can also do a relative date</p>
<pre><code>"modified": { "$before":"6m" }
</code></pre>
|
Capture two parts of the same string with PHP <p>I have a list with this structure</p>
<pre><code>Boss: (test 23, of 2014)
Boss: (test 42, of 2015)
Boss: (test 70, of 2016)
</code></pre>
<p>How can I capture the numbers in the string and wrap then in spans? So the structure will end like this:</p>
<pre><code>Boss: (test <span class="test_23">23</span>, of <span class="year_2014">2014<span>)
Boss: (test <span class="test_42">42</span>, of <span class="year_2014">2015<span>)
Boss: (test <span class="test_70">70</span>, of <span class="year_2016">2014<span>)
</code></pre>
| <p>This function can help here</p>
<p>step one:</p>
<p><code>preg_replace('# ([0-9]{2}),#','<span class="test_$1">$1</span>',$input);</code></p>
<p>step two:</p>
<p><code>preg_replace('# ([0-9]{4})#','<span class="year_$1">$1</span>',$input);</code></p>
|
Javascript create array with fixed value but matching column amount from another array <p>I have an array which is built from data dynamically, so it can change.</p>
<p>It's basically this:</p>
<pre><code>["t1", "something", "bird", "dog", "cow", "fish"]
</code></pre>
<p>What I need to do is to count how many of them there are and create another array with the same amount of columns but all with the value of 1.</p>
<p>For example, if the array is:</p>
<pre><code>["bird", "dog", "cow", "fish"]
</code></pre>
<p>then it creates an array of:</p>
<pre><code>[1, 1, 1, 1]
</code></pre>
<p>If the array is:</p>
<pre><code>["bird", "fish"]
</code></pre>
<p>then it creates an array of:</p>
<pre><code>[1, 1]
</code></pre>
<p>How can I do this?</p>
| <p>You can use the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" rel="nofollow"><code>Array.prototype.map</code></a> method:</p>
<pre><code>var input = ["foo", "bar", "baz"];
var mapped = input.map(function () { return 1; });
</code></pre>
|
PHPUnit - Mocking a trait <p>I have a trait that is used by multiple classes, i.e </p>
<pre><code>class SomeClass
{
use TimeoutTrait;
function handle() {
$this->traitFunction() // can this be mocked?
}
}
</code></pre>
<p>PHP unit is capable to mock the traitFunction()?.</p>
<p>Thanks in advance for the help.</p>
<p>Greetings </p>
| <p>The simplest way is to mock the parent class and then do your unit tests on the trait. Or you can make a specific class to implement the trait, solely for unit testing, but that assumes your trait doesn't do anything that interacts with the parent or vice versa.</p>
|
Unit testing apache httpconfig <p>I have a big, complex config file for httpd, which contains many reverse proxy blocks, redirects, IP whitelists and aliases.</p>
<p>Is it possible to run unit tests against this config file?</p>
<p>i.e.</p>
<ol>
<li>Request to /account/login should be sent to the reverse proxy loginserver.example.com</li>
<li>Request to /admin should be served from /var/www/html/content if the IP of the client is 192.168.1.10</li>
<li>Request to /admin should give response code 403 if the IP of the client is 192.168.1.100</li>
<li>Request to /old/page should give a 301 redirect</li>
</ol>
<p>My current process is integration testing which requires that I run a full server, and have all of the reverse proxies running, and it's difficult to test ip whitelists. I'm looking to automate all of that without all of the dependencies.</p>
<p>An ideal solution would have to hook deeply into apache, so that it can see the routing decisions made - an http client wouldn't know that the request was served by a reverse proxy. Also, the request to /admin would only return a 200 if there was actually content in the location (which there won't be while testing) so the system would only test that apache would serve content from the location, not require that there's actually content there.</p>
| <p>How about this:</p>
<ol>
<li>install bats - <a href="https://github.com/sstephenson/bats" rel="nofollow">https://github.com/sstephenson/bats</a></li>
<li>install docker - <a href="https://docs.docker.com" rel="nofollow">https://docs.docker.com</a></li>
<li>install host-manager - <a href="https://github.com/macmade/host-manager" rel="nofollow">https://github.com/macmade/host-manager</a> </li>
</ol>
<p>Example BATS test suite:</p>
<p><strong>EDITED TO INCLUDE DUMMY LOGIN SERVER AND WEB ROOT</strong></p>
<pre><code>#!/usr/bin/env bats
setup () {
#change port and volumes accordingly
docker run -d -h -v /directory/with/apache/conf/for/simulation:/opt/docker/etc/httpd/conf.d loginserver.example.com --name reverse webdevops/base:ubuntu-16.04
docker run -d -p 80:80 -v /directory/for/200:/app -v /directory/with/apache/conf:/opt/docker/etc/httpd/conf.d --name web --link="reverse" webdevops/base:ubuntu-16.04
#if you need a host name
host-manager -add website.host.name 127.0.0.1
docker run -d
}
@test "Request to /account/login should be sent to the reverse proxy loginserver.example.com" {
result="$(curl -I http://website.host.name/account/login | sed '4q;d')"
[ "$result" -eq "Location: http://loginserver.example.com" ]
}
@test "Request to /admin should be served if the IP of the client is 192.168.1.10" {
result="$(curl -I --header 'REMOTE_ADDR:192.168.1.10' http://website.host.name/admin | sed '1q;d' | cut -d$' ' -f2)"
[ "$result" -eq 200 ]
}
@test "Request to /admin should give response code 403 if the IP of the client is 192.168.1.100" {
result="$(curl -I --header 'REMOTE_ADDR:192.168.1.100' http://website.host.name/admin | sed '1q;d' | cut -d$' ' -f2)"
[ "$result" -eq 403 ]
}
@test "Request to /old/page should give a 301 redirect" {
result="$(curl -I --header 'REMOTE_ADDR:192.168.1.100' http://website.host.name/old/page | sed '1q;d' | cut -d$' ' -f2)"
[ "$result" -eq 301 ]
}
teardown() {
docker kill web
docker rm web
docker kill reverse
docker rm reverse
host-manager -remove website.host.name
}
</code></pre>
|
Deleting file on sdcard on Android 4.4.x KitKat <p>I am attempting to delete a file on the sdcard on Android 4.4.x (KitKat). From my understanding, we cannot simply invoke File.delete(...) since this is no longer supported. We'll need to use the storage access framework.</p>
<p><a href="https://developer.android.com/guide/topics/providers/document-provider.html" rel="nofollow">https://developer.android.com/guide/topics/providers/document-provider.html</a></p>
<p>I have some sample code that uses the storage access framework that opens the file picker. This part seems to work well. </p>
<pre><code> final Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, OPEN_DOCUMENT_REQUEST_CODE);
</code></pre>
<p>However, once the picker loads and when I find the file and click on it, I do not get the call back in "onActivityResult" as documented. Instead, the picker just closes and nothing happens :(</p>
<p>Is there something missing?</p>
<p>I am trying to delete a file on the sdcard on android KitKat. Thanks!</p>
| <p>Alrighty, I found a solution. For whatever reason, I updated my android support library from 23.0.1 -> 24.2.0 and it seems to have worked. I tried looking through the release notes of the support library as well as closed issues in the Android source, but couldn't find anything related to my fix. I guess I should just be grateful :)</p>
|
Can't run tests from Espresso Test Recorder <p>I used the test recorder to create a simple UI Test. However when I run the test that was generated, I get an error</p>
<pre><code>Error:(4, 37) error: package android.support.test.espresso does not exist
Error:(5, 33) error: package android.support.test.rule does not exist
Error:(6, 35) error: package android.support.test.runner does not exist
Error:(14, 20) error: package org.hamcrest does not exist
Error:(15, 20) error: package org.hamcrest does not exist
Error:(16, 20) error: package org.hamcrest does not exist
Error:(17, 25) error: package org.hamcrest.core does not exist
Error:(18, 17) error: package org.junit does not exist
Error:(19, 17) error: package org.junit does not exist
Error:(20, 24) error: package org.junit.runner does not exist
Error:(22, 44) error: package android.support.test.espresso does not exist
Error:(22, 1) error: static import only from classes and interfaces
Error:(23, 51) error: package android.support.test.espresso.action does not exist
Error:(23, 1) error: static import only from classes and interfaces
</code></pre>
<p>You get the idea. I don't see any warnings or errors in Android Studio until I try to run the test. </p>
<p>Does anyone have an idea of what may be the problem?</p>
| <p>Did you add forget add espresso to your dependencies ?</p>
<pre><code>androidTestCompile 'com.android.support.test.espresso:espresso-contrib:2.2.2'
</code></pre>
|
Python: Pandas, dealing with spaced column names <p>If I have multiple text files that I need to parse that look like so, but can vary in terms of column names, and the length of the hashtags above: <img src="https://s4.postimg.org/8p69ptj9p/feafdfdfdfdf.png" alt="txt.file"></p>
<p>How would I go about turning this into a pandas dataframe? I've tried using <code>pd.read_table('file.txt', delim_whitespace = True, skiprows = 14)</code>, but it has all sorts of problems. My issues are... </p>
<p>All the text, asterisks, and pounds at the top needs to be ignored, but I can't just use skip rows because the size of all the junk up top can vary in length in another file. </p>
<p>The columns "stat (+/-)" and "syst (+/-)" are seen as 4 columns because of the whitespace.</p>
<p>The one pound sign is included in the column names, and I don't want that. I can't just assign the column names manually because they vary from text file to text file.</p>
<p>Any help is much obliged, I'm just not really sure where to go from after I read the file using pandas.</p>
| <p>Consider reading in raw file, cleaning it line by line while writing to a new file using <code>csv</code> module. Regex is used to identify column headers using the <em>i</em> as match criteria. Below assumes more than one space separates columns:</p>
<pre><code>import os
import csv, re
import pandas as pd
rawfile = "path/To/RawText.txt"
tempfile = "path/To/TempText.txt"
with open(tempfile, 'w', newline='') as output_file:
writer = csv.writer(output_file)
with open(rawfile, 'r') as data_file:
for line in data_file:
if re.match('^.*i', line): # KEEP COLUMN HEADER ROW
line = line.replace('\n', '')
row = line.split(" ")
writer.writerow(row)
elif line.startswith('#') == False: # REMOVE HASHTAG LINES
line = line.replace('\n', '')
row = line.split(" ")
writer.writerow(row)
df = pd.read_csv(tempfile) # IMPORT TEMP FILE
df.columns = [c.replace('# ', '') for c in df.columns] # REMOVE '#' IN COL NAMES
os.remove(tempfile) # DELETE TEMP FILE
</code></pre>
|
Undefined Reference to sem_wait and pthread_create when compiling with g++ <p>I am fairly new to C and do not understand why I am getting these errors when I try to compile my program using <code>g++ ./main.c</code>. I have tried looking at other resources and I am unable to find the answers I need. If there is a solution that you already know of, please post it here as well. </p>
<pre><code>/tmp/ccSGRAcp.o: In function `producer(void*)':
main.c:(.text+0x12): undefined reference to `sem_wait'
main.c:(.text+0x1c): undefined reference to `sem_wait'
main.c:(.text+0xa0): undefined reference to `sem_post'
main.c:(.text+0xaa): undefined reference to `sem_post'
/tmp/ccSGRAcp.o: In function `consumer(void*)':
main.c:(.text+0xc5): undefined reference to `sem_wait'
main.c:(.text+0xcf): undefined reference to `sem_wait'
main.c:(.text+0x153): undefined reference to `sem_post'
main.c:(.text+0x15d): undefined reference to `sem_post'
/tmp/ccSGRAcp.o: In function `main':
main.c:(.text+0x17e): undefined reference to `sem_init'
main.c:(.text+0x192): undefined reference to `sem_init'
main.c:(.text+0x1a6): undefined reference to `sem_init'
main.c:(.text+0x1c1): undefined reference to `pthread_create'
main.c:(.text+0x1dc): undefined reference to `pthread_create'
main.c:(.text+0x1f7): undefined reference to `pthread_create'
main.c:(.text+0x212): undefined reference to `pthread_create'
main.c:(.text+0x22d): undefined reference to `pthread_create'
/tmp/ccSGRAcp.o:main.c:(.text+0x248): more undefined references to `pthread_create' follow
collect2: error: ld returned 1 exit status
</code></pre>
<p>The code I am trying to compile is </p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <semaphore.h>
#include <pthread.h>
#define N 10000000
typedef struct
{
char const* buf[N];
char in;
char out;
sem_t mutex;
sem_t full;
sem_t empty;
} bufferItems;
bufferItems sharedBuffer;
void *producer(void *arg) {
while(1) {
sem_wait(&sharedBuffer.empty);
sem_wait(&sharedBuffer.mutex);
sharedBuffer.buf[sharedBuffer.in] = "X";
sharedBuffer.in = (sharedBuffer.in+1)%N;
printf("Producer ");
printf("%c", sharedBuffer.in);
printf("\n");
sem_post(&sharedBuffer.mutex);
sem_post(&sharedBuffer.full);
}
}
void *consumer(void *arg){
while(1){
sem_wait(&sharedBuffer.full);
sem_wait(&sharedBuffer.mutex);
sharedBuffer.buf[sharedBuffer.out] = NULL;
sharedBuffer.out = (sharedBuffer.out+1)%N;
printf("Consumer ");
printf("%c", sharedBuffer.out);
printf("\n");
sem_post(&sharedBuffer.mutex);
sem_post(&sharedBuffer.empty);
}
}
int main(void) {
sem_init(&sharedBuffer.mutex, 0, 0);
sem_init(&sharedBuffer.full, 0, 0);
sem_init(&sharedBuffer.empty, 0, N);
pthread_t p1;
pthread_t p2;
pthread_t p3;
pthread_t p4;
pthread_t c1;
pthread_t c2;
pthread_t c3;
pthread_t c4;
// create four producer threads
pthread_create(&p1,NULL,producer,NULL);
pthread_create(&p2,NULL,producer,NULL);
pthread_create(&p3,NULL,producer,NULL);
pthread_create(&p4,NULL,producer,NULL);
// create four consumer threads
pthread_create(&c1,NULL,consumer,NULL);
pthread_create(&c2,NULL,consumer,NULL);
pthread_create(&c3,NULL,consumer,NULL);
pthread_create(&c4,NULL,consumer,NULL);
}
</code></pre>
| <p>Add the <code>-pthread</code> param to pull in all the threading stuff for linking</p>
<pre><code>g++ ./main.c -pthread
</code></pre>
|
How to make Windows 10 Store "forget" an app download for testing purposes? <p>I'm testing my Win32 app converted to UWP, so I'm new to the whole Windows 10 Store concept.</p>
<p>So far I was able to get my app certified & published in the store via a private link. Now I would like to download and test it, but there's an issue.</p>
<p>The first time someone sees the app it has the following options:</p>
<p><a href="https://i.stack.imgur.com/xrT34.png" rel="nofollow"><img src="https://i.stack.imgur.com/xrT34.png" alt="enter image description here"></a></p>
<p>but once you get it, all you see is this:</p>
<p><a href="https://i.stack.imgur.com/a0OXe.png" rel="nofollow"><img src="https://i.stack.imgur.com/a0OXe.png" alt="enter image description here"></a></p>
<p>and even if you log in under a different Microsoft account (on the same computer), or previously uninstall the app, you get this:</p>
<p><a href="https://i.stack.imgur.com/LmOsO.png" rel="nofollow"><img src="https://i.stack.imgur.com/LmOsO.png" alt="enter image description here"></a></p>
<p>and "free trial" simply installs it w/o a trial in that case.</p>
<p>So my question is, how do I make Windows Store "forget" that I have this app?</p>
| <p>If you have bought the app you can't undo that, but you can always create a new user who has never bought for the testing purpose.</p>
<p>EDIT: Windows Store is for real transactions and not for testing. If you want to test, you should have a custom build that uses <a href="https://msdn.microsoft.com/en-us/library/windows/apps/windows.applicationmodel.store.currentappsimulator.aspx" rel="nofollow">CurrentAppSimulator</a> instead of <a href="https://msdn.microsoft.com/en-us/library/windows/apps/windows.applicationmodel.store.currentapp.aspx" rel="nofollow">CurrentApp</a> </p>
|
Turbolinks wipes out jQuery Mobile classes <p>When I load a page in my rails app using Turbolinks, the DOM lacks the styles that are normally applied by <a href="https://jquerymobile.com/" rel="nofollow">jQuery Mobile</a>. All of my JavaScript files run; the only problem is that I lose some of the styles I need for the JavaScript to <em>actually</em> work.</p>
<p>For example, with Turbolinks, my header is:</p>
<pre><code><a rel="external" href="/">MY SITE</a>
</code></pre>
<p>Without, it is:</p>
<pre><code><a rel="external" href="/" class="ui-link">MY SITE</a>
</code></pre>
<p>I have confirmed that my JS files are running with Turbolinks. The trouble is that the expected jQuery Mobile classes don't exist.</p>
<p>I'm not sure how to ensure the application of these classes when a Turbolink is clicked. I would appreciate any suggestions as to the right direction or area.</p>
<p>I've tried wrapping JavaScript in the following ways:</p>
<pre><code>$(document).ready(function () {
//functions
});
</code></pre>
<p>and:</p>
<pre><code>$(document).on('turbolinks:load', function() {
//functions
});
</code></pre>
<p>I've wrapped coffeescript in the same:</p>
<pre><code>ready = ->
#coffee
$(document).on('turbolinks:load', ready)
</code></pre>
<p>Both seem to work for my normal JS/coffeescript activities, so that is not the issue--it's only the jQuery Mobile classes that are lost.</p>
<p>My application.js file is:</p>
<pre><code>//= require jquery
//= require jquery_ujs
//= require jquery.mobile
//= require js-routes
//= require turbolinks
//= require twitter/bootstrap
//= require_tree .
</code></pre>
<p>I've tried reordering these a few different ways to no avail.</p>
<p>All my JavaScript is written in <code>app/assets/javascripts/base.js</code>, and there are several coffeescript files in <code>app/assets/javascripts</code>.</p>
<p>I tried using <a href="https://rubygems.org/gems/jquery-turbolinks/versions/2.1.0" rel="nofollow">jquery-turbolinks</a>, but it didn't help, nor does it seem designed to sovle the root problem here, so I removed it.</p>
<p>I've also run <code>bundle exec rake assets:precompile</code> (<code>:clean</code>, <code>:clobber</code>) many times, so I don't think this is the issue.</p>
<p>This is all in development, but the problem also exists in production.</p>
| <p>The "answer" is that Turbolinks and jQuery Mobile do many of the same things (both replace full page loads with AJAX), and <a href="https://forum.jquery.com/topic/using-pjax-or-turbolinks-with-jquery-mobile-on-a-rails-app" rel="nofollow">one does not need to use both</a>, and they are not designed to work together. JQM is better suited for a site that has to be mobile optimized (most sites?).</p>
<p>I <a href="http://blog.steveklabnik.com/posts/2013-06-25-removing-turbolinks-from-rails-4" rel="nofollow">uninstalled Turbolinks</a>, and everything was solved.</p>
<p>Please correct anything I've mischaracterized.</p>
|
Is it possible to use something like @RequestParam for JSON in spring rest services? <p>I use Spring boot and i am writing rest services server in Spring
I have a lot of different requestmappings, and i need to accept content in json</p>
<p>I can do that with <code>@RequestBody</code> annotation
But in this case i will have a lot of POJO classes for every request and every possible response.</p>
<p>And a lot of JSONs I need to send and receive are very simple - one or two or three values</p>
<p>Is it possible to use something like <code>@RequestParam("field1_from_my_json")</code> and <code>@RequestParam("field2_from_my_json")</code> for extracting the JSON fields as the request parameters, and not to create the new POJO every time?</p>
| <p>I am not aware of anything like that which spring offers.
But I have some suggestions, if you will :)</p>
<ol>
<li>You can generate the Spring model classes from the contract (a json
schema, or swagger spec). Even though this adds classes, at least
you are not manualluy maintaining it</li>
<li>If you are so concerned about too many classes, how about a generic
class with generic fields (I will strongly discourage this though)</li>
</ol>
<blockquote>
<pre><code>public class GenericClass {
private String field1;
private String field2;
private String field3;
}
</code></pre>
</blockquote>
|
Databases won't update after upgrade to MAMP Pro 4 <p>After upgrading to MAMP Pro 4, I see two issues.</p>
<hr>
<h2>1. Hosts can't be found</h2>
<p>Opening sites in the browser fail - sites can't be found. This isn't a database issue and looks to be an apache error</p>
<hr>
<h2>2. Mysql upgrade scripts fail</h2>
<p>The MAMP Pro 4 MySQL upgrade scripts aren't working for me - I see the following errors for every table in each database.</p>
<pre><code>database.btpagelist
Error : Table 'database.btpagelist' doesn't exist
status : Operation failed
</code></pre>
<p>So each time I open Mamp Pro it asks me to upgrade the databases.</p>
<hr>
<p>Does anyone know how to troubleshoot and fix these issues?</p>
<p>Cheers</p>
<p>Ben</p>
<hr>
<ul>
<li>Mac OS 10.11.6 </li>
<li>MAMP Pro 4.0.5 upgraded from Mamp Pro 3.5.2</li>
</ul>
| <p>In the end, I had to use these steps to downgrade to 3.5.2.</p>
<p><a href="https://appsolute.zendesk.com/entries/111595586-I-want-to-revert-back-to-MAMP-PRO-3-52-" rel="nofollow">https://appsolute.zendesk.com/entries/111595586-I-want-to-revert-back-to-MAMP-PRO-3-52-</a></p>
<p>Very frustrating but as others have noted (and from my own experience) Appsolute have no interest in supporting their products (yes, even their paid ones).</p>
|
Design Service Manager Class which uses external services using GUICE <p>In my application I have a Service Manager that handles all my requests. Now this Service Manager uses external services in order to fulfill some particular kind of requests.</p>
<p>For example,consider below sample code:</p>
<pre><code> Class ServiceManager{
private final A a;
private final B b;
private ExternalService externalService;
@Inject
public ServiceManager(A a, B b)
{
this.a =a;
this.b =b;
}
public void processIncomingRequestUsingExternalService(){...}
}
</code></pre>
<p>Now in order initialize ExternalService which approach is better using GUICE</p>
<ul>
<li>Use setter injection, as in future there might be 'n' number of different type of external service come into picture which this Service Manager might want to use.</li>
<li>Or use constructor injection, as I have used for class A and B objects which are internal class of my application.</li>
</ul>
<p>Note:- Here ExternalService is a Helper for External Service. </p>
| <p>Constructor injection has following advantages over setter injection:</p>
<ul>
<li>Explicitly declare dependencies to whoever is reading the code.</li>
<li>Unit testing becomes cleaner.</li>
<li>Dependencies can be marked âfinalâ, thereby increasing immutability.</li>
</ul>
<p>A good documentation that discusses the differences in more detail: <a href="https://www.petrikainulainen.net/software-development/design/why-i-changed-my-mind-about-field-injection/" rel="nofollow">https://www.petrikainulainen.net/software-development/design/why-i-changed-my-mind-about-field-injection/</a></p>
|
Python regex issue. Validation works but in two parts, I to extract each valid 'part' separately <p>My code is:</p>
<pre><code>test1 = flight
###Referencelink: http://academe.co.uk/2014/01/validating-flight-codes/
#Do not mess up trailing strings
p = re.compile(r'^([a-z][a-z]|[a-z][0-9]|[0-9][a-z])[a-z]?[0-9]{1,4}[a-z]?$')
m = p.search(test1) # p.match() to find from start of string only
if m:
print '[200],[good date and time]' # group(1...n) for capture groups
else:
print('[error],[bad flight number]'),quit()
</code></pre>
<p>I need to get the carrier code (the first bit) and the flight number(second bit) separately. </p>
<p>Can I extract the regex as in: a = 'first valid part' of regex, b = 'second valid part'</p>
| <p>Try this maybe.</p>
<pre><code>p = re.compile(r'^([a-z][a-z]|[a-z][0-9]|[0-9][a-z])([a-z]?[0-9]{1,4}[a-z]?)$')
m = p.findall(test1)
</code></pre>
|
Why additional memory allocation makes multithread Python application work few times faster? <p>I'm writing python module which one of the functions is to check multiple IP addresses if they're active and write this information to database. As those are I/O bound operations I decided to work on multiple threads:</p>
<ul>
<li>20 threads for pinging host and checking if it's active (function <code>check_if_active</code>)</li>
<li>5 threads for updating data in database (function <code>check_if_active_callback</code>)</li>
</ul>
<p>Program works as followed:</p>
<ol>
<li>Main thread takes IPs from database and puts them to queue <code>pending_ip</code></li>
<li>One of 20 threads takes record from <code>pending_ip</code> queue, pings host and puts answer to <code>done_ip</code> queue</li>
<li>One of 5 threads takes record from <code>done_ip</code> queue and does update in database if needed</li>
</ol>
<p>What I've observed (during timing tests to get answer how many threads would suit the best in my situation) is that program works aprox. 7-8 times faster if in 5 loops I first declare and start 20+5 threads, delete those objects and then in 6th loop run the program, than if I run program without those additional 5 loops.</p>
<p>I suppose this could be somehow related to memory management. Not really sure though if deleting objects makes any sense in python. My questions are:</p>
<ul>
<li>why is that happening?</li>
<li>how I can achieve this time boost without additional code (and additional memory allocation)?</li>
</ul>
<p>Code:</p>
<pre><code>import time, os
from threading import Thread
from Queue import Queue
from readconfig import read_db_config
from mysql.connector import Error, MySQLConnection
pending_ip = Queue()
done_ip = Queue()
class Database:
connection = MySQLConnection()
def connect(self):
db_config = read_db_config("mysql")
try:
self.connection = MySQLConnection(**db_config)
except Error as e:
print(e)
def close_connection(self):
if self.connection.is_connected() is True:
self.connection.close()
def query(self, sqlquery):
if self.connection.is_connected() is False:
self.connect()
try:
cursor = self.connection.cursor()
cursor.execute(sqlquery)
rows = cursor.fetchall()
except Error as e:
print(e)
finally:
cursor.close()
return rows
def update(self,sqlquery, var):
if self.connection.is_connected() is False:
self.connect()
try:
cursor = self.connection.cursor()
cursor.execute(sqlquery, var)
self.connection.commit()
except Error as e:
self.connection.rollback()
print(e)
finally:
cursor.close()
db=Database()
def check_if_active(q):
while True:
host = q.get()
response = os.system("ping -c 1 -W 2 %s > /dev/null 2>&1" % (host))
if response == 0:
ret = 1
else:
ret = 0
done_ip.put((host, ret))
q.task_done()
def check_if_active_callback(q, db2):
while True:
record = q.get()
sql = "select active from table where address_ip='%s'" % record[0]
rowIP = db2.query(sql)
if(rowIP[0][0] != record[1]):
sqlupdq = "update table set active=%s where address_ip=%s"
updv = (record[1], record[0])
db2.update(sqlupdq, updv)
q.task_done()
def calculator():
#some irrelevant code
rows = db.query("select ip_address from table limit 1000")
for row in rows:
pending_ip.put(row[0])
#some irrelevant code
if __name__ == '__main__':
num_threads_pinger = 20
num_threads_pinger_callback = 5
db = Database()
for i in range(6):
db_pinger_callback =[]
worker_p = []
worker_cb = []
#additional memory allocation here in 5 loops for 20 threads
for z in range(num_threads_pinger):
worker = Thread(target=check_if_active, args=(pending_ip))
worker.setDaemon(True)
worker.start()
worker_p.append(worker)
#additional memory allocation here in 5 loops for 5 threads
for z in range(num_threads_pinger_callback):
db_pinger_callback.append(Database())
worker = Thread(target=check_if_active_callback, args=(done_ip, db_pinger_callback[z]))
worker.setDaemon(True)
worker.start()
worker_cb.append(worker)
if i == 5:
start_time = time.time()
calculator()
pending_ip.join()
done_ip.join()
print "%s sec" % (time.time() - start_time)
#freeing (?) that additional memory
for z in range(num_threads_pinger - 1, 0, -1):
del worker_p[z]
#freeing (?) that additional memory
for z in range(num_threads_pinger_callback - 1, 0, -1):
db_pinger_callback[z].close_connection()
del db_pinger_callback[z]
del worker_cb[z]
db.close_connection()
</code></pre>
| <p>In order to give you an exact explanation it would help to know what version of Python you're using. For instance if you're using PyPy then what you've observed is the JIT kicking in after you call your loop 5 times and it just returns a pre-calculated answer. If you're using a standard version of Python then this speed up is due to the interpreter using the compiled byte code from the .pyc files. How it works is basically Python will first create an in memory representation of your code and run it from there. During repeated calls the interpreter will convert some of the more often used code into byte code and store it on disk in .pyc files (this is python byte code similar to java byte code not to be confused with native machine code). Every time you call the same function the interpreter will go to your .pyc files and execute the corresponding byte code this makes the execution much faster as the code you're running is precompiled compared to when you call the function once and python has to parse and interpret your code.</p>
|
VBA excel English 2007 cause error msg on excel 2016 french <p>I have this Macro used to invert the order of the selected row.
This Macro run smooth on my english pc with excel 2007 but doesn't work on my french pc with excel 2016.
When i run it in the french pc, this line <code>For j = 1 To UBound(Arr, 2) / 2</code>gets me a error msg </p>
<p>''Compilation error: Syntax error''</p>
<pre><code> Sub FlipRows()
'Updateby20131126
Dim Rng As Range
Dim WorkRng As Range
Dim Arr As Variant
Dim i As Integer, j As Integer, k As Integer
On Error Resume Next
xTitleId = "KutoolsforExcel"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
Arr = WorkRng.Formula
For i = 1 To UBound(Arr, 1)
k = UBound(Arr, 2)
For j = 1 To UBound(Arr, 2) / 2
xTemp = Arr(i, j)
Arr(i, j) = Arr(i, k)
Arr(i, k) = xTemp
k = k - 1
Next
Next
WorkRng.Formula = Arr
End Sub
</code></pre>
| <p>You will need to change , to ;</p>
<p>It is a regional setting causing the problem, the reason for the semicolon is to distinguish from the decimal separator that in many countries is comma instead of dot.</p>
<p>Another option is to change the separators in your Excel version (, . and ;)</p>
|
Got problems with replacing xml nodes within text <p>I'm working on XML-to-XML transformation (Windows 10, Oxygen XML Editor) and got this task: replace <code><xref id="id1">text</xref></code> with <code>id1</code>.</p>
<p>I've done some work but can't get why doesn't scenario replace all xref-s in parentheses. Any ideas?</p>
<p>And just in case if somebody know how to remove parentheses outside of xref-s, please tell. I was trying <code>concat('(',$temp,')')</code> but it also skips parenteses and <code>concat('(',$temp,';')</code> even doesn't work.</p>
<p><strong>Here the example</strong> (I keep punctuation just in case):</p>
<pre><code><section>
<somenode>Lorem ipsum</somenode>
<p>Lorem ipsum (<xref id="id1">TEXT1, 2014</xref>) dolor.</p>
<p>Lorem ipsum (<xref id="id5">TEXT5., 2016</xref>) dolor.</p>
<p>Lorem ipsum (<xref id="id6">TEXT6., 2004</xref>; <xref id="id7">TEXT7., 2014</xref>; <xref id="id8">TEXT8., 2012</xref>), dolor.</p>
<p>Lorem ipsum (<xref id="id6">TEXT6., 2004</xref>; <xref id="id7">TEXT7., 2014</xref>; <xref id="id8">TEXT8., 2012</xref>), dolor.</p>
...
</section>
...
</code></pre>
<p><strong>Here the result</strong>:</p>
<pre><code><section>
<somenode>Lorem ipsum</somenode>
<p>Lorem ipsum (id1) dolor.</p>
<p>Lorem ipsum (id5) dolor.</p>
<p>Lorem ipsum (id6; TEXT7., 2014; TEXT8., 2012), dolor.</p>
<p>Lorem ipsum (TEXT6., 2004; id7; TEXT8., 2012), dolor.</p>
...
</section>
...
</code></pre>
<p><strong>I expect</strong>:</p>
<pre><code><section>
<somenode>Lorem ipsum</somenode>
<p>Lorem ipsum (id1) dolor.</p>
<p>Lorem ipsum (id5) dolor.</p>
<p>Lorem ipsum (id6; id7; id8), dolor.</p>
<p>Lorem ipsum (id6; id7; id8), dolor.</p>
...
</section>
...
</code></pre>
<p>and <strong>Here the scenario</strong>:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" exclude-result-prefixes="xs" version="2.0">
<xsl:output method="xml" encoding="UTF-8"/>
<xsl:template name="xrefs">
<xsl:for-each select="section">
<xsl:for-each select="p">
<xsl:variable name="tempP">
<xsl:value-of select="."/>
</xsl:variable>
<xsl:for-each select="xref">
<xsl:variable name="temp">
<xsl:value-of select="."/>
</xsl:variable>
<xsl:value-of select="replace($tempP,$temp,./@id)"/>
</xsl:for-each>
</xsl:for-each>
</xsl:for-each>
</xsl:template>
<xsl:template match="/">
<xsl:call-template name="xrefs"/>
</xsl:template>
</code></pre>
<p></p>
| <blockquote>
<p>got this task: replace <code><xref id="id1">text</xref></code> with <code>id1</code>.</p>
</blockquote>
<p>That could be done easily by:</p>
<pre><code><xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>
<!-- identity transform -->
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="xref">
<xsl:value-of select="@id"/>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>Applies to the following <strong>well-formed (!)</strong> input example:</p>
<p><strong>XML</strong></p>
<pre><code><section>
<somenode>Lorem ipsum</somenode>
<p>Lorem ipsum (<xref id="id1">TEXT1, 2014</xref>) dolor.</p>
<p>Lorem ipsum (<xref id="id5">TEXT5., 2016</xref>) dolor.</p>
<p>Lorem ipsum (<xref id="id6">TEXT6., 2004</xref>; <xref id="id7">TEXT7., 2014</xref>; <xref id="id8">TEXT8., 2012</xref>), dolor.</p>
<p>Lorem ipsum (<xref id="id6">TEXT6., 2004</xref>; <xref id="id7">TEXT7., 2014</xref>; <xref id="id8">TEXT8., 2012</xref>), dolor.</p>
...
</section>
</code></pre>
<p>the result will be:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<section>
<somenode>Lorem ipsum</somenode>
<p>Lorem ipsum (id1) dolor.</p>
<p>Lorem ipsum (id5) dolor.</p>
<p>Lorem ipsum (id6; id7; id8), dolor.</p>
<p>Lorem ipsum (id6; id7; id8), dolor.</p>
...
</section>
</code></pre>
<hr>
<blockquote>
<p>And just in case if somebody know how to remove parentheses outside of
xref-s, please tell.</p>
</blockquote>
<p>That could be achieved by adding these two templates (requires XSLT 2.0):</p>
<pre><code><xsl:template match="text()[following-sibling::*[self::xref]][ends-with(., '(')]">
<xsl:value-of select="substring(., 1, string-length() - 1) "/>
</xsl:template>
<xsl:template match="text()[preceding-sibling::*[self::xref]][starts-with(., ')')]">
<xsl:value-of select="substring(., 2) "/>
</xsl:template>
</code></pre>
<p>Then the result will be:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<section>
<somenode>Lorem ipsum</somenode>
<p>Lorem ipsum id1 dolor.</p>
<p>Lorem ipsum id5 dolor.</p>
<p>Lorem ipsum id6; id7; id8, dolor.</p>
<p>Lorem ipsum id6; id7; id8, dolor.</p>
...
</section>
</code></pre>
|
Design query Like Datasheet ...Ms Access <p>I have a table Exams (ID, StudentID, ExamDate, Subject, Marks)</p>
<p>How can I design a query so that Subjects become headers?</p>
<p>Like
Student Name Math | Biology | History | Language...</p>
<p>subquery or any other suggestion?</p>
<p>Thanks</p>
| <p>Oh, needed to do a crosstab query... Just now figuring out how best to implement it.</p>
|
How to tell which provider to choose <p>All:</p>
<p>I am pretty new to Deepstream, when I try its example of request-response <a href="https://deepstream.io/" rel="nofollow">https://deepstream.io/</a>:</p>
<pre><code>// remote procedure call for "times-three" with 7
client.rpc.make( "times-three", 7, function( err, result ){
// And get 21 back
console.log( result );
});
// register as a provider
client.rpc.provide( 'times-three', function( num, response ){
// ...and respond to requests
response.send( num * 3 );
});
</code></pre>
<p>I wonder if I open multiple provider with same name but different logic(for example I put <code>client.rpc.provide</code> in several pages and open them all), which one should <code>client.rpc.make</code> choose?</p>
<p>Thanks</p>
| <p>Deepstream does loadbalancing by a combination of randomly selecting the order providers are selected to fulfill the RPC and giving the provider the option of rejecting the RPC if it isn't willing to process it.</p>
<p>If your providers do different logic it would be best to name them differently to distinguish the calls. Similar to having different HTTP paths for different request.</p>
<p>So for example:</p>
<pre><code>// remote procedure call for "times-three" with 7
client.rpc.make( "times-three", 7, function( err, result ){
// And get 21 back
console.log( result );
});
// this might be triggered, but will always reject it ( for the sake of this example )
client.rpc.provide( 'times-three', function( num, response ){
response.reject();
});
// this will always be triggered, either first or second
client.rpc.provide( 'times-three', function( num, response ){
response.send( num * 3 );
});
// this will never be triggered
client.rpc.provide( 'times-four', function( num, response ){
response.send( num * 4 );
});
</code></pre>
|
4 Floating DIVs that respond symmetrically on narrowing screens with CSS <p>[ 1 ] [ 2 ] [ 3 ] [ 4 ]</p>
<p>I have four DIVs floating left (above), using simple CSS: float:left; width:128px;height:128px</p>
<p>As I narrow the screen, the last DIV jumps correctly onto the next line:</p>
<p>[ 1 ] [ 2 ] [ 3 ]</p>
<p>[ 4 ]</p>
<p>But what I'd really like is for the last two blocks to jump onto the next line in order to keep the look symmetrical:</p>
<p>[ 1 ] [ 2 ]</p>
<p>[ 3 ] [ 4 ]</p>
<p>And when the screen narrow further, the blocks stack one above the other:</p>
<p>[ 1 ]</p>
<p>[ 2 ]</p>
<p>[ 3 ]</p>
<p>[ 4 ]</p>
| <p>Group [3] and [4] together in a div (and [1] and [2] if you desire). Give it a max width, but auto height. That way, when the screen narrows, the two divs should move together side by side, but jump down when the screen gets narrower.</p>
<p>ex:</p>
<pre><code>.contain {
max-width:256px;
height:auto;
}
<div class="contain">
<div class="div3">contents</div>
<div class="div4">contents</div>
</contain>
</code></pre>
|
R - Issues parsing JSON stream <p>I have searched a lot but unable to find a good solution to my problem.</p>
<p>I am trying to automate some of my work and scrape some data from a site that my company uses. (FYI - TOS do not seem to indicate they don't want to be scraped in case anyone is wondering. So I should be good.)</p>
<p>So far I have the following code</p>
<pre><code>library(devtools)
library(RSelenium)
library(XML)
library(rvest)
library(stringr)
library(dplyr)
library(knitr)
library(magrittr)
library(rjson)
library(stringi)
#login
appURL <- 'URL I Am accessing/'
pJS <- phantom()
remDr <- remoteDriver(browserName = "phantomjs")
remDr$open()
remDr$maxWindowSize()
remDr$navigate(appURL)
UN <- remDr$findElement(using = 'xpath', "//*[@id='login-form']/div[2]/div[2]/input")
UN$sendKeysToElement(list("Username"))
PW <- remDr$findElement(using = 'xpath', "//*[@id='login-form']/div[2]/div[3]/input")
PW$sendKeysToElement(list("password", key = "enter"))
URL <- 'URL of page with data'
remDr$navigate(URL)
Sys.sleep(2)
Source <- remDr$getPageSource()[[1]]
Text <- read_xml(Source,encoding = "", as_html = F, options = "NOBLANKS") %>%
xml_text(trim = T)
Text <- unlist(Text)
</code></pre>
<p>At this point I have a lot of text that contains JSON but the JSON is organized like this:</p>
<pre><code>event: optionCollection
id: 229
data: [{JSON}]
:
event: pageDescription
id: 230
data: [{JSON}]
:
event: dataTable.headerRows
id: 232
data: [{JSON}]
:
event: dataTable.dataRows
id: 233
data: [{JSON}]
</code></pre>
<p>Where the JSON I need is the JSON related to the event: dataTable.headerRows and dataTable.dataRows.</p>
<p>There are usually multiple dataRows events I need to extract data from. </p>
<p>Can anyone make a suggestion on how to get these into R?</p>
<p>Open to any suggestions or if you need more clarification please let me know.</p>
<p>Thanks!</p>
<p>*Edit - Added current library's per request.</p>
<p>*Edit - @Parfait this is what is returned:</p>
<pre><code>$event
[1] "report.finished"
$id
[1] "2277"
$data
[1] "{\"status\":1}"
$event
[1] "report.finished"
$id
[1] "2277"
$data
[1] "{\"status\":1}"
</code></pre>
<p>This only appears in the tempfile.txt once so I am not clear what is causing the issue because it seems the code should work.</p>
<p>Here is the written tmpfile with the data substituted for the samples you provided in your post: </p>
<p><a href="https://1drv.ms/t/s!AlEviX19YBNogaZGAHCUCC_ZDEI5OA" rel="nofollow">https://1drv.ms/t/s!AlEviX19YBNogaZGAHCUCC_ZDEI5OA</a></p>
| <p>Consider reading the string line by line with <code>readLines()</code> and building a list of <em>event</em>, <em>id</em>, and <em>data</em> items, where <em>data</em> will be json strings. But first dump your string to file with <code>writeLines()</code>. The colon-only line is used as the separator between list elements and must appear as you have it:</p>
<pre><code>writeLines(Text, "tempfile.txt") # CREATE TEMP FILE
con <- file("tempfile.txt", open="r") # OPEN CONNECTION
datalist <- c()
while (length(line <- readLines(con, n=1, warn = FALSE)) > 0) {
if (grepl("event:", line)==TRUE){
eventitem <- gsub("event: ", "", line) # EVENT LINE
}
else if (grepl("id:", line)==TRUE){
iditem <- gsub("id: ", "", line) # ID LINE
}
else if (grepl("data:", line)==TRUE){
dataitem <- gsub("data: ", "", line) # DATA LINE
}
else if (grepl("^:", line)==TRUE) {
# COLON ONLY-LINE (APPENDING NESTED LIST ITEMS)
datalist <- c(datalist, list(event=eventitem, id=iditem, data=dataitem))
}
else {
dataitem <- paste0(dataitem, gsub("data: ", "", line)) # ADD DATA LINES
}
}
# REMAINING LAST LIST ITEMS
datalist <- c(datalist, list(event=eventitem, id=iditem, data=dataitem))
close(con) # CLOSE CONNECTION
unlink("tempfile.txt") # DELETE TEMP FILE
</code></pre>
<p><strong>Output</strong> <em>(using an example repeat JSON)</em></p>
<pre><code>$event
[1] "optionCollection"
$id
[1] "229"
$data
[1] "[{\"sales\": {\"sales_val\": 22549,\"units_in_stock\":
251,\"product_id\": \"0141602\"},\"sales\": {\"sales_val\":
22549,\"units_in_stock\": 251,\"product_id\": \"0141602\"},\"sales\":
{\"sales_val\": 22549,\"units_in_stock\": 251,\"product_id\": \"0141602\"}}]"
$event
[1] "pageDescription"
$id
[1] "230"
$data
[1] "[{\"sales\": {\"sales_val\": 22549,\"units_in_stock\":
251,\"product_id\": \"0141602\"},\"sales\": {\"sales_val\":
22549,\"units_in_stock\": 251,\"product_id\": \"0141602\"},\"sales\":
{\"sales_val\": 22549,\"units_in_stock\": 251,\"product_id\": \"0141602\"}}]"
$event
[1] "dataTable.headerRows"
$id
[1] "232"
$data
[1] "[{\"sales\": {\"sales_val\": 22549,\"units_in_stock\":
251,\"product_id\": \"0141602\"},\"sales\": {\"sales_val\":
22549,\"units_in_stock\": 251,\"product_id\": \"0141602\"},\"sales\":
{\"sales_val\": 22549,\"units_in_stock\": 251,\"product_id\": \"0141602\"}}]"
$event
[1] "dataTable.dataRows"
$id
[1] "233"
$data
[1] "[{\"sales\": {\"sales_val\": 22549,\"units_in_stock\":
251,\"product_id\": \"0141602\"},\"sales\": {\"sales_val\":
22549,\"units_in_stock\": 251,\"product_id\": \"0141602\"},\"sales\":
{\"sales_val\": 22549,\"units_in_stock\": 251,\"product_id\": \"0141602\"}}]"
</code></pre>
|
Filehelpers WriteStream only writing the first 2048 characters to output <p>I am using the Filehelpers library and outputting my csv using the WriteStream method. It is working fine except the file is cutting off in the middle of the data and upon opening the file it only has the first 2048 characters. How do I get it to output the entire dataset?</p>
<pre><code>// gisList is a list of objects whose class is set to be a [DelimitedRecord(",")]
var gisEngine = new FileHelperEngine<GisRecord>();
var gisstream = new MemoryStream();
var gisstreamWriter = new StreamWriter(gisstream);
gisEngine.WriteStream(gisstreamWriter, gisList);
gisstream.Position = 0;
Response.ContentType = @"application/x-msdownload";
Response.AppendHeader("content-disposition", "attachment; filename=gisOutput.txt");
var reader = new StreamReader(gisstream);
Response.Write(reader.ReadToEnd());
Response.Flush();
Response.End();
</code></pre>
| <p>I figured it out. </p>
<p>I set the Streamwriter's Autoflush property to true and removed the "Response.Flush" line and it outputs the whole amount of data now.</p>
|
Sum of the difference of pairs of numbers in an array - Java <p>I'm working on an assignment for a beginning Java course and I am completely stuck on this problem. </p>
<p>Write a program that computes the sum of the differences of pairs of numbers in an array. For example if the array is [2, 3, 7, 8, 9, 12] the sum of the differences of pairs is
(2-3) + (7-8) + (9-12)
** we are not allowed to use built in Java functions. </p>
<p>Here is what I have so far.. (I know it is terrible)</p>
<pre><code>public static void main(String[] args)
{
int[] A = {3, 4, 5, 6, 1, 2};
int total = 0;
int sum = 0;
for(int i = 0; i < A.length; i++)
{
for(int j = i+1; j < A.length; j++)
sum = (A[i] - A[j]);
}
System.out.println(sum);
}
}
</code></pre>
| <p>When you use that nested cycle you're doing this:</p>
<pre><code>i = 0,
j = 1,
sum = 3 - 4;
// next cycle,
i = 0,
j = 2,
sum = 3 - 5;
// etc...,
i = 1,
j = 2,
sum = 4 - 5,
// etc..;
</code></pre>
<p>Which means for each value of <code>A[i]</code> you're making the difference of <code>A[i]</code> and all the values in the array for <code>A[j + 1]</code>. Also you're not updating the sum variable. When you do <code>sum = A[i] - A[i + 1]</code> because this operation only gives the variable sum a new value. What you want is <code>sum+= value</code>, which means <code>sum = sum + newValue (newValue = A[i] - A[i +1])</code>. This operation adds the new value to the old value stored in sum.
So what you need to do is add the two values and jump 2 indexes (<code>i+=2</code>) so you don't do (for example) 3-4, 4-5, 5-6 etc. what you want is 3-4, 5-6, etc.<br>
Try this:</p>
<pre><code>public static void main(String[] args)
{
int[] A = {3, 4, 5, 6, 1, 2};
int total = 0;
int sum = 0;
for(int i = 0; i < A.length; i+=2)
{
sum +=(A[i] - A[i + 1]);
}
System.out.println(sum);
}
}
</code></pre>
|
Object becoming null after leaving base class in C# <p>I am trying to reduce code from the data layer (Class Library) of a project by making a generic DAO class with virtual methods, this way I will have implementations of this class for the various types needed.</p>
<p>For simplicity's sake I will only write the read method for all classes and only the necessary parameters. </p>
<p>One requirement is the object used as return for all methods within this layer, which is a generic class as below:</p>
<pre><code>public class ReturnObject<T>
{
public T Object { get; set; }
}
</code></pre>
<p>I started with an interface IDao:</p>
<pre><code>public interface IDao<T>
{
ReturnObject<T> Read(Guid id);
}
</code></pre>
<p>And then, the "default implementation":</p>
<pre><code>public abstract class Dao<T> : IDao<T>
{
// Database context.
protected Context Context { get; } = new Context();
public virtual ReturnObject<T> Read(Guid id)
{
// Creating return object.
var returnObject = new ReturnObject<dynamic>();
// Reading entity from database.
try
{
switch (typeof(T).ToString())
{
case "Foo":
returnObject.Object = Context.Foos.First(o => o.Id == id) as dynamic;
break;
case "Bar":
returnObject.Object = Context.Bars.First(o => o.Id == id) as dynamic;
break;
}
}
catch (Exception exception)
{
...
}
finally
{
...
}
// Returning result.
return returnObject as ReturnObject<T>;
}
}
</code></pre>
<p>So, basically this is the code reduction I'm trying to get. Based on the <strong>T</strong> class type I will be able to switch the proper set from the context, store the read object into the returnObject and then send it back to the caller.</p>
<p>For organization and other reasons, I also have several inherited classes, like this:</p>
<pre><code>public class DaoFoo : Dao<Foo>
{
}
</code></pre>
<p>And finally, my problem. I'm positive I'm misinterpreting some concepts here and that's why I'm getting null values when calling the method read as exampled below:</p>
<pre><code>public class FooController : ApiController
{
public IHttpActionResult Get(Guid id)
{
var foo= new DaoFoo().Read(id);
return Content(HttpStatusCode.OK, new foo.Object);
}
}
</code></pre>
<p>When debugging I can see that the <strong>Dao</strong> class is sending the right object, with all its parameters, like in the image:</p>
<p><a href="https://i.stack.imgur.com/SvCCo.png" rel="nofollow"><img src="https://i.stack.imgur.com/SvCCo.png" alt="enter image description here"></a></p>
<p>However, the calling method always gets <strong>null</strong>, like in the image:</p>
<p><a href="https://i.stack.imgur.com/uOr3x.png" rel="nofollow"><img src="https://i.stack.imgur.com/uOr3x.png" alt="enter image description here"></a></p>
<p>With all that said, can someone point out what I'm doing wrong here?
Thanks in advance!</p>
| <p>You cast dynamic as ReturnObject which results in null, because it cannot cast one type to another.</p>
<p>Try not using dynamic, your method is generic so use T instead, so you dont have to cast</p>
|
train_on_batch error after first a successful first batch <p>I have the following code. This is within the class CNNEnv. </p>
<pre><code> def step(self, a_t, i):
self.a_t = a_t
self.i = i
# Batch size of 32
# 1875 * 32 = 60000 -> # of training samples
self.X_train = self.X_train[self.i * 32:(self.i + 1) * 32]
self.y_train = self.y_train[self.i * 32:(self.i + 1) * 32]
# Train & evaluate one iteration
self.model.train_on_batch(self.X_train, self.y_train)
self.scores = self.model.test_on_batch(self.X_test, self.y_test)
self.scores = self.scores[1] * 100
return self.X_train.shape, self.y_train.shape, self.scores
</code></pre>
<p>The following is an external script that calls this. It works for the first iteration. However, on the second iteration, there's an error.</p>
<pre><code>from CNN import CNNEnv
# Instantiate class and assign to object env
env = CNNEnv()
# Call function within class
a, b, c = env.step(0.001, 1)
print(a)
print(b)
print(c)
# Call function within class second time
d, e, f = env.step(0.001, 2)
print(d)
print(e)
print(f)
</code></pre>
<p>Error after first batch</p>
<pre><code>First batch:
(32, 1, 28, 28)
(32, 10)
9.42000001669
Error on second batch:
F tensorflow/stream_executor/cuda/cuda_dnn.cc:422] could not set cudnn tensor descriptor: CUDNN_STATUS_BAD_PARAM
</code></pre>
<p>The weird thing is that if I were to do the following, it works when I call the <code>train_on_batch</code> twice without using a class. But I need the class because my external script has to call the function this way. Any idea?</p>
| <p>Solved it. User error. Variable assignment issue.</p>
<p>Should use self.X_batch instead of self.X_train. This would solve the problem if anyone is facing it.</p>
|
Calculate the largets and smallest number fiven exp, bias, and fract <p>Give 8 bits total, where 3 bits are <code>exp bits</code>, 4 bits are <code>frac bits</code> and 1 for <code>sign bit</code>. Have to find the largest and smallest values.</p>
<pre><code>0 110 1111 - largest
1 110 1111 - smallest
1) E = exponent - Bias = 6 - 7 = -1
2) M = 1 + f = 1 + 1/2 + 1/4 + 1/8 + 1/16 = 31/16
Value = (-1)^s * M * 2^E = 31/16 + 1/2 = 2.4375 - largest value
-2.4375 - smallest value
</code></pre>
<p>Is this correct? Im not sure about it because im getting a "small" number as a largest value ?</p>
| <p>I don't know why you chose your bias at 7, but that way you won't be able to get large values.</p>
<p>Choose a bias of 3. And make the exponent 7, then you get:</p>
<pre><code>0 111 1111 - largest
</code></pre>
<p>This is </p>
<pre><code>M = 1 + 1/2 + 1/4 + 1/8 + 1/16 = 31/16
E = 7 - 3 --> 2^4 = 16
</code></pre>
<p>So your large value becomes <code>31/16 * 16 = 31</code>.</p>
<p>The "smallest" (positive) value would be</p>
<pre><code>0 000 0001 - smallest
M = 1 + 0 + 0 + 0 + 1/16 = 17/16
E = 0 - 3 --> 2^-3 = 1/8
</code></pre>
<p>So your small value becomes <code>17/16 * 1/8 = 17/128 = 0.1328125</code></p>
<p>Of course, with a sign bit of 1, you get the negatives of these values.</p>
<p>And I would count all zero bits (<code>0 000 0000</code>) as +zero, or just a sign bit set (<code>1 000 0000</code>) as -zero.</p>
|
Google Maps two finger pinch/stretch callbacks <p>In my map, I am trying to capture zoom in/out using <code>ScaleGestureDetector</code> but I am <strong>never</strong> receiving any callbacks to either of <code>onScale</code> or <code>onScaleBegin</code> or <code>onScaleEnd</code>.</p>
<p>In my Fragment's <code>onCreateView</code>, I initialize:</p>
<p><code>scaleGestureDetector = new ScaleGestureDetector(getContext(), new simpleOnScaleGestureListener());</code></p>
<p>And I implement the callbacks like so:</p>
<pre><code>public class simpleOnScaleGestureListener extends
SimpleOnScaleGestureListener {
@Override
public boolean onScale(ScaleGestureDetector detector) {
// TODO Auto-generated method stub
startScale = detector.getScaleFactor();
Log.d(TAG, "::onScale:: " + detector.getScaleFactor());
return true;
}
@Override
public boolean onScaleBegin(ScaleGestureDetector detector) {
// TODO Auto-generated method stub
Log.d(TAG, "::onScaleBegin:: " + detector.getScaleFactor());
return true;
}
@Override
public void onScaleEnd(ScaleGestureDetector detector) {
// TODO Auto-generated method stub
Log.d(TAG, "::onScaleEnd:: " + detector.getScaleFactor());
endScale = detector.getScaleFactor();
}
</code></pre>
<p>Also, is it fair to assume that the callbacks will be called continuously whenever the user zooms in/out?</p>
| <p>I was able to get past the issue of getting callbacks. Essentially, two things:</p>
<ol>
<li>In your activity/fragment, implement, <code>GoogleMap.OnCameraIdleListener</code></li>
<li>In <code>onMapReady()</code>, <code>call mMap.setOnCameraIdleListener(this);</code></li>
<li>Hence, override <code>onCameraIdle()</code>:</li>
</ol>
<p><code>@Override
public void onCameraIdle() {
Log.i(TAG, "::onCameraIdle::" + mMap.getCameraPosition().toString());
}</code></p>
<p>to get lat/long, zoom, tilt and bearing, essentially <code>CameraPosition</code>.</p>
<p>I found a way to get radius in meters by referring to this <a href="http://stackoverflow.com/questions/29222864/get-radius-of-visible-map-in-android/29264003#comment67545444_29264003">response</a> </p>
<pre><code>VisibleRegion vr = map.getProjection().getVisibleRegion();
Location center = new Location("center");
center.setLatitude(vr.latLngBounds.getCenter().latitude);
center.setLongitude(vr.latLngBounds.getCenter().longitude);
//Location("radiusLatLng") as mentioned in google maps sample
Location farVisiblePoint = new Location("radiusLatLng");
farVisiblePoint.setLatitude(vr.farLeft.latitude);
farVisiblePoint.setLongitude(vr.farLeft.longitude);
radius = center.distanceTo(farVisiblePoint);
</code></pre>
|
C2660: _splitpath_s fails with std::array error in Visual Studio 2013 <p>Visual Studio 2013 is a bit weird on language array that in global function it's allowed to initialize one as <code>char result[100] = { 0 };</code>, but not if it's a class's member -- referring to
<a href="https://stackoverflow.com/questions/19877757/workaround-for-error-c2536-cannot-specify-explicit-initializer-for-arrays-in-vi">Workaround for error C2536: cannot specify explicit initializer for arrays in Visual Studio 2013</a>, for <code>int m_array[3];</code> inside <code>class A</code>, <code>A() :m_array{ 0, 1, 2 } {}</code> fails with Error C2536: "'A::A::m_array' : cannot specify explicit initializer for arrays".</p>
<p>In the same post <a href="https://stackoverflow.com/a/19890214/826203">a work-around is suggested</a>, using
<code>std::array<int, 3> m_array;</code> instead and initilzie with
<code>A() : m_array ({ 0, 1, 2 }) {}</code>
, IDE red underlined "0" hinting "<em>Error: braces cannot be omitted for this subobject initializer.</em>" but can compile. </p>
<p>Even better, <a href="https://stackoverflow.com/questions/19877757/workaround-for-error-c2536-cannot-specify-explicit-initializer-for-arrays-in-vi#comment29863977_19890214">one comments</a> suggested use an extra pair of braces
<code>A() : m_array ({ { 0, 1, 2 } }) {}</code> , and now all smooth!</p>
<p>To pass a <code>std::array</code> to a function requiring a <code>char *</code> parameter, <a href="http://stackoverflow.com/questions/24226276/stdarray-over-c-style-array">std::array over c style array</a> suggest use <code>my_array.data()</code> where <code>my_array</code> is a <code>std::array</code>. </p>
<p>Now I met a problem with <code>_spitpath_s</code>:</p>
<p>The traditional <code>char *</code> style compiles
<code>_splitpath_s(fullpathfilename, drive, dir, name, ext)</code> where the parameters are all <code>char</code> arrays; but using <code>std::array</code> will trigger error C2660:</p>
<pre><code>class B2
{
public:
const int MAX_LEN = 200;
std::array<char, 200> drive, dir, name, ext;
B2() :drive({ { 0 } }), dir({ { 0 } }), name({ { 0 } }), ext({ { 0 } }) {}
void split(const char * fullpathfilename) {
_splitpath_s(fullpathfilename, drive.data(), dir.data(), name.data(), ext.data()); //error C2660: '_splitpath_s' : function does not take 5 arguments
}
};
</code></pre>
<p>.</p>
<p>Why <code>_splitpath_s</code> fails here? This is an old C style function, defined in <code>stdlib.h</code>, if there's a work-around in C++, also acceptable.</p>
| <p>The 5 parameter version of <code>_splitpath_s</code> is a template function, expecting a character pointer for the input path, and C-style character arrays for the other 4. Since you are passing in C++ <code>array</code> objects, the template is not generated and, due to SFINAE it is not available so there is no function that takes 5 parameters.</p>
<p>To use it you'll have to use the 9 parameter version, where you pass in the input addresses and buffer sizes.</p>
|
Integrating COUNT into postgres query <p>I have a table titled <code>users</code> and below it is the <code>tracks</code> table and below that is the <code>likes</code> table. The <code>users</code> table has an <code>id</code> column for the users ID and the <code>tracks</code> table has a <code>id</code> column for the track ID and a <code>user_ID</code> column for the user ID that owns the track. The <code>likes</code> table has a <code>user_id</code> column for the user that liked the track and a <code>track_id</code> column for the track ID. Right now my query is working perfectly, but I'd like to get a count for the number of likes a specific track ID has. </p>
<p>My current fetch request:</p>
<pre><code>cur.execute('SELECT t.title, t.share, t.id, u.id, u.username, l.date_liked, '
'FROM (tracks t INNER JOIN users u ON t.user_id = u.id)'
'LEFT JOIN (SELECT * FROM likes WHERE user_id = %s)'
'l ON l.track_id = t.id ORDER BY t.id DESC', [current_user.id])
</code></pre>
<p>I'm not super savvy when it comes to Postgres. I know I need to do <code>SELECT COUNT(track_id) FROM likes</code>, but I'm not sure how to integrate it into my current query. </p>
<p>Playing around with Alan Samets answer below, I was able to come with this:</p>
<pre><code>cur.execute('WITH t_count AS'
'(SELECT tracks.id,'
'COUNT(*) like_count '
'FROM tracks '
'INNER JOIN likes '
'ON tracks.id = likes.track_id '
'GROUP BY tracks.id)'
', t_mylike AS'
'(SELECT likes.track_id, likes.date_liked FROM likes WHERE likes.user_id = %s )'
'SELECT t.title, t.share, t.id, t_count.like_count, u.id, u.username, ml.date_liked '
'FROM tracks t '
'LEFT JOIN t_count '
'ON t.id = t_count.id '
'INNER JOIN users u '
'ON u.id = t.user_id '
'LEFT JOIN t_mylike ml ON t.id = ml.track_id '
'ORDER BY t.id DESC', [current_user.id])
</code></pre>
<p>This is almost working perfectly, but it doesn't return correctly when the user has liked their own track. Right now when a user likes another users track, it returns the date that was liked, but when a user likes their owner track its returning <code>None</code> - which is incorrect. </p>
| <p>I believe that PostgreSQL supports common table expressions. I assume that the query that you're writing is to drive a UI component and that you want to show the track information, the date that the current user liked the track alongwith the count of total likes. </p>
<pre><code>WITH t_count AS
(
SELECT tracks.id
, COUNT(*) like_count
FROM tracks
INNER JOIN likes
ON tracks.id = likes.track_id
GROUP BY tracks.id
)
SELECT t.title, t.share, t.id, t_count.like_count, u.id, u.username, l.date_liked
FROM tracks t
INNER JOIN t_count
ON t.id = t_count.id
INNER JOIN users u
ON u.id = t.user_id
LEFT JOIN likes l
ON u.id = likes.user_id
WHERE user_id = %s
ORDER BY ...
</code></pre>
|
CMFCMenuButton not properly repainting when toggling high contrast mode <p>In an C++ MFC project I'm using <a href="https://msdn.microsoft.com/library/bb983215(v=vs.100).aspx" rel="nofollow"><code>CMFCMenuButton</code></a> using MSVC 2013.</p>
<p>When I toggle the <a href="https://support.microsoft.com/en-us/instantanswers/ece8e1d7-1a7c-473c-a0f4-3c9d66fee295/turn-on-high-contrast-mode" rel="nofollow">high contrast mode</a> the button is not properly repainted (for comparison a normal button is displayed):</p>
<p><img src="https://i.stack.imgur.com/4cUE8.png" alt="broken repaint of CMFCMenuButton after toggling high contrast mode"></p>
<p>Calling <a href="https://msdn.microsoft.com/library/ax04k970(v=vs.80).aspx" rel="nofollow"><code>Invalidate()</code></a> or <code>ShowWindow(SW_HIDE);ShowWindow(SW_SHOW);</code> seem to have no effect - even minimizing the dialog does not cause a proper redraw. How can I force the button to repaint with the updated system color?</p>
<p><em>Update:</em> Forcing the colors after toggling contrast mode just makes the button text visible, however the button itself, the border, is not visible.</p>
<pre><code>m_ctrlOkButton.SetFaceColor(::GetSysColor(COLOR_BTNFACE));
m_ctrlOkButton.SetTextColor(::GetSysColor(COLOR_BTNTEXT));
</code></pre>
| <p>Took me a while, but I was able to solve this. I'm inheriting from the <a href="https://msdn.microsoft.com/library/bb983215(v=vs.100).aspx" rel="nofollow"><code>CMFCMenuButton</code></a> class so that I can handle some events:</p>
<ol>
<li><p>Get the color on the button right:<br>Handle the <a href="https://msdn.microsoft.com/library/windows/desktop/dd145223(v=vs.85).aspx" rel="nofollow"><code>WM_SYSCOLORCHANGE</code></a> event and call <code>GetGlobalData()->UpdateSysColors();</code> (make sure it's propagated to our parent before, e.g., by <code>__super::OnSysColorChange();</code>)</p></li>
<li><p>Get the border and background right:<br>Handle the <a href="https://msdn.microsoft.com/library/windows/desktop/ms632650(v=vs.85).aspx" rel="nofollow"><code>WM_THEMECHANGED</code></a> event and call <code>CMFCVisualManager::GetInstance()->DestroyInstance();</code> in order to close all <a href="https://msdn.microsoft.com/library/windows/desktop/bb759821(v=vs.85).aspx" rel="nofollow">opened theme data handles</a>.</p></li>
</ol>
|
Scrolling up or down from section to section automatically <p>I'm trying to implement something in JS like the following.
In a page, every time I scroll up or down, the following div(section) in viewport has to be shown.
For example, if I scroll down, the page has to move automatically down to the next div(section) and so on. Same for when I scroll up.
Each div(section) has the viewport height in order to show a full div(section) content every time I scroll up or down. Does it make sense?
Can anyone suggest if it's achievable and how?</p>
<p>The code could be the following:</p>
<pre><code><div class"container">
<div class="section"> content </div> <!-- viewport height -->
<div class="section"> content </div> <!-- viewport height -->
<div class="section"> content </div> <!-- viewport height -->
<div class="section"> content </div> <!-- viewport height -->
<div class="section"> content </div> <!-- viewport height -->
</div>
</code></pre>
<p>Thanks!</p>
| <p>Personally, I would recommend against scrolling panes into view on a scroll, they are inconsistent and awkward to use, especially on things such as trackpads or other "mice" with accelerating scrolling.</p>
<p>However, a jQuery solution to scrolling one view port at a time could look like:</p>
<pre><code>var lastScrollTop = 0;
$(window).scroll(function(event){
var scrollTop = $(this).scrollTop();
if (scrollTop > lastScrollTop){
$("html,body").animate({
scrollTop: $("html,body").css("scrollTop") + $(".section").first().height()
}, 500);
} else {
$("html,body").animate({
scrollTop: $("html,body").css("scrollTop") - $(".section").first().height()
}, 500);
}
lastScrollTop = scrollTop;
});
</code></pre>
|
How to resolve constructor signature in factory function <p>I want to support one of two possible signatures of the constructor of the class <code>T</code> when creating its instance in the <code>create(...)</code> function below:</p>
<pre><code>template <class Т, typename... Args>
T* create(Special* s, Args&&... args) {
T* t =
// If such a constructor exists, this:
new T(s, std::forward<Args>(args)...);
// Otherwise, this:
new T(std::forward<Args>(args)...);
}
</code></pre>
<p>I tried a few monstrous template constructions that did not cut it. The <a href="http://stackoverflow.com/a/257382/1149924">solution for resolving a member function</a> involves SFINAE-failing a <code>decltype</code> of a member function, but this is not apparently possible with a constructor, as it does not have a signature type of its own.</p>
<p>Is this even possible in C++11, and is there any library support? </p>
| <p>Just use <a href="http://en.cppreference.com/w/cpp/types/is_constructible"><code>std::is_constructible</code></a>:</p>
<pre><code>namespace detail
{
template<typename T, typename... Ts>
auto create(std::true_type, Special* s, Ts&&... args) {
return new T(s, std::forward<Ts>(args)...);
}
template<typename T, typename... Ts>
auto create(std::false_type, Special*, Ts&&... args) {
return new T(std::forward<Ts>(args)...);
}
}
template<class T, typename... Args>
T* create(Special* s, Args&&... args) {
using tag = is_constructible<T, Special*, Args...>;
return detail::create<T>(tag{}, s, std::forward<Args>(args)...);
}
</code></pre>
<p><a href="http://melpon.org/wandbox/permlink/7oaFOTHPCrMNtUz6">live demo</a></p>
|
Python runs the commented-out code <p>I have a problem that sometimes <code>docker-py</code> returns an error:</p>
<pre><code>Permission denied.
</code></pre>
<p>I'm trying to fix it. I commented out the piece of code, and received the following picture.</p>
<pre><code>File "/opt/dst/src/utils/runner.py", line 48, in run_code
\#if len(cli.containers(filters={'status': ['running', 'created']})) >= settings.DOCKER_CONTAINER_COUNT:
</code></pre>
<pre class="lang-html prettyprint-override"><code>Traceback (most recent call last):
File "/opt/dst/env/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task
R = retval = fun(*args, **kwargs)
File "/opt/dst/env/lib/python2.7/site-packages/celery/app/trace.py", line 438, in __protected_call__
return self.run(*args, **kwargs)
File "/opt/dst/src/core/tasks.py", line 12, in run
return 'Solution not found'
File "/opt/dst/src/utils/runner.py", line 48, in run_code
#if len(cli.containers(filters={'status': ['running', 'created']})) >= settings.DOCKER_CONTAINER_COUNT:
File "/opt/dst/env/lib/python2.7/site-packages/docker/api/container.py", line 85, in containers
res = self._result(self._get(u, params=params), True)
File "/opt/dst/env/lib/python2.7/site-packages/docker/utils/decorators.py", line 47, in inner
return f(self, *args, **kwargs)
File "/opt/dst/env/lib/python2.7/site-packages/docker/client.py", line 132, in _get
return self.get(url, **self._set_request_timeout(kwargs))
File "/opt/dst/env/lib/python2.7/site-packages/requests/sessions.py", line 487, in get
return self.request('GET', url, **kwargs)
File "/opt/dst/env/lib/python2.7/site-packages/requests/sessions.py", line 475, in request
resp = self.send(prep, **send_kwargs)
File "/opt/dst/env/lib/python2.7/site-packages/requests/sessions.py", line 585, in send
r = adapter.send(request, **kwargs)
File "/opt/dst/env/lib/python2.7/site-packages/requests/adapters.py", line 453, in send
raise ConnectionError(err, request=request)
ConnectionError: ('Connection aborted.', error(13, 'Permission denied'))
</code></pre>
<p>The runner.pyc file is updated.
What could be the problem?
Thank you for your help and sorry for my bad english</p>
<p>UPDATE:</p>
<pre><code>cli = Client('unix://var/run/docker.sock', version='1.19')
kill_client = Client('unix://var/run/docker.sock', version='1.19', timeout=0.5)
config = cli.create_host_config(**get_host_config(file_path))
#if len(cli.containers(filters={'status': ['running', 'created']})) >= settings.DOCKER_CONTAINER_COUNT:
# return 'must retry', None
run_string = 'timeout {} python /tmp/script.py'.format(settings.DOCKER_EXECUTE_TIME)
container = cli.create_container('python:2', run_string, user=uid, host_config=config)
</code></pre>
| <p>Due to an error in the script, worked two instance celery and this error occurred during the operation instance, who has worked with the old code.</p>
|
Search for value within a range of values in two separate vectors <p>This is my first time posting to Stack Exchange, my apologies as I'm certain I will make a few mistakes. I am trying to assess false detections in a dataset. </p>
<p>I have one data frame with "true" detections </p>
<pre><code>truth=
ID Start Stop SNR
1 213466 213468 10.08
2 32238 32240 10.28
3 218934 218936 12.02
4 222774 222776 11.4
5 68137 68139 10.99
</code></pre>
<p>And another data frame with a list of times, that represent possible 'real' detections</p>
<blockquote>
<p>possible=
ID Times</p>
<p>1 32239.76</p>
<p>2 32241.14</p>
<p>3 68138.72</p>
<p>4 111233.93</p>
<p>5 128395.28</p>
<p>6 146180.31</p>
<p>7 188433.35</p>
<p>8 198714.7</p>
</blockquote>
<p>I am trying to see if the values in my 'possible' data frame lies between the start and stop values. If so I'd like to create a third column in possible called "between" and a column in the "truth" data frame called "match. For every value from possible that falls between I'd like a 1, otherwise a 0. For all of the rows in "truth" that find a match I'd like a 1, otherwise a 0.</p>
<p>Neither ID, not SNR are important. I'm not looking to match on ID. Instead I wand to run through the data frame entirely. Output should look something like:</p>
<blockquote>
<p>ID Times Between</p>
<p>1 32239.76 0</p>
<p>2 32241.14 1</p>
<p>3 68138.72 0</p>
<p>4 111233.93 0</p>
<p>5 128395.28 0</p>
<p>6 146180.31 1</p>
<p>7 188433.35 0</p>
<p>8 198714.7 0</p>
</blockquote>
<p>Alternatively, knowing if any of my 'possible' time values fall within 2 seconds of start or end times would also do the trick (also with 1/0 outputs)</p>
<p>(Thanks for the feedback on the original post)</p>
<p>Thanks in advance for your patience with me as I navigate this system.</p>
| <p>I'll post a solution that I'm pretty sure works like you want it to in order to get you started. Maybe someone else can post a more efficient answer. </p>
<p>Anyway, first I needed to generate some example data - next time please provide this from your own data set in your post using the function <code>dput(head(truth, n = 25))</code> and <code>dput(head(possible, n = 25))</code>. I used:</p>
<pre><code>#generate random test data
set.seed(7)
truth <- data.frame(c(1:100),
c(sample(5:20, size = 100, replace = T)),
c(sample(21:50, size = 100, replace = T)))
possible <- data.frame(c(sample(1:15, size = 15, replace = F)))
colnames(possible) <- "Times"
</code></pre>
<p>After getting sample data to work with; the following solution provides what I believe you are asking for. This should scale directly to your own dataset as it seems to be laid out. Respond below if the comments are unclear.</p>
<pre><code>#need the %between% operator
library(data.table)
#initialize vectors - 0 or false by default
truth.match <- c(rep(0, times = nrow(truth)))
possible.between <- c(rep(0, times = nrow(possible)))
#iterate through 'possible' dataframe
for (i in 1:nrow(possible)){
#get boolean vector to show if any of the 'truth' rows are a 'match'
match.vec <- apply(truth[, 2:3],
MARGIN = 1,
FUN = function(x) {possible$Times[i] %between% x})
#if any are true then update the match and between vectors
if(any(match.vec)){
truth.match[match.vec] <- 1
possible.between[i] <- 1
}
}
#i think this should be called anyMatch for clarity
truth$anyMatch <- truth.match
#similarly; betweenAny
possible$betweenAny <- possible.between
</code></pre>
|
What Should I fix in my C code? <p>I want to start off by saying that I am not asking for the answer, however I would like some advice on what I should be looking for in the syntax. This is one of my first few C assignments. My code have an output like shown below.</p>
<pre><code>How many grade items would you like to enter? 4
Enter the grade for grade item number 1: 67
Enter the grade for grade item number 2: 79.4
Enter the grade for grade item number 3: 90
Enter the grade for grade item number 4: 83.5
Average grade: 79.97%
Letter grade: C
</code></pre>
<p>I'm trying to figure out how to make it replicate for the number inputted however I'm stuck on the below code that I wrote for the first assignment and I understand that loops could have been used to make this a LOT shorter but I have only about a weeks usage experience in C.</p>
<pre><code>#include <stdio.h>
int main() {
int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, sum, total = 1200;
float per;
printf("\nEnter the score for Assignment 1: "); // Assignment statements
scanf("%d", &a1);
printf("\nEnter the score for Assignment 2: ");
scanf("%d", &a2);
printf("\nEnter the score for Assignment 3: ");
scanf("%d", &a3);
printf("\nEnter the score for Assignment 4: ");
scanf("%d", &a4);
printf("\nEnter the score for Assignment 5: ");
scanf("%d", &a5);
printf("\nEnter the score for Assignment 6: ");
scanf("%d", &a6);
printf("\nEnter the score for Assignment 7: ");
scanf("%d", &a7);
printf("\nEnter the score for Assignment 8: ");
scanf("%d", &a8);
printf("\nEnter the score for Assignment 9: ");
scanf("%d", &a9);
printf("\nEnter the score for Assignment 10: ");
scanf("%d", &a10);
printf("\nEnter the score for Assignment 11: ");
scanf("%d", &a11);
printf("\nEnter the score for Assignment 12: ");
scanf("%d", &a12);
sum = a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12;
per = (sum * 100) / total;
printf("\nPercentage : %f", per);
return (0);
}
</code></pre>
<p>Any advice would be great(or a link to what I should review?), I get pretty confused after simple print/scan statement.</p>
| <p>You can use <code>for</code> loop to input a number of values:</p>
<pre><code>int a, sum = 0;
int n;
printf("\nHow many grade items would you like to enter? ");
scanf("%d", &n);
int i;
for (i = 1; i <= n; ++i) {
printf("\nEnter the score for Assignment %d: ", i);
scanf("%d", &a);
sum = sum + a;
}
printf("\nsum: %d", sum);
</code></pre>
<p>Now when you have the sum you're able to calculate avg. grade and so on.</p>
<p>P.S. Note that questions like "fix my code" are not welcome here. I know that it's not easy to do first steps in learning C. Read some basic tutorials, run example code from them. And try to do your questions more specific.</p>
|
Javascript Class Variable Scope Becomes Undefined <p>so I have a class names <code>Session</code>.</p>
<p>I declare it as:</p>
<pre><code>function Session() {
}
</code></pre>
<p>I have a function called as: <code>Session.prototype.parseCommand(){}</code>.</p>
<p>For some reason, if I call the function as: <code>this.parseCommand()</code> it is declared as undeclared.</p>
<p>This also occurs with functions such as: <code>this.textInput = false</code>. On some functions, I can call it, but on others it is undefined.</p>
<p>What is the problem?</p>
<pre><code>function Session() {
this.textInput = null;
this.lineGutter = null;
}
Session.prototype.parseCommand = function(command) {
if (command === 'clear') {
} else {
var line = document.createElement('div');
line.className = 'line';
line.setAttribute('id', 'line command');
line.innerHTML = command;
document.getElementById('sessionLineGutter').appendChild(line);
}
};
Session.prototype.textInputKey = function(e) {
if (e.keyCode === 13) {
this.parseCommand(document.getElementById('sessionText').innerHTML);
e.preventDefault();
}
};
</code></pre>
<p>Here is the full code and the error. I also notice that I cannot use <code>this.lineGutter.appendChild(line);</code> and instead I have to use <code>document.getElementById('sessionLineGutter').appendChild(line)</code>. Why is this?</p>
<p>Thanks,</p>
| <p>When any method in declared on prototype you cannot call them using this
it has to be called directly through the object</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function session(){
}
session.prototype.method1=function(){
alert("here");
}
var sess1=new session();
sess1.method1();
//this -here refers to window object</code></pre>
</div>
</div>
</p>
<p>this here refers to window(global) object</p>
<p>In this code snippet</p>
<pre><code>function Session() {
this.textInput = null;
this.lineGutter = null;
}
</code></pre>
<p>this refers to global(window) object</p>
<p>you can call parsecommand method using
var session1=new Session() and it can be called as session1.parseCommand
and now inside parseCommand this would be Session object ,so that's why when you are trying to access
this.lineGutter.appendChild(line); </p>
<p>It would not happen,because here it is pointing to lineGutter in Session object,but i guess you are expecting it to append to the body which does not happen here because this is an object here</p>
<p>so that's the reason you have to document.getElementById('sessionLineGutter').appendChild(line)</p>
<p>I hope you understand</p>
|
error in code involving while loop and removing items from string <p>I have a code that downloads tweets and I am trying to sort through it labeling it as positive or negative each time i label a tweet I want to remove it from the string so I won't be asked to label it again here is my code so far</p>
<pre><code>while True:
if len(tweet_list) == 0:
break
else:
tweet1= (np.random.choice(tweet_list))
print tweet1
judge = input("1 pos, 2 neg 3 skip: ")
if judge == 1:
tweet_pos.append(tweet1)
tweet_list.remove(tweet1)
if judge == 2:
tweet_neg.append(tweet1)
tweet_list.remove(tweet1)
</code></pre>
<p>after I label the second tweet I am given this error</p>
<pre><code>ValueError: list.remove(x): x not in list
</code></pre>
| <p>You could do something like:</p>
<pre><code>newList = []
for myLetter in myList:
if myLetter is not 'x':
newList.append(myLetter)
newString = ''.join(newList)
</code></pre>
|
Combine an array based on iteration and make it multidimensional <p>So I have two arrays. Let's call them member_ids and member_names</p>
<p>So the first array (member_ids) could look like:</p>
<pre><code>Array
(
[0] => 572149922960422
[1] => 1586735531587728
[2] => 1084479334908663
[3] => 9875443331682
[4] => 9291002010388
[5] => 2108382717199939
[6] => 911647002295982
[7] => 100222991929377
)
</code></pre>
<p>The second array (member_names) could look like</p>
<pre><code>Array
(
[0] => John Doe
[1] => Jane Doe
[2] => Shawn Smith
[3] => Jack Nickleson
[4] => Brad Pitt
[5] => Chad Kroger
[6] => Angelina Jolie
[7] => Bruce Campell
)
</code></pre>
<p>The most important thing, is that even though the variables can be different, the iterations will always match up with each other (meaning that member_id[0] is the member ID for member_name[0], and so on). But I'd like to create a multidimensional called member_info that uses data from both arrays, so the new URL (if you take data from both the arrays) would look like this:</p>
<pre><code>Array
(
[0] => Array
(
[member_id] => 572149922960422
[member_name] => John Doe
)
[1] => Array
(
[member_id] => 1586735531587728
[member_name] => Jane Doe
)
[2] => Array
(
[member_id] => 1084479334908663
[member_name] => Shawn Smith
)
[3] => Array
(
[member_id] => 9875443331682
[member_name] => Jack Nickleson
)
[4] => Array
(
[member_id] => 9291002010388
[member_name] => Brad Pitt
)
[5] => Array
(
[member_id] => 2108382717199939
[member_name] => Chad Kroger
)
[6] => Array
(
[member_id] => 911647002295982
[member_name] => Angelina Jolie
)
[7] => Array
(
[member_id] => 100222991929377
[member_name] => Bruce Campell
)
)
</code></pre>
<p>Keep in mind both arrays vary, so the variables for both the id and name for both arrays will depend on the database. This is just an example of what I'm trying to achieve. </p>
| <p>You could do something like:</p>
<pre><code><?php
$ids = [
572149922960422,
1586735531587728,
1084479334908663,
9875443331682,
9291002010388,
2108382717199939,
911647002295982,
100222991929377
];
$names = [
"John Doe",
"Jane Doe",
"Shawn Smith",
"Jack Nickleson",
"Brad Pitt",
"Chad Kroger",
"Angelina Jolie",
"Bruce Campell"
];
function customCombine($combined){
$final = [];
$i = 0;
foreach($combined as $id => $name){
$final[$i]['member_id'] = $id;
$final[$i]['member_name'] = $name;
$i++;
}
return $final;
}
print_r(customCombine(array_combine($ids,$names)));
</code></pre>
<p>You can see the results <a href="https://3v4l.org/aHBjI" rel="nofollow">here</a>.</p>
|
Unable to use echo with php form <p>My PHP form seems to be operating fine. The page comes up and when I click on the submit button, the isset($_POST['submitted']) condition at the start is hit and the code run.</p>
<p>The only issue is that I have a couple of echo lines in the code to produce a JS alert box. Neither seem to be getting called. I'm not sure that the external PHP functions are being called either as I have no way of testing the value returned.</p>
<p>My PHP looks like this</p>
<pre><code><?php if (isset($_POST['submitted'])) {
$output = checkData();
if ($output != "done")
{
echo '<script type="text/javascript">alert("' . $output . '"); </script>';
}
else
{
createMeeting();
echo '<script type="text/javascript">alert("You meeting has been created. All of the recipients should shortly receive an email"); </script>';
header('Location: index.php');
}
} else { ?>
<center>
<form method="POST" action="">
...
<input type="submit" name="submitted" value="Create Meeting">
</form>
<?php
}
?>
</code></pre>
<p>My checkData() function simply checks to see if the other parts of the form data are empty and exit with either "done" (no errors) or a message if one of the form elements is empty.</p>
<p>createMeeting() will create a meeting based on the data and submit it to my server - currently, it takes the same data as checkData() and then returns.</p>
<p>Both functions come back with no errors when I run it through an online PHP code checker.</p>
| <p>I've tried your code and it seems to work fine in my case. </p>
<pre><code><?php if (isset($_POST['submitted'])) {
$output = "done"; //even if this line is not equal to 'done', the code still works fine
if ($output != "done")
{
echo '<script type="text/javascript">alert("' . $output . '");</script>';
}
else
{
// createMeeting();
echo '<script type="text/javascript">alert("You meeting has been created. All of the recipients should shortly receive an email"); </script>';
// header('Location: index.php');
}
} else { ?>
<center>
<form method="POST" action="">
...
<input type="submit" name="submitted" value="Create Meeting">
</form>
<?php
}
?>
</code></pre>
<p>So to my knowledge, there're errors with your createMeeting() or checkData() functions. Can you please be more specific with the error messages (if any)?</p>
|
Javascript making image rotate to always look at mouse cursor? <p>I'm trying to get an arrow to point at my mouse cursor in javascript. Right now it just spins around violently, instead of pointing at the cursor. </p>
<p><strong>Here is a fiddle of my code: <a href="https://jsfiddle.net/pk1w095s/" rel="nofollow">https://jsfiddle.net/pk1w095s/</a></strong></p>
<p>And here is the code its self:</p>
<pre><code>var cv = document.createElement('canvas');
cv.width = 1224;
cv.height = 768;
document.body.appendChild(cv);
var rotA = 0;
var ctx = cv.getContext('2d');
var arrow = new Image();
var cache;
arrow.onload = function() {
cache = this;
ctx.drawImage(arrow, cache.width/2, cache.height/2);
};
arrow.src = 'https://d30y9cdsu7xlg0.cloudfront.net/png/35-200.png';
var cursorX;
var cursorY;
document.onmousemove = function(e) {
cursorX = e.pageX;
cursorY = e.pageY;
ctx.save(); //saves the state of canvas
ctx.clearRect(0, 0, cv.width, cv.height); //clear the canvas
ctx.translate(cache.width, cache.height); //let's translate
var centerX = cache.x + cache.width / 2;
var centerY = cache.y + cache.height / 2;
var angle = Math.atan2(e.pageX - centerX, -(e.pageY - centerY)) * (180 / Math.PI);
ctx.rotate(angle);
ctx.drawImage(arrow, -cache.width / 2, -cache.height / 2, cache.width, cache.height); //draw the image
ctx.restore(); //restore the state of canvas
};
</code></pre>
| <p>In the first instance, get rid of the conversion to degrees - both the <code>Math.atan2</code> and the <code>ctx.rotate</code> functions take radians.</p>
<p>That fixes the wild rotation - you still then have some math errors, which are most easily sorted out by splitting out the drawing from the math.</p>
<p>The function below draws the arrow rotated by the given angle:</p>
<pre><code>// NB: canvas rotations go clockwise
function drawArrow(angle) {
ctx.clearRect(0, 0, cv.width, cv.height);
ctx.save();
ctx.translate(centerX, centerY);
ctx.rotate(-Math.PI / 2); // correction for image starting position
ctx.rotate(angle);
ctx.drawImage(arrow, -arrow.width / 2, -arrow.height / 2);
ctx.restore();
}
</code></pre>
<p>and the <code>onmove</code> handler just figures out the direction.</p>
<pre><code>document.onmousemove = function(e) {
var dx = e.pageX - centerX;
var dy = e.pageY - centerY;
var theta = Math.atan2(dy, dx);
drawArrow(theta);
};
</code></pre>
<p>Note that on a canvas the Y axis points downwards (contrary to normal cartesian coordinates) so the rotations end up going clockwise instead of anti-clockwise.</p>
<p>working demo at <a href="https://jsfiddle.net/alnitak/5vp0syn5/" rel="nofollow">https://jsfiddle.net/alnitak/5vp0syn5/</a></p>
|
Pattern for asking Javascript to pay attention to multiple element events? <p>I'm writing a Javascript library to monitor how the user interacts with form fields. It will have to monitor multiple events for a given element, so I can't use an onblah handler.</p>
<p>I would like the HTML author to decide what fields are monitored. I thought I'd offer something like this:</p>
<pre><code><script src="formWatch.js"></script>
<form ...>
<textarea name="blah" onload="watch(this)"/>
<input type="submit" value="Submit" />
</form>
</code></pre>
<p>Then <code>watch()</code> would register various event handlers on the element. But it seems <code>onload</code> only fires on elements which load resources?</p>
<p>What is a good pattern for allowing the HTML author to decide what elements a Javascript library will pay attention to?</p>
| <p>You have many options. Maybe try going with a <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes" rel="nofollow">data</a> tag:</p>
<pre><code><textarea name="blah" data-monitored="true">
</code></pre>
<p>and in your JS you collect all these elements using a method like so:</p>
<pre><code>var nodeList = document.querySelectorAll("[data-monitored='true']");
</code></pre>
|
Docker compose extra hosts with wildcards <p>I'm trying to create a container based on PHP:5-apache with many virtual hosts like</p>
<ul>
<li><p>account.site1.local</p></li>
<li><p>account.site2.local</p></li>
<li><p>account.site3.local</p></li>
</ul>
<p>I can add all the vhosts with a wildcard on the apache conf. Is it possible to do something similar for the hosts file?</p>
| <p>Docker sets up the <code>hosts</code> file when you run a container, so you don't want to manually edit it. Instead you can use the <code>add-host</code> option:</p>
<pre><code>> docker run --add-host 1.local:127.0.0.1 alpine ping 1.local
PING 1.local (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: seq=0 ttl=64 time=0.050 ms
</code></pre>
<p>You can have multiple <code>add-host</code> options in the <code>run</code> command. </p>
<p>In Docker Compose the equivalent is <code>extra-hosts</code>:</p>
<pre><code>extra_hosts:
- "1.local:127.0.0.1"
- "2.local:127.0.0.1"
</code></pre>
|
Power BI DAX Calculating Last week Sales for All the Filter Options <p>I have following Data Structure</p>
<pre><code>Date | Category | Sales Amount
----------------------------------------------------
01-Sep-2016 | Food | 100
02-Sep-2016 | Food | 120
03-Sep-2016 | Food | 130
01-Sep-2016 | Electricity | 180
02-Sep-2016 | Electricity | 60
01-Sep-2016 | Perfumes | 80
02-Sep-2016 | Perfumes | 40
</code></pre>
<p>I want to calculate the Two Week Sales for Each Category, I might add another column like Territory as well in the future. I used following Formula which worked fine if I only select Date but Does Not Work if I select Category. </p>
<pre><code>SalesTwoWeeksAgo =
CALCULATE (
SUM ( 'Table'[SalesAmount] ),
FILTER (
ALL ( 'Table' ),
COUNTROWS (
FILTER (
'Table',
EARLIER ( 'Table'[Date] ) = DATEADD ( 'Table'[Date], -14, DAY )
)
)
)
)
</code></pre>
<p>The Above Formula was contributed by alejandro zuleta and link is </p>
<p><a href="http://stackoverflow.com/questions/39716057/power-bi-getting-2-week-back-same-day-value">Power BI getting 2 week back same day value</a></p>
| <p>If I understand your question, the problem is that you have a <code>Category</code> column so you need to get the sales two weeks back in the time in the current category value evaluated in the expression. You just have to add an additional condition in the <code>FILTER</code> function to take the current <code>Category</code> and the current <code>Date</code> substracting 14 days, then it will return the related <code>Sales Amount</code> values to the <code>SUM</code> function. </p>
<pre><code>SalesTwoWeeksAgo =
CALCULATE (
SUM ( 'Table'[Sales Amount] ),
FILTER (
ALL ( 'Table' ),
COUNTROWS (
FILTER (
'Table',
EARLIER ( 'Table'[Date] ) = DATEADD ( 'Table'[Date], -14, DAY )
&& 'Table'[Category] = EARLIER ( 'Table'[Category] )
)
)
)
)
</code></pre>
<p>Also if you add <code>Territory</code> column to your table you may need to get the <code>Sales Amount</code> two weeks before per <code>Date</code>, <code>Category</code> and <code>Territory</code> so you just need to add a third conditional in the <code>FILTER</code> function.</p>
<pre><code>SalesTwoWeeksAgo =
CALCULATE (
SUM ( 'Table'[Sales Amount] ),
FILTER (
ALL ( 'Table' ),
COUNTROWS (
FILTER (
'Table',
EARLIER ( 'Table'[Date] ) = DATEADD ( 'Table'[Date], -14, DAY )
&& 'Table'[Category] = EARLIER ( 'Table'[Category] )
&& 'Table'[Territory] = EARLIER ( 'Table'[Territory] )
)
)
)
)
</code></pre>
<p>The solution provided here is not tested yet but hopefully it is what you need.</p>
<p>Let me know if this helps.</p>
|
Command pattern for restaurant use case <p>I just start to learn design patterns, one is the command pattern. After reading some materials and some documentations, such as </p>
<p><a href="http://www.oodesign.com/command-pattern.html" rel="nofollow">http://www.oodesign.com/command-pattern.html</a>
<a href="https://www.tutorialspoint.com/design_pattern/command_pattern.htm" rel="nofollow">https://www.tutorialspoint.com/design_pattern/command_pattern.htm</a></p>
<p>I got the idea of using command pattern for stock buying and selling. The client can first decide which stock he/she would like to sell or buy and then let the agent/broker to invoke the command's execute function. I think this makes sense.</p>
<p>While another 'classic' example is restaurant, which confuses me for quite a while. As a customer, how can a customer know which cook (receiver) will be able to cook the item (soup or grill in the example)? The cook shall be not decided by the customer I think. Can anyone point me out how I should approach this idea?</p>
<p>Thanks! </p>
| <p>I believe you're not thinking about the restaurant example correctly. A customer doesn't give it's order directly to the cooks, a waitress takes the order to the kitchen and puts it in the queue where the cooks can take an order to make when they're available.</p>
<p>In code, this would look like a shared queue that the waitress adds to, and the cooks are in a continuous loop where they cook something then take the next order that they are able to cook. The command pattern in this example is simply the order that gets transferred from the customer to the kitchen.</p>
|
html javascript - onclick() reference error: function not defined <p>Given my html file, the console gives an error code: </p>
<blockquote>
<p>Reference Error: loadData not defined.</p>
</blockquote>
<p>Based from other answers I've rechecked mine where, </p>
<ol>
<li>My function is declared just before the <code></body></code>, </li>
<li>I included the javascript library at the <code><head></head></code> ;</li>
<li>and even changed my <code><input type= submit</code> to <code><input type= button</code></li>
<li>and if it helped, I tried deleting my form tags where it is enclosed <em>(but this is for another question regarding query strings).</em></li>
</ol>
<p>Here's how it would look like now:</p>
<pre><code><head>
<script src = "//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
{%for document in documents %}
<li> {{document.filename}}
<input type="button" id="{{ document.id }}" onclick="loadData(this.id)" name = "load-data" value="Add to Layer"/>
</li>
{%endfor%}
<script type ="text/javascript">
function loadData(documentId){
$.ajax({
url:"/load",
data: {'documentId': documentId},
type: 'GET',
success: function(){
window.location.href = "http://127.0.0.1:8000/url/locations";
}
});
}
</script>
</body>
</code></pre>
<p>I can't seem to find an explanation why the function won't fire.</p>
| <p>I've tested your html and everything seems to be working properly. The only error that I found was that $ajax is not a function. It is missing a dot $ajax => $.ajax</p>
<p>Try using:</p>
<pre><code>function loadData(documentId){
$.ajax({
url:"/load",
data: {'documentId': documentId},
type: 'GET',
success: function(){
window.location.href = "http://127.0.0.1:8000/url/locations";
}
});
}
</code></pre>
|
How to write unittest for variable assignment in python? <p>This is in <code>Python 2.7</code>. I have a class called <code>class A</code>, and there are some attributes that I want to throw an exception when being set by the user:</p>
<pre><code>myA = A()
myA.myattribute = 9 # this should throw an error
</code></pre>
<p>I want to write a <code>unittest</code> that ensures that this throws an error. </p>
<p>After creating a test class and inheriting <code>unittest.TestCase</code>, I tried to write a test like this:</p>
<pre><code>myA = A()
self.assertRaises(AttributeError, eval('myA.myattribute = 9'))
</code></pre>
<p>But, this throws a <code>syntax error</code>. However, if I try <code>eval('myA.myattribute = 9')</code>, it throws the attribute error, as it should.</p>
<p>How do I write a unittest to test this correctly? </p>
<p>Thanks.</p>
| <p>You can also use <code>assertRaises</code> as a context manager:</p>
<pre><code>with self.assertRaises(AttributeError):
myA.myattribute = 9
</code></pre>
<p>The <a href="https://docs.python.org/3/library/unittest.html#basic-example" rel="nofollow">documentation shows more examples for this if you are interested</a>. The documentation for <a href="https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertRaises" rel="nofollow">assertRaises</a> has a lot more detail on this subject as well.</p>
<p>From that documentation:</p>
<blockquote>
<p>If only the exception and possibly the msg arguments are given, return a context manager so that the code under test can be written
inline rather than as a function:</p>
<pre><code>with self.assertRaises(SomeException):
do_something()
</code></pre>
</blockquote>
<p>which is exactly what you are trying to do.</p>
|
How to get max of the rows above in each group(Sql or SAS) <p>Data:</p>
<pre><code>ID step order
100 1 1
100 2 2
100 3 3
100 1 4
200 2 5
200 3 6
200 1 7
</code></pre>
<p>Desired Result( I want to get the max of the rows above in each group)</p>
<pre><code>ID step max_step
100 1 1
100 2 2
100 3 3
100 1 3
200 2 2
200 3 3
200 1 3
</code></pre>
<p>Thank you very much!:)</p>
| <p>If your database supports windowed aggregate then</p>
<pre><code>SELECT id,
step,
Max(step) OVER( partition BY ID ORDER BY "order") as max_step
From yourtable
</code></pre>
<p>If you want to max step from above rows irrespective of <code>ID</code> then remove the <code>partition by</code></p>
<pre><code>SELECT id,
step,
Max(step) OVER(ORDER BY "order") as max_step
From yourtable
</code></pre>
|
Where is the memory allocated for p <pre><code>package main
import (
"io"
"os"
"strings"
)
type rot13Reader struct {
r io.Reader
}
func (rot *rot13Reader) Read(p []byte) (n int, err error) {
n, err = rot.r.Read(p) //<---- where allocated the mem for p?
for i := 0; i < len(p); i++ {
if p[i] >= 'A' && p[i] <= 'Z' {
p[i] = 65 + (p[i] - 65 + 13) % 26
} else if p[i] >= 'a' && p[i] <= 'z' {
p[i] = 97 + (p[i] - 97 + 13) % 26
}
}
return
}
func main() {
s := strings.NewReader("Lbh penpxrq gur pbqr!")
r := rot13Reader{s}
io.Copy(os.Stdout, &r)
}
</code></pre>
<p>This is an exercise from A tour of go. The code above can run properly, but I just don't understand where allocated the mem of p.</p>
| <p>io.Copy will call the method Read() of the io.Reader, take a look to the implementation <a href="https://golang.org/src/io/io.go?s=12490:12550#L349" rel="nofollow">https://golang.org/src/io/io.go?s=12490:12550#L349</a> and if you keep reading just a few lines below you'll find the method copyBuffer() and inside you will see these lines:</p>
<pre><code>if buf == nil {
buf = make([]byte, 32*1024)
}
for {
nr, er := src.Read(buf)
// ...more stuff
</code></pre>
|
updateTabsetPanel now, without delay <p>In the following minimal example, note that while the <code>file.choose()</code> line is commented out, the code works as expected: clicking the OK button on the <em>Input</em> tab switches to the <em>Results</em> tab.</p>
<p>However, uncomment the <code>file.choose()</code> line and the <code>updateTabsetPanel()</code> function no longer works. Is there some way to get the tab to change on the screen before the <code>file.choose()</code> begins?</p>
<pre><code>ui <- fluidPage(fluidRow(
tabsetPanel(id="main",
tabPanel("Input", actionButton("okButton", "OK")),
tabPanel("Results", h3(textOutput("results")))
)))
server <-function(input, output, session) {
output$results = renderText("Results Tab")
observeEvent(input$okButton, {
updateTabsetPanel(session, "main", "Results")
# file.choose()
})
}
shinyApp(ui = ui, server = server)
</code></pre>
| <p>You can do it in two steps: 1. Switch the tab; 2. Based on the tab switching event, open the file choose window.</p>
<pre><code>ui <- fluidPage(fluidRow(
tabsetPanel(id="main",
tabPanel("Input", actionButton("okButton", "OK")),
tabPanel("Results", h3(textOutput("results")))
)))
server <-function(input, output, session) {
output$results = renderText("Results Tab")
observeEvent(input$okButton, {
updateTabsetPanel(session, "main", "Results")
})
observeEvent(input$main, {
if (input$main == "Results") {
file.choose()
}
})
}
shinyApp(ui = ui, server = server)
</code></pre>
|
What is the symbol for the integer modulo operation in ATS? <p>For instance,
how to write in ATS the following C code:</p>
<pre><code>int intmod(int m, int n) { return m % n; }
</code></pre>
| <p>There are mod and nmod in ATS. You can also use % for mod.</p>
<p>Note that mod is given a non-dependent types while nmod is given a
dependent type. For details, please visit:</p>
<p><a href="http://ats-lang.sourceforge.net/DOCUMENT/ATS-Postiats/prelude/HTML/SATS/integer_sats.html" rel="nofollow">http://ats-lang.sourceforge.net/DOCUMENT/ATS-Postiats/prelude/HTML/SATS/integer_sats.html</a></p>
<p>Also note that mod and % are infix operators but nmod is not infix.</p>
|
Iterating through list in reverse <p>Assume the following (non-functioning) code, that takes a predicate such as <code>(==2)</code> and a list of integers, and drops only the last element of the list that satisfies the predicate:</p>
<pre><code>cutLast :: (a -> Bool) -> [Int] -> [Int]
cutLast a [] = []
cutLast pred (as:a)
| (pred) a == False = (cutLast pred as):a
| otherwise = as
</code></pre>
<p>This code does not work, so clearly lists cannot be iterated through in reverse like this. How could I implement this idea? I'm not 100% sure if the code is otherwise correct - but hopefully it gets the idea across.</p>
| <p>Borrowing heavily from <a href="http://stackoverflow.com/questions/40030460/haskell-split-string-on-last-occurence/40032635#40032635">myself</a>: the problem with this sort of question is that you don't know which element to remove until you get to the end of the list. Once we observe this, the most straightforward thing to do is traverse the list one way then back using <code>foldr</code> (the second traversal comes from the fact <code>foldr</code> is not tail-recursive).</p>
<p>The cleanest solution I can think of is to rebuild the list on the way back up, dropping the first element.</p>
<pre><code>cutLast :: Eq a => (a -> Bool) -> [a] -> Either [a] [a]
cutLast f = foldr go (Left [])
where
go x (Right xs) = Right (x:xs)
go x (Left xs) | f x = Right xs
| otherwise = Left (x:xs)
</code></pre>
<p>The return type is <code>Either</code> to differentiate between not found anything to drop from the list (<code>Left</code>), and having encountered and dropped the last satisfying element from the list (<code>Right</code>). Of course, if you don't care about whether you dropped or didn't drop an element, you can drop that information:</p>
<pre><code> cutLast' f = either id id . cutLast f
</code></pre>
<hr>
<p>Following the discussion of speed in the comments, I tried swapping out <code>Either [a] [a]</code> for <code>(Bool,[a])</code>. Without any further tweaking, this is (as @dfeuer predicted) consistently a bit slower (on the order of 10%).</p>
<p>Using irrefutable patterns on the tuple, we can indeed avoid forcing the whole output (as per @chi's suggestion), which makes this much faster for lazily querying the output. This is the code for that:</p>
<pre><code>cutLast' :: Eq a => (a -> Bool) -> [a] -> (Bool,[a])
cutLast' f = foldr go (False,[])
where
go x ~(b,xs) | not (f x) = (b,x:xs)
| not b = (False,x:xs)
| otherwise = (True,xs)
</code></pre>
<p>However, this is 2 to 3 times slower than either of the other two versions (that don't use irrefutable patterns) when forced to normal form.</p>
|
TabLayout change selected TabSize <pre><code>TextView title = (TextView)(((LinearLayout ((LinearLayout) mTabLayout.getChildAt(0)).getChildAt(tabPosition)).getChildAt(1));title.setTextSize(...);
</code></pre>
<p>I got the tabs <code>Textview</code> in <code>Tablayout</code> by this method,but this method is strangeï¼if i <code>setTextSize(10)</code>,it works,tab has small textsize,but when i <code>setTextSize</code> above 10,it always use default textsize whatever tab is selected or not.i think it only has two default textsize,anyone met this question,how can i set other textsize for it?</p>
| <p>You could try this one.. You can set each tabs text size and other properties.. You can take a look here for more info <a href="https://programmingcode4life.blogspot.my/2016/07/custom-tablayout-android.html" rel="nofollow">Custom tablayout</a></p>
<pre><code> ViewGroup vg = (ViewGroup) tabs.getChildAt(0);
int tabsCount = vg.getChildCount();
for (int j = 0; j < tabsCount; j++) {
ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
int tabChildsCount = vgTab.getChildCount();
for (int i = 0; i < tabChildsCount; i++) {
View tabViewChild = vgTab.getChildAt(i);
// Get TextView Element
if (tabViewChild instanceof TextView) {
// change font
((TextView) tabViewChild).setTypeface(tf);
// change color
((TextView) tabViewChild).setTextColor(getResources().getColor(R.color.white));
// change size
((TextView) tabViewChild).setTextSize(18);
// change padding
tabViewChild.setPadding(0, 0, 0, 0);
//..... etc...
}
}
}
</code></pre>
|
Looking for an explanation for the following code regarding loops in Java <p>I needed to create a program in Java using loops to print the following numbers
5,13,17.
My professor gave us the following solution for the program </p>
<pre><code> public class nowtry {
public static void main(String[] args){
int i=1;
for (int x=2;x<5;x++){
if (x==2)System.out.println(5*i);
else System.out.println(5*x-i);
i++;
}
}
}
</code></pre>
<p>I would like a detail explanation line by line how this prints 13 and 17. I know the if statement prints the first number of 5 because 2 is equal to 2 so it takes the int i=1 and multiplies it by 5. but how do I get the other two values</p>
| <p>First,</p>
<pre><code>x = 2
i = 1
print 5 * 1 = 5
</code></pre>
<p>Second,</p>
<pre><code>x = 3
i = 2
print (5 * 3) - 2 = 13
</code></pre>
<p>Third,</p>
<pre><code>x = 4
i = 3
print (5 * 4) - 3 = 17
</code></pre>
|
Google Maps V3 API - Center on a category pulling from xml file <p><a href="http://www.geocodezip.com/v3_MW_example_categories.html" rel="nofollow">I'm working with this example from Geocodezip</a></p>
<p>The markers on the map change depending on which category is selected. I would like them to automatically center on the category of markers but I'm having difficulty getting it to work. </p>
<p>The issue I'm having with all the fitbounds examples I've found on here and elsewhere is that they require the markers to be defined in the Javascript whereas mine are being imported from an XML file. I'm not sure what to try next. </p>
<p>The script:</p>
<pre><code><script type="text/javascript">
//<![CDATA[
// this variable will collect the html which will eventually be placed in the side_bar
var side_bar_html = "";
var gmarkers = [];
var gicons = [];
var map = null;
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
gicons["red"] = new google.maps.MarkerImage("mapIcons/marker_red.png",
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(20, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 9,34.
new google.maps.Point(9, 34));
// Marker sizes are expressed as a Size of X,Y
// where the origin of the image (0,0) is located
// in the top left of the image.
// Origins, anchor positions and coordinates of the marker
// increase in the X direction to the right and in
// the Y direction down.
var iconImage = new google.maps.MarkerImage('mapIcons/marker_red.png',
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(20, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 9,34.
new google.maps.Point(9, 34));
var iconShadow = new google.maps.MarkerImage('http://www.google.com/mapfiles/shadow50.png',
// The shadow image is larger in the horizontal dimension
// while the position and offset are the same as for the main image.
new google.maps.Size(37, 34),
new google.maps.Point(0,0),
new google.maps.Point(9, 34));
// Shapes define the clickable region of the icon.
// The type defines an HTML &lt;area&gt; element 'poly' which
// traces out a polygon as a series of X,Y points. The final
// coordinate closes the poly by connecting to the first
// coordinate.
var iconShape = {
coord: [9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0],
type: 'poly'
};
function getMarkerImage(iconColor) {
if ((typeof(iconColor)=="undefined") || (iconColor==null)) {
iconColor = "red";
}
if (!gicons[iconColor]) {
gicons[iconColor] = new google.maps.MarkerImage("mapIcons/marker_"+ iconColor +".png",
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(20, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 6,20.
new google.maps.Point(9, 34));
}
return gicons[iconColor];
}
function category2color(category) {
var color = "red";
switch(category) {
case "theatre": color = "blue";
break;
case "golf": color = "green";
break;
case "info": color = "yellow";
break;
default: color = "red";
break;
}
return color;
}
gicons["theatre"] = getMarkerImage(category2color("theatre"));
gicons["golf"] = getMarkerImage(category2color("golf"));
gicons["info"] = getMarkerImage(category2color("info"));
// A function to create the marker and set up the event window
function createMarker(latlng,name,html,category) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
icon: gicons[category],
shadow: iconShadow,
map: map,
title: name,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
// === Store the category and name info as a marker properties ===
marker.mycategory = category;
marker.myname = name;
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
}
// == shows all markers of a particular category, and ensures the checkbox is checked ==
function show(category) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].setVisible(true);
}
}
// == check the checkbox ==
document.getElementById(category+"box").checked = true;
}
// == hides all markers of a particular category, and ensures the checkbox is cleared ==
function hide(category) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].setVisible(false);
}
}
// == clear the checkbox ==
document.getElementById(category+"box").checked = false;
// == close the info window, in case its open on a marker that we just hid
infowindow.close();
}
// == a checkbox has been clicked ==
function boxclick(box,category) {
if (box.checked) {
show(category);
} else {
hide(category);
}
// == rebuild the side bar
makeSidebar();
}
function myclick(i) {
google.maps.event.trigger(gmarkers[i],"click");
}
// == rebuilds the sidebar to match the markers currently displayed ==
function makeSidebar() {
var html = "";
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].getVisible()) {
html += '<a href="javascript:myclick(' + i + ')">' + gmarkers[i].myname + '<\/a><br>';
}
}
document.getElementById("side_bar").innerHTML = html;
}
function initialize() {
var myOptions = {
zoom: 11,
center: new google.maps.LatLng(53.8363,-3.0377),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
// Read the data
downloadUrl("categories.xml", function(doc) {
var xml = xmlParse(doc);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var address = markers[i].getAttribute("address");
var name = markers[i].getAttribute("name");
var html = "<b>"+name+"<\/b><p>"+address;
var category = markers[i].getAttribute("category");
// create the marker
var marker = createMarker(point,name,html,category);
}
// == show or hide the categories initially ==
show("theatre");
hide("golf");
hide("info");
// == create the initial sidebar ==
makeSidebar();
});
}
// This Javascript is based on code provided by the
// Community Church Javascript Team
// http://www.bisphamchurch.org.uk/
// http://econym.org.uk/gmap/
// from the v2 tutorial page at:
// http://econym.org.uk/gmap/example_categories.htm
//]]>
</code></pre>
| <p>To zoom to the last "shown" category, add the markers to a <a href="https://developers.google.com/maps/documentation/javascript/reference#LatLngBounds" rel="nofollow">google.maps.LatLngBounds</a> object, then call <a href="https://developers.google.com/maps/documentation/javascript/reference#Map" rel="nofollow">map.fitBounds</a> with that object as its argument.</p>
<pre><code>// == shows all markers of a particular category, and ensures the checkbox is checked, zooms to the displayed markers of this category ==
function show(category) {
var bounds = new google.maps.LatLngBounds();
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].setVisible(true);
bounds.extend(gmarkers[i].getPosition());
}
}
map.fitBounds(bounds);
// == check the checkbox ==
document.getElementById(category+"box").checked = true;
}
</code></pre>
<p><a href="http://www.geocodezip.com/v3_MW_example_categories_zoom2cat.html" rel="nofollow">working example</a></p>
|
Selenium printing <pre><code>public void Check()
{
String[] List = new String[3];
PageSource = driver.getPageSource();
List[0]= "Test1";
List[1]= "Test2";
List[2]= "Test3";
for (int count = 0; count < List.length; count++)
{
if (PageSource.equals(List))
{
System.out.println(List);
}
else
{
System.out.println("No Match");
}
</code></pre>
<p>}</p>
<pre><code>}
</code></pre>
<p>}</p>
<p>Example: The string from the PageSource is "Test1".</p>
<p>Exepected output:</p>
<p>Test1</p>
<p>Hi, I wanted to just display the string that matched with the string that I'll get from the PageSource. I only want the match printed, if there is no match, "No Match" should be printed. In short, I want to search from all the strings in the array if the string from the PageSource has a match. Please let me know what should I change or add with my code. Thanks!</p>
| <p>i think if your Page Source contains the specific value you are searching, your integer code is always going to print a numeric value. code is printing value of "foundKey" which is a integer in your case, you can change the below line code according to your need: </p>
<pre><code> System.out.println(foundKey)
</code></pre>
|
str.replace function raise erorr that an integer is required <p>I wanna ask the problem I encountered. At first,
Let me show you my whole code</p>
<pre><code>df1 = pd.read_excel(r'E:\ë´ë
¼ë¬¸ìë£\골목ìê¶ ë°ì´í°\ì´íìë¡ 54길 ë´ì©ëºê±°.xlsx' , sheetname='first_day_datas')
df1.registerdate= df1.registerdate.astype(str) # ì¹¼ë¼ ìì± ë°ê¾¸ê¸°
df2 = pd.to_datetime(df1['registerdate'].str[0:10])
df3 = df2['registerdate'].str.replace('-', '').str.strip()
</code></pre>
<p>I just wanna change the string in registerdate column.
when I put print(df2.head(3)). It shows like below</p>
<pre><code>0 2016-10-11
1 2016-10-15
2 2016-10-15
</code></pre>
<p>so I wanna replace '-' with ''.
I type the code and 'TypeError: an integer is required' popped out.
How can I solve this problem??</p>
| <pre><code>df2 = pd.to_datetime(df1['registerdate'].str[0:10])
# \____________/
# returns a series
</code></pre>
<hr>
<pre><code>df2['registerdate'].str.replace('-', '').str.strip()
#\_______________/
# is only something
# if 'registration
# is in the index
# this is probably the source of your error
</code></pre>
<hr>
<p>At this point <code>df2</code> is a <code>pd.Series</code> of <code>Timestamps</code>. the format <code>yyyy-mm-dd</code> is just the way that <code>Timestamp</code> is being displayed. To display it as <code>yyyymmdd</code>, do this</p>
<pre><code>df2.dt.strftime('%Y%m%d')
0 20160331
1 20160401
2 20160402
3 20160403
4 20160404
Name: registerdate, dtype: object
</code></pre>
|
Why does chunk_while return Enumerator Class object <p>Why does chunk_while return Enumerator Class object</p>
<p>This code</p>
<pre><code>array = [0, 1, 2, 3, 4, 5, 7, 8, 9, 15, 16]
p array.chunk_while {|i,j| i + 1 == j }
</code></pre>
<p>print this</p>
<pre><code>#<Enumerator::Generator:0x00000002bef0a8>:each>
</code></pre>
<p>I have ruby version <code>ruby 2.3.1p112 (2016-04-26 revision 54768) [x64-mingw32]</code></p>
| <p>Methods in the <a href="http://ruby-doc.org/core-2.3.0/Enumerable.html" rel="nofollow">Enumerable</a> module, such as <code>chunk_while</code>, require that receivers be enumerators, that is, instances of the class <a href="http://ruby-doc.org/core-2.3.0/Enumerator.html" rel="nofollow">Enumerator</a>. Therefore if an <code>Enumerable</code> method such as <code>chunk_while</code> returns an enumerator, it can be the receiver to another <code>Enumerable</code> method (and that method can be the receiver of another <code>Enumerable</code> method, and so on). This is called <em>method chaining</em>. That's why you see many <code>Enumerable</code> methods return an enumerator if no block is provided. </p>
<p>The chaining of methods that have enumerators as receivers may also include methods in other modules or in the class <code>Enumerator</code>, such as <a href="http://ruby-doc.org/core-2.3.0/Enumerator.html#method-i-with_index" rel="nofollow">Enumerator#with_index</a>.</p>
<p>This is why we can write expressions such as the following.</p>
<pre><code>array.chunk_while {|i,j| i + 1 == j }.map.with_index { |a,i| i.even? ? a.reduce(:+) : 0 }
#=> [15, 0, 31]
</code></pre>
<p>Let's break this down.</p>
<pre><code>e0 = array.chunk_while {|i,j| i + 1 == j }
#=> #<Enumerator: #<Enumerator::Generator:0x007fa01b9639e0>:each>
e1 = e0.map
#=> #<Enumerator: #<Enumerator: #<Enumerator::Generator:0x007fa01b9639e0>:each>:map>
e2 = e1.with_index
#=> #<Enumerator: #<Enumerator: #<Enumerator:
# #<Enumerator::Generator:0x007fa01b9639e0>:each>:map>:with_index>
e2.each { |a,i| i.even? ? a.reduce(:+) : 0 }
#=> [15, 0, 31]
</code></pre>
<p>Examine the return values for the operations that produce <code>e0</code>, <code>e1</code> and <code>e2</code>. <code>e1</code> and <code>e2</code> may be thought of as <em>compound iterators</em>.</p>
<p>As a matter of practice, <code>chunk_while</code> is almost always chained to another method, so it makes sense for it to return an enumerator.</p>
<p>You might well ask, "why must all enumerable methods require a receiver that is an enumerator, considering that <code>chunk_while</code>'s receiver in the example, <code>array</code>, is not an enumerator"? The answer lies in the fact that every class that includes the <code>Enumerable</code> module must have a method <code>each</code> that returns an enumerator. One therefore could write</p>
<pre><code>array.each.chunk_while {|i,j| i + 1 == j }.to_a
</code></pre>
<p>but Ruby saves you the trouble. Ruby will invoke <a href="http://stackoverflow.com/questions/40066614/convert-array-of-hashes-to-array/40066893?noredirect=1#comment67536024_40066893">Array#each</a> for you when it sees that the method being invoked on an array requires an enumerator as its receiver. The same is true of all classes that have a method <code>each</code>.</p>
|
Creating a New Variable in SPSS with a Value Equal to Another Variable <p>I apologize for the confusing title. Essentially, the intended functionality in SPSS is working with the following data file:</p>
<pre><code>Monday Tuesday Wednesday Day of Interest Temperature on Day of interest
72 78 80 2
</code></pre>
<p>Here we have three variables and then the temperature for each of those days. The goal is to create a new variable, in the example it's Temperature on Day of Interest, that has the same value as the day it corresponds to (e.g. The second day of the week is a Monday, so we want to temperature on Monday in the new variable column). So the outcome of the syntax should make the data file read:</p>
<pre><code>Monday Tuesday Wednesday Day of Interest Temperature on Day of interest
72 78 80 2 72
</code></pre>
<p>My thoughts are that I can use an If statement, but I'm not sure on exactly how the syntax would be in SPSS. Here is what I have written: </p>
<pre><code>IF (Day of Interest = 2) Temperature on Day of Interest = $Monday.
IF (Day of Interest = 3) Temperature on Day of Interest = $Tuesday.
</code></pre>
<p>Does anyone happen to know how to properly reference the value in various variables in this manner? I hope this is clear, I'll be able to answer any questions!</p>
| <p>Creating some fake data to demonstrate on:</p>
<pre><code>data list list/Sunday Monday Tuesday Wednesday Thursday Friday Saturday Day_of_Interest .
begin data
41 42 43 44 45 46 47 2
51 52 53 54 55 56 57 6
61 62 63 64 65 66 67 4
71 72 73 74 75 76 77 7
81 82 83 84 85 86 87 1
end data.
</code></pre>
<p>Now it is possible of course to work with separate IF statements like this:</p>
<pre><code>IF (Day_of_Interest = 2) Temperature_on_Day_of_interest = Monday.
IF (Day_of_Interest = 3) Temperature_on_Day_of_interest = Tuesday.
IF (Day_of_Interest = 4) Temperature_on_Day_of_interest = Wednesday.
EXECUTE.
</code></pre>
<p>But instead of creating seven separate statements for seven days, you can use a loop this way:</p>
<pre><code>do repeat Dname=Sunday Monday Tuesday Wednesday Thursday Friday Saturday/Dval=1 2 3 4 5 6 7.
IF (Day_of_Interest = Dval) Temperature_on_Day_of_interest = Dname.
end repeat.
EXECUTE.
</code></pre>
|
Bluetooth BLE programming import error <p>everyone !</p>
<p>I am designing a <strong>Bluetooth BLE 4.0</strong> application and I firstly copied a sample application from the internet to see how to develop it.<br>
I expect to see somebody else to write search and display and do some works on BLE device. And everything nears OK, except these two underlined errors.</p>
<p><img src="https://i.stack.imgur.com/jTRht.png" alt="enter image description here"></p>
<p>So where should I import these two classes?</p>
<p>Any suggestions would be very helpful! </p>
| <p><a href="https://developer.android.com/reference/android/bluetooth/le/ScanCallback.html" rel="nofollow">ScanCallback</a> and <a href="https://developer.android.com/reference/android/bluetooth/le/ScanResult.html" rel="nofollow">ScanResult</a> were only added in API 21.<br>
Make sure that API 21 is installed and also the project's build target is set o >= 18.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.