text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Mantis bugnotes formatting
Is it possible to format bugnotes(comments) entered in Mantis bug tracker for an issue ?
I am using Mantis v1.0.8
e.g.
"sample mantis bug notes"
which appears as plain text.
I would like to make it bold or to display in different color
e.g. similar to https://stackoverflow.com/editing-help
does any other bug tracking system allow such feature ?
A:
As it was said by Gawcio and mhu, the list is limited and in current mantis 1.2.15 use of following tags is allowed in description and other multi-line fields: <p>, <li>, <ul>, <ol>, <br>, <pre>, <i>, <b>, <u>, <em>, <strong>.
Additionally, following tags are allowed in summary and other single-line fields (e.g. OS or Platform): <i>, <b>, <u>, <em>, <strong>. That's funny to have some emphasis in issue summary, right? :)
What is not explicitly said, is that these lists are customizable. Unfortunately, they are so-called global settings, so they can't be set using web interface, but if you have a possibility of tweaking the installed mantis code, you can modify the <mantis-doc-root>/config_inc.php file (which is purposed to be modified locally) and add following options there:
/**
* These are the valid html tags for multi-line fields (e.g. description)
* [...]
*/
$g_html_valid_tags = 'p, li, ul, ol, br, pre, i, b, u, em, strong, code';
/**
* These are the valid html tags for single line fields (e.g. issue summary).
* [...]
*/
$g_html_valid_tags_single_line = 'i, b, u, em, strong, code';
After server restart, you should be able to use the <code> tag in summary and description of your issues.
Unfortunately, mantis tags filters seem to disallow any tag attributes, so it won't be easy to allow free formatting. Personally, I have adjusted its style sheet to tweak the colour in which content of <pre> and <code> tags is displayed. To achieve it, you can edit the <mantis-doc-root>/css/default.css` file and add/adjust following rules:
pre { margin-top: 0px; margin-bottom: 0px; color: #0000CC; }
code { color: #0000CC; }
em > strong { color: #CC0000; }
This way your report may gain some colours :)
A:
In Mantis one can use some of HTML tags (unfortunately not all are supported). From my experience (as I remember well) I've successfully used: <B>, <I>, <U>, <S> and lists, both ordered <OL><LI> and unordered (bullets): <UL><LI>. It makes notes and descriptions more readable.
Currently I'm using 1.1.8 version of Mantis but I was successfully using it in older version (prior to 1.0) - so yours should also handle that.
| {
"pile_set_name": "StackExchange"
} |
Q:
OSMDroid/OSMBonusPack adding marker with info bubble on marker click
I've written some simple code to add a mapview to my app and then add markers to the mapview. What I would like to happen is when the user taps on the marker it should bring up an information bubble with more information about the marker such as the marker title. I've found there isn't a huge amount of information on the internet about OSMDroid and I was wondering if anyone knows a simple way of doing this?
my code for adding a marker to my mapview:
// create GeoPoint
GeoPoint mGeoP = new GeoPoint(51.000000, -2.000000);
// build a new marker pin
Marker mPin = new Marker(mapView);
mPin.setPosition(mGeoP);
mPin.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
mPin.setIcon(getResources().getDrawable(R.drawable.ic_green_pin2));
mPin.setTitle("POINT");
// add new marker pin to map
mapView.getOverlays().add(mPin);
mapView.invalidate();
A:
Problem solved:
Turns out i was missing the .XML and .PNG files needed to create the bubble!
| {
"pile_set_name": "StackExchange"
} |
Q:
Syntax highlighting strongly varying from one color scheme to another
I currently have lots of documentation to write in markdown and, therefore, I'd like my favorite editor to properly syntax-highlight it.
Problem is: the default color scheme of SublimeText (in my case, Monokai) doesn't seem to make a good use of colors with markdown. See by yourself.
That being, while searching for a solution, I found a comment on github mentioning other color schemes working way better for markdown: Cobalt, Dawn and Sunburst.
The thing is I'm pretty used to Monokai (never switched to another color scheme so far) and I'd like to avoid switching everytime I have to work with markdown.
Why does syntax highlight vary that much while I'm only using non-exotic themes ?
More important: what can I do ?
A:
It's slightly annoying, but you can customize the existing color scheme. You simply need to determine the scopes for certain blocks of code, then create a color "binding" for that. I'd recommend copying the contents of the Monokai color scheme out and saving it in Packages/User. That way, you aren't messing up the built in one if you accidentally mess things up beyond repair. This also makes it easy to move the color scheme between machines (if that applies to you).
To determine scope, I'd recommend using ScopeHunter. There is built in functionality also, but I like ScopeHunter better (but that's a personal preference). To find the default key bindings, search for the command "show_scope_name`. You can look at the entries already there for an example of how to set up colors, though if you need some additional clarification, please comment as such. Oh and if you would rather work in JSON instead of XML, you might also want to take a look at PlistJsonConverter
As an alternative, you can try to find someone who has already made the appropriate modifications to the color scheme file.
| {
"pile_set_name": "StackExchange"
} |
Q:
AngularJS: how can I call a function after certain time interval?
My Scenario is:
I want to call logout function after let say 30 mins automatically in my app. Is this possible to acheive this? And more over i want to know the time of user's last interactivity with my application. Can anybody help me regarding this??
A:
Use below for any function that requires time out. But I will not suggest this for Logout. Better you can use browser session to logout after 30 min.
$timeout(function() {
// your code
}, 3000); // 3 seconds
A:
use setTimeout() pure javascript function that can be invoked after a time of interval
setTimeout(function(){
logout();
},5000)
| {
"pile_set_name": "StackExchange"
} |
Q:
What timezone are Magento cron jobs being run in?
My system's timezone is US/Eastern, my default store is US/Central and the database is UTC. At what time will the following doStuff method be called?
<mymodule_do_stuff>
<schedule><cron_expr>15 0 * * *</cron_expr></schedule>
<run>
<model>mymodule/observer::doStuff</model>
</run>
</mymodule_do_stuff>
Update: I ran this script .
echo date('r'), PHP_EOL;
require_once 'app/Mage.php';
Mage::app();
echo date('r'), PHP_EOL;
and got
Mon, 30 Dec 2013 18:01:33 -0600
Tue, 31 Dec 2013 00:01:34 +0000
So it looks like UTC is what I should be using.
A:
The default time used will be the system time of linux. Use the date function on the command line to find out what it is set to.
Magento 'overwrites' that by setting the locale to whatever you have specified during the installation of the shop. This is specified in the System > Configuration > General per store or on default scope.
A:
Times stored in the cron_schedule table are in UTC, but Magento converts it to your store's configured timezone (general/locale/timezone) when checking if a job should run.
I recommend installing Aoe_Scheduler to get a better idea of when your store's cron jobs are being run.
| {
"pile_set_name": "StackExchange"
} |
Q:
using TRDSConnection component in Delphi
Someone can explain me what is the use of ADO component TRDSConnection.y give an small example of use.
Thanks in advance.
A:
From MS doc:
The Microsoft Remote Data Service (RDS) allows you to use an ADO recordset remotely across one of three protocols (HTTP, HTTPS, or DCOM). RDS was originally intended for Web-based clients, but you are free to implement your RDS client in any development environment or language you choose. You can optionally implement a server side business object for generating and receiving a recordset, or you can use the default business object that RDS provides within its server-side components. You are required to use Internet Information Server (IIS) to host the RDS Server components only if using the HTTP or HTTPS protocols. Using DCOM to marshal objects (recordset or otherwise) with RDS eliminates the IIS dependency. RDS provides the advantages of client-side caching of data results, updateable data, and support for some data-aware ActiveX controls.
RDS demo (Up to Delphi2007): in ...Documents\RAD Studio\5.0\DEmos\DelphiWin32\VCL\ADO\RDS for D2007.
Very rudimentary server and client (look in Appserver.pas and ClientMain.pas). You can try and combine it with the AdoTest Demo in the sibling folder.
see also:
http://edn.embarcadero.com/article/28502
http://msdn.microsoft.com/en-us/library/ms676550%28VS.85%29.aspx
http://msdn.microsoft.com/en-us/library/ms677528%28VS.85%29.aspx
Note: Do not forget to modify Windows\MSDFMAP.INI as indicated in ClientMain.pas
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use . in re.match()
I want to make a basic chat program using socket and I want to ask client the address. The address format is IP port. IP is like num.num.num.num and port is just a 4 or 5 digit number. I want to use re.match function to check if inpu is a valid address. How can I use . as character?
A:
To use . as a character in regular expressions, escape it with a backslash like this: \.
So, to match an IP port address, you could use:
[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*
Edit: As suggested in the comments, for more accurate IPv4 matching you would need to limit the number of digits in each number, like this:
\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}
| {
"pile_set_name": "StackExchange"
} |
Q:
Implementing Java's getResponseCode() in C?
If it's any help, there is also a similar class in C#'s WebRequest. Although I do not want it in java or .NET, i am wondering how to implement this in native C/C++ code (for windows).
for reference:
try {
URL url=new URL("http://google.ca");
HttpURLConnection con=(HttpURLConnection)url.openConnection();
con.connect();
int code = con.getResponseCode();
System.out.println(code);
} catch (MalformedURLException e) {
System.err.println("Error reading URL.");
}
prints out:
200
meaning "OK"
I understand I probably need to use sockets and send a User-Agent string, but I haven't a clue where to begin. Whenever I learn a new language the first thing I like to do is try porting my code to it, but this one has stumped me.
Any help is appreciated
A:
There is no HTTP support in standard C library.
So you have two options - use 3rd-party HTTP library, such ar libcurl, or handle HTTP yourself:
open socket
resolve hostname
connect to server
build HTTP request
send request to server
receive HTTP response
parse response and get response code from it.
| {
"pile_set_name": "StackExchange"
} |
Q:
List if-else not giving the expected result
I have the following list of list:
[['3', 2], ['2370447', 282], ['5300058', 610], ['81615', 615], ['3294332', 624], ['3078798', 624], ['1804986', 643]]
Please note that in index 5 and 6, the second item is identical. I am trying to turn this list ordered on the second item in each list into a ranking.
I used the following if-else to correct for time when values were the same:
for i in range(len(sortedCounts)):
if i == 0:
sortedCounts[i][1] = 0
elif sortedCounts[i][1] == sortedCounts[i-1][1]:
sortedCounts[i][1] = i-1
else:
sortedCounts[i][1] = i
However, when I print the list, I am getting different rankings even when the numbers are the same:
[['3', 0], ['2370447', 1], ['5300058', 2], ['81615', 3], ['3294332', 4], ['3078798', 5], ['1804986', 6]]
Expected output is:
[['3', 0], ['2370447', 1], ['5300058', 2], ['81615', 3], ['3294332', 4], ['3078798', 4], ['1804986', 6]]
Appreciate any advice, or if there is a better way, please advise.
A:
rank, last_value = -1, -1
for i, e in enumerate(sortedCount):
if last_value < e[1]:
rank = i
last_value = e[1]
sortedCount[i][1] = rank
| {
"pile_set_name": "StackExchange"
} |
Q:
Store AutoFilter Row Numbers using VBA
How do I store and retrieve the row numbers returned from an AutoFilter action using VBA? For example, I used @brettdj code from this question (see code below) to delete all rows with "X" under column B. Now I need to store the row numbers with X (B4,B6,B9 - see screen shots below) because I need to delete the same rows on other sheets in the same workbook.
Sub QuickCull()
Dim ws As Worksheet
Dim rng1 As Range
Set ws = Sheets("Sheet1")
Set rng1 = ws.Range(ws.[b2], ws.Cells(Rows.Count, "B").End(xlUp))
Application.ScreenUpdating = False
With ActiveSheet
.AutoFilterMode = False
rng1.AutoFilter Field:=1, Criteria1:="X"
rng1.Offset(1, 0).EntireRow.Delete
.AutoFilterMode = False
End With
Application.ScreenUpdating = True
End Sub
A:
Using the code from Is it possible to fill an array with row numbers which match a certain criteria without looping? you could return these rows quickly without the AutoFilter
For example, this code will return a range of rows where X is found within B2:B50000
Sub GetEm()
Dim StrRng As String
StrRng = Join(Filter(Application.Transpose(Application.Evaluate("=IF(B2:B50000=""X"",""B""&ROW(B2:B50000),""X"")")), "X", False), ",")
If Len(StrRng) > 0 Then MsgBox Range(StrRng).EntireRow.Address & " could be deleted elsewhere"
End Sub
| {
"pile_set_name": "StackExchange"
} |
Q:
Ajax AutoCompleteExtender - automatically highlight first item
Is it possible to automatically highlight the first item of the list created by the Ajax Control Toolkit's AutoCompleteExtender?
I would like the first item to be highlighted the same way it would be if the user presses down key when the textbox is selected and the autocomplete list is visible. This would make the textbox be filled with the highlighted value if the user presses tab afterwards.
This is the code for the basic AutoCompleteExtender field:
<asp:TextBox ID="namebox" runat="server"></asp:TextBox>
<cc1:AutoCompleteExtender ServiceMethod="GetNames"
MinimumPrefixLength="1"
CompletionInterval="100" EnableCaching="false" CompletionSetCount="10"
TargetControlID="namebox"
ID="AutoCompleteExtender1" runat="server" FirstRowSelected="false"
OnClientItemSelected="HandleChange_Name"
>
</cc1:AutoCompleteExtender>
A:
Seems that I completely missed the option firstRowSelected property already visible in the code of the question. It was enough to set it to true.
Eventually I found this reading the documentation in the AutoCompleteExtender Wiki page on GitHub.
| {
"pile_set_name": "StackExchange"
} |
Q:
Possible to make a form button take multiple actions?
I am wondering if it is possible to make a submit form button take multiple actions. Currently I am using custom made form that will be sent to a Google Spreadsheet using AJAX. I am also using the Blueimp Jquery File Upload plugin. What I am hoping for is that onsubmit all relevant information can be sent to the Google Spreadsheet and the uploaded image sent to my server. I am open to any potential solution that does not involve Blueimp Jquery Upload and am using Google Spreadsheets to allow accessibility to the data for multiple collaborators.
I apologize for any details left out as I am not well versed in file uploads, but please ask and I will do my best to present any and all relevant information.
Google Spreadsheet submit code:
// Handle form submission
$('form').submit(function(e) {
var button = $('input[type=submit]', this),
data = $(this).serialize();`
e.preventDefault();
if (validate($(this))) {
button.button('loading');
$.ajax({
type: 'POST',
url: formUrl,
data: data,
complete: function() {
button.button('reset');
window.location = 'index.html#new';
}
});
}
function validate(form) {
$('.control-group').removeClass('error');
$('input, textarea', form).each(function() {
var tag = $(this)[0].tagName.toLowerCase(),
type = $(this).attr('type');
// Validate radio buttons
if (tag === 'input' && type === 'radio') {
var name = $(this).attr('name');
if ($('[name="' + name + '"]:checked').length < 1) {
$(this).parent().parent().parent().addClass('error');
}
}
// Validate text fields
if ((tag === 'input' && type === 'text') || tag === 'textarea') {
if ($(this).val() === '' && !$(this).parent().hasClass('radio')) {
$(this).parent().parent().addClass('error');
}
}
});
if ($('.control-group.error').length < 1) return true;
$('.control-group.error').length
$('html, body').animate({
scrollTop: $('.control-group.error').offset().top - 20
}, 500);
return false;
}
});
A:
If you have a form submission button (or any other input for that matter):
<button href="#" id="formButton" type="button">Submit</button>
Using JavaScript, you create a click event on the button to do the form submission:
$('#formButton').click(submitMultipleForms());
And then in your function you can then submit the forms. Each form should have an id:
function submitMultipleForms() {
$("#form1").submit(function() { //Handler for form1
});
$("#form2").submit(function() { //Handler for form2
});
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Merging multiple related firebird select procedure using If else or case method
How to merge this two firebird select procedure using this REFERENCE variable thru if else, case, or other method. If REFERENCE = 1 then the procedure 1 will display, if REFERENCE = 2 then the procedure 2 will display. I am trying to have 1 select procedure with conditions rather than 2 procedure.
CREATE PROCEDURE PRINT_NON_REF1(
M VARCHAR(50) CHARACTER SET ISO8859_1 COLLATE ISO8859_1,
Y VARCHAR(50) CHARACTER SET ISO8859_1 COLLATE ISO8859_1,
REFERENCE VARCHAR(50) CHARACTER SET ISO8859_1 COLLATE ISO8859_1)
RETURNS(
AP_PSTIONLVL_NON VARCHAR(50) CHARACTER SET ISO8859_1 COLLATE ISO8859_1,
AP_POSTION_NON VARCHAR(50) CHARACTER SET ISO8859_1 COLLATE ISO8859_1,
RANKING_MONTH VARCHAR(50) CHARACTER SET ISO8859_1 COLLATE ISO8859_1,
RANKING_YEAR VARCHAR(50) CHARACTER SET ISO8859_1 COLLATE ISO8859_1)
AS
BEGIN
FOR
SELECT
'',
'',
RANKING_MONTH,
RANKING_YEAR
FROM APPLICANT
WHERE RANKING_MONTH = :M AND RANKING_YEAR = :Y
GROUP BY
RANKING_MONTH,
RANKING_YEAR
INTO
:AP_PSTIONLVL_NON,
:AP_POSTION_NON,
:RANKING_MONTH,
:RANKING_YEAR
DO
BEGIN
SUSPEND;
END
END;
and
CREATE PROCEDURE PRINT_NON_REF2(
M VARCHAR(50) CHARACTER SET ISO8859_1 COLLATE ISO8859_1,
Y VARCHAR(50) CHARACTER SET ISO8859_1 COLLATE ISO8859_1,
REFERENCE VARCHAR(50) CHARACTER SET ISO8859_1 COLLATE ISO8859_1)
RETURNS(
AP_PSTIONLVL_NON VARCHAR(50) CHARACTER SET ISO8859_1 COLLATE ISO8859_1,
AP_POSTION_NON VARCHAR(50) CHARACTER SET ISO8859_1 COLLATE ISO8859_1,
RANKING_MONTH VARCHAR(50) CHARACTER SET ISO8859_1 COLLATE ISO8859_1,
RANKING_YEAR VARCHAR(50) CHARACTER SET ISO8859_1 COLLATE ISO8859_1)
AS
BEGIN
FOR
SELECT
AP_PSTIONLVL_NON,
AP_POSTION_NON,
RANKING_MONTH,
RANKING_YEAR
FROM APPLICANT
WHERE RANKING_MONTH = :M AND RANKING_YEAR = :Y
GROUP BY
AP_PSTIONLVL_NON,
AP_POSTION_NON,
RANKING_MONTH,
RANKING_YEAR
INTO
:AP_PSTIONLVL_NON,
:AP_POSTION_NON,
:RANKING_MONTH,
:RANKING_YEAR
DO
BEGIN
SUSPEND;
END
END;
A:
You may try a construct like this:
WITH
Q_2 as (
SELECT
AP_PSTIONLVL_NON,
AP_POSTION_NON,
RANKING_MONTH,
RANKING_YEAR
FROM APPLICANT
WHERE RANKING_MONTH = :M
AND RANKING_YEAR = :Y
GROUP BY
AP_PSTIONLVL_NON,
AP_POSTION_NON,
RANKING_MONTH,
RANKING_YEAR
),
Q_1 as (
SELECT
'',
'',
RANKING_MONTH,
RANKING_YEAR
FROM APPLICANT
WHERE RANKING_MONTH = :M
AND RANKING_YEAR = :Y
GROUP BY
RANKING_MONTH,
RANKING_YEAR
)
SELECT * FROM Q_2 WHERE :REFERENCE=2
UNION ALL
SELECT * FROM Q_1 WHERE :REFERENCE=1
Things to notice:
Making a stored procedure which contains nothing but a single SELECT is bad idea in Firebird/Interbase. It will disable SQL optimizer job on joining, and will add nothing of value. Firebird is not MS SQL.
The second query was set first in the unioned chain, because it is the first query where UNION takes column names and data types from. Would Q_1 go first - the two anonymous columns would be a problem.
Some database access libraries might have problems with several parameters in a query having same names. You might need to rename :M into :M_1 and :M_2, etc. Or maybe not, test your library.
Your specific programming language/library can have different SQL parameters syntax than :name used above. Especially, that Firebird itself on SQL level only supports unnamed parameters. Check your library documentation. You might also get insights reading code examples at https://bobby-tables.com/
Read documentation about UNION and CTE (Common Table Expressions) at https://firebirdsql.org/file/documentation/reference_manuals/fblangref25-en/html/fblangref25-dml-select.html
| {
"pile_set_name": "StackExchange"
} |
Q:
JSON-like Object Syntax In Java
I hate to ask something so trivial, but I can't work this one out. I'm trying to create a basic object for convenience, like this:
triangle = {
side: { A: 0, B: 0, C: 0 },
angle: { a, b, c },
function calcAngle(){}
}
Ideally, I'd like to just create a generic object on the fly. I'm only creating one "triangle", must I create a whole class for one instance? I'm sure this is answered somewhere, but I can't seem to word the question right for anything useful. For your amusement I'll post some of my failures:
public class TGUI{
// Attempt One
public Object triangle = new Object(){ int test; };
public static void main(String[] args) {
triangle.test = 1;
// ^- Cannot make a static reference to the non-static field triangle
triangle tri = new triangle();
// ^- Made the compiler cry; triangle cannot be resolved to as type
}
// Attempt Two
public class triangle{ int test; }
public static void main(String[] args) {
triangle tri = new triangle();
/* ^- No enclosing instance of TGUI is accessible. Must qualify the allocation with an enclosing instance of type TGUI (eg x.new A() where x is an instance of TGUI) */
}
// Attempt Three
public void triangle(){ int test = 1; }
public static void main(String[] args) {
triangle tri = new triantle();
// ^- triangle cannot be resolved to a type
}
// Attempt Four
public TGUI(){ int test; }
/* I'm gonna quit here, you get the idea */
}
A:
Attempt 2 was closer. You needed a nested static class:
public static class triangle{ int test; }
(or triangle can be in a separate file).
It's still far from how Java operates on its static type system.
| {
"pile_set_name": "StackExchange"
} |
Q:
Query inside while loop repeats results from 2 tables
I am not sure if the title expresses the problem accurately or not. Anyways, here is the explanation:
I have 2 tables, the first one holds users IDs, the other one holds their posts.
The fist query selects user IDs from the fist table, and it loop through the second table to find the users (IDs) posts.
The problem is that when the query finds eg. 5 results (user IDs 1, 6, 999.. etc) in the fist table, then it loops 5 times to search in the second table, it shows 5 results even if the real results is 2 post only created by user 1 and 6.
How can I avoid this repeatation?
Here is the code:
$stmt = $conn->prepare('select userid from table where para=?');
$stmt->bind_param('i', $para);
$stmt->execute();
$result = $stmt->get_result();
while( $row = $result->fetch_assoc()) {
$userid = $row["userid "];
$qname = "select postid,title from posts where uid='$userid'";
$result2 = $conn->query($qname);
$row2 = $result2->fetch_array(MYSQLI_ASSOC);
if ($row2 > 0) {
$postid= $row2['postid'];
$title= $row2['title'];
}
echo $postid." ".$title."<br>";
}
A:
Try
$qname = "select postid,title from posts as P left join table as T on T.userid=P.uid where where para=?";
Or
You can store the results in a common array during the loop.
like
$tempResult = array();
while( $row = $result->fetch_assoc()) {
$userid = $row["userid "];
$qname = "select postid,title from posts where uid='$userid'";
$result2 = $conn->query($qname);
$row2 = $result2->fetch_array(MYSQLI_ASSOC);
if ($row2 > 0) {
$tempResult[$userid][] = $row2['postid'];
$tempResult[$userid][] = $row2['title'];
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Was the word “communist” used prior to Marxist/Leninist writings?
The word 'communism' and 'communist' were certainly popularized by the title of 'The Communist Manifesto' by Mark and Engels.
But was the word 'communist' used prior to Marxist writings? Or was it coined for use in the Communist Manifesto?
A:
The word was used in English in 1840 according to the OED, which I believe narrowly beats out Marx’s writings:
Noun:
The Communists have their meetings, and the Radical Reformers, who do not go the length of an agrarian law, dine together in numbers.
1840 Morning Chron. 13 July 2/7
Adjective:
A social banquet of the adherents of the Communist, or Communitarian school is expected to take place.
1840 J. G. Barmby in New Moral World 1 Aug. 75/1
Communism:
A man named Dufraisse..concluded with an exposition of the doctrines of Communism..much the same as what Mr. Owen preaches in England, under the name of Socialism.
1840 N.-Y. Spectator 22 Aug. 2/1
Both communist and communism in this sense come from French.
| {
"pile_set_name": "StackExchange"
} |
Q:
Mortarboard / Epic / Legendary badges threshold too high?
I was looking through badges, and I've noticed that those three actually have a really high threshold to be reached in order to be awarded (compared to the difficulty of the task itself), proven by the fact that only 391 users have been awarded Mortarboard, only 5 have been awarded Epic and none has ever been awared Legendary. Perhaps an escalation along the lines of Popular Question / Notable Question / Famous Question like 1 (Mortarboard) - 25 (Epic) - 100 (Legenday) would fit better?
Leaderboard here!
A:
No, I don't think they are too high. Each SE site has its own voting culture, and it's been noted time and again that we don't vote much - we vote less than, for example, Unix & Linux. We have only two 100k users, U&L have two of those and one 200k user. They also have awarded the Legendary badge thrice. Yet we best them on all but one of the traffic stats. We are just a tough community.
A:
The Legendary badge is there to be hard to get. Epic was not that hard to get :)
"and none has ever been awared Legendary"
One of us soon will reach it. I am not that one by the way since I am on 76/150 (in case anyone wonders how to find out: see https://askubuntu.com/reputation at the bottom).
Quality over quantity :D
| {
"pile_set_name": "StackExchange"
} |
Q:
Most efficient way to subset a dataframe according to matching values between two dataframes
I have two dataframes, df1 and df2. I want to subset df1 so that I only get the area-time pairs present in df2.
What is the most efficient way to do this in R? (Python too would be a bonus)
df1=structure(list(area = c("1", "1", "1", "1", "1", "1"), time = c(12138L,
12198L, 12659L, 12670L, 12672L, 12719L)), .Names = c("area", "time"
), row.names = c(NA, 6L), class = "data.frame")
df2=structure(list(area = c("1", "1", "1", "1", "1", "1"), time = c(12138L,
12198L, 12266L, 12272L, 12284L, 12332L)), .Names = c("area", "time"
), row.names = c(NA, 6L), class = "data.frame")
A:
If your example is representative of your data try:
merge(df1,df2)
area time
1 1 12138
2 1 12198
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I add a service to Finder to add a movie/track to a VLC playlist?
I am using VLC for playing videos in MacOSX 10.8, the VLC version is 2.0.5, I want a context menu in Finder with option to add a video file to vlc now playing list.
A:
Using the Open With to make sure you open the file with VLC will add it to the current playlist
| {
"pile_set_name": "StackExchange"
} |
Q:
How to convert a numeric value into a Date value
So, I have a data.frame with a column called Date.birth, but I have these values in a numeric format:
Date.birth
43067
43060
Probably is problem format. But I need in a Date format like these:
Date.birth
11/28/17
11/21/17
Actually the above format is the correct. I tried this command:
as.Date(levels(data$Date.birth), format="%d.%m.%Y")
but didn't work. Anyone has a suggestion?
Thanks.
A:
We need to specify the origin if it is a numeric value
as.Date(data$Date.birth, origin = "1899-12-30")
e.g.
as.Date(43067, origin = "1899-12-30")
#[1] "2017-11-28"
After converting to Date class, if it needs to be in a custom format, use format
format(as.Date(43067, origin = "1899-12-30"), "%m/%d/%y")
#[1] "11/28/17"
If your column is factor, do convert to numeric first
as.Date(as.numeric(as.character(data$Date.birth)), origin = "1899-12-30")
A:
If this is an excel numeric date, janitor has a great solution:
library(janitor)
excel_numeric_to_date(data$Date.birth)
| {
"pile_set_name": "StackExchange"
} |
Q:
How to switch the code from Select Range (Input Box) to Row Count?
Current Code is provided below. The user selects the Range of cells from which unique values needs to be found out. Instead of this, I know the Range of cells which is entire Column B of Sheet Database. I tried switching the code by the code below but it's giving "Run-time error '424': Object Required" where I am trying to count the number of rows with data.
Sheets("Database").Activate
last_row = Cells(Row.Count, "B").End(xlUp).Row <- Error
Set rngTarget = Sheets("Database").Range("B2:B" & last_row)
If rngTarget Is Nothing Then Exit Sub
Current Code:
strPrompt = "Select the Range from which you'd like to extract uniques"
On Error Resume Next
Set rngTarget = Application.InputBox(strPrompt, "Get Range", Type:=8)
On Error GoTo 0
If rngTarget Is Nothing Then Exit Sub
Changed Code: (Doesn't work - Gives Run-Time Error)
Sheets("Database").Activate
last_row = Cells(Row.Count, "B").End(xlUp).Row <- Error
Set rngTarget = Sheets("Database").Range("B2:B" & last_row)
If rngTarget Is Nothing Then Exit Sub
rngTarget function should contain the range of cells from which unique values needs to be found out.
Update 1
Complete Code for reference:
Public Sub WriteUniquesToNewSheet()
Dim wksUniques As Worksheet
Dim rngUniques As Range, rngTarget As Range
Dim strPrompt As String
Dim varUniques As Variant
Dim lngIdx As Long
Dim last_row As Long
Dim colUniques As Collection
Set colUniques = New Collection
'Prompt the user to select a range to unique-ify
'strPrompt = "Select the Range from which you'd like to extract uniques"
'On Error Resume Next
' Set rngTarget = Application.InputBox(strPrompt, "Get Range", Type:=8)
'On Error GoTo 0
'If rngTarget Is Nothing Then Exit Sub '<~ in case the user clicks Cancel
Sheets("Database").Activate
last_row = Cells(Row.Count, 2).End(xlUp).Rows
Set rngTarget = Sheets("Database").Range("B2:B" & last_row)
If rngTarget Is Nothing Then Exit Sub
'Collect the uniques using the function we just wrote
Set colUniques = CollectUniques(rngTarget)
'Load a Variant array with the uniques
'(in preparation for writing them to a new sheet)
ReDim varUniques(colUniques.Count, 1)
For lngIdx = 1 To colUniques.Count
varUniques(lngIdx - 1, 0) = CStr(colUniques(lngIdx))
Next lngIdx
'Create a new worksheet (where we will store our uniques)
Set wksUniques = Worksheets("Lists")
Set rngUniques = wksUniques.Range("A2:A" & colUniques.Count + 1)
rngUniques = varUniques
'Let the user know we're done!
MsgBox "Finished!"
End Sub
A:
To get you started, you have refered to Row instead of a range object representing all Rows. Follow the links to see the difference :)
Next you have used .Activate and therefor not specified what worksheet you working from. A better practice would be to use something like:
With Thisworkbook.Sheets("Database") 'Can even be dereferenced from worksheets collection
last_row = .Cells(.Rows.Count, "B").End(xlUp).Row
Set rngTarget = .Range("B2:B" & last_row) 'Tricky if last_row is 1
If rngTarget Is Nothing Then Exit Sub 'Superfluous and can be deleted
End with
| {
"pile_set_name": "StackExchange"
} |
Q:
Change value in dictionary of dictionary
I want to change values I have stored in a dictionary of dictionaries.
This is the code I tried to implement. The problem is p remains the same, and I'm not sure how to update p.
j = {'a':1.0}
k = {'c':3.0}
p = {'e':j,'f':k}
for n in p.itervalues():
print n
n = {key:value/3.0 for key, value in n.items()}
print n
print p
A:
You need to assign the updated value back to the original dictionary.
j = {'a':1.0}
k = {'c':3.0}
p = {'e':j,'f':k}
for k,v in p.items():
p[k] = {key:value/3.0 for key, value in v.items()}
print p
| {
"pile_set_name": "StackExchange"
} |
Q:
Changes don't propagate through the component
I have the following example of a component that toggles an element (div) when a button is clicked. The problem is that the first click does absolutely nothing: the changes don't propagate at all and it is needed a second click to achieve the desired behaviour.
import { Component } from '@angular/core';
var exec = require('child_process').exec; //electron part
@Component({
selector: 'my-component',
template: `
<button (click)="showDiv()">Toggle Div</button>
<div *ngIf="show" style="width: 50px; height: 50px; background-color: green">
</div>
`
})
export class MyComponent {
private show = false;
public showDiv() {
exec("wmic logicaldisk get caption", function(error, stdout, stderr){
console.log(stdout);
this.show = !this.show;
}.bind(this));
}
}
So the tricky part happens when I try to execute a Windows command prompt command, i.e. wmic logicaldisk get caption using electron packages and update the component after the command returns its values.
In a scenario where some files are being copied using electron (exec("copy a.txt dir", function(error, stdout, stderr){...})) and after the operation ends my component needs to be updated with some status (let's say: Files copied successfully!), this solution won't work.
SO what could be wrong in this approach?
A:
when we change anything out of angular, angular not take account of it. Try use ngZone (I don't know if work)
export class MyComponent {
private show = false;
constructor(private ngZone:NgZone) //<--ID NgZone
public showDiv() {
exec("wmic logicaldisk get caption", function(error, stdout, stderr){
console.log(stdout);
this.ngZone.run(()=>{
this.show = !this.show;
});
}.bind(this));
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there an Emergency Rescue Disc (ERD) that allows for slipstreaming SATA drivers?
I have a computer at work that was baselined with the DISA Gold Disc, to include disabling the built-in admin account and setting its password to something unknown. So, while trying to use the repair console, I can't use it without the password (another Gold Disc setting).
However, my ERD does not have the proper SATA drivers to "see" this drive. And, since I know I'm going to need this soft of disc in the future anyway, I thought I'd ask: Does anyone know of an ER disc that allows one to slipstream the drivers, a la nLite?
A:
You can with any winPE based boot disk. The Ultimate Boot CD for Windows is a personal favorite.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can I use Pro-Tools 9 on my PC and Mac
I am thinking moving to Pro Tools 9 soon, but I am unsure if I can register Pro tools 9 on both my PC and Mac, cause sometimes I need to work on both systems and its going to get messy.
A:
With iLok you can use it on both Systems, however, only one at a time.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is after entering _start rsp is aligned
When programs enter _start routine at the program start does the stack pointer is aligned at 16 byte boundary or it should be manually aligned to that boundary? I mean is it aligned before prologue(push rbp; mov rbp, rsp) in _start?
I know that on x64 at the start of the program the RSP is aligned to 8 bytes,
but do now know is it aligned on 16 byte boundary. For some tasks I might need that alignment to properly execute SSE instructions which require alignment on 16 byte boundary.
A:
The x86-64 ABI explicitly says (3.4.1 Initial Stack and Register State) :
%rsp The stack pointer holds the address of the byte with lowest
address which is part of the stack. It is guaranteed to be 16-byte
aligned at process entry.
Since _start is the first symbol that's called when a process is entered, you can be entirely sure that it is 16-byte aligned when the OS calls _start in your executable.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to print 2 keys from a python dictionary
group is a dictionary and 'Admin Name' and 'Admin Link' are keys in the dictionary.
When I execute the following statement, I receive a KeyError.
print(group['Admin Name','Admin Link'])
How can I print the values corresponding to the aforementioned keys?
A:
Use two subscription expressions, not one. There is no 'Admin Name','Admin Link' key (a tuple with two strings), only 'Admin Name' and 'Admin Link':
print(group['Admin Name'], group['Admin Link'])
Subscription on dictionaries does not support multiple keys, because you can use tuples as keys, e.g. 'Admin Name', 'Admin Link' is a different key from both 'Admin Name' and 'Admin Link':
>>> group = {
... 'Admin Name': 'foo',
... 'Admin Link': 'bar',
... ('Admin Name', 'Admin Link'): 'spam',
... }
>>> print(group['Admin Name', 'Admin Link'])
spam
| {
"pile_set_name": "StackExchange"
} |
Q:
Do not allow null in Mongodb
I am using mongoose. I want to create a field with not null as sql does means when a null value try to insert in a collection, it shouldn't allow to store null value.
A:
You can use Mogoose validators to validate your model before saving it. There is no way for doing it at mongodb level. MongoDB is a NoSQL, schemaless database.
The required option might be useful
SchemaName = mongoose.Schema(
fieldName: {type: type, required: true}
)
| {
"pile_set_name": "StackExchange"
} |
Q:
getting Missing Start Boundary in javax.mail.multipart
I'm trying to read the emails using java mail API.
and when I tries to get count from multipart like this:
multipart.getCount()
I am getting the below exception:
javax.mail.MessagingException: Missing start boundary
at javax.mail.internet.MimeMultipart.parsebm(MimeMultipart.java:872)
at javax.mail.internet.MimeMultipart.parse(MimeMultipart.java:493)
at javax.mail.internet.MimeMultipart.getCount(MimeMultipart.java:240)
Any help is appreciated.
A:
this issue can be resolved with the two properties that MimeMultipart holds...
I was also having the same issue and I resolved it with:
System.setProperty("mail.mime.multipart.ignoreexistingboundaryparameter", "true");
System.setProperty("mail.mime.multipart.allowempty", "true");
When you'll read the MimeMulutiPart.java, you'll find 5 properties:
1. mail.mime.multipart.ignoremissingendboundary(def. true)
2. mail.mime.multipart.ignoremissingboundaryparameter(def. true)
3. mail.mime.multipart.ignoreexistingboundaryparameter(def. false)
4. mail.mime.multipart.allowempty(def. false)
5. mail.mime.multipart.bmparse(def. true)
and when I tried setting the remaining false to true. it worked for me.
| {
"pile_set_name": "StackExchange"
} |
Q:
VerQueryValueA writes invalid memory outside of the resource block
I am retrieving a version string for the current executable using the following code:
// http://stackoverflow.com/questions/13941837/how-to-get-version-info-from-resources
std::string get_version_string()
{
auto hInst = GetModuleHandle(NULL);
// The following functions allocate persistent one-time space in the process's memory - they don't need to have results freed
auto hResInfo = FindResourceA(hInst, MAKEINTRESOURCE(1), RT_VERSION);
auto dwSize = SizeofResource(hInst, hResInfo);
auto hResData = LoadResource(hInst, hResInfo);
char *pRes = static_cast<char *>(LockResource(hResData));
if ( !dwSize || !pRes ) return {};
// Copy is required because VerQueryValue modifies the object, but LoadResource's resource is non-modifiable.
// SizeofResource yielded the size in bytes, according to its documentation.
std::vector<char> ResCopy(dwSize);
std::copy(pRes, pRes + dwSize, ResCopy.begin());
// https://stackoverflow.com/a/1174697/1505939
LPVOID pvFileVersion{};
UINT iFileVersionLen{};
if ( !VerQueryValueA(&ResCopy[0], "\\StringFileInfo\\040904E4\\FileVersion", &pvFileVersion, &iFileVersionLen) )
return "(unknown)"s;
char buf[200];
sprintf(buf, "%p\n%p\n%p", &ResCopy[0], &ResCopy[0] + ResCopy.size(), pvFileVersion);
debug_output ( buf );
auto s = static_cast<char *>(pvFileVersion);
return std::string( s, s + iFileVersionLen );
}
The VerQueryValue documentation, and other SO questions on the topic, indicate that VerQueryValue is supposed to return a pointer into the resource block. However, the output I get is:
000000000594b460
000000000594b748
000000000594b802
Furthermore, if I change the allocation of ResCopy to std::vector<char> ResCopy(dwSize + 0x200); , then I get the output:
000000000594b460
000000000594b948
000000000594b802
and the only thing I can conclude from this is that the VerQueryValueA function is doing an out-of-bounds write in the original case; it's writing past the end of the resource's size as was given by SizeofResource; it's writing outside of my vector.
Even though the function seems to work properly I suspect this might actually be a bug.
My question is: am I doing something wrong, or is this a bug in VerQueryValueA ? And how should I fix the problem?
Note: If I use VerQueryValueW then it does return a pointer inside ResCopy in the first place.
This answer seems to allude to the issue however I'm not using GetFileVersionInfo (which requires a filename, there doesn't seem to be any equivalent function that takes the module handle).
The greater purpose of this is to be able to log my application's version string in the log file, and trying to find and open a file based on filename seems like a bunch more possible points of failure when we have obviously already loaded the executable to be running it.
A:
GetFileVersionInfo() performs fixups and data conversions that VerQueryValue() relies on. Raymond Chen even wrote a blog article about it:
The first parameter to VerQueryValue really must be a buffer you obtained from GetFileVersionInfo
The documentation for the VerQueryValue function states that the first parameter is a "pointer to the buffer containing the version-information resource returned by the GetFileVersionInfo function." Some people, however, decide to bypass this step and pass a pointer to data that was obtained some other way, and then wonder why VerQueryValue doesn't work.
The documentation says that the first parameter to VerQueryValue must be a buffer returned by the GetFileVersionInfo function for a reason. The buffer returned by GetFileVersionInfo is an opaque data block specifically formatted so that VerQueryValue will work. You're not supposed to look inside that buffer, and you certainly can't try to "obtain the data some other way". Because if you do, VerQueryValue will look for something in a buffer that is not formatted in the manner the function expects.
Other than querying the VS_FIXEDFILEINFO at the very beginning of the resource data, it is really not safe to use VerQueryValue() to query other version data from the raw resource data. That data hasn't been prepared for VerQueryValue() to use. The answers to the question you linked to even state this, as does the above article:
If it wasn't obvious enough from the documentation that you can't just pass a pointer to a version resource obtained "some other way", it's even more obvious once you see the format of 32-bit version resources. Notice that all strings are stored in Unicode. But if you call the ANSI version VerQueryValueA to request a string, the function has to give you a pointer to an ANSI string. There is no ANSI version of the string in the raw version resource, so what can it possibly return? You can't return a pointer to something that doesn't exist. VerQueryValueA needs to produce an ANSI string, and it does so from memory that GetFileVersionInfo prepared when the resources were extracted.
For what you are attempting to do, querying the VS_FIXEDFILEINFO from the copied resource is all you need. It contains the version number you are looking for, is language agnostic, and is not dependent on GetFileVersionInfo():
std::string get_version_string()
{
auto hInst = GetModuleHandle(NULL);
auto hResInfo = FindResourceA(hInst, MAKEINTRESOURCE(1), RT_VERSION);
if ( !hResInfo ) return {};
auto dwSize = SizeofResource(hInst, hResInfo);
if ( !dwSize ) return {};
auto hResData = LoadResource(hInst, hResInfo);
char *pRes = static_cast<char *>(LockResource(hResData));
if ( !pRes ) return {};
std::vector<char> ResCopy(pRes, pRes + dwSize);
VS_FIXEDFILEINFO *pvFileInfo;
UINT uiFileInfoLen;
if ( !VerQueryValueA(ResCopy.data(), "\\", reinterpret_cast<void**>(&pvFileInfo), &uiFileInfoLen) )
return "(unknown)"s;
char buf[25];
int len = sprintf(buf, "%hu.%hu.%hu.%hu",
HIWORD(pvFileInfo->dwFileVersionMS),
LOWORD(pvFileInfo->dwFileVersionMS),
HIWORD(pvFileInfo->dwFileVersionLS),
LOWORD(pvFileInfo->dwFileVersionLS)
);
return std::string(buf, len);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
python execution directly via command line linux
how can i run an easy python script and save it in a file but directly in linux command line:
fox@fox:/opt/gera# python -c print "aaaaa" > myfileName
but it is just print nothing instead of "aaaaa".
A:
You have to quote the whole command:
python -c 'print "aaaaa"' > myfileName
Otherwise you execute print in Python (which, in Python 2 prints a linebreak and in Python 3 does nothing since you'd just evaluate the function print without calling it) and pass aaaaa as an argument to the script.
| {
"pile_set_name": "StackExchange"
} |
Q:
My ffmpeg output always add extra 30s of silence at the end
This is a code / argument I use to merge 1 audio and 1 image into 1 video. For some reason it adds 30s silence to the end of output video no matter the source.
I run this on Win10 x64, with latest ffmpeg installed.
I have checked the code but cannot identify where it makes the silence.
ffmpeg -y -loop 1 -framerate 2 -i "some.png" -i "with.mp3"
-c:v libx264 -tune stillimage -c:a aac -b:a 192k -pix_fmt yuv420p -shortest "result.mkv"
The output should not conatin the additional 30s of silence. It should end when audio runs out.
I should add that I copied most of the arguments from some website, and that OP seems to use it just fine, so I'm not sure if this is just my problem.
A:
Use
ffmpeg -y -loop 1 -framerate 2 -i "some.png" -i "with.mp3" -c:v libx264 -tune stillimage -c:a aac -b:a 192k -pix_fmt yuv420p -shortest -fflags +shortest -max_interleave_delta 100M "result.mkv"
Containers (AVI, MP4, MKV) usually store multiple streams in an interleaved fashion i.e. a few seconds of video, then a few seconds of audio, and so on. So ffmpeg buffers data from all streams, when writing.
-shortest acts at a relatively high-level and is triggered when the first of the streams has finished. However, buffered data from other streams will still be written to file. -fflags shortest acts at a lower level and stops the buffered data from being written when used with a sufficiently high max_interleave_delta.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cell walls in Conway's Game of Life?
Do there exist robust structures in Conway's Game of Life? For instance, has anyone constructed a spaceship with a shield that absorbs all small oscillators and gliders it collides with?
A:
See "eaters" category.
They can absorbe gliders and spaceships, but I'm not an expert and I don't know if there are "walls" capable of absorbing everything. Perhaps it is a nice subject to investigate! (see the references at the bottom of Wikipedia pages for modern approaches using constraint solvers).
From the lexicon:
:eater Any still life that has the ability to interact with certain patterns without suffering any permanent damage. (If it doesn't suffer even temporary damage then it may be referred to as a rock.) The eater1 is a very common eater, and the term "eater" is often used specifically for this object. Other eaters include eater2, eater3, eater4 and even the humble block. (In fact the block was the first known eater, being found capable of eating beehives from a queen bee.) Another useful eater is shown below, feasting on a glider.
| {
"pile_set_name": "StackExchange"
} |
Q:
Как удалить строки из огромного (большого) файла
Читать весь файл, размером 500-600 Мб я не могу, так как эти данные грузятся в оперативную память, для меня это слишком затратно.
Читаю файл file_get_content'ом c лимитом строк (условно по 1000 строк). Как мне после этого скажем удалить конкретные строки. Без использования $f = file.
Подробнее:
Я читаю очень большой файл по 1000 строк (первые 1000 строк), по своему их обрабатываю и в зависимости от условий, какие-то строки нужно удалить, а какие-то оставить.
Я могу записывать результат во временный файл, а что если скрипт остановится или что-то еще, а возможности отката нет.
A:
cat myfile.txt | grep -v текст_строки_которого_удалить > newfile.txt
а вообще более подробно опишите, пару строк исходного файла, и что удаляете по какому принципу. Данный выше пример убог, и явно не для вашего случая, но и инфы мало ))
A:
Идея такая.
Вычитываем с файла 100 (200, 1000 строк), фильтруем и пишем в результирующий файл. Потом отмечаем в специальном файле, сколько строк вычитали и с какой позиции (либо просто номер блока). И так далее в цикле.
Если скрипт упадет и его перезапустят, то он вычитает с спец файла метку для старта и начнет обрабатывать далее.
Минусов два:
некоторые блоки будут фильтроваться два раза и более (так как скрипт будет перезапускаться).
нужно как то отмечать в результирующем файле, что весь блок был записан. Например добавлять в конец файла метку, а при записи следующего блока - удалять и добавлять снова в конец.
| {
"pile_set_name": "StackExchange"
} |
Q:
Replace state on Ionic link click
I'm using Ionic and I have a template with a code like this:
<ion-item ng-repeat="model in models" href="#/app/ctrl/{{model.id}}">
{{model.name}}
</ion-item>
When I click the link, the state is changed to another view. Everything is fine.
But how do I replace the current view with the new one without keeping it on history?
I have the following code, which works in a controller:
$ionicHistory.currentView($ionicHistory.backView());
$state.go('app.products', {location: 'replace'});
But I don't know how to achive the same clicking on the link.
A:
According to this docs site you can try this:
<ion-item ng-repeat="model in models"
ui-sref="name.of.state"
ui-sref-opts="{location: 'replace'}">
{{model.name}}
</ion-item>
| {
"pile_set_name": "StackExchange"
} |
Q:
Android run a project on device with automatic signing? how?
I have an app, that uses mapview. i can only see the map, when i signing my apk file, but it is a long time to signing every time. Is there a way to run my mapview .apk file with automatic signing?
How?
Thanks, Leslie
A:
create a mapkey with your debug.keystore and use it in you mapview.
| {
"pile_set_name": "StackExchange"
} |
Q:
run bash script after git clone
I want to run a simple bash script after a git clone was made, that checks the url of the repository origin and applies specific git-author settings.
this configuration shall be done on the local environment (not in the repository).
is there a configuration setting that I can apply to call a bash script after a git clone has completed?
A:
Let us say the bash script you intend to run is in a file by the name shellscript.sh and it is on your path:
You can add the following bash function to your ~/.bashrc.
git() {
if [[ $1 == "clone" ]]; then
command git "$@" && shellscript.sh;
else
command git "$@";
fi;
}
Note: You can add any command after &&.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I copy my database
I am working on visual studio 2010 and i have a database in Server Explorer that i can see that is not in the App_data in the solution explorer.. I need to copy it somewhere to upload it to the host..
I think the database is suitable for SQL server2005 , cause that is the only sql server version installed on my computer with the vs2010.
Here are my connection string:
<add name="YourGuruDB" connectionString="Data Source=DIMA-00AA1DA557;Initial Catalog=model;Integrated Security=True" />
A:
You can back up the database by right click on db and choose back up. Restore it on your host /web server.
| {
"pile_set_name": "StackExchange"
} |
Q:
SQLZOO not accepting answer and showing Skype sign beside my answer
My Table Structure:
And:
I'm trying to solve this problem:
Use COALESCE to print the mobile number. Use the number '07986 444 2266' there is no number given. Show teacher name and mobile number or '07986 444 2266'
My query is:
select name, coalesce (mobile, '07986 444 2266')
from teacher t
Expected result is:
But I'm getting this:
Can anyone explain to me what am I doing wrong? Or is my answer ok, it's that unwanted Skype sign beside the phone numbers that is causing the problem, so SQLZOO is not accepting that as answer?
A:
I actually edited my post, so, my query, after editing, looks like this:
select name, coalesce (mobile, '07986 444 2266')
from teacher t
Before editing, it looked something like this:
select name, coalesce (mobile, '0798 644 2266')
from teacher t
Basically, due to the typo, a skype extension appeared beside my answer. It actually has nothing to do with malwares or any other problems. My query was partially right, only except for the desired result, where there exists a typo.
Previously, my answer was:
After editing and then re-running the query, it returns the correct answer:
Thanks to @TomasPastircak and @MatBailie for pointing out my mistake, I give full credit to them.
Sorry everyone, for asking such a silly question here in SO. My bad!!!
| {
"pile_set_name": "StackExchange"
} |
Q:
Angularjs routconfig for different pages than specified in otherwise
Usually we have following type of config for route in angularjs:
app.config(['$routeProvider',
function($routeProvider) {
//Setting up HTML pages and controllers depending upon the suffix in the URL
$routeProvider.
when('/xyz', {
templateUrl: '/etc/topproducts.html',
controller: 'CategoryListCtrl'
}).
when('/abc/:alphabet?', {
templateUrl: '/etc/allproducts.html',
controller: 'CategoryListCtrl'
}).
otherwise({
redirectTo: '/xyz'
});
}
]);
So if user goes to homepage then he gets redirected to topproducts.html and if he/she types /abc in url then user is shown allproducts.html in my case.
My question how to control which page to be shown if user types unexpected path in url like /blahblah
Since in my config above, otherwise({ is pointing to xyz, user is landing on topproducts.html. I want user to be shown different pages when user types /blahblah and /
A:
If I could understand your problem then you want to Show Page Not Found, if that Url or page doee not exits in config.
Try below
app.config(['$routeProvider',
function($routeProvider) {
//Setting up HTML pages and controllers depending upon the suffix in the URL
$routeProvider.
when('/xyz', {
templateUrl: '/etc/topproducts.html',
controller: 'CategoryListCtrl'
}).
when('/abc/:alphabet?', {
templateUrl: '/etc/allproducts.html',
controller: 'CategoryListCtrl'
}).
otherwise({
templateUrl: myLocalized.partials + '404.html',
controller: '404'
});
}
]);
Your 404 controller will be
app.controller('404', function() {
document.querySelector('title').innerHTML = 'Page not found | AngularJS Demo Theme';
});
And template can be
<h1>Page Not Found</h1>
<p>Sorry, but nothing can be found at this location.</p>
Try this and let me know if it works for you
| {
"pile_set_name": "StackExchange"
} |
Q:
Make input type file required based on condition in AngularJS
I am receiving a JSON data from backend like these
{
"data":{
"xyz":[
{
"number":"1",
"short_text":"Vertrag unterzeichnen",
"long_text":"Nach Vertrabsunterzeichnung Namen eintragen",
"is_photo":false
},
{
"number":"2",
"short_text":"HR unterrichten",
"long_text":"HR hat eigene Workflows",
"is_photo":true
}
]
}
}
And in the html i am populating a form by ng-repeat
<tr data-ng-repeat="choice in choices track by $index">
<td>{{choice.number}}</td>
<td><p>{{choice.short_text}}</p></td>
<td><input type="textbox" size="50" class="des-textinput" ng-model="choice.desc" required></td>
<td><input type="checkbox" ng-model="choice.include"></td>
<td><input type="file" id="abc{{$index}}" class="photo-upload"
file-model="pic{{$index}}" accept="image/*">
</td>
</tr>
Now I want to make the input type file required if the value of is_photo is true in the JSON I am receiving. For each row if the value if is_photo is false then it will be not required.
From the given JSON the condition will be the first input type file will be not required as first row is_photo is false, but the second one will be required as the value of is_photo is true.
How will I do that?
A:
You can use "ng-required"
For documentation you could read this: https://docs.angularjs.org/api/ng/directive/ngRequired
Like this
<input name="myInput" ng-model="myInput" ng-required="myVar == 2">
//If photo is true required will be true else false
<input name="myInput" ng-model="myInput" ng-required="_photo">
<input name="myInput" ng-model="myInput" ng-required="choice.is_photo">
//Or use some function which returns boolean
<input name="myInput" ng-model="myInput" ng-required="isRequired(choice)">
//This is how you would use it with form and stop form from submittion
<form ng-app="myApp" ng-controller="validateCtrl"
ng-init="isRequired=true"
name="myForm" novalidate ng-submit="myForm.$valid && submit()">
Username: <input type="text" name="user" ng-model="user"
ng-required="isRequired">
Email : <input type="email" name="email" ng-model="email" required>
<input type="submit" ng-click="isRequired=!isRequired;" />
</form>
<script>
var app = angular.module('myApp', []);
app.controller('validateCtrl', function($scope) {
$scope.user = 'John Doe';
$scope.email = '[email protected]';
$scope.submit = () => {console.log("s");}
});
</script>
| {
"pile_set_name": "StackExchange"
} |
Q:
What is a regular expression that satisfies all valid options for a JOB card in JCL?
I'm working on a program that will need to remove a JOB card from a JCL member. I'm having a lot of trouble building something that satisfies all possible options and configurations.
Below is a good guide on the JOB statement:
http://www.tutorialspoint.com/jcl/jcl_job_statement.htm
Some issues though:
There may be multiple job cards in a member
There may be comments in the job card
There may be characters in columns 73-80
There may be a SYSAFF, SET or similar statement directly following the JOB statement that should be retained but may begin with slashes and spaces just like a job card
Any help would be appreciated. Currently I have the following regular expression:
//.*JOB.*\n(//\s{4,}[^\s]+(\s|\d)*\n)+
Ultimately I only need to change the JOB name to fit the restriction of the FTP JES reader which requires your job name to be the submitting USERID plus exactly one character under JESINTERFACELEVEL 1 which is used by our site. Changing only the job name would also be acceptable.
A:
You will need to account for the two positional parameters -- 142 bytes of accounting information and 30ish bytes for programmers name. Also, you will have to account for the optional keyword parameters:
ADDRSPC= BYTES= CARDS= CLASS= COND=
GROUP= LINES= MEMLIMIT= MSGCLASS= MSGLEVEL=
NOTIFY= PAGES= PASSWORD= PERFORM= PRTY=
RD= REGION= RESTART= SECLABEL= SCHENV=
TIME= TYPRUN= USER=
Dealing with the JES commands like SYSAFF and other JCL commands like SET make it very complicated.
You might want to approach it in steps -- regex to handle the "//" followed by up to 69 bytes and continued with a comma except in cases of comments where it starts with "//*".
It might help to know what you are trying to accomplish. You can ask JES to process the JCL for you and there are ways you can inspect the parsed JCL via macros, exits and control blocks.
| {
"pile_set_name": "StackExchange"
} |
Q:
Global variable isn't global or doesn't contain the value I expected it to contain?
I've got the following code in Form1.
public
{ Public declarations }
cas: integer;
end;
Then I work with the variable, and then I call another form with Form2.ShowModal; On Form2 I try to execute the following: Label9.Caption:=Format('%ds',[Form1.cas]);. But no matter what I do, in Form1 'cas' is assigned the proper value but in Form2 it always shows "0s". Why does that happen?
EDIT:
Now I have in the first unit called 'kolecka' this
var
Form1: TForm1;
barvy: array[1..6] of TColor;
kola: array[1..22] of TShape;
valid: integer;
bezi: boolean;
presnost: real;
skore: integer;
chyb: integer;
kliku: integer;
cas: integer;
and this in the other unit called 'dialog':
implementation
uses
kolecka;
{$R *.dfm}
procedure Statistiky();
begin
With Form2 do begin
Label8.Caption:=IntToStr(kolecka.skore);
Label9.Caption:=Format('%ds',[kolecka.cas]);
Label10.Caption:=IntToStr(kolecka.cas);
Label11.Caption:=IntToStr(skore);
Label12.Caption:=Format('%.2f%%',[presnost]);
end;
end;
But it still doesn't work.. still shows a zero.
EDIT2:
I feel like every answer says something different and I'm very confused..
EDIT3: This is how 'cas' is manipulated in Form1
procedure TForm1.Timer3Timer(Sender: TObject);
begin
cas:=cas+1;
Form1.Label5.Caption:=IntToStr(cas);
end;
FOUND IT!
Meh. I figured out where was the problem.
I was assigning the label captions on Form2 Create and not Show, so of course they were at 0 >.>
A:
In your original question, you declared a field in an object, and you thought it was a global, perhaps?
unit unit1;
interface
uses Stuff;
type
TForm1 = class(TForm)
public
THisIsAFieldInAnObject:Integer;
end
var
ThisIsAGlobal:Integer;
implementation
uses OtherStuff;
...
Notice where you put globals above. Global variables are not fields inside a class. Where you put something, when you write code is called "the context you are in". Inside a class declaration, something like public makes sense as a visiblity specifier. It does not make things global, it makes them visible to users of the class.
To access the global, access it as unitName.VariableName, and don't forget to add 'Uses unitName' to the other unit.
Update You are now correctly accessing the global variable, and it doesn't contain the value you expected. That's where we start debugging. Set a breakpoint on the place where you set the variable, and on any other place where it is changed back to 0. Now set a breakpoint on the place where you read the variable. I find that variable writes work better when they actually happen, and when they aren't over-written by a subsequent write to the same place, that contains a different value. Variables are like a box which contains a number. Zero things writing to it (the code you thought got called did not get called) or two things writing to it (the thing you think should be there but is not there because the second write zapped the first value) are common sources of your sort of confusion.
| {
"pile_set_name": "StackExchange"
} |
Q:
mySQL search function returning invalid results
When running a SQL command to search a small database (using for testing as I'm learning) it gives me very strange results. Can you see what's wrong with my command?
SELECT * FROM users,departments WHERE name LIKE '%Alex%' OR lastname LIKE '%Alex%' OR email LIKE '%Alex%' AND departments.departmentid = users.departmentid
As you can see below it shows the users it searches for in all departments, when each user is only registered to one.
Search Query and results
Users Table
Departments table
A:
Try this:
SELECT * FROM users,departments WHERE (name LIKE '%Alex%' OR lastname LIKE '%Alex%' OR email LIKE '%Alex%') AND departments.departmentid = users.departmentid
You have to make brackets arround the or statements.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to update custom field metadata via the tooling api?
I can successfully make a patch request to the tooling api to update a custom fields api name. However, if I include any of the field properties in the CustomFieldMetadata object I get an internal salesforce error.
successful request:
PATCH: /services/data/v29.0/tooling/sobjects/CustomFieldDefinition/{ID}
{
"DeveloperName" : "NewName"
}
failed request:
PATCH: /services/data/v29.0/tooling/sobjects/CustomFieldDefinition/{ID}
{
"DeveloperName" : "NewName",
"Metadata" : {"length": 100}
}
gack ids:
118968544-21444 (-1657627855)
1623052628-129393 (-1657627855)
A:
This is a known issue with the tooling api with no current ETA for the fix. The bug number is W-1904760.
For other people who want to programmatically work with their custom field metadata I would recommend Andrew Fawcett's excellent metadata api wrapper.
A:
Do not have enough reputation points to post this as a comment, so having to post as an "answer".
Just wanted to let you know that you are not alone.
It looks like a common problem on SFDC side.
Here is what I get when try to update text field length using SOAP flavour of Tooling API.
val f = new CustomField
f.setId("00Ni0000009THQL")
val md = new CustomFieldMetadata
md.setLength(12)
f.setMetadata(md)
session.update(Array(f))
Result
[ApiFault exceptionCode='UNKNOWN_EXCEPTION'
exceptionMessage='An unexpected error occurred. Please include this ErrorId if you contact support: 497298247-26206 (803645494)'
upgradeURL='null'
upgradeMessage='null'
]
| {
"pile_set_name": "StackExchange"
} |
Q:
meaning of "the binding is fragile"
what is the meaning of "The binding is fragile" ?
I saw it in one of the harry potters movie. But didn't know what it means
UPDATE: pretend that someone wants to take your book away from you and you don't want it to do.It insists and tells you why
you say "The binding is fragile"
Thanks.
A:
Book binding often involves the use of glues. Many of the older glue formulations become brittle over time.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error: Cannot find module './definitions/init' while parsing file
I got this error when running watchify -t babelify --presets es2015 --presets react -d -e javascripts/main.jsx -o public/bundle.js -v.
Error: Cannot find module './definitions/init' while parsing file: /home/Desktop/front/javascripts/main.jsx
I have run npm install. I ran npm install -g npm. I ran npm install -g definition. But it didn't work.
I have not idea what definitions/init is. My main.jsx is as follows
import Wrapper from './wrapper.js';
import React from 'react';
import { render } from 'react-dom';
render(
<Wrapper/>,
document.getElementById('content')
);
Any one have any idea? Thank you.
A:
The primary API for rendering into the DOM looks like this:
ReactDOM.render(reactElement, domContainerNode)
ReactDOM.render(
<Wrapper />,
document.getElementById('content')
);
You also need to import ReactDOM like so:
import ReactDOM from 'react-dom'
Here is the official React tutorial:
https://facebook.github.io/react/docs/tutorial.html
Here are the ReactDOM docs:
https://facebook.github.io/react/blog/2015/10/01/react-render-and-top-level-api.html
| {
"pile_set_name": "StackExchange"
} |
Q:
Get data from the database in small parts in C#
In my C# application, I have a stored procedure which returns some kind of data from the database. The input parameters which I pass to the procedure are start date, end date and a such called "number of lines" parameter. Each line represents an entry in the database. Due to the database call restrictions I can't pass more than 5000 lines to the procedure per a call. That's why I want to create a some kind of loop to send 5000 lines, get the corresponding data, then another 5000 lines, etc, until I get an output of lines less than 5000 which would mean that there are no more lines left. Could anybody help me with an idea on how this can be done?
Thanks.
A:
I see only one possible solution for you - you should select your data by primary key. The DBMS will return data ordered by primary key. You should remember key with "maximum value" and at next time you should add condition PK > "maximum value", where PK is primary key. This will force DBMS to return to you next package of data, size of the package you can regulate by "number of lines" as previously
[EDIT]
I cant provide code sample because of I actually never work with DB in C#. But this fact didnt eliminate that DBMS always sorts table primary key. For example you have table with next columns:
ID (int) [PK]
DATA (CHAR255)
In this table ID is a primary key. So you may do simething like below (pesudo code):
< declaration of array which will hold you data from DB > - intTab
SELECT * FROM < your DB tab > UP TO 5000 ROWS
INTO CORRESPONDING FIELDS OF TABLE intTab
WHERE < your conditions >
AND ID > 0.
This SELECT would return to you "first" 5000 rows from table. "first" means first rows in index by primary key. To select next 5000 rows you should do:
var maxID = < max id from intTab >
SELECT * FROM < your DB tab > UP TO 5000 ROWS
INTO CORRESPONDING FIELDS OF TABLE intTab
WHERE < your conditions >
AND ID > maxID.
This select will return "next" 5000 rows due ID > maxID condition.
| {
"pile_set_name": "StackExchange"
} |
Q:
Load external js file to execute javascript code in IE devtool bar console
I want to use jquery to automatically fill some details in a web site which is not having reference to jquery. Using IE devtool bar script console, I want to load jquery then use it to write some code. But I do not know how to load jquery file and then use it.
Can anybody help me in that?
A:
Just copy this in your adresse bar or console:
javascript:var s=document.createElement('script');s.setAttribute('src', 'http://jquery.com/src/jquery-latest.js');document.getElementsByTagName('body')[0].appendChild(s);void(s);
| {
"pile_set_name": "StackExchange"
} |
Q:
Using Filter on Array of Objects & Div's for Objects
Here is my code:
HTML
<input type="text" id=“search”>
<div id = “items”></div>
JAVASCRIPT
var items =
[ { name: 'toy1', price: '12.00', quantity: 12 }
, { name: 'toy2', price: '1.00', quantity: 5 }
, { name: 'toy3', price: '11.00', quantity: 2 }
, { name: 'toy4', price: '1.00', quantity: 2 }
]
items.filter(name(function)){
});
Here is an ex. of what I want to do: https://www.w3schools.com/howto/howto_js_filter_lists.asp
For my case I want the user to be able to search by the name but I am stuck on what to write inside the function.
I want each of the objects in div's so when the user searches by name,
ex:toy4, then the other divs filter out and only the div containing the information for toy4 is displayed.
I know filter is the correct method to use here but I'm not sure how to link the users input from the input box and "check/filter" the divs out to only display what the user is searching for and put each object in divs.
*I can only use javascript.
Note
I have read most questions posted similar to mine but they were in languages which I have not learned yet or were not able to answer my question.
A:
In your filter function, you could just generate all your html there, but I would prefer to keep them seperate. It looks to me like you have 3 different pieces:
Your data
A filter function to filter the data based off the search term
An HTML generator function that will generate your html based off your data
Here's a quick way of bringing it all together
const items = [{
name: 'toy1',
price: '12.00',
quantity: 12
},
{
name: 'toy2',
price: '1.00',
quantity: 5
},
{
name: 'toy3',
price: '11.00',
quantity: 2
},
{
name: 'toy4',
price: '1.00',
quantity: 2
}
];
/**
* Create a function to generate your elements based
* off the passed in array of data
*/
function makeList(data) {
// Grab your container
const container = document.getElementById('items');
// Clear it (reset it)
container.innerHTML = '';
// Iterate through your data and create the elements
// and append them to the container
data.forEach(i => {
const element = document.createElement('div');
element.innerText = i.name;
container.append(element);
});
}
/**
* Create an event listener to react to
* search updates so you can filter the list.
* keyUp is used so that you wait for the
* user to actually finish typing that specific
* char before running. Otherwise, you'll be missing
* a char. (Try changing it to 'keypress' and see what happens)
*/
document.getElementById('search').addEventListener('keyup', function(e) {
// Get the textbox value
const searchTerm = e.target.value;
// If no value, reset the list to all items
if (!searchTerm) {
makeList(items);
return;
}
// Filter your list of data
// based off the searchTerm
const data = items.filter(i => i.name.toLowerCase().includes(searchTerm.toLowerCase()));
// Pass the list filtered list of data to your makeList function
// to generate your html
makeList(data);
});
// Generate your initial list
makeList(items);
<input type="text" id="search">
<div id="items"></div>
Alternatively, you could just hide the elements in the DOM instead of regenerating a fresh html list each time.
| {
"pile_set_name": "StackExchange"
} |
Q:
Flutter - using MultiBlocProvider but can't render BlocListener at sub screen
I am going to describe my problem and an error I have faced. And then I will copy my code for making it more clear. The problem as:
I am using MultiBlocProvider at root widget (StartupScreen) with declared 2 blocs are
AuthenticationBloc, ApplicationBloc.
Use BlocListener<AuthenticationBloc, AuthenticationState> at root widget (StartupScreen).
If AuthenticationBloc's state changes to AuthAuthenticatedState then routing to MainScreen, otherwise to LoginScreen.
If user has sigined in, then routing to MainScreen:
I am going to get currentUser from storage (asynchronously) then I wrap BlocListener inner FutureBuilder. it end up with can't display the screen and occur an error as following:
BlocProvider.of() called with a context that does not contain a Bloc of type ApplicationBloc.
No ancestor could be found starting from the context that was passed to BlocProvider.of<ApplicationBloc>().
This can happen if the context you used comes from a widget above the BlocProvider.
The context used was: BlocListener<ApplicationBloc, ApplicationState>(dirty, state: _BlocListenerBaseState<ApplicationBloc, ApplicationState>#1abf7(lifecycle state: created))
The relevant error-causing widget was
FutureBuilder<UserCredentials> package:my_app/…/ui/main_screen.dart:43
When the exception was thrown, this was the stack
#0 BlocProvider.of package:flutter_bloc/src/bloc_provider.dart:106
#1 _BlocListenerBaseState.initState package:flutter_bloc/src/bloc_listener.dart:160
#2 StatefulElement._firstBuild package:flutter/…/widgets/framework.dart:4355
#3 ComponentElement.mount package:flutter/…/widgets/framework.dart:4201
#4 SingleChildWidgetElementMixin.mount package:nested/nested.dart:223
...
StartupScreen.dart
class StartupScreen extends StatelessWidget {
final ApplicationBloc appBloc;
final AuthenticationBloc authBloc;
StartupScreen(this.appBloc, this.authBloc) : super();
@override
Widget build(BuildContext context) {
ScreenSizeConfig().init(context);
authBloc.add(AuthStartedEvent());
return MultiBlocProvider(
providers: [
BlocProvider<ApplicationBloc>(
create: (context) => appBloc,
),
BlocProvider<AuthenticationBloc>(
create: (context) => authBloc,
),
],
child: BlocListener<AuthenticationBloc, AuthenticationState>(
listener: (context, state) {
if (state is AuthUnauthenticatedState) {
Navigator.of(context).pushReplacementNamed(RouteConstants.LOGIN_SCREEN);
} else if (state is AuthAuthenticatedState) {
Navigator.of(context).pushReplacementNamed(RouteConstants.MAIN_SCREEN);
}
},
child: BlocBuilder<AuthenticationBloc, AuthenticationState>(
builder: (context, state) {
return Center(
child: Container(
child: Text('Startup Screen'),
),
);
},
),
),
);
}
}
MainScreen.dart
class MainScreen extends StatelessWidget {
final ApplicationBloc appBloc;
final AuthenticationBloc authBloc;
MainScreen(this.appBloc, this.authBloc) : super();
@override
Widget build(BuildContext context) {
return _MainPageWidget(appBloc, authBloc);
}
}
class _MainPageWidget extends StatefulWidget {
final ApplicationBlocappBloc;
final AuthenticationBloc authBloc;
_MainPageWidget(this.appBloc, this.authBloc) : super();
@override
State<StatefulWidget> createState() => _MainPageState();
}
class _MainPageState extends State<_MainPageWidget> {
Future<UserCredentials> getUserCredentials() async {
return await widget.appBloc.authService.getUser();
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return FutureBuilder<UserCredentials>(
future: getUserCredentials(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: CircularProgressIndicator(),
);
} else {
return _buildBlocListener(snapshot.data);
}
});
}
Widget _buildBlocListener(UserCredentials userCredentials) {
return BlocListener<ApplicationBloc, ApplicationState>(
listener: (context, state) {
if (userCredentials.isNewUser) {
widget.appBloc.add(AppNewUserEvent());
} else {
widget.appBloc
.add(AppAlreadyCompletedNewUserProcessEvent());
}
},
child: _buildBlocBuilder(context, widget.appBloc),
);
}
Widget _buildBlocBuilder(BuildContext context, ApplicationBloc appBloc) {
return BlocBuilder<ApplicationBloc, ApplicationState>(
builder: (context, state) {
print('main_screen.dart: go to mainscreen BlocBuilder builder: state: $state');
return Container(
child: Text('Main Screen'),
);
},
);
}
}
A:
From the documentation of bloc library:
You cannot access a bloc from the same context in which it was provided so you must ensure BlocProvider.of() is called within a child BuildContext
https://bloclibrary.dev/#/faqs?id=blocproviderof-fails-to-find-bloc
You would have to take out your BlocListener and put it in a separate widget, or wrap your BlocListener with a builder widget.
| {
"pile_set_name": "StackExchange"
} |
Q:
R: unexpected `ifelse` behavior
I have a data frame like the following:
mydf <- data.frame(letter=LETTERS[1:10],
val1=sample(1:1000, 10, replace=F),
val2=sample(1:1000, 10, replace=F))
> mydf
letter val1 val2
1 A 877 250
2 B 554 427
3 C 747 92
4 D 353 890
5 E 957 194
6 F 593 338
7 G 723 731
8 H 218 849
9 I 585 932
10 J 873 642
I just want to make a new column which (for this MWE) is equal to one of the value columns, depending on a choose variable, and I wanted to use ifelse for this purpose.
I do this:
choose <- 1
mydf$chosen <- ifelse(choose==1, mydf$val1, mydf$val2)
mydf
But it just uses the first value of val1 for the chosen column... what am I doing wrong here? Thanks
> mydf
letter val1 val2 chosen
1 A 878 984 878
2 B 880 80 878
3 C 296 999 878
4 D 558 230 878
5 E 112 414 878
6 F 132 450 878
7 G 429 693 878
8 H 608 89 878
9 I 409 50 878
10 J 974 980 878
A:
ifelse returns the output of same length as the condition we are checking. Since the length of the condition is 1 here it returns only the first value and the same value is recycled for all the values. Use if/else instead.
mydf$chosen <- if(choose=="a") mydf$val1 else mydf$val2
mydf
# letter val1 val2 chosen
#1 A 415 244 415
#2 B 463 14 463
#3 C 179 374 179
#4 D 526 665 526
#5 E 195 602 195
#6 F 938 603 938
#7 G 818 768 818
#8 H 118 709 118
#9 I 299 91 299
#10 J 229 953 229
data
set.seed(123)
mydf <- data.frame(letter=LETTERS[1:10],
val1=sample(1:1000, 10, replace=F),
val2=sample(1:1000, 10, replace=F))
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I use the permanent unlock token?
I prestiged. I'm at level 16 and I see no way to permanently unlock a weapon or perk. Where is this located?
A:
For Xbox 360, once you have your unlock token after prestiging, just go to the weapon / perk and press RB (you might be able to press LB too).
RB is the button above the right trigger (I think it stands for Right Bump).
For PS3, the button is R1.
| {
"pile_set_name": "StackExchange"
} |
Q:
Let $a$,$b$ be arbitrary integers. Find $g$, also an integer, such that $\langle a \rangle$ $\cap$ $\langle b\rangle$ = $\langle g\rangle$
Notation: For any $a \in \mathbb Z$ we have $\langle a \rangle$ = {$na | n \in \mathbb Z$}.
I believe $g = a^Ib^L$ for $I,L \in \mathbb Z$
[This is an assignment, so please hints only.]
But I have no idea how to prove this, could I perhaps show that $\langle a \rangle$ $\cap$ $\langle b \rangle$ is a subgroup of $\langle g \rangle$ and vice versa? Am I right in thinking this way?
A:
Hint: $\Bbb Z$ is principal ideal domain so $\langle a\rangle \cap \langle b\rangle=\langle g \rangle$.
Now you must show that $g= l.c.m.(a,b)$.
$\textbf{Note:}$ It is also true for a finite element of integers. i.e.,
If $a_1,a_2,\cdots, a_n\in \Bbb Z$ then $\bigcap\limits_{i=1}^{n}(a_i) =(a)$ and, $a=l.c.m(a_1,a_2\cdots, a_n)$
| {
"pile_set_name": "StackExchange"
} |
Q:
How to remove subscriber from list
I try to figure out how unsubscribe an Subscriber from a List.
We use FuelSDK and RestAPI.
any help would be appreciate
A:
You just have to set their status to Unsubscribed or better, log an UnsubEvent.
Reference: Unsubscribing and Logging an UnsubEvent with a LogUnsubEvent Execute Call
| {
"pile_set_name": "StackExchange"
} |
Q:
Godot: How to get mouse button input for a Tilemap for Cellular Automata
Conway's Game of Life
I have been working with a tilemap for the implementation of a cellular automata game. My current method for getting mouse button input is using an Area2D as a child of the Tilemap and detecting mouse button input like that.
I have done this and have since been wondering if there is something built in that I can use for this. I have looked into it and cannot find anything better.
Is there something built-in to Node2Ds or Canvas Items that I can use.
A:
The recommended way would be to override Node._unhandled_input() and use TileMap.world_to_map() and TileMap.map_to_world() methods.
Example:
# tile_map.gd
extends TileMap
func _unhandled_input(event):
if event is InputEventMouseButton:
if event.button_index == BUTTON_LEFT and event.pressed:
var clicked_cell = world_to_map(event.position)
Do note that world_to_map() takes a local position. Node2D supplies the to_global() and to_local() methods to ease the conversion.
I recommended using _unhandled_input() rather than _input() so gui input events are not passed through to the tile map. If the the tile map is undesirably receiving mouse events when you interact with a control, make sure that the control's mouse_filter property is not set to "Ignore".
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL find entire row where only 2 columns values
I'm attempting to
select columns Age, Height, House_number, Street
from my_table
where count(combination of House_number, Street)
occurs more than once.
My table looks like this
Age, Height, House_number, Street
15 178 6 Mc Gill Crst
85 166 6 Mc Gill Crst
85 166 195 Mc Gill Crst
18 151 99 Moon Street
52 189 14a Grimm Lane
My desired outcome looks like this
Age, Height, House_number, Street
15 178 6 Mc Gill Crst
85 166 6 Mc Gill Crst
Stuck!
A:
The best way to do this is with window functions, assuming your database supports them:
select columns Age, Height, House_number, Street
from (select t.*, count(*) over (partition by house_number, street) as cnt
from my_table t
) t
where cnt > 1
This is using a windows function (also called analytic function) in Oracle. The expression count(*) over (partition by house_number, street) is counting the number of rows for each house_number and street combination. It is kind of like doing a group by, but it adds the count to each row rather than combining multiple rows into one.
Once you have that, it is easy to simply choose the rows where the value is greater than 1.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to check data in a column separated by a colon (:)?
I have an Oracle database column, say col1, that has the following values:
Col1 (A:B:C)
I now need to come along and add to this Col1, only if it doesn’t exist, additional values but unsure how to go about checking to see if Col1 already contains these values.
Scenario might be as follows:
1) Need to add B => Outcome=> check Col1 – B exists, do not add.
2) Need to add A:C => Outcome=> check Col1 – A and C exists, do not add.
3) Need to add C:D => Outcome=> check Col1 – C exists but D doesn’t, do not add C but need to add D
4) Need to add G => Outcome=> check Col1 – G doesn’t, need to add G
Using Oracle SQL or PL/SQL I am unsure how to go about processing the above to ensure whether items exist or don’t exist and whether to add or not to add to Col1
A:
This might get you started:
UPDATE mytable
SET Col1 = Col1 || ':A'
WHERE INSTR(':' || Col1 || ':', ':A:') = 0;
To remove a value:
UPDATE mytable
SET Col1 = TRIM(':' FROM REPLACE(Col1, ':A:', ':'))
WHERE INSTR(':' || Col1 || ':', ':A:') > 0;
| {
"pile_set_name": "StackExchange"
} |
Q:
How to solve these problems with Asynchronous Callback?
I need to run 5 algorithms parallely each takes an image as input and gives image as output. After each of these is done, I need to display the 5 output images. I'm using Asynchronous Callback using delegates for this task.
So, I created 5 delegates for these 5 algos and calling them like algo1Delegate.BeginInvoke().
Algorithms are running fine and giving the output too. I'm facing 2 problems in displaying these images.
For displaying images, I created a class ImageViewer (windows form with picturebox element in it).
//ImageViewer constructor
ImageViewer(Image img, String Title)
{
this.pictureBox1.Image = img;
this.Text = Title;
}
I'm displaying images like this:
void showImage(Image image, String title)
{
ImageViewer imageviewer = new ImageViewer(image, title);
imageviewer.Show();
}
Since I need to display an image after algo. I'm passing new AsyncCallback(showImage) delegate for each of these BeginInvoke() as 3rd parameter
private void showImage(IAsyncResult iasycResult)
{
MessageBox.Show("white" + Thread.CurrentThread.ManagedThreadId);
// Retrieve the `caller` delegate.
AsyncResult asycResult = (AsyncResult)iasycResult;
caller = (Algo1Delegate)asycResult.AsyncDelegate;//### PROBLEM!!!
// Retrieve the string Title that is passed in algodelegate.BeginInvoke().
string title = (string)iasycResult.AsyncState;
Image outputImage = caller.EndInvoke(iasycResult);
showImage(outputImage, title);
}
I think you can see the problem in the above callback function. it only works for Algo1 for other 4 alog's it needs to be casted to Algo2Delegate , Algo3Delegate etc.. because asycResult.AsyncDelegate is of type object. How can I solve this problem? How can I make it work for others too?
The imageViewer window is getting "unresponsive". I don't understand why? ImageViewer object is initialized and displayed on the same thread for each of these algos. Why is it becoming unresponsive.
Any other alternative solutions?
PS: I cannot declare one delegateType for all the algos since there are some differences in input parameters.
EDIT:
Well, I got enough inputs for my 1st and 3rd questions. I used separate callbacks for each of these algorithms. My 2nd problem is still unsolved. I changed the constructor of ImageViewer() Just to check if they are executing on two different threads:
public ImageViewer(Image img, String title)
{
InitializeComponent();
if (pictureBox1.InvokeRequired) MessageBox.Show("You must Invoke()");
else MessageBox.Show("No need of Invoke()");
this.pictureBox1.Image = img;
this.Text = title + " : Image Viewer";
}
in every case it says No need of Invoke(). I don't understand what is the problem. Can any one please address this too? I don't get any execptions also. Just the window is becoming unresponsive. I checked if algorithms are causing any trouble. But no, they arent.
A:
I can't think of a clean solution to your problem. You'd have to write fugly code like this:
AsyncResult result = (AsyncResult)iresult;
if (result.AsyncDelegate is AsyncDelegate1) {
(result.AsyncDelegate as AsyncDelegate1).EndInvoke(iresult);
}
else if (result.AsyncDelegate is AsyncDelegate2) {
(result.AsyncDelegate as AsyncDelegate2).EndInvoke(iresult);
}
//etc...
ComputationResult answer = result.AsyncState as ComputationResult;
Yuck. You really ought to have an individual callback method for each delegate type. A generic method cannot help here, the constraint cannot be a delegate type. A lambda in the BeginInvoke method call doesn't look that much better:
var task1 = new AsyncDelegate1(Compute1);
var result1 = new ComputationResult("task1");
task1.BeginInvoke(42, result1,
new AsyncCallback((ia) => {
AsyncResult result = ia as AsyncResult;
(result.AsyncDelegate as AsyncDelegate1).EndInvoke(ia);
CommonCallback(result.AsyncState as ComputationResult);
}),
result1);
Nah. I'd tackle this by using only one delegate type. The WaitCallback type is suitable, although mis-named, you should write little helper classes that store the arguments for the delegate target so you can pass it through the WaitCallback.state argument.
Your second problem is induced because you are creating the ImageViewer instance in the callback method. The callback executes on a threadpool thread, not the UI thread. InvokeRequired returns false because the PictureBox control was created on the threadpool thread. This threadpool thread is however not suitable to display UI components, it doesn't pump a message loop. And has the wrong apartment state. And it terminates too soon.
InvokeRequired will return the proper value (true) when you use a Control that was created on the UI thread. Your main startup form for example. Or Application.OpenForms[0]. There's little point in using InvokeRequired however, you know for a fact that the callback executes on the wrong thread. Just use BeginInvoke directly. The invoked method should create the ImageViewer instance.
You are well on your way re-inventing the BackgroundWorker class. It does exactly what you are trying to do. But takes care of the gritty details of getting the RunWorkerCompleted event fired on the correct thread. You ought to consider it.
| {
"pile_set_name": "StackExchange"
} |
Q:
Power maximum output power for each pin
A have Arduino Mega 2560. I found in the spec that the maximum output current for each I/O pin is 40 mA.
Can i use 40 IO in parallel? That's mean 40*40ma*5 volt = 8000 mw = 8 watt.
What about the heat?!
A:
There are also limits on the total power of groups of pins,
The sum of all IOH, for ports J0-J7, G2, A0-A7 should not exceed
200mA.
The sum of all IOH, for ports C0-C7, G0-G1, D0-D7, L0-L7 should not exceed 200mA.
The sum of all IOH, for ports G3-G4, B0-B7, H0-H7 should not exceed 200mA.
The sum of all IOH, for ports E0-E7, G5 should not exceed 100mA.
The sum of all IOH, for ports F0-F7, K0-K7 should not exceed 100mA.
So you are already limited to 800mA.
Secondly, you have to be careful to change all the pins at exactly the same time. Otherwise some pins will be low, and others high creating effectively a dead short. Or if you make sure the pins are inputs before changing, some pins will be on sooner, and those pins will then for a short period, handle all the current, and thus exceeding their limit for a brief moment. Which isn't that bad, but still not ideal.
So definitely don't use digitalWrite to change all the pins, one after the other.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to convert edged image in OpenCV to svg file?
I am using OpenCV canny edge detection module to find the contours of an image which gives me a B&W output image.
Here's the code for that:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (3, 3), 0)
edged = cv2.Canny(blurred, 180, 200)
Now I want to write this image to disk in SVG file format. How do I obtain the same from the cannied image?
A:
I assume you want just the contours to be saved as SVG image.
First, you need to compute the contours in your canny image using the findContorus function of OpenCV. Please be careful here, your contours MUST be well defined.
Second, having your contours just follow this question:
Convert contour paths to svg paths
The SVG paths can be opened in any image processing software (e.g. Inkscape, Photoshop, etc)
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL: Select only if multiple values are IN 1 column from CatalogTable
I would really appreciate if you could help me with the following query; Having the following tables:
----------
**TableResults**
ResultId1
ResultId2
----------
---------------------
**TableResultsPatterns**
ResultId1 pattern1
ResultId1 pattern2
ResultId1 pattern4
ResultId2 pattern3
---------------------
---------------------
**TablePatterns**
pattern1 Name1
pattern2 Name2
pattern3 Name3
pattern4 Name4
---------------------
What is the best way to check if list of values (patternNames from User)
are IN or exist in the list of patterns of a particular Result
For example select only the Results that have pattern Names(Name2, Name3)?
I have something like:
SELECT***
JOINs***
WHERE***
and exists(select TablePatterns from TableResultsPatterns left join
TablePatterns f on TableResultsPatterns.patternId = f.id
where TableResultsPatterns.ResultsId = ResultIdX and patternName in ('Name2', 'Name4'))
GROUPBY***
***
Edit 1:
----------------
**TableResults**
(ResultId pk)
ResultId1
ResultId2
---------------
--------------------------------------------------------
**TableResultsPatterns**
(ResultId (fk TablePatterns.PatternId)
fk TableResults.ResultId)
ResultId1 pattern1
ResultId1 pattern2
ResultId1 pattern4
ResultId2 pattern3
--------------------------------------------------------
------------------------------
**TablePatterns**
(PatternId pk) (PatternName)
pattern1 Name1
pattern2 Name2
pattern3 Name3
pattern4 Name4
------------------------------
in my main query i have:
right join TableResults wsr on wsr.patient_well_sample_id=XXX.id
left join TableResultsPatterns wsrfp on wsr.ResultId=wsrfp.ResultId
left join TablePatterns fp on wsrfp.final_patterns_id=fp.id
note: I´m string_agg(the PAtternNAmes for every TableResult) in select
A:
If you have a list of patterns and you want the results that contain them, you can use aggregation. For instance:
select resultid
from resultpatterns rp
where pattern in (?, ?, ?)
group by resultid
having count(distinct pattern) = 3; -- 3 is the size of the list
| {
"pile_set_name": "StackExchange"
} |
Q:
Django - Group by column and where on a different column
These are my django models (simplified):
class Status(models.Model):
status = models.CharField(max_length=20)
class Project(models.Model):
client = models.ForiegnKey(Client)
class TicketRequest(models.Model):
status = models.ForiegnKey(Status, related_name='ticket_requests')
project = models.ForiegnKey(Project)
created = models.DateTimeField()
Required result
status.value | client.id | count
--------------+-------------+---------
is_assigned | 4 | 2
is_closed | 4 | 66
is_open | 4 | 7
Queryset annotate
Status.objects.filter(
ticket_requests__project__client_id=4
).values('value').annotate(
count=Count('ticket_requests__project__client')
)
returns
[{'count': 2, 'value': u'is_assigned'}, {'count': 66, 'value': u'is_closed'}, {'count': 7, 'value': u'is_open'}]
which is exactly what is required.
But I need to filter the queryset on TicketRequest.createdwith filters such as today, this week and month.
Since these filters need to be reused a lot, I created a handy helper:
def qs_time_range(qs, time_range, field_name):
now = timezone.now()
if time_range == 'month':
past = now - timedelta(days=30)
return qs.filter(
**{field_name + '__date__range': [past, now]}
)
Problem
When I use the helper to filter the ticket requests, the results are not what I expect.
data = filters.qs_time_range(
Status.objects.filter(ticket_requests__project__client_id=4),
'month',
'ticket_requests__created'
).values('value').annotate(
count=Count('ticket_requests__project__client')
)
Result
[{'count': 27, 'value': u'is_assigned'}]
When instead this should have been the result:
[{'count': 3, 'value': u'is_assigned'}, {'count': 3, 'value': u'is_closed'}, {'count': 3, 'value': u'is_open'}]
Question: Is the filtering messing up the SQL? What should I try instead?
Additional Info - Raw SQL
data.query reveals this SQL (modified for Postgres)
SELECT "tickets_status"."value",
COUNT("projects_project"."client_id") AS "count"
FROM "tickets_status"
INNER JOIN "tickets_ticketrequest" ON ("tickets_status"."id" = "tickets_ticketrequest"."status_id")
INNER JOIN "projects_project" ON ("tickets_ticketrequest"."project_id" = "projects_project"."id")
INNER JOIN "tickets_ticketrequest" T5 ON ("tickets_status"."id" = T5."status_id")
WHERE ("projects_project"."client_id" = 4
AND T5."created"::date BETWEEN '2016-09-02' AND '2016-10-02')
GROUP BY "tickets_status"."value",
"tickets_status"."name"
ORDER BY "tickets_status"."name" ASC;
which returns
value | count
-------------+-------
is_assigned | 27
(1 row)
But this is the SQL that I want generated:
SELECT "tickets_status"."value",
COUNT("projects_project"."client_id") AS "count"
FROM "tickets_status"
INNER JOIN "tickets_ticketrequest" ON ("tickets_status"."id" = "tickets_ticketrequest"."status_id")
INNER JOIN "projects_project" ON ("tickets_ticketrequest"."project_id" = "projects_project"."id")
WHERE ("projects_project"."client_id" = 4
AND "tickets_ticketrequest"."created"::date BETWEEN '2016-09-02' AND '2016-10-02')
GROUP BY "tickets_status"."value",
"tickets_status"."name"
ORDER BY "tickets_status"."name" ASC;
which returns the right result
value | count
-------------+-------
is_assigned | 3
(3 rows)
A:
Lovely to hear that you got your stuff working, but this answer is 1 explanation short of a reasoning behind this magic. I remembered that this works, but if someone comes up with an explanation WHY it works, then that is the real correct answer. But yeah, if django.db.models.Count doesn't work as expected, you can replace it with a combination of Sum(Case(When(field='value'), then=1), default=0, output_field=models.IntegerField()) (in Django >= 1.9).
The original comment that solved the problem:
First of all have to state the obvious: are you sure you have any
closed or open ticket requests created in the last month? That would
be the most obvious cause. But if you already double- and
triple-checked that, then I have a vague memory of having a similar
problem somewhere, but can't remember why. But I fixed it by changing
Count() to Sum(Case(When(set__the__condition='set_the_value'),
then=1), default=0, output_field=models.IntegerField())).
| {
"pile_set_name": "StackExchange"
} |
Q:
SQL invalid conversion return null instead of throwing error
I have a table with a varchar column, and I want to find values that match a certain number. So lets say that column contains the following entries (except with millions of rows in real life):
123456789012
2345678
3456
23 45
713?2
00123456789012
So I decide I want all the rows which are numerically 123456789012 write a statement that looks something like this:
SELECT * FROM MyTable WHERE CAST(MyColumn as bigint) = 123456789012
It should return the first and last row, but instead the whole query blows up because it can't convert the "23 45" and "713?2" to bigint.
Is there another way to do the conversion that will return NULL for values that can't convert?
A:
If you are using SQL Server 2012 you can use the 2 new methods:
TRY_CAST()
TRY_CONVERT()
Both methods are equivalent. They return a value cast to the specified data type if the cast succeeds; otherwise, returns null. The only difference is that CONVERT is SQL Server specific, CAST is ANSI. using CAST will make your code more portable (although not sure if any other database provider implements TRY_CAST)
A:
SQL Server does NOT guarantee boolean operator short-circuit, see On SQL Server boolean operator short-circuit. So all solution using ISNUMERIC(...) AND CAST(...) are fundamentally flawed (they may work, but hey can arbitrarily fail later dependiong on the generated plan). A better solution is using CASE, as Thomas suggests: CASE ISNUMERIC(...) WHEN 1 THEN CAST(...) ELSE NULL END. But, as gbn pointed out, ISNUMERIC is notoriously finicky in identifying what 'numeric' means and many cases where one would expect it to return 0 it returns 1. So mixing the CASE with the LIKE:
CASE WHEN MyRow NOT LIKE '%[^0-9]%' THEN CAST(MyRow as bigint) ELSE NULL END
But the real problem is that if you have millions of rows and you have to search them like this, you'll always end up scanning end-to-end since the expression is not SARG-able (no matter how we rewrite it). The real issue here is data purity, and should be addressed at the appropriate level, where the data is populated. Another thing to consider is if is possible to create a persisted computed column with this expression and create a filtered index on it which eliminates NULL (ie. non-numeric). That would speed up things a little.
A:
ISNUMERIC will accept empty string and values like 1.23 or 5E-04 so could be unreliable.
And you don't know what order things will be evaluated in so it could still fail (SQL is declarative, not procedural, so the WHERE clause probably won't be evaluated left to right)
So:
you want to accept value that consist only of the characters 0-9
you need to materialise the "number" filter so it's applied before CAST
Something like:
SELECT
*
FROM
(
SELECT TOP 2000000000 *
FROM MyTable
WHERE MyColumn NOT LIKE '%[^0-9]%' --double negative rejects anything except 0-9
ORDER BY MyColumn
) foo
WHERE
CAST(MyColumn as bigint) = 123456789012 --applied after number check
Edit: quick example that fails.
CREATE TABLE #foo (bigintstring varchar(100))
INSERT #foo (bigintstring )VALUES ('1.23')
INSERT #foo (bigintstring )VALUES ('1 23')
INSERT #foo (bigintstring )VALUES ('123')
SELECT * FROM #foo
WHERE
ISNUMERIC(bigintstring) = 1
AND
CAST(bigintstring AS bigint) = 123
| {
"pile_set_name": "StackExchange"
} |
Q:
win32 c++ detecting 'enter' in a edit control withot subclassing?
Basically I want an Enter to trigger a message I can catch when a edit control har focus and a user press enter. All solutions online seems to be about subclassing, but I was wondering if there was another way around it?
For example, my button has an identifier ID_BUTTON_SEND. Here's how I imagine it;
case WM_COMMAND:
switch (LOWORD(wParam))
case ID_BUTTON_SEND
if ('enter was pressed')
do this
else
default
...you get the idea :) I've read the http://support.microsoft.com/kb/102589 but frankly option 1 dosn't make much sense to me.
Cheers
A:
Best way to catch this is before TranslateMessage gets called. So, if using MFC, override CWnd::PreTranslateMessage. If using only Win API, then just check in your message pump what the message contains before the call to TranslateMessage.
A:
You could trap the focus change event and when the edit control gets the focus event just change the dialog default button to be the *ID_BUTTON_SEND* button. Then when the focus is lost remove this default button flag.
That would means that whenever the user hits enter when the edit control has the foucs the dialog would automatically fire the *ID_BUTTON_SEND* default button.
You can make the button the default button by adding the BS_DEFPUSHBUTTON to the GWL_STYLE of the button.
A:
Just to reiterate upon the KB article. For option 1 you can actually simply handle IDOK in WM_COMMAND.
case WM_COMMAND:
if(wParam == IDOK){
ENTER WAS PRESSED
}else{
REGULAR EVENT HANDLING
}
This is a much easier and cleaner way to check for the Enter.
| {
"pile_set_name": "StackExchange"
} |
Q:
Best practice to handle double negatives when using the expectancy-value model?
My question is regarding the multiplicative combination rule in the Expectancy-value model developed by Fishbein and Ajzen, and the issues regarding the expectancy value-muddle, or the case of "double negatives," in the multiplicative combination.
For my master thesis, I conducted a questionnaire toward a sample of people and asked questions about their attitudes toward a hospitality company. My intention is to derive their attitudes with the help from the expectancy-value model:
$$
\ a=\sum_{i=1}^{n}b_{i}e_{i}
$$
a is one respondent's attitude towards the object.
$$\ b_i$$ is the belief that the object has the attribute
i.
$$\ e_i$$ is the evaluation of the attribute.
a is one respondent's attitude toward the object.
$b_i$ is the belief that the object has the attribute
i.
$e_i$ is the evaluation of the attribute i.
The first question (e) accesses the respondent's opinion of the importance of attribute i (e.g. central location), and the second question (b) accesses the respondent's belief that the hospitality company will deliver attribute i. I also have a direct attitude variable, which is not in the scope of this problem unless it is, of course, a part of the solution.
The respondents choose one alternative on a bipolar semantic differential scale with the extremes between "unimportant - important" (e) and "unlikely - likely" (b) for every attribute with a coded scale between -3 to +3.
The attitude points are compared with various hypothesis t-test. One independent t-test between the experimental group and the control group. And one dependent t-test to investigate a difference within the groups.
It's beyond the scope of the examination to carry out a focus group to elicit the attributes from a representative sample of the population (hospitality company customers). Thus, the reason to use a bipolar scale to "permit" a negative response e.g. "unlikely" instead of "slightly likely" on the lower scale:
"For example, when - as part of belief elicitation - a person indicates 'my drinking alcohol makes me nauseous,' it is reasonable to use, for that person a unipolar scale to assess the strength of this belief. However, when the same statement is presented to an individual who did not personally emit it, the individual may well judge it to be highly unlikely or false. To permit this kind of response, a bipolar belief scale should be used, such as a seven-point scale ranging from unlikely to likely or fall to true." (Fishbein & Ajzen, 2010, p.106)
A problematic issue, the expectancy-value muddle or the case of the double negative, occurs when the respondents answer with a negative evaluation and belief. Newton et al. (2011, p.3) claim that the phenomenon "expectancy-value muddle" occurs since the b*e "computation are uninterpretable":
"if both responses were coded on bipolar scales, then the individual would receive the highest score possible due to the multiplication of the two negative terms (-3*-3=9). Thus, the ranking of scores in the expectancy-value framework becomes contingent upon the method of scaling used. Hence, the rankings of expectancy-value scores are dependent on item scaling can have important implications for the analysis and interpretation of results." (Newton et al., 2011, p.2-3)
Fishbein and Ajzen have also dealt with this problem; French and Hankins (2003) explain the 'psychology of the double negative', which was originally presented by Ajzen and Fishbein (1980):
"The rationale given by Fishbein and Ajzen for the scoring system adopted is based on what they term the ‘psychology of the double negative’. For instance, if an ‘expectancy’ belief and its associated evaluation were both scored from - 3 to + 3, as recommended by Ajzen and Fishbein (1980), an individual who indicated that (s)he thought an outcome was both likely and good would score the maximum possible (+ 3 * + 3 = + 9), as would an individual who thought the outcome was both unlikely and bad (-3 * -3 = + 9). That is, a negatively valued consequence with a perceived low probability of occurring is thought to be as much a reason for inferring a positive attitude as a positively valued consequence with a perceived high probability of occurring. Note that, according to this viewpoint, the distant positions have led to the same numerical outcome." (French & Hankins, 2003, p.39)
Fishbein and Ajzen thus state that bipolar scaling is the best choice:
"In sum, evidence available to date indicates that bipolar scoring is generally superior to unipolar scoring of behavioral beliefs." (Fishbein & Ajzen, 2008, p.2231)
And they have also stated that the multiplicative combination is correct:
"We thus conclude that the multiplication of belief strength and outcome evaluation, which is at the core of the expectancy-value model, is a reasonable and well-supported assumption." (Fishbein & Ajzen, 2010, p.118)
What puzzles me is that Fishbein and Ajzen, both in 2008 and 2010, have suggested to convert from a bipolar to a unipolar scale after the data has been collected:
"Even though the shift from unipolar to bipolar scoring involves a simple linear transformation (i.e., subtraction by 4), it results in a nonlinear transformation of the product term (be). This can be seen in the following computation where the original values of b are transformed by the addition of a constant B, and the values of e by a constant E. For simplicity, only one behavioral belief is entered into the expectancy–value equation:
$$
\ A_{B}\propto(b+B)(e+E)\propto be+Eb+Be+BE
$$
In practice, however, the impact of a linear transformation is often relatively small as a result of a restricted range of belief strength or outcome evaluation scores. In the limiting condition in which scores on either variable are the same for all participants, a linear transformation of that variable will
result in a linear transformation of the b * e product, thus having no effect on correlations with external criteria." (Fishbein & Ajzen, 2008, p.2226-2226)
To conclude, both French and Hankins (2003) and Newton et al. (2011) problematize the multiplicative combination because of the double negatives, also called the expectancy-value muddle.
They do suggest various solutions but recommend two other models developed by Schmidt (1973) and Haddock and Zanna (1998), the "expectancy-valence model" and "open-ended measures of attitudinal components," respectively.
These models, however, are not applicable to my problem. I have already carried out questionnaires that do have double negatives in the resulting data.
I'm considering to either use the suggestion by Fishbein and Ajzen (2008) or to accept this issue as a "psychology of the double negative" presented by the same authors (1980).
But I'm not sure, and that's why I'm reaching out to this community to ask: What is the best and common practice to overcome this issue with double negatives when using the expectancy-value model?
Bibliography
Ajzen, I., & Fishbein, M. (2008). Scaling and Testing Multiplicative Combinations in the Expectancy–Value Model of Attitudes. Journal of Applied Social Psychology, 38(9), 2222–2247. doi:10.1111/j.1559-1816.2008.00389.x
Ajzen, I., & Fishbein, M. (1980). Understanding attitudes and predicting social behavior. Prentice-Hall.
Fishbein, M., & Ajzen, I. (2010). Predicting and Changing Behavior: The Reasoned Action Approach. Taylor & Francis Group.
French, D. P., & Hankins, M. (2003). The expectancy-value muddle in the theory of planned behaviour — and some proposed solutions. British Journal of Health Psychology, 8(1), 37–55. doi:10.1348/135910703762879192
Haddock, G., & Zanna, M. P. (1998). On the use of open-ended measures to assess attitudinal components. British Journal of Social Psychology, 37(2), 129–149. doi:10.1111/j.2044-8309.1998.tb01161.x
Newton, J. D., Ewing, M. T., Burney, S., & Hay, M. (2011). Resolving the theory of planned behaviour’s “expectancy-value muddle” using dimensional salience. Psychology & Health, 27(5), 588–602. doi:10.1080/08870446.2011.611244
Schmidt, F. L. (1973). Implications of a measurement problem for expectancy theory research. Organizational Behavior and Human Performance, 10(2), 243–251. doi:10.1016/0030-5073(73)90016-0
A:
Have you read this:
Fishbein, M., Middlestadt, S. (1995) Noncognitive Effects on Attitude Formation and Change: Fact or Artifact? Journal of Consumer Psychology, 4(2),181-202. [DOI]
Direct quote from page 187:
Note that the psychology of the double negative is an essential part of an expectancy-value formulation (Ajzen & Fishbein, 1980; Fishbein, 1967; Fish-
bein & Ajzen, 1975). From the perspective of an expectancy-value theory, and consistent with Heider's (1958) balance theory, believing that an object does not have a negative characteristic or that performing a behavior will prevent a negative outcome should contribute positively (rather than negatively) to the attitude toward that object or behavior. For example, if a student does not believe (i.e., if he or she disbelieves) that "my professor is a capricious grader," this belief should, according to an expectancy-value formulation, contribute positively (not negatively) to his or her attitude toward my professor.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using bzr with SFTP on Windows/Cygwin
Note: I'm not sure if this belongs on ServerFault or StackOverflow
I'm currently working on a project which has an SFTP-only bzr repository. All works fine using my Linux machine, but when using Windows with Cygwin I get the following issue:
$ bzr checkout sftp://user@hostname/var/bzr/project
bzr: ERROR: Unsupported protocol for url "sftp://user@hostname/var/bzr/project": Unable to import paramiko (required for sftp support): No module named Crypto
I have installed Cygwin's python-paramiko package, so I'm not sure why it's refusing to use it.
Any suggestions much appreciated.
Clarification: This does work with Windows bazaar GUI tool & Windows cmd shell, I'm just wondering if I can make it work in Cygwin as I prefer UNIXy command line tools.
A:
Played around with this today.
Had to install python-crypto which should be a prerequisite of python-paramiko but isn't.
| {
"pile_set_name": "StackExchange"
} |
Q:
Troubleshooting: how to see errors from folder action scripts
I am trying to set up a "drop" folder: i.e. A watched folder with an associated Apple Script in "Folder Action Scripts".
The script is fairly simple. It defines a source link (the watched folder) and a destination path (a folder with the same parent as the watched folder) and runs a python script on the dropped file using the two variables defined as python arguments:
on adding folder items to this_folder after receiving added_items
set dropFolder to quoted form of POSIX path of "IN/" -- use relative path
set destinationFolder to quoted form of POSIX path of "OUT/" -- use relative path
try
repeat with EachItem in added_items
set ItemInfo to info for EachItem
if not folder of ItemInfo then
set FileExtensionOfItem to name extension of ItemInfo
if FileExtensionOfItem is "txt" then
set theBaseName to my getBaseNameOf(ItemInfo)
set pythonArg1 to theBaseName + "/packageElement"
set pythonArg2 to destinationFolder
set run_cmd to "python parser.py " + pythonArg1 + " " + pythonArg2
tell application "Terminal" -- pass file name to python using BASH from within this script
activate
do script run_cmd
end tell
end if
end if
end repeat
end try
end adding folder items to
There is some problem - likely minor in the script. Or perhaps there is a file permissions error?
I normally would trace my code using some simple technique like display dialog ...; however, I can not see these dialogues if they are run from the watched folder.
My question is this: What tools can we use to troubleshoot a folder action script such as this?
A:
I've found it useful to put the folder action code into a template that can also be run as an applet, droplet, or from the Script Editor. It can then be used for testing and/or manually run for chosen files:
on run -- applet or from the Script Editor
doStuff for (choose file with multiple selections allowed)
end run
on open droppedItems -- droplet
doStuff for droppedItems
end open
on adding folder items to theFolder after receiving newItems -- folder action
doStuff for newItems
end adding folder items to
to doStuff for someItems -- do stuff with the file items
try
repeat with anItem in someItems
-- whatever
end repeat
on error errmess number errnum
display alert "Error " & errnum message errmess
end try
end doStuff
| {
"pile_set_name": "StackExchange"
} |
Q:
Should I store references in classes in c++?
When I was learning C++, I was told that if you want to have multiple classes reference the same object, you should give both a pointer to the object. In Modern C++, I'd probably interpret this as the object being a unique_ptr and the classes holding non-owning-raw-pointers.
Recently, my mentor at work suggested that you should only use pointers when you plan on having the store point to a different object or null at some point. Instead, you should store references in classes.
Reference member variables are a thing I've actually never seen before, so I was looking for advice on what the concerns were... It makes sense... You're saying that this reference is assumed to never be null... I guess the concern would then be that you couldn't /check/ for null. It would have to be an invariant of your class...
How about how this applies to using the references for polymorphism?
Update:
The answer that I selected covers my questions pretty well, but I thought I'd clarify for future readers. What I was really looking for was an idea of the consequences of using a reference rather than a pointer as a class member. I realise that the way the question was phrased made it sound more like I was looking for opinions on the idea.
A:
Should I store references in classes in c++?
yes, why not. This question is IMO 'primarily opinion-based', so my answer is based on my own experience.
I use member references when I dont need what pointers have to offer, this way I limit possiblity that my class will be wrongly used. This means among other possibility to bind new value, assign nullptr, you cant take pointer to reference, you cannot use reference arithmetics - those features are missing in references. You should also remember that reference is not an object type, this means among others that if you put a reference as struct member, then it is no longer POD - i.e. you cannot use memcpy on it.
You should also remember that for classes which have non static reference member, compiler will not generate implicit constuctors.
For me this means references as variable members are mostly usefull when class is some kind of wrapper, or a holder. Below is an example which also shows an alternative implementation using pointer member type. This alternative implementation gives you no additional benefit to the reference one, and only makes it possible to introduce Undefined Behaviour.
struct auto_set_false {
bool& var;
auto_set_false(bool& v) : var(v) {}
~auto_set_false() { var = false; }
};
struct auto_set_false_ptr {
bool* var;
auto_set_false_ptr(bool* v) : var(v) {}
~auto_set_false_ptr() { *var = false; }
};
int main()
{
// Here auto_set_false looks quite safe, asf instance will always be
// able to safely set nval to false. Its harder (but not imposible) to
// produce code that would cause Undefined Bahaviour.
bool nval = false;
auto_set_false asf(nval);
bool* nval2 = new bool(true);
auto_set_false_ptr asf2(nval2);
// lots of code etc. and somewhere in this code a statement like:
delete nval2;
// UB
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Detect non-programmatic url hash changes
I'm using window.onhashchange to detect browser hash changes. But is there a way to only trigger the callback if the hash was changed in a non-programmatic way?
I am not asking how to use onhashchange. I am trying to avoid triggering it when I set the hash programmatically.
Basically, I want to do something similar to:
window.onhashchange = () => { /* ... */ };
But I don't want the callback to trigger if the code did the following:
window.location.hash = 'hello-world';
Thanks!
A:
I ended up solving it by simply setting a flag, which seems like a hack, but given JavaScript execution environments are single-threaded, should work fine.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does throw inside a catch ellipsis (...) rethrow the original error in C++?
If in my code I have the following snippet:
try {
doSomething();
} catch (...) {
doSomethingElse();
throw;
}
Will the throw rethrow the specific exception caught by the default ellipsis handler?
A:
Yes. The exception is active until it's caught, where it becomes inactive. But it lives until the scope of the handler ends. From the standard, emphasis mine:
§15.1/4: The memory for the temporary copy of the exception being thrown is allocated in an unspecified way, except as noted in 3.7.4.1. The temporary persists as long as there is a handler being executed for that exception.
That is:
catch(...)
{ // <--
/* ... */
} // <--
Between those arrows, you can re-throw the exception. Only when the handlers scope ends does the exception cease to exist.
In fact, in §15.1/6 the example given is nearly the same as your code:
try {
// ...
}
catch (...) { // catch all exceptions
// respond (partially) to exception <-- ! :D
throw; //pass the exception to some
// other handler
}
Keep in mind if you throw without an active exception, terminate will be called. This cannot be the case for you, being in a handler.
If doSomethingElse() throws and the exception has no corresponding handler, because the original exception is considered handled the new exception will replace it. (As if it had just thrown, begins stack unwinding, etc.)
That is:
void doSomethingElse(void)
{
try
{
throw "this is fine";
}
catch(...)
{
// the previous exception dies, back to
// using the original exception
}
try
{
// rethrow the exception that was
// active when doSomethingElse was called
throw;
}
catch (...)
{
throw; // and let it go again
}
throw "this replaces the old exception";
// this new one takes over, begins stack unwinding
// leaves the catch's scope, old exception is done living,
// and now back to normal exception stuff
}
try
{
throw "original exception";
}
catch (...)
{
doSomethingElse();
throw; // this won't actually be reached,
// the new exception has begun propagating
}
Of course if nothing throws, throw; will be reached and you'll throw your caught exception as expected.
| {
"pile_set_name": "StackExchange"
} |
Q:
Show that $7\mid(3^{2n+1}+2^{n+2})$ for all $n\in\mathbb{N}$
Prove that the following is true for every $n∈ℕ$:
$$7\mid(3^{2n+1}+2^{n+2}).$$
I've noticed
$$3^{2n+1}+2^{n+2} =3^{2n} \cdot 3+2^{n} \cdot 4.$$
Any suggestions how to continue from there to get something like $7k$ for $k\in\mathbb{N}$.
Thank you in advance!
A:
Hint $\ \ 7\mid\color{#c00}{3^2}\!\color{#c00}-\!\color{#c00}2,\,\ 7\mid\overbrace{\color{#0a0}{3^{2k+1}}\!\color{#0a0}+\! \color{#0a0}{2^{k+2}}}^{\large P(k)} \Rightarrow\, 7\mid 2(\color{#0a0}{3^{2k+1}\!\!+\!2^{k+2}}) + (\color{#c00}{3^2\!-2})3^{2k+1}\! =\, \overbrace{3^{2k+3}\!+2^{k+3}}^{\large P(k+1)}$
Or, notice $\ 2^2\!+2+1 = 7\ $ so we can apply
Lemma $\ \ a^2\!+a+1\mid a^{n+2}+(a+1)^{2n+1}\! =: b$
Proof $\, \ {\rm mod}\,\ a^2\!+a+1\!:\ \color{#0a0}{a(a+1)\equiv -1}$ and $\,\color{#c00}{a^3\equiv 1}\ $ by $\,0\equiv (a\!-\!1)(a^2\!+a+1) = a^3\!-1,\,$ so
$\qquad\quad\! a^{2n+1}b = a^{3n+3} + (\color{#0c0}{a(a+1)})^{2n+1} \equiv\, (\color{#c00}{a^3})^{n+1}\!-1\equiv 0\ $ so $\ b\equiv 0\ \ $ QED
Remark $\ $ Below I explain how the first explicit inductive proof is a special case of the latter congruence arithmetic proof, which boils down to $\color{#0a0}{(-1)^{2n+1}\equiv -1}\,$ and $\color{#c00}{1^{n+1}\equiv 1},\,$ both of which have trivial inductive proofs (a special case of the Congruence Power Rule inductive proof).
Here is the inductive step $\,P(k)\,\Rightarrow\,P(k\!+\!1)\,$ written in intuitive congruence arithmetical form
$$\begin{eqnarray} {\rm mod}\ 7\!:\quad\ \ \color{#c00}{3^{\large 2}} &\equiv& \color{#c00}2\\
\color{#0a0}{3^{\large 2k+1}}&\equiv& \color{#0a0}{-2^{\large k+2}},\quad\ {\rm i.e.}\ \ \ P(k)\\
\Rightarrow\ \ 3^{\large 2(k+1)+1} &\equiv& \color{#c00}{3^{\large 2}}\: \color{#0a0}{3^{\large 2k+1}}\\
&\equiv& \color{#c00}2 (\color{#0a0}{- 2^{\large k+2}})\\
&\equiv& {-}\!2^{\large k+3},\quad {\rm i.e.}\ \ \ P(k+1)
\end{eqnarray}\qquad$$
by the Congruence Product Rule $\ A\equiv a,\ B\equiv b\,\Rightarrow\, AB\equiv ab.\, $ If congruence arithmetic is unfamiliar it can be eliminated by unwinding the proof of the Product Rule, yielding
$\quad \begin{eqnarray} 0\,\equiv\, \color{#c00}{A}&\color{#c00}-&\color{#c00}a, &&\ \color{#0a0}{B}&\color{#0a0}-& \color{#0a0}b &\Rightarrow& \qquad AB\ -\ ab &=& a\ \ (\color{#0a0}{\ B\ \ -\ \ b}\ ) &+& (\color{#c00}{A-a})B\,\equiv\, 0\\
7\,\mid\, \color{#c00}{3^2}&\color{#c00}-&\color{#c00}2, && \color{#0a0}{3^{2k+1}}\!&\color{#0a0}+&\! \color{#0a0}{2^{k+2}} &\Rightarrow& 7\mid 3^{2k+3}\!+2^{k+3}\! &=& 2(\color{#0a0}{3^{2k+1}\!+2^{k+2}}) &+& (\color{#c00}{3^2\!-2})3^{2k+1}\phantom{I^{I^I}} \\
\end{eqnarray}$
The prior is precisely the standard inductive proof that is usually pulled out of hat, like magic, without any intuitive motivation. We can employ further congruence arithmetic to make it even more obvious than above. Note $\,P(k)\,$ is $\,3\cdot 9^k\equiv -4\cdot 2^k\equiv 3\cdot 2^k\ $ so $\,P(k\!+\!1)$ arises simply by multiplying by $\,9\equiv 2\ $ to get $\, P(k\!+\!1)\!:\ 3\cdot 9^{k+1}\equiv 3\cdot 2^{k+1}.\, $ Even more clearly, by dividing, we see that $\,P(k)\,$ is equivalent to $\,(9/2)^k\equiv 1.\,$ But $\,9\equiv 2\,$ so $\,9/2\equiv 1,\,$ so the induction boils down to the trivial induction that $\,1^k\equiv 1,\,$ which is a simple special case of the inductive proof of the Congruence Power Rule.
Similarly, many inductions can be transformed into such standard or trivial inductions. Hence it is well-worth the effort to spend some time looking for such innate structure. This is especially true for divisibility problems, since transforming to congruence form allow us to exploit our well-honed arithmetical intuition, which is much stronger than our intuition on divisibility relation caculus.
A:
\begin{align}3^{2n+1}+2^{n+2}=3\cdot 9^n + 4\cdot 2^n&=7\cdot 9^n -4(9^n-2^n)\\
&=7\cdot 9^n-4(9-2)(9^{n-1}+9^{n-2}\cdot2+\cdots+2^{n-1})\\
&=7[ 9^n-4(9^{n-1}+9^{n-2}\cdot 2\cdots+2^{n-1})]\end{align}
Which is divisible by $7$
Here is a solution based on congruences,
$$3\cdot 9^n +4\cdot 2^n \equiv 3\cdot 2^n +4\cdot 2^n \equiv 7\cdot 2^n \equiv 0\text{(mod 7)}$$
| {
"pile_set_name": "StackExchange"
} |
Q:
Scanner not finding blank lines, returning index out of bounds
I am trying to read a file line by line and take action on every line that begins with the character 'Q'. I keep getting this error after trying many solutions from SO and the JavaDoc. I cannot figure out for the life of me what I am getting it. My method looks like this:
public Question makeQuestion(){
//scanner checks line and takes action
while(fileScan.hasNextLine()){
//save the line
String line = fileScan.nextLine();
//if line is blank move on to next line
if(line.isEmpty()) fileScan.nextLine();
//if line starts with Q do something
if(line.charAt(0) == 'Q'){
System.out.println(line);
}
}
The method finds the first line that begins with Q but fails after that. What could I be doing wrong?
A:
You don't want to execute a send nextLine() within your loop.
Try this:
while(fileScan.hasNextLine()){
//save the line
String line = fileScan.nextLine();
//if line is NOT empty AND starts with Q do something
if(!line.isEmpty() && line.charAt(0) == 'Q'){
System.out.println(line);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Custom winforms authentication against SQL Server: how to handle password expiration?
We've got a project built on Winforms and Entity Framework 4.2 (code-first) and SQLServer 2008 R2.
In this project users must authenticate against the SQL Server using their username/password (from the login screen).
So there will be no "master" or "system" user and there will be no query to retrieve/compare the username/password: the process is already done using the login into the SQL Server.
The users will have their own SQL user accounts and it should be handled within the application.
However we've come across password expiration policy and it got us stuck in the dark.
How may we handle that? Specifically, how may we handle this when the account is already expired?
We have already handled the exception but we simply don't know how to change the password remotely for the user.
It's not about the user A changing password for B. It's about A changing it's own password because it has expired (and I cannot ask the users to login into the SQL Server Management Studio to do that).
A:
You can use the ALTER LOGIN statement
However, note that this theoretically allows any user to change any other user's password provided they have the ALTER LOGIN permission, so you should ensure you make the user supply the old password too (which I believe is the default).
Out of interest, why didn't you go for Windows Authentication? That way the login expiry and password handling would be transparent to you.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible to have UNIQUE on the date portion of the datetime field?
I have a website where the URL contains the year, the month, the date, plus the permalink generated from the article's title. For example
www.example.com/1999/12/31/techno-party
But since the publishing time for articles needs to be per hour, not just per date (e.g. you are able to set the publishing time at 12:00 or 13:00 during the day), that means the publish time column in the database needs to be of datetime datatype, not just date. That means I could then have an article with the permalink techno-party that is being published on December 31st at 12:00, and another (with the same permalink) that is being published on the same day at 13:00 (duplicated created by another user, or by mistake, irrelevant), and their URL's would end up being the same.
So in order to avoid duplicates in this scenario, I need a UNIQUE index for the permalink string, the month, the date, and the year. But obviously, if I set the UNIQUE index on the permalink column and the datetime column, I can still have a lot of duplicates, because the would only restrict them from being published the same exact second.
In theory what I need is a UNIQUE index on the year, month, and date values from the datetime column (ignoring the hour/minute/second) + the permalink column. But is such a thing possible from the database level?
A:
One solution would be to store separately date and time.
Otherwise, you can try adding a ("hidden") DATE field and a trigger.
create trigger setArticleDate BEFORE INSERT ON article
for each row set NEW.__date = DATE(NEW.publish);
Then you create a UNIQUE on permalink and __date.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I resolve "Cannot find module" error using Node.js?
After pulling down a module from GitHub and following the instructions to build it, I try pulling it into an existing project using:
> npm install ../faye
This appears to do the trick:
> npm list
/home/dave/src/server
└─┬ [email protected]
├── [email protected]
├── [email protected]
└── [email protected]
But Node.js can't find the module:
> node app.js
node.js:201
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: Cannot find module 'faye'
at Function._resolveFilename (module.js:334:11)
at Function._load (module.js:279:25)
at Module.require (module.js:357:17)
at require (module.js:368:17)
at Object.<anonymous> (/home/dave/src/server/app.js:2:12)
at Module._compile (module.js:432:26)
at Object..js (module.js:450:10)
at Module.load (module.js:351:31)
at Function._load (module.js:310:12)
at Array.0 (module.js:470:10)
I really want to understand what is going on here, but I'm at a bit of a loss as to where to look next. Any suggestions?
A:
Using npm install installs the module into the current directory only (in a subdirectory called node_modules). Is app.js located under home/dave/src/server/? If not and you want to use the module from any directory, you need to install it globally using npm install -g.
I usually install most packages locally so that they get checked in along with my project code.
Update (8/2019):
Nowadays you can use package-lock.json file, which is automatically generated when npm modifies your node_modules directory. Therefore you can leave out checking in packages, because the package-lock.json tracks the exact versions of your node_modules, you're currently using. To install packages from package-lock.json instead of package.json use the command npm ci.
Update (3/2016):
I've received a lot of flak for my response, specifically that I check in the packages that my code depends on. A few days ago, somebody unpublished all of their packages (https://kodfabrik.com/journal/i-ve-just-liberated-my-modules) which broke React, Babel, and just about everything else. Hopefully it's clear now that if you have production code, you can't rely on NPM actually maintaining your dependencies for you.
A:
I had a very similar issue. Removing the entire node_modules folder and re-installing worked for me:
rm -rf node_modules
npm install
A:
npm install --save module_name
For example, if the error is:
{ [Error: Cannot find module '/root/.npm/form-data'] code: 'MODULE_NOT_FOUND' }
then you can resolve this issue by executing the command npm install --save form-data.
| {
"pile_set_name": "StackExchange"
} |
Q:
Can alpha-beta pruning be used for applications apart from games?
Can alpha-beta pruning/ minimax be used for systems apart from games? Like for selecting the right customer for a product, etc. (the typical data science problems)? I have seen people do it, but can't understand how. Can someone help me understand that?
Can I do something like if - find two criteria on which customers can buy product depends on like gender and age. Find the probability for all the customers depending on age and gender if they can buy it.
like if there are 3 customers - there probability to buy a product on the basis of their age and gender is - Customer 1 - (20%, 30%), Customer 2 - (30%, 60%), Customer 3 - (40%, 20%). here the x and y represents - (probability based on age, probability based on gender ). Probability is probability to buy the product.
For minimax, will it be correct if one player(max) tries to select the customer on basis of gender and other player(min) on basis of age. so, one can be max and one can be min.
Dont know if this correct or not, but just a idea.
A:
Thinking about this more, the answer is in fact yes, but not for the application you mention.
You cannot use alpha-beta pruning to learn a model to predict customer outcomes, because it is only useful for domains where you are concerned about an adversary. In finding a customer model, there is no reason to worry about someone coming in and forcing you to make bad decisions about the optimization of the model. Consequentially, there is no reason to use minimax search, and thus, to use alpha-beta pruning.
There are applications other than (video) games where you could use these techniques though. For example, there are security games. In these "games" we want to use AI to find a strategy to protect an airport. It is reasonable to try and design our model under the assumption that someone else wants to break it. You could use Alpha-Beta pruning here (although in practice, more sophisticated algorithms are used).
| {
"pile_set_name": "StackExchange"
} |
Q:
I can't export more than four artboards in Adobe Illustrator
I am trying to export artboards as PNGs from an AI file. I have a bunch of artboards created, but when I try to export the file and use the artboards, the export dialog only recognizes four artboards.
I've googled and searched all around and I can't seem to find any record of anyone else having this same problem.
See these examples:
However, when I try to export I get a dialog allowing me the option to only export 4:
If I try to change the range to something like "1-8", it still only saves artboards 1-4.
This same thing is happening when I try to save as a pdf, or any other thing in AI that uses the artboards. It only returns 4.
I've tried restarting AI, restarting my computer, but it still does the same thing.
I have Illustrator CS6, not the Creative Cloud, I have the single license, one time fee version.
Anyone ever run into this issue? It's driving me crazy.
Thanks for your help!
A:
Either the file must be damaged.
Or application prefs need dumped..
or application needs reinstalled.
There's no limit to the number of artboards you can export other than the global 100 artboard limit in any AI file.
| {
"pile_set_name": "StackExchange"
} |
Q:
boost pool_alloc
Why is the boost::fast_pool_allocator built on top of a singleton pool, and not a separate pool per allocator instance? Or to put it another way, why only provide that, and not the option of having a pool per allocator? Would having that be a bad idea?
I have a class that internally uses about 10 different boost::unordered_map types. If I'd used the std::allocator then all the memory would go back to the system when it called delete, whereas now I have to call release_memory on many different allocator types at some point.
Would I be stupid to roll my own allocator that uses pool instead of singleton_pool?
thanks
A:
It's difficult for an allocator to have state, since all instances of an allocator had to be 'equivalent' to be used by the standard library (at least portably).
From 20.1.5/4 "Allocator requirements":
Implementations of containers described in this International Standard are permitted to assume that their Allocator template parameter meets the following two additional requirements beyond those in Table 32.
All instances of a given allocator type are required to be interchangeable and always compare equal to each other
It then goes on to say:
Implementors are encouraged to supply libraries that can accept allocators that encapsulate more general memory models and that support non-equal instances. In such implementations, any requirements imposed on allocators by containers beyond those requirements that appear in Table 32, and the semantics of containers and algorithms when allocator instances compare non-equal, are implementation-defined.
So an implementation can be written to allow non-equivalent allocator instances, but then your allocator is dependent in implementation-defined behavior.
See this other SO answer for some additional details (and it looks like I need to tend to some promised updating of that answer...)
| {
"pile_set_name": "StackExchange"
} |
Q:
spinner setOnItemSelectedListener doesn't work
I have a spinner that I put its items dynamically from my database but the problem is I can't know which item is selected by the method setOnItemSelectedListener
Here is my java code :
public class Choix extends Activity {
JSONArray ja1 = null;
List<String> list = new ArrayList<String>();
ArrayAdapter<String> dataAdapter;
Spinner spinner;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.choix_espace);
spinner = (Spinner) findViewById(R.id.spinner);
liste_ecoles k = new liste_ecoles();
k.execute();
dataAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), ""+arg2, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
private class liste_ecoles extends AsyncTask<String, Integer, Object> {
String ch1="";
@Override
protected Object doInBackground(String... params) {
JSONArray ja = null;
try {
URL twitter = new URL("...");
URLConnection tc = twitter.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
ja = new JSONArray(line);
}
} catch (Exception e) {
}
return ja;
}
@Override
protected void onPostExecute(Object resultat) {
JSONArray ja = (JSONArray) resultat;
if (resultat != null) {
try {
for (int i = 0; i < ja.length(); i++) {
JSONObject jo1 = null;
jo1 = ja.getJSONObject(i);
ch1 = jo1.getString("nom_ecole");
list.add(ch1);
}
}
catch (Exception e) {
}
}
}
}
}
so can someone helps me please ?
A:
I solved my problem ; I've just added " dataAdapter.notifyDataSetChanged(); " after adding items on my spinner
| {
"pile_set_name": "StackExchange"
} |
Q:
robot types the wrong chars
I got a java robot to type characters, however it prints stuff like:
.. 5./. .. .. //5 / /55/ /.. ..5.. .. 5 5 . 5.
Instead of the wanted string.
Does someone know how to avoid this?
import java.awt.Robot;
import java.awt.AWTException;
Robot robot;
String txt = "o noes ";
char[] chars;
void setup() {
chars = txt.toCharArray();
try {
robot = new Robot();
}
catch(AWTException e) {
}
robot.setAutoDelay(1);
for (int i = 0; i < 10000; i++) {
int c = chars[(int)random(chars.length)];
robot.keyPress(c);
robot.keyRelease(c);
}
}
A:
You might consider this kind of lengthy but it works http://pastebin.com/p0BdJxpy
| {
"pile_set_name": "StackExchange"
} |
Q:
Ember: Model as content for CollectionView
How can I add the model data from an ajax request to the content of a Ember.CollectionView so that I can create a list of items? I would like to render a list displaying the title from each object in the array returned from the API. I am using Ember Data as I am trying to learn that along with Ember.
Here is a fiddle to my current code. http://jsfiddle.net/ahzk5pv1/
Here is my JavaScript, Templates, and the data I am returning from an API:
JS:
App = Ember.Application.create();
App.ListView = Ember.CollectionView.extend({
tagName: 'ul',
//How do I set the content to be the data from the API???
content: App.Page,
itemViewClass: Ember.View.extend({
template: Ember.Handlebars.compile('the letter is = {{view.content}}')
})
});
App.ApplicationAdapter = App.RESTAdapter = DS.RESTAdapter.extend({
host: 'https://api.mongolab.com/api/1/databases/embertest2/collections',
//Construct query params for adding apiKey to the ajax url
findQuery: function(store, type, query) {
var url = this.buildURL(type.typeKey),
proc = 'GET',
obj = { data: query },
theFinalQuery = url + "?" + $.param(query);
console.log('url =',url);
console.log('proc =',proc);
console.log('obj =',obj);
console.log('theFinalyQuery =',theFinalQuery);
return this._super(store, type, query);
}
});
App.ApplicationSerializer = DS.RESTSerializer.extend({
normalizePayload: function(payload) {
var pagesArray = [];
payload[0].pages.forEach(function(element, index) {
element.id = index;
pagesArray.push(element);
})
return {pages: pagesArray};
}
});
App.Page = DS.Model.extend({
character: DS.attr('string'),
title: DS.attr('string')
});
App.HomeRoute = Ember.Route.extend({
model: function() {
return this.store.find('page', {apiKey: 'somekey'});
}
});
App.Router.map(function() {
this.route('home', {path: '/'});
});
Template:
<script type="text/x-handlebars">
<nav>
{{#link-to 'home'}}Home{{/link-to}}
</nav>
<div class="container">
{{view 'list'}}
</div>
</script>
Data from API:
{
"_id": {
"$oid": "54640c11e4b02a9e534aec27"
},
"start": 0,
"count": 5,
"total": 1549,
"pages": [
{
"character": "Luke Skywalker",
"title": "Star Wars"
},
{
"character": "Sauron",
"title": "Lord Of The Rings"
},
{
"character": "Jean Luc Piccard",
"title": "Star Trek: The Next Generation"
}
]
}
A:
It took some time but this is what I eventually used.
JavaScript:
App = Ember.Application.create();
App.Router.map( function() {
});
App.IndexController = Ember.ArrayController.extend({
});
App.IndexRoute = Ember.Route.extend({
model : function(){
return this.store.find('page', {apiKey: 'keyForApi'});
},
})
App.HomeView = Ember.CollectionView.extend({
tagName: 'ul',
contentBinding: 'controller',
itemViewClass : Ember.View.extend({
tagName : "li",
template : Ember.Handlebars.compile('<p><a href="#">Name:{{view.content.title}}</a></p>')
})
});
App.ApplicationAdapter = App.RESTAdapter = DS.RESTAdapter.extend({
host: 'https://api.mongolab.com/api/1/databases/embertest2/collections',
//Construct query params for adding apiKey to the ajax url
findQuery: function(store, type, query) {
var url = this.buildURL(type.typeKey),
proc = 'GET',
obj = { data: query },
theFinalQuery = url + "?" + $.param(query);
console.log('url =',url);
console.log('proc =',proc);
console.log('obj =',obj);
console.log('theFinalyQuery =',theFinalQuery);
return this._super(store, type, query);
}
});
App.ApplicationSerializer = DS.RESTSerializer.extend({
normalizePayload: function(payload) {
var pagesArray = [];
payload[0].pages.forEach(function(element, index) {
element.id = index;
pagesArray.push(element);
})
return {pages: pagesArray};
}
});
App.Page = DS.Model.extend({
character: DS.attr('string'),
title: DS.attr('string')
});
Templates:
<script type="text/x-handlebars" data-template-name="application">
<nav>
Example
</nav>
<div class="container">
{{outlet}}
</div>
</script>
<script type="text/x-handlebars" data-template-name="index">
{{view 'home'}}
</script>
| {
"pile_set_name": "StackExchange"
} |
Q:
NavMesh baking finished very quickly and does not include some objects
I am doing one of Unity's official tutorials: Survival Shooter.
Unity version: 5.3.4f1 Device: Macbook, OSX 10.11
http://unity3d.com/learn/tutorials/projects/survival-shooter/environment?playlist=17144
The problem: Baking process completes almost instantly and the floor is not highlighted by a blue mesh (where highlight should mean that navmesh is calculated for there).
Here is the screenshot of it:
Then, I checked the completed scene (which was already created by Unity Team), it showed the floor fully highlighted. I just hit the bake again without touching anything and the same problem happened. So, there must be something else as I tried the original scene file without changing anything.
What am I missing here? Is there a Unity editor setting or something like that which can break the baking process?
A:
When baking a NavMesh for your game, a crucial thing to verify is that every object which should affect navigation is marked as a Static GameObject, or at least Static for Navigation. This setting may be found in a checkbox/dropdown at the top of the properties Inspector:
It sounds like the floor object in your scene hasn't been marked as Static, meaning it won't factor into the NavMesh baking.
| {
"pile_set_name": "StackExchange"
} |
Q:
Setting up LAMP Web Server on AWS EC2 t1 Micro
I'm sorry for being dumb, but I am really stuck for few days. This is my first time using AWS. I have successfully installed LAMP web server under t1.micro on my customer's AWS account http://54.72.132.215/ following this tutorial . But I don't know what to do next after the installation. My goal is:
Setup a Domain
Run a Prestashop.
I hope you can guide me to the right path, I am totally lost. Thanks.
A:
You need to register a domain with someone, this is outside of Amazon. Just google domain name registrars:
https://www.google.com/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=domain%20name%20registrar
Then you'll need to point your domain to your Amazon EC2 instance. I would suggest using Route 53 to do this, another Amazon AWS service that makes it easier to setup and control your domains:
http://aws.amazon.com/route53/
Once you have that setup, visiting your name domain should show the default apache It works! page, if you've correctly setup your LAMP server. It'll look something like these:
https://www.google.co.uk/search?q=default+apache+web+page&espv=2&source=lnms&tbm=isch&sa=X&ei=yRfWU_v8OeHe7Abp1ICICw&ved=0CAYQ_AUoAQ&biw=1457&bih=881#imgdii=_
You'll want to add a new vhost for your new PrestaShop site, this will allow you to setup a specific set of files to serve for your new URL, and means you can add other sites to the server later on. Just a quick google shows multiple tutorials on doing this, here's one of them:
http://calebogden.com/multiple-websites-amazon-ec2-linux-virtual-hosts/
Then follow the tutorial in the PrestaShop documentation about installing PrestaShop via the command line:
http://doc.prestashop.com/display/PS16/Installing+PrestaShop+using+the+command-line+script
Now I'm guessing that all those steps in one go is a little overwhelming, so I would suggest you break this task down into chunks and work on them one at a time, and post a few different questions on StackOverflow and probably ServerFault: https://serverfault.com/, as that is better suited to setting up servers.
To summarise you need to:
register a domain name and point it to your EC2 server, you should see the default apache page
create a new vhost to server web pages for your new domain
follow the guide on PrestaShop about installing the software
Treat each of those a separate task. This question covers lots of topics in one very general idea, the full answer to your problem wouldn't really fit in a single post.
ServerFault will probably have a lot of your answers already, regarding setting up domains and vhosts at least.
| {
"pile_set_name": "StackExchange"
} |
Q:
Using PR Build as a Subdomain to Google Cloud Triggered Builds
We are using Google Cloud triggered builds (refer documentation) and are successfully able to see results like:
https://VERSION_ID-dot-PROJECT_ID.appspot.com
We use API keys for Maps etc. and would like to restrict access to websites. For this, there's wild card allowed in API Credentials page (refer documentation) for ex:
https://*.example.com
however, it doesn't allow:
https://*-some-random-string.example.com
We would like to overcome this issue so we can restrict the keys to our PR builds only, how do we do this?
One option would be to have PR builds like:
https://VERSION_ID.PROJECT_ID.appspot.com
so we could use https://*.PROJECT_ID.appspot.com in API Credential restrictions, but I can't figure how to create PR builds as sub domains.
Any help would be much appreciated!
A:
Answering my own question:
GCP does indeed allow patterns in URLs for Credentials:
*-some-random-string.example.com/*
The reason it wasn't working for us was something else, and not this capability.
| {
"pile_set_name": "StackExchange"
} |
Q:
UserRecoverableAuthException: NeedPermission
I tried to follow tutorial: https://developers.google.com/android/guides/http-auth.
Code:
token = GoogleAuthUtil.getToken(getApplicationContext(),
mEmail, mScope);
Manifest:
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
<uses-permission android:name="android.permission.NETWORK"/>
<uses-permission android:name="android.permission.USE_CREDENTIALS"/>
<uses-permission android:name="android.permission.INTERNET"/>
Errors:
01-17 18:37:38.230: W/System.err(3689): com.google.android.gms.auth.UserRecoverableAuthException: NeedPermission
01-17 18:37:38.230: W/System.err(3689): at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source)
01-17 18:37:38.230: W/System.err(3689): at com.google.android.gms.auth.GoogleAuthUtil.getToken(Unknown Source)
01-17 18:37:38.230: W/System.err(3689): at com.example.mgoogleauth.MainActivity$GetIOStreamTask.doInBackground(MainActivity.java:39)
01-17 18:37:38.230: W/System.err(3689): at com.example.mgoogleauth.MainActivity$GetIOStreamTask.doInBackground(MainActivity.java:1)
01-17 18:37:38.230: W/System.err(3689): at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-17 18:37:38.230: W/System.err(3689): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
01-17 18:37:38.230: W/System.err(3689): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
01-17 18:37:38.230: W/System.err(3689): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
01-17 18:37:38.230: W/System.err(3689): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
01-17 18:37:38.230: W/System.err(3689): at java.lang.Thread.run(Thread.java:856)
A:
Try following the Drive quickstart for Android, it is a step-by-step guide showing how to authorize and upload a file to Drive: https://developers.google.com/drive/quickstart-android
To be more specific, it looks like you are not catching the UserRecoverableException and triggering the intent to have the user authorize the app.
This is documented in the Google Play Services docs you linked and handled in the quickstart sample as follows:
...
} catch (UserRecoverableAuthIOException e) {
startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
}
...
A:
the method getAndUseAuthTokenBlocking() of the official GoogleAuthUtil tutorial explains pretty well how to handle the exception:
// Example of how to use the GoogleAuthUtil in a blocking, non-main thread context
void getAndUseAuthTokenBlocking() {
try {
// Retrieve a token for the given account and scope. It will always return either
// a non-empty String or throw an exception.
final String token = GoogleAuthUtil.getToken(Context, String, String)(context, email, scope);
// Do work with token.
...
if (server indicates token is invalid) {
// invalidate the token that we found is bad so that GoogleAuthUtil won't
// return it next time (it may have cached it)
GoogleAuthUtil.invalidateToken(Context, String)(context, token);
// consider retrying getAndUseTokenBlocking() once more
return;
}
return;
} catch (GooglePlayServicesAvailabilityException playEx) {
Dialog alert = GooglePlayServicesUtil.getErrorDialog(
playEx.getConnectionStatusCode(),
this,
MY_ACTIVITYS_AUTH_REQUEST_CODE);
...
} catch (UserRecoverableAuthException userAuthEx) {
// Start the user recoverable action using the intent returned by
// getIntent()
myActivity.startActivityForResult(
userAuthEx.getIntent(),
MY_ACTIVITYS_AUTH_REQUEST_CODE);
return;
} catch (IOException transientEx) {
// network or server error, the call is expected to succeed if you try again later.
// Don't attempt to call again immediately - the request is likely to
// fail, you'll hit quotas or back-off.
...
return;
} catch (GoogleAuthException authEx) {
// Failure. The call is not expected to ever succeed so it should not be
// retried.
...
return;
}
}
A:
I had the same error, in my case I was using a wrong scope, I just change
https://www.googleapis.com/auth/plus.login
for
https://www.googleapis.com/auth/userinfo.profile
| {
"pile_set_name": "StackExchange"
} |
Q:
AS3 Alchemy and ByteArray.setPixels() issue. "bytearray.position = 0" doesn't work
I'm encoding the BitmapData using this method:
http://www.websector.de/blog/2009/06/21/speed-up-jpeg-encoding-using-alchemy/
Code example:
var loader:CLibInit = new CLibInit;
as3_jpeg_wrapper = loader.init();
var baSource: ByteArray = bitmapData.clone().getPixels( new Rectangle( 0, 0, WIDTH, HEIGHT) );
var baAlchmey: ByteArray = as3_jpeg_wrapper.write_jpeg_file(baSource, WIDTH, HEIGHT, 3, 2, quality);
After encoding i need to convert resulting byteArray back to BitmapData. I'm using setPixels() method.
For example:
baAlchemy.position = 0;
var bd:BitmapData = new BitmapData(width, height);
bd.setPixels(rect, baAlchemy);
And i get "Error #2030: End of file was encountered?".
Can anybody help me?
A:
It looks like you are trying to pass the bytes of a compressed JPEG to setPixels().
However, according to the documentation setPixels(), it the second argument to be:
A ByteArray object that consists of 32-bit unmultiplied pixel values to be used in the rectangular region
Or, in other words, an uncompressed image. You will first have to decompress your image, before you can render it into a BitmapData
| {
"pile_set_name": "StackExchange"
} |
Q:
Boost how to create a map for types selection?
so i use BOOST.EXTENTION to load modules. I have a special file that describes each module. I read variables from that file.
so such example:
shared_library m("my_module_name");
// Call a function that returns an int and takes a float parameter.
int result = m.get<int, float>("function_name")(5.0f);
m.close();
for me would turn into:
shared_library m("my_module_name");
// Call a function that returns an int and takes a float parameter.
int result = m.get<myMap["TYPE_1_IN_STRING_FORM"], myMap["TYPE_2_IN_STRING_FORM"]>("function_name")(5.0f);
m.close();
How to create such map that would map standard and costume types?
Update:
may be with variant:
shared_library m("my_module_name");
int result = m.get<boost::variant< int, float, ... other types we want to support >, boost::variant< int, float, ... other types we want to support > >("function_name")(5.0f);
m.close();
can halp? so we would not care as long as all types we want are declared in it?
A:
For that, you would need a heterogeneous map - that is, its elements can be of different types. Furthermore you would need the ability to return types from functions, not just variables.
Now, a heterogeneous map would be possible with Boost.Variant or a simple union, but that binds it to compile time: we need to know every type that is possible to create that variant/union.
Of course a Boost.Any would be possible to store everything and its dog, but the problem strikes again: you need to extract the real type out of that Boost.Any again. The problem repeats itself. And if you know the real type, you can aswell just make a variant/union and save yourself the any_cast trouble.
Now, for another troublesome thing:
m.get<myMap["TYPE_1_IN_STRING_FORM"], myMap["TYPE_2_IN_STRING_FORM"]>
To make the above line work, you'd need two features that C++ doesn't have: the ability to return types and runtime templates. Lets ignore the first point for a moment.
Templates are compile-time, and the get function is such a template. Now, to use that template, your myMap would need to be able to return types at compile-time, while getting populated at runtime. See the contradiction? That's why runtime templates would be needed.
Sadly, exactly those three things are not possible (or extremely hard and very very limited) in C++ at runtime: heterogeneous data types (without constant size), returning types and templates.
Everything that involves types needs to be done at compile-time. This blogpost by @Gman somewhat correlates with that problem. It's definitly worth a read if you want to know what C++ just can't do.
So, to conclude: You'll need to rethink and refactor your problem and solution. :|
| {
"pile_set_name": "StackExchange"
} |
Q:
JMeter environment specific configuration
I have several JMeter test plans which should be executed in different environments, say Dev, Test, UAT, Live. In each test plan I would like to have a simple way to specify which environment to use. Each environment has a lot of configuration such as hostname, port, ssl-cert, user name, password, account numbers and other test data.
One thing I'm trying to achieve is the ease of switching environments while using JMeter GUI or running scenarios from build scripts.
One of my ideas is to use the "Include Controller" to include another jmx file which has list of User Defined Variables and other config elements. However, JMeter does not support variables in the included file name, so I cannot parametrise the scenario by an environment name. Include Controller supports JMeter parameter "includecontroller.prefix", but it is not very flexible, e.g. I cannot change it from JMeter GUI, I should change JMeter config files and restart it.
I've tried to use Switch Controller, but no luck, it doesn't switch configuration elements, only samplers.
What is the best practice to externalise environment specific configuration from test scenarios and share it between several scenarios?
A:
I would suggest to substitute all environment-specific variables or values with JMeter Properties. See following functions for reference:
__property()
__P()
For example you can define a property called hostname in either jmeter.properties file or as JMeter command line argument as follows
jmeter -Jhostname=169.140.130.120 -n -t yourscript.jmx -l yourscriptresults.jtl
and refer to in inside your script as:
${__P(hostname,)}
or
${__property(hostname,,)}
See Apache JMeter Properties Customization Guide for more details.
A:
Like the Manish Sapariya mentioned, Parametrized Controller is quite useful to prepare configuration for more than one environment. I used it in the previous place I worked and started the configuration now in new place. It is a bit of work at the beginning, but later it is easy in maintenance. There is a bit of tutorial in the link that is provided above, but it won't take in consideration that you want to run just one env at a time. I will describe it a bit below, maybe it will be useful.
So, slowly step by step:
First of all - you need two thread groups - one for environment profiles (no 1 on the first screenshot - Env Profiler) and one for your test cases, included test plans etc. (no 2 - API Requests). The latter has to be disabled as it is container that should not be executed straight from here (right click -> disable or Ctrl+T)
Then you need your User Defined Variables elements (no 3) - I'm using three of them:
first for defining which environment will be executed (environmentType var) and logins/passwords, tokens etc.
second with IDs for items needed for tests
third with IPs, ports, path prefixes and so on.
The most important thing here is that I have them separated at this moment by prefixes in variable names, so in one UDV element I have variables like dev.serverIP, dev.serverPort, preprod.serverIP and so on (second screenshot) populated with values relevant for that environment.
Additionally in one of this UDVs I have environmentType variable (mentioned earlier) with default value 'dev' (which you can change manually here or provide different value when launching through command line/CI or whatever)
Now in the Env Profiler I have If Controllers(no 4 on the first screenshot). For dev env I have (no 5 on the first screen):
"${environmentType}" == "dev"
For each env (if controller) you have to provide proper condition like this above.
Each IfController contains that "jp@gc - Parametrized Controller" mentioned before (that you can download as part of Extras Set here by the way). In each Param Controller you assign to variables that you use in test plans variables specific for that environment, e.g. name: serverIP, value: ${dev.serverIP} for dev env (third screenshot)
And now the last thing - tests and plans you want to execute.
In that disabled Thread Group (API Requests) you add Simple Controllers that contains your tests or Include Controllers that import some tests from other files.
When you have those tests, for each one that you want to run in that particular environment you have to add Module cotroller inside Parametrized Controller with path to that test (screenshot below)
And that it is pretty much it. Now maintaining:
to add new variable you have to add it in UDV with prefixes (dev.newVar, preprod.newVar) and fill the relevant values, then add proper entry in Parametrized controllers (those newVar = ${dev.newVar}) and that's it
to add new test from other Test Plan - add Include controller with path to that file and add Module controller in each Paramterized controller directing them to that Include Controller
to add new environment just copy the one you already have, change its If contr., Parametrized controller and fill values in UDVs
The nice thing here is that if you want, lets say, dev env with all tests and the other with just some somke tests you can prepare a copy, change If controller to take some other value of env variable (like dev for all tests, devsmoke for smoke tests) and add or delete some of the module controllers in that new profile.
Of course you can build it up a bit and you can ues different threads for different parts of the system for easier maintanance, just do not forget to disable those threads working as containers.
I know it's a lot to do when you start, but it is not so bad later, when just adding some stuff - probably the easiest way to do it anyway.
| {
"pile_set_name": "StackExchange"
} |
Q:
how can I have picture to my ontology
How can I have a picture for my ontology where you can read the names of all content (class, object properties and data properties) using protege?
A:
See the OntoGraph or OWLViz tab in Protege editor. From there, you can save the graph (if that's what you want).
| {
"pile_set_name": "StackExchange"
} |
Q:
A question about prime divisors of Mersenne number $M_n= 2^n-1$ when $n$ is odd
Is this true that a prime divisor of a Mersenne number $M_n = 2^n-1$ when $n$ is odd, cannot be a Proth prime (i.e. a prime number of the form $2^mk+1$, where $k<2^m$)?
If yes, how is it demonstrated?
thank you!
because, if I am not wrong, for any prime $p>3$ ($= r2^v +1$, where $r$ is odd and $v>1$),
either there exists a unique $j < v-1$ so that $p$ is a divisor of $2^J+1$, where $J=r2^j$,
or $p$ is divisor of $2^r-1$.
In the latter case, whenever I have checked so far, if I write $p$ as $k2^m+1$, ($k$ odd) $k$ is larger than $2^m$. Is this always like that?
In the former case, most of the times $j$ is $v-2$ or a slightly smaller. In particular, so far I have checked, it is rather rare that $v$ and $j$ differ by more than say $5$, like for instance when $p=65537(j=4,v=16)$, or $p=59393(j=2,v=11)$, or $p=25601 (j=3,v=10)$, or $p=2113 (j=1,v=6)$ or $p=6529 (j=0,v=7)$... I wonder how many such prime numbers exist ?
A:
Interesting conjecture! It holds for quite some time...
... before failing at $n=225$. The corresponding Proth prime factor is $p=115201=225\times 2^9+1$. It's not too difficult to see that any odd multiple of $n$ would be a counter-example too, since the corresponding Mersenne number would be divisible by $p$ as well.
The next two non-trivial cases seem to be:
$n=6281$ and $p=51453953=6281\times 2^{13}+1$
$n=7695$ and $p=126074881=7695\times 2^{14}+1$
Interestingly, those are all the counter-examples I managed to find even after searching for quite some more time. It's not too surprising, though, since Proth primes are relatively rare.
| {
"pile_set_name": "StackExchange"
} |
Q:
Android TextInputLayout is not showing error
I am using EditText with TextInputLayout. This is the code, that I am using to display error.
private boolean validateEmail() {
String email = inputEmail.getText().toString().trim();
if (email.isEmpty() || !isValidEmail(email)) {
inputLayoutEmail.setErrorEnabled(true);
inputLayoutEmail.setError(getString(R.string.err_msg_email));
requestFocus(inputEmail);
return false;
} else {
inputLayoutEmail.setErrorEnabled(false);
}
return true;
}
I am calling this method in edittext's textwatcher like in this link http://www.androidhive.info/2015/09/android-material-design-floating-labels-for-edittext/
Once I entered a valid input then clear that ,it will show error message as expected,But it wont work if i enter the text again and then clear it again.ie.It is not showing any error message.
I am using compile 'com.android.support:design:23.1.0' library.
inputLayoutEmail.setErrorEnabled(true);
is calling but error is not displaying. What might be the problem? How I can solve this?
A:
In your layout file, ensure you have layout_height="wrap_content" for the TextInputLayout
instead of a dimension. This was causing the issue for me.
A:
You just need apply,
inputLayoutEmail.setErrorEnabled(false);
inputLayoutEmail.setError(null);
It worked for me. Hope it will work for you too.
A:
The example worked for me.
you use
compile 'com.android.support:design:23.1.0'
and the right one is
compile 'com.android.support:design:23.0.1'
| {
"pile_set_name": "StackExchange"
} |
Q:
What folders should I backup to my computer
I have a SGS2 with ICS. The phone is rooted. I use Titanium Backup Pro for backup, but that only backups to the phone itself, so if the phone is stolen or lost those backups are gone as well.
I have SSHDroid installed, and yesterday I made a backup of the sdcard folder to my home server using rsync. Now I would like to know if there are other folders that have data in them that I miss. I don't necessarily need a full backup of the phone, don't know if that's useful. I just want all user data safe.
So is there something that I'm missing? If so, what folders should I backup as well?
A:
Your SD card contains pretty much all the data you need.
In addition to app backup, you can also use SMS Backup+ to backup your texts to the SD card (and then to the home server).
Titanium Backup Pro version has an option to backup files to your Dropbox folder, so you can use that instead of rsync if you like.
Also, try to move as much data to the cloud as you can - including contacts, settings, photos etc - you get peace of mind knowing that most things are already backed up even if your phone gets damaged or stolen.
| {
"pile_set_name": "StackExchange"
} |
Q:
What Properties are available for purchase in Grand Theft Auto V?
In GTA5:
What properties are available for purchase?
What is their income?
What additional benefits do they offer (if any)?
A:
This IGN interactive map of Los Santos will show you where all 25 properties (and everything else) is located: http://www.ign.com/maps/gta-5/los-santos-blaine-county
IGN also has a great list of all the properties, what they cost, who can access them, and how long it takes to payback the initial investment.
A:
You can buy the following properties in Grand Theft Auto V (note some properties can only be bought by certain characters). There are sometimes bonuses for owning properties, and almost all will ask for assistance from time to time (give you mini-missions).
Any
The Hen House ($80,000)
$920 (87 weeks before profit)
Sonar Collections Dock ($250,000)
$23,000 per collection (11 collections before profit - 30 total)
$250,000 for collecting all 30 (total profit: 940,000)
Bonus: Unlocks "Death at Sea" mission
Car Scrapyard ($275,000)
$150 per car (1,834 tows before profit)
Pitchers ($750,000)
$7,100 (106 weeks before profit)
Tequi-la-la ($2,000,000)
$16,500 (122 weeks before profit)
Los Santos Golf Club ($150,000,000)
$264,500 (568 weeks before profit)
Free golf for all players.
Trevor
McKenzie Field Hangar ($150,000)
$7,000 per air mission / $5,000 per ground mission
Bonus: Trevor gets the Cuban 800 and BF Injection vehicles.
Vanilla Unicorn (free with "Hang Ten" mission)
$5,000
Bonus: Trevor gets free lap dances and drinks. All characters can use hands.
Franklin
LSPD Auto Impound ($150,000)
$500 per car (300 cars before profit)
Downtown Cab Co. ($200,000)
$2,000 (100 weeks before profit)
Bonus: Free taxi rides for Franklin
Smoke on the Water ($204,000)
$9,300 (22 weeks before profit)
Los Santos Customs ($349,000)
$1,600 (219 weeks before profit)
Bonus: Free custom upgrades for Franklin at the Route 68 location
Michael
Cinema Doppler ($10,000,000)
$132,200 (76 weeks before profit)
Ten Cent Theater ($20,000,000)
$264,000 (76 weeks before profit)
Tivoli Cinema ($30,000,000)
$142,300 (211 weeks before profit)
Franklin or Michael
Hookies ($600,000)
$4,700 (128 weeks before profit)
Total Costs
The total money to buy everything in each of the categories above are:
ANY - $153,355,000
TREVOR ONLY - $150,000
FRANKLIN ONLY - $903,000
MICHAEL ONLY - $60,000,000
MICHAEL OR TREVOR - $600,000
TOTAL MONEY REQUIRED: $215,008,000
Total Earnings
Once all the properties becomes profitable (max 568 weeks after purchasing them all), the total weekly profit is:
ANY - $289,020 (568 weeks)
TREVOR ONLY - $9700 (128 weeks)
FRANKLIN ONLY - $17,600 (219 weeks)
MICHAEL ONLY - $538,500 (211 weeks)
NOTE: One week in GTAV equals five hours and 36 minutes in real life.
| {
"pile_set_name": "StackExchange"
} |
Q:
Programmatically added auto layout view not displaying
I have a view controller with a table (defined through Interface Builder). I am trying to programmatically add a button 18px from the bottom of the table.
I have following in loadView:
- (void)loadView {
[super loadView];
UIButton *testButton = [UIButton buttonWithType:UIButtonTypeSystem];
testButton.titleLabel.font = [UIFont fontWithName:@"System" size:13];
[testButton setTitle:@"Logout" forState:UIControlStateNormal];
[testButton setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:testButton];
self.testButton = testButton;
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:testButton attribute:NSLayoutAttributeWidth
relatedBy:NSLayoutRelationEqual
toItem:self.twitterAuthButton
attribute:NSLayoutAttributeWidth
multiplier:1 constant:0]];
NSLayoutConstraint *centerXConstraint = [NSLayoutConstraint constraintWithItem:testButton
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1.0 constant:0.0];
NSLayoutConstraint *alignToBottomOfTable = [NSLayoutConstraint constraintWithItem:testButton
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:availableStreamsTableView
attribute:NSLayoutAttributeBottom
multiplier:1 constant:18];
[self.view addConstraint:centerXConstraint];
[self.view addConstraint:alignToBottomOfTable];
}
But the button is not displaying. Not sure why. When I debug (in AppCode), it seems to be there and at the right x and y:
Any idea why the button is not showing?
A:
Ah, I think I see it. You want a negative constant for your alignToBottomOfTable constraint. The positive 18 constant is pushing your button below the bottom of your table.
NSLayoutConstraint *alignToBottomOfTable = [NSLayoutConstraint constraintWithItem:testButton
attribute:NSLayoutAttributeTop
relatedBy:NSLayoutRelationEqual
toItem:availableStreamsTableView
attribute:NSLayoutAttributeBottom
multiplier:1 constant:-18];
| {
"pile_set_name": "StackExchange"
} |
Q:
Linq query - get first object of related entity
I have a problem with my query
var ninjas = from n in this.dbContext.Ninjas
join e in this.dbContext.Equipment on n.Id equals e.NinjaId
select ( new NinjaModel()
{
Id = n.Id,
Name = n.Name,
FirstEquipmentItemName = n.Equipment.FirstOrDefault()?.Name,
BornDate = DbFunctions.TruncateTime(n.BornDate).Value
});
I cant use FirstOrDefault in my query and I want to get first item name of ninja equipment there. Is it possible? I know I can use
this.dbContext.Ninjas.AsEnumerable()
but then DbFunctions.TruncateTime wont work.
A:
Your problems is usage of null-conditional operator in query:
FirstEquipmentItemName = n.Equipment.FirstOrDefault()?.Name
That will give an error
An expression tree lambda may not contain a null propagating
operator.
What you need - just get name without null-conditional operator. In case if there is no related entites, name will have null value:
FirstEquipmentItemName = n.Equipment.FirstOrDefault().Name
What is happening behind the scene - EF generates SQL query which returns TOP (1) equipment name from related table. Something like:
SELECT
[Extent1].[Id] AS [Id],
[Extent1].[Name] AS [Name],
(SELECT TOP (1)
[Extent2].[Name] AS [Name]
FROM [dbo].[Equipment] AS [Extent2]
WHERE [Extent1].[Id] = [Extent2].[Id]) AS [C1]
FROM [dbo].[Ninjas] AS [Extent1]
| {
"pile_set_name": "StackExchange"
} |
Q:
Clarification about equivalence irreducibility and prime ideals
It is known the following equivalence: Let $Y \subset \mathbb{A}^{n}$ be an algebraic set. Then $Y$ is irreducible if and only if $I(Y)$ is prime, where:
$I(Y) = \{f \in K[x_{1},x_{2},..,x_{n}]: \textrm{for all p in Y}, \ f(p)=0 \}$.
So as an example, the author considers $J = \langle (xz-y^2,x^3-yz) \rangle \subset k[x,y,z]$. Then let $Y=V(J)$ (the locus set).
So if we want to find whether $Y$ is irreducible we must study $I(Y)=I(V(J))$ and show
this ideal is prime (or show it is not).
The author then shows that $J$ is not a prime ideal. But why is this? don't we need to show that $I(V(J))$ is a prime ideal? why we must check $J$? or do we always have $J=I(V(J))$?
A:
No, we don't always have $I(V(J))=J$ - the Nullstellensatz says that we always have $I(V(J))=\sqrt{J}$, where $\sqrt{J}$ is the radical of the ideal $J$, but there are many ideals that are not equal to their radical. For example, the radical of the non-prime ideal $J=(x^2)$ in $k[x]$ is the prime ideal $(x)$, so that $V(J)$ is irreducible even though $J$ is not prime. So your complaint is valid; it sounds like the book's argument for why $V(J)$ is not irreducible is in error. Could you specify the author/title?
| {
"pile_set_name": "StackExchange"
} |
Q:
bower install fails silently on any package
I can install Bower and it seems just fine via npm. I create a bower.json file using bower init, and add dependencies. Then when I use bower install, literally nothing happens in the terminal. I can use bower update to install packages, but bower install does not work and I cannot get any error to produce, even with --verbose. I've included bower.json below:
{
"name": "testing",
"version": "0.0.0",
"authors": [
"AJ"
],
"main": "index.html",
"license": "private",
"private": true,
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
],
"dependencies": {
"polymer": "Polymer/polymer#~0.3.0",
"core-menu": "Polymer/core-menu",
"core-ajax": "Polymer/core-ajax"
}
}
edit: using 1.3.3, but I've reproduced this using 1.3.2 as well
A:
Try removing the bower_components directory and running bower install again.
Edit:
This is also related to a circular dependency in Polymer see: https://github.com/bower/bower/issues/1324#issuecomment-44436595
| {
"pile_set_name": "StackExchange"
} |
Q:
Draw on a custom widget, without event
I'm playing around with pyqt4. I want to create a custom widget, and draw some rectangles on it. I've already used similar stuff on QCanvas, but now I just want it to draw my rectangles if I create an object from my custom class...
self.IND = [] contains colors (QColor)
class labelBOX(QtGui.QWidget):
def __init__(self, parent, X,Y, holes):
super(labelBOX , self).__init__(parent)
self.gridL = QtGui.QGridLayout(self)
self.setGeometry(X,Y, 50, 100)
self.setWindowTitle("LEGEND")
self.HOLES = holes
self.LBL = []
self.setLayout(self.gridL)
self.i = 0
self.j = 0
self.genLBL()
self.IND = []
self.qp = QtGui.QPainter()
self.genIND(self.qp)
self.show()
"""
Generate labels
"""
def genLBL(self):
for k in range(len(self.HOLES)):
self.LBL.append(QtGui.QLabel(QtCore.QString(self.HOLES[k].getNAME())))
for k in range(len(self.LBL)):
self.gridL.addWidget(self.LBL[k])
"""
Generate indicators
"""
def genIND(self, qp):
self.i = 0
self.j = 1
for k in range(len(self.HOLES)):
self.IND.append(self.HOLES[k].getCOLOR())
for k in range(len(self.IND)):
qp.setBrush(self.IND[k])
self.gridL.addWidget(qp.fillRect(10,10,50,50, ))
class OTHERCLASS():
....
self.WIDGET = labelBOX(self, 550, 350, dummyLOAD)
....
A:
If you want to manually draw on the custom widget then you can override the paintEvent or use absolute positioning and place the rectangles where you want. The paintEvent might be better, but it is more complex. http://zetcode.com/gui/pyqt4/drawing/ example and http://pyqt.sourceforge.net/Docs/PyQt4/qpainter.html is the class reference. I wrote an example below.
def paintEvent(self, event):
super().paintEvent(event)
painter = QtGui.QPainter()
painter.begin(self)
rect = self.rect()
gradient = QtGui.QRadialGradient(rect.center(), rect.width())
gradient.setColorAt(0.0, QtGui.QColor(255, 255, 255, 10)
gradient.setColorAt(0.90, QtGui.QColor(0, 0, 0, 255))
gradient.setColorAt(0.98, QtGui.QColor(0, 0, 0, 100))
painter.setPen(QtGui.QColor(0, 0, 0) # Pen works on the border
painter.setBrush(grad) # Main color
# Draw the rectangle
painter.drawRect(rect) # Try to keep your rectangle within the widget area
painter.end()
event.accept()
| {
"pile_set_name": "StackExchange"
} |
Q:
Instance variable inheritance problems
For some unknown reason my program seems to be creating an instance of the character but not assigning an _id even though the _id even has a default in the __init__.
I'm not sure why this is and yes I'm new to python and trying to learn OOP and inheritance to make sure I fully understood the tutorials I had watched I decided to create a kind of complex program for this.
class Entity(object):
def __init__(self, _id = None):
self._id = _id
self._pos = (0, 0)
self._vel = (0, 0)
# --------------------------------------------------------------
class Character(Entity):
def __init__(self, _id = None, _name = None):
self._id, self._name = _id, _name
self._entity = Entity.__init__(self._id)
# --------------------------------------------------------------
character = Character(0, 'End')
The error's I get is as follow's...
File "test.py", line 119, in <module>
character = Character(0, 'End')
File "test.py", line 59, in __init__
self._entity = Entity.__init__(self._id)
File "test.py", line 5, in __init__
self._id = _id
AttributeError: 'int' object has no attribute '_id'
I think this means that when a new object of Character/Entity is created it cannot find, init or define the _id variable? This is probably a simple error and I'm doing something very wrong but thanks in advance.
A:
You are initializing the super-class incorrectly. You must pass self in as well:
self._entity = Entity.__init__(self, self._id)
However, it is easier to use super() in most cases:
self._entity = super().__init__(self._id)
In both cases:
character = Character(0, 'End')
print(vars(character))
# {'_id': 0, '_name': 'End', '_pos': (0, 0), '_vel': (0, 0), '_entity': None}
Also, it is pointless to assign the return value of the init (always None) to self._entity. You can just make it
Entity.__init__(self, self._id)
or
super().__init__(self._id)
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.