text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Simple AJAX/PHP problem but with long explanation
I just started this book - "AJAX and PHP Second edition" and I failed on the very first example.I'm pretty sure the code is just as it is shown in the book, but still when I run index.htm in the error console(Mozzila 6.0) I get this : "xmlResponse is NULL http://localhost/ajax/quickstart/quickstart.js.I don't know what's going on but really don't want to give up at the very begining so I'll pase all the 3 files and hopefully anyone would point me where the problem is.
Here is the index.htm :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>AJAX with PHP, 2nd Edition: Quickstart</title>
<script type="text/javascript" src="quickstart.js"></script>
</head>
<body onload="process();">
Server wants to know your name:
<input type="text" id="myName" />
<div id="divMessage" ></div>
</body>
</html>
here is the quickstart.js :
// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject();
// retrieves the XMLHttpRequest object
function createXmlHttpRequestObject()
{
// stores the reference to the XMLHttpRequest object
var xmlHttp;
// if running Internet Explorer 6 or older
if(window.ActiveXObject)
{
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
xmlHttp = false;
}
}
// if running Mozilla or other browsers
else
{
try {
xmlHttp = new XMLHttpRequest();
}
catch (e) {
xmlHttp = false;
}
}
// return the created object or display an error message
if (!xmlHttp)
alert("Error creating the XMLHttpRequest object.");
else
return xmlHttp;
}
// make asynchronous HTTP request using the XMLHttpRequest object
function process(name)
{
// proceed only if the xmlHttp object isn't busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
{
// retrieve the name typed by the user on the form
name = encodeURIComponent(
document.getElementById("myName").value);
// execute the quickstart.php page from the server
xmlHttp.open("GET", "quickstart.php?name=" + name, true);
// define the method to handle server responses
xmlHttp.onreadystatechange = handleServerResponse;
// make the server request
xmlHttp.send();
}
else
// if the connection is busy, try again after one second
setTimeout('process()', 1000);
}
// callback function executed when a message is received from the
//server
function handleServerResponse()
{
// move forward only if the transaction has completed
if (xmlHttp.readyState == 4)
{
// status of 200 indicates the transaction completed
//successfully
if (xmlHttp.status == 200)
{
// extract the XML retrieved from the server
xmlResponse = xmlHttp.responseXML;
// obtain the document element (the root element) of the XML
//structure
xmlDocumentElement = xmlResponse.documentElement;
// get the text message, which is in the first child of
// the the document element
helloMessage = xmlDocumentElement.firstChild.data;
// display the data received from the server
document.getElementById("divMessage").innerHTML =
'<i>' + helloMessage
+ '</i>';
// restart sequence
setTimeout('process()', 1000);
}
// a HTTP status different than 200 signals an error
else
{
alert("There was a problem accessing the server: " +
xmlHttp.statusText);
}
}
}
and finally the quickstart.php :
<?php
// we'll generate XML output
header('Content-Type: text/xml');
// generate XML header
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
// create the <response> element
echo '<response>';
// retrieve the user name
$name = $_GET['name'];
// generate output depending on the user name received from client
$userNames = array('YODA', 'AUDRA', 'BOGDAN', 'CRISTIAN');
if (in_array(strtoupper($name), $userNames))
echo 'Hello, master ' . htmlentities($name) . '!';
else if (trim($name) == '')
echo 'Stranger, please tell me your name!';
else
echo htmlentities($name) . ', I don\'t know you!';
// close the <response> element
echo '</response>';
?>
Thanks in advanced!
Leron
A:
There are a couple of problems I found with your code. Mentioning some of them
You are calling the process() on body-onload. This means, when the DOM is ready, the browser calls the process() function. This, IMO, is not something you would want. Instead, have a button, which calls this process function with the onclick event. Something like:
<button onclick="process('YODA');return false;">Click Me!</button>
Process is defined as taking one parameter called name, you are passing none. So, make a fix something like this:
<button onclick="myProcess();return false;">Click Me!</button>
And is your JS section/file
function myProcess(){
process(encodeURIComponent(document.getElementById('myName').value));
}
Do not have that document.getElementById(..) inside the process function. It defeats the entire purpose of passing that parameter 'name'
I would ask you to use a really good browser like Mozilla Firefox, or Google Chrome (since you seem to give IE6 a prefence in your code, atleast seems like it!). Chrome has a fantastic inspector window. Once you get the hang of it, you will almost fall in love with it. I did! ;-)
I would suggest, you use libraries like jQuery(www.jquery.com) or something, for ajax. Makes your life easier! :-)
EDIT
I would suggest the following steps, since you want to get this piece of code working.
First open the url [BASE-URL]/quickstate.php?name=YODA. If everything is just fine, you should see the XML that should be the response to your AJAX call. If not, there's some problem with the PHP file(or a few settings of your server), and not anything else. I feel this step wouldn't be a problem.
Next, once the page is loaded, type 'YODA' in the textbox, type this in the browser's URL box: javascript:process(''). This should call the function that has the ajax call. You could keep a tab on the data transferred section of the firebug(I dont know the name exactly, but its the 'Network' section in Google Chrome). You could analyse the headers sent to the PHP scripts, and the response (including the HTTP error codes) sent back to you from the server. I also feel this wont be a problem.
What causes the problem is: The DOM of the page is loaded. The AJAX call is made once the DOM is ready. This means the AJAX request is made even before you type anything in that textbox. And thus, the request that goes to the server has a empty value for name parameter. This is exactly, (IMO) the reason why things are not working for you. But even then, this is not the reason why you see a null for XML out there. Could you do a console.log(xmlHttp) and tell us the results?
| {
"pile_set_name": "StackExchange"
} |
Q:
Linux shell programming string compare syntax
What is the difference between = and == to compare strings in Linux shell programming?
Maybe the following code works:
if [ "$NAME" = "user" ]
then
echo "your name is user"
fi
But I think it's not a correct syntax. It would be used to compare string by == statement.
What is correct?
A:
The single equal is correct
string1 == string2
string1 = string2
True if the strings are equal. ‘=’ should be used with the test command for POSIX conformance
NAME="rafael"
USER="rafael"
if [ "$NAME" = "$USER" ]; then
echo "Hello"
fi
A:
In general, the = operator works the same as == when comparing strings.
Note:
The == comparison operator behaves differently within a double-brackets test than within single brackets.
[[ $a == z* ]] # True if $a starts with an "z" (pattern matching).
[[ $a == "z*" ]] # True if $a is equal to z* (literal matching).
[ $a == z* ] # File globbing and word splitting take place.
[ "$a" == "z*" ] # True if $a is equal to z* (literal matching).
source: http://tldp.org/LDP/abs/html/comparison-ops.html
A:
These pages explain the various comparison operators in bash:
http://www.tech-recipes.com/rx/209/bournebash-shell-scripts-string-comparison/
http://tldp.org/LDP/abs/html/comparison-ops.html
http://www.faqs.org/docs/Linux-HOWTO/Bash-Prog-Intro-HOWTO.html#ss11.2
On the second linked page, you will find:
==
is equal to
if [ "$a" == "$b" ]
This is a synonym for =.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to capture submit event using jQuery in an ASP.NET application?
I'm trying to handle the submit event of a form element using jQuery.
$("form").bind("submit", function() {
alert("You are submitting!");
});
This never fires when the form submits (as part of a postback, e.g. when I click on a button or linkbutton).
Is there a way to make this work? I could attach to events of the individual elements that trigger the submission, but that's less than ideal - there are just too many possibilities (e.g. dropdownlists with autopostback=true, keyboard shortcuts, etc.)
Update: Here's a minimal test case - this is the entire contents of my aspx page:
<%@ page language="vb" autoeventwireup="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:scriptmanager id="ScriptManager" runat="server" enablepartialrendering="true">
<scripts>
<asp:scriptreference path="/Standard/Core/Javascript/Jquery.min.js" />
</scripts>
</asp:scriptmanager>
<p>
<asp:linkbutton id="TestButton" text="Click me!" runat="server" /></p>
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
alert("Document ready.");
$("form").submit(function() {
alert("Submit detected.");
});
});
</script>
</body>
</html>
I get the "Document ready" alert, but not the "Submit detected" when clicking on the linkbutton.
A:
Thanks, @Ken Browning and @russau for pointing me in the direction of hijacking __doPostBack.
I've seen a couple of different approaches to this:
Hard-code my own version of __doPostBack, and put it later on the page so that it overwrites the standard one.
Overload Render on the page and inject my own custom code into the existing __doPostBack.
Take advantage of Javascript's functional nature and create a hook for adding functionality to __doPostBack.
The first two seem undesirable for a couple of reasons (for example, suppose in the future someone else needs to add their own functionality to __doPostBack) so I've gone with #3.
This addToPostBack function is a variation of a common pre-jQuery technique I used to use to add functions to window.onload, and it works well:
addToPostBack = function(func) {
var old__doPostBack = __doPostBack;
if (typeof __doPostBack != 'function') {
__doPostBack = func;
} else {
__doPostBack = function(t, a) {
if (func(t, a)) old__doPostBack(t, a);
}
}
};
$(document).ready(function() {
alert("Document ready.");
addToPostBack(function(t,a) {
return confirm("Really?")
});
});
Edit: Changed addToPostBack so that
it can take the same arguments as __doPostBack
the function being added takes place before __doPostBack
the function being added can return false to abort postback
A:
I've had success with a solution with overriding __doPostBack() so as to call an override on form.submit() (i.e. $('form:first').submit(myHandler)), but I think it's over-engineered. As of ASP.NET 2.0, the most simple workaround is to:
Define a javascript function that you want to run when the form is submitted i.e.
<script type="text/javascript">
function myhandler()
{
alert('you submitted!');
}
</script>
Register your handler function within your codebehind i.e.
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
ScriptManager.RegisterOnSubmitStatement(Page, Page.GetType(),
"myHandlerKey", "myhandler()");
}
That's all! myhandler() will be called from straightforward button-input submits and automatic __doPostBack() calls alike.
A:
Yeah, this is annoying. I replace __doPostBack with my own so that I could get submit events to fire.
Iirc, this is an issue when submitting a form via javascript (which calls to __doPostBack do) in IE (maybe other browsers too).
My __doPostBack replacement calls $(theForm).submit() after replicating the default behavior (stuffing values in hidden inputs)
| {
"pile_set_name": "StackExchange"
} |
Q:
Why can't I do forEach on a Javascript deep cloned array?
This gives me an alert for the numbers 1, 2, and 3.
[1,2,3].forEach(alert);
This gives me an error:
$.extend(true, {}, [1,2,3]).forEach(alert);
The error:
TypeError: Object #<Object> has no method 'forEach'
Why does this happen, and how can I loop over the cloned object?
A:
Your .extend() call is creating an plain object, not an array. (That is, you're not actually creating a "deep cloned array".) There's no iterator like .forEach on plain objects.
| {
"pile_set_name": "StackExchange"
} |
Q:
disability insurance on a car loan
I have a car loan which i am the primary borrower and my daughter is the second . I recently became disabled. The bank put the disability insurance on the loan . My question is will they pay my car payments or try to go after my Daughter for the payments ?
A:
Check the policy paperwork. That should explain how the terms of the policy are triggered. It should define disabled, how long before payments start, what doctors proof is needed, and what it means to return to work.
Because there are two borrowers involved in the loan, the paperwork should also address what happens when only one is disabled.
| {
"pile_set_name": "StackExchange"
} |
Q:
Token errors, syntax
I am writing a function in Java, but I can't compile the code. I don't see the syntax error; can you help me?
public String getUserInput(String prompt){
String inputLine = null;
System.out.print(prompt + " ");
try(
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
inputLine = is.readLine();
if (inputLine.length() == 0 )
return null;
)
catch (IOException e) {
System.out.println("IOException: " + e);
}
return inputLine.toLowerCase();
}
It doesn't compile.
A:
Replace the ( and ) enclosing your try-Block with { and }
| {
"pile_set_name": "StackExchange"
} |
Q:
Find most frequent occurrence with condition on Google Sheets
I have a list of countries and company types (A, B, C and D) in a Google Sheet. For each country, there are multiple entries, one entry per company. Countries are in column A of the spreadsheet, the type of the companies is in column B.
I would like to find out, for each country, what is the most common type of company. In other words, I would like to know, for each country, what is the letter in column B, that appears the most.
I have managed to find out what is the letter that appears the most in the entire list of countries. To do that, I have used this formula in cell D2:
=ARRAYFORMULA(INDEX(B1:B,MATCH(MAX(COUNTIF(B1:B,B1:B)),COUNTIF(B1:B,B1:B),0)))
It gives me the most common letter overall. However, I am not sure how to include a condition in the formula that will give me the answer considering one particular country only.
I have created a sample sheet, which you can find here. I have created a table on D1:E16 in which I would like to have the formula.
Thank you.
A:
This should do it:
=ARRAYFORMULA(INDEX($B$1:$B,MATCH(MAX(COUNTIFS($B$1:$B,$B$1:$B,$A$1:$A,D2)),COUNTIFS($B$1:$B,$B$1:$B,$A$1:$A,D2),0)))
| {
"pile_set_name": "StackExchange"
} |
Q:
navigate not working ONLY for empty fragment after enabling pushState
So, I had a Backbone Marionette app fully working with hashes. Then, I decided to enable pushState for better UX URLs.
I access the app at:
http://localhost:8888/multikanban/app
I applied the following changes:
Enable pushState
Backbone.history.start({pushState: true, root: "/multikanban/app/"});
Define the following .htaccess
<ifModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !index
RewriteRule (.*) app/index.html [L]
</ifModule>
At this point, the app loads without issues, I can move around, login, etcetera. However, when App.navigate("") is called (when I need to go to the initial app state) I get the following error:
Uncaught SyntaxError: Unexpected token <
landing_app.js:15 Uncaught TypeError: Cannot read property 'showLanding' of undefinedlanding_app.js:15 (anonymous function)require.js:1658 context.execCbrequire.js:874 Module.checkrequire.js:1121 (anonymous function)require.js:132 (anonymous function)require.js:1164 (anonymous function)require.js:57 eachrequire.js:1163 Module.emitrequire.js:925 Module.checkrequire.js:1151 Module.enablerequire.js:782 Module.initrequire.js:1178 callGetModulerequire.js:1572 context.completeLoadrequire.js:1679 context.onScriptLoad
require.js:1903 Resource interpreted as Script but transferred with MIME type text/html: "http://localhost:8888/multikanban/scripts/apps/landing/show/show_controller.js".
With App.navigate("") I am only updating the URL, nothing should be being "transferred" as the error states...
Observations:
The App.navigate("") worked before using pushState.
Changing App.navigate("") to something like App.navigate("a") makes it work but ofcourse the URL is wrong..
Commenting the App.navigate("") doesnt get the app to crash, it simply doesn't update the URL, so yeah the problem should be with App.navigate("")
How can I get App.navigate("") to work? Why is that command apparently interacting with the server, shouldn't it just update the URL and history? Any ideas of where could I ask about this?
A:
Ok, so after a lot of struggling I fixed it. Apparently, it had nothing to do with the latter changes, but with the requirejs configuration, which had been mysteriously working for the last month :D
I changed the data-main and src in the index.html from
<script data-main="scripts/main.js" src="scripts/vendor/requirejs/require.js"></script>
to
<script data-main="/multikanban/app/scripts/main.js" src="/multikanban/app/scripts/vendor/requirejs/require.js"></script>
Also, make sure to define the absolute path in the href for styles if you have any.
Cheerio!
Thanks @jdaudier for the help
| {
"pile_set_name": "StackExchange"
} |
Q:
findAndModify fails with error: "Cannot update 'field1' and 'field1' at the same time
I'm trying to build MongoDB Java findAndModify query.
The main purpose is that I would like to set _id in insert query by myself.
Here is my code:
BasicDBObject findFilter = new BasicDBObject("type", "group")
//
BasicDBObject dialogInsertObject = new BasicDBObject("name", "my group").append("_id", new ObjectId());
//
BasicDBObject dialogUpdateObject = new BasicDBObject("name", "my group");
//
BasicDBObject upsertMap = new BasicDBObject();
upsertMap.append("$setOnInsert", dialogInsertObject);
upsertMap.append("$set", dialogUpdateObject);
DBObject dialogObject = dialogCollection.findAndModify(findFilter,
new BasicDBObject("_id", "1"), null, false, upsertMap, true, true);
And I get an error:
com.mongodb.CommandFailureException: { "serverUsed" : "localhost:27017" ,
"errmsg" : "exception: Cannot update 'name' and 'name' at the same time" ,
"code" : 16836 , "ok" : 0.0}
Can somebody help please
A:
The essential problem here is this:
db.collection.update(
{ "type": "group" },
{
"$set": { "mygroup": "value" }
"$setOnInsert" { "mygroup": "value" }
}
)
Which is basically what you are trying to do.
You cannot address the same field in a $set operation as a $setOnInsert operation.
There is a general problem in the logic that causes the error you are experiencing.
| {
"pile_set_name": "StackExchange"
} |
Q:
Need explanation on block behaviour in for loop
Please take a look at this piece of code:
NSMutableArray *array = [NSMutableArray array];
for (int i = 0; i < 10; i++)
{
void (^b)() = ^{printf("%d\n", i);};
[array addObject:b];
}
for (id obj in array)
{
void(^b)() = obj;
b();
}
[array removeAllObjects];
I expected this code to output 0, 1, 2 and so on but it prints 9 always. But why? Doesn't it capture i on every loop iteration? Why the last value is always captured? But what is more confusing for me is that if i change this line:
void (^b)() = ^{printf("%d\n", i);};
to
void (^b)() = [^{printf("%d\n", i);} copy];
then it starts printing 0, 1, 2 and so on. Can anybody please explain why it works this way?
A:
This is not a problem with what the block captures, but rather with what block gets stored in the array. If you print addresses of the blocks after the first loop, you should see identical addresses being printed:
for (id obj in array)
{
printf("%p\n", (void*)obj);
}
This is because all ten blocks are created on the stack in a loop, and are placed at the same address. Once the loop is over, the block created inside it is out of scope. Referencing it is undefined behavior. However, now that you stored the address of the block, you have a way to reference it (illegally).
Since the last block that was created in your loop has captured the last value of i (which is nine) all invocations of your block from your second loop would invoke the same block that prints nine.
This behavior changes if you copy the block, because now it is completely legal to reference it outside the scope where it has been created. Now all your blocks have different addresses, and so each one prints its own different number.
| {
"pile_set_name": "StackExchange"
} |
Q:
Numbered references Elsevier style
I have to make my references on model1-num-names.bst,
when I compile the main file (.tex), references appear correctly on my paper like [1]..[12] and so on.
but in the reference section, references appear without the itemlist (bibitem), and number of pages on each reference doesn't match the real one.
example:
my main file
\documentclass[3p,times]{elsarticle}
%% The `ecrc' package must be called to make the CRC functionality available
\usepackage{ecrc}
\usepackage{epsfig,graphicx,epstopdf}
\usepackage{subfigure}
\usepackage{calc}
\usepackage{amssymb}
\usepackage{amstext}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{multicol}
\usepackage{pslatex}
\usepackage{apalike}
\usepackage[small]{caption}
\usepackage{algorithm, algorithmic}
\usepackage{color}
\usepackage{longtable}
\usepackage[colorlinks=true]{hyperref}
\hypersetup{urlcolor=blue,linkcolor=blue,citecolor=blue,colorlinks=true}
\begin{}
....
....
....
\bibliographystyle{model1-num-names}
\bibliography{references}
\end{}
after compilation, references appear directly like this:
References
A.Padmanabhan, S.Ghosh, and S.Wang (2010).A self-organized grouping sog framework for efficient grid resource discovery.J Grid Computing, 8:365–38.
where I want it to appear like:
References
[1] A.Padmanabhan, S.Ghosh, and S.Wang (2010).A self-organized grouping sog framework for efficient grid resource discovery.J Grid Computing, 8:365–389.
here is an example of my (.bib) file for the above reference:
@article{PGW-2010,
Author = {A.Padmanabhan and S.Ghosh and S.Wang},
Journal = {J Grid Computing},
Pages = {365-389},
Publisher = {Springer},
Title = {A Self-Organized grouping SOG framework for efficient grid resource discovery},
Volume = 8,
Year = 2010
}
Regards.
A:
I resolved the problem, it was the fault of my use of the apalike package \usepackage{apalike}, once I've removed it, it works very well.
| {
"pile_set_name": "StackExchange"
} |
Q:
configuring MySql cluster failover using the .Net connector
I've got an ASP.Net website which is running on a load-balanced environment (2 Windows servers). It connects to a clustered MySql database which is running on two linux servers running Ubuntu.
We've been running into a number of errors while trying to route the MySql data through our JetNexus load-balancer, so I'm trying to find out if there's a way of configuring the individual web-servers with some sort of automatic database server failover detection. If I were using MS-SQL, I'd configure the connection string using the "Failover partner" parameter, but MySql doesn't support that. Is there anything else like that out there, or is there an alternate solution to this issue?
Extra info:
I'm using MySql connector 6.4.3, ASP.Net 4.0, MVC 3.0, the database is running MySql cluster 7.1.15a, cluster_server 5.1
I've tried specifying multiple MySql hosts in the connection file (using "server=192.168.0.1 & 192.168.0.2") and while this appears to work it doesn't automatically detect the failover and crashes as soon as I take out one of the databases.
I've come across something called "MySQL Proxy" which looks like it should fit the bill, but we have a hardware load-balancer so I'm going to spend time trying to get that working properly rather than implementing an extra software proxy.
The errors we are getting are "System.IO.EndOfStreamException: Attempted to read past the end of the stream.". This happens intermittently when we run MySql through the load-balancer. This is a separate issue and may not be related to the question but I've included it here for completeness.
Thanks for reading !
A:
I do not fully understand MySQL Cluster (Never used it) but I have suggestion:
Is it possible to put the cluster servers under a single ip? So the Ubuntu or MySQL Cluster load balance handles the fail-over?
| {
"pile_set_name": "StackExchange"
} |
Q:
Blog page hit counter
I'm creating a page hit counter for my busy blog.
I have a DB table called blog_article_hits, which contains three columns:
article_id INT
hit_counter INT
last_viewed DateTime
Each time a visitor hits my page, my plan is to pull the current number of hits for the article, add 1 to it, and update the table again with the new value and time. I know this works, but is this the right way to accomplish this? My concern is what happens when two unique people visit the same article, at exactly the same time. Is it possible that I could lose a count? Am I supposed to be using a stored procedure or another method?
A:
Just issue an update state directly or from a stored procedure. You will not miss any hits.
update blog_article_hits set article_id=article_id+1, last_viewed=Now()
| {
"pile_set_name": "StackExchange"
} |
Q:
Showing that a subspace is invariant of a specific dimension.
I'm studying for a qualifying exam in algebra and I'm slightly stuck on the following problem:
Let $\mathbb{F}$ be a field, and let $A$ be an $n\times n$ matrix over $\mathbb{F}$. Suppose that $p\in\mathbb{F}[x]$ is an irreducible polynomial of degree $d$ with $p(A)=O$, where $O$ is the zero linear operator on $\mathbb{F}^n$. For $x\in\mathbb{F}^n$, let $S(x)$ denote the span of the set $\{A^ix:i=0,1,\cdots,\}$.
(a) Show that if $x$ is nonzero, then $S(x)$ is an $A$-invariant subspace of dimension $d$.
(b) Prove that $d$ divides $n$.
I believe part (b) is straightforward:
Because $p(A)=O$, $p$ is a multiple of the minimal polynomial of $A$. Because the characteristic polynomial of $A$ is also a multiple of the minimal polynomial of $A$, the degree $d$ of $p$ divides the degree of the characteristic polynomial of $A$. Since the characteristic polynomial of a matrix has degree equal to the dimension of the vector space, and $\operatorname{dim}(\mathbb{F}^n)=n$, the desired result follows. $\square$
For part (a), I think I can show invariance, but I'm stuck on dimension:
Note that $S(x)$ is $A$-invariant provided $As\in S(x)$ for all $s\in S(x)$. Equivalently, since $S(x)$ is the span of $\{A^ix:i=0,1,\cdots,\}$, then $S(x)$ is $A$-invariant provided $A(A^ix)\in S(x)$ for each $i=0,1,\cdots,$. Since $A(A^ix)=(AA^i)x=A^{i+1}x\in S(x)$, $S(x)$ is in fact $A$-invariant. $\square$
Thanks in advance for any help on showing the dimension of $S(x)$, and for any comments/critiques on what I have done already.
A:
EDIT.
Of course, the @TheWildCat and the OP 's proofs cannot be correct because they do not use the fact that $p$ is irreducible....
For b). This exercise is essentially about the polynomials.
I assume that the field $F$ is perfect (if $r\in F[x]$ is irreducible, then its roots in an algebraic extension are simple). cf. the comments below.
Clearly, $p\in F[x]$ is the minimal polynomial of $A$. On the other hand, $\chi_A\in F[x]$ -the characteristic polynomial of $A$- has degree $n$, is a multiple of $p$ and has (up to multiplicity), the same roots $(\lambda_i)_i$ as $p$ -in an algebraic extension $K$-.
The key is that if some $\lambda_i$ is a root of $q\in F[x]$, then $q$ is a multiple of $p$ (because it's irreducible). We deduce that the multiplicities of the $(\lambda_i)_i$, in $\chi_A$, are the same and, consequently, $\chi_A$ is a power of $p$; finally, $d$ divides $n$.
For a) (cf. also the @David C. Ullrich 's comment about this part).
Let $B=A_{|S(x)}$ where $x\not= 0$; clearly $\delta=dim(S(x))\leq d$; then, $s\in F[x]$, the minimal polynomial of $B$ (that is also the minimal polynomial of $x$) divides $\chi_A$ and has degree $\leq \delta$. Thus $s=p$ and $\delta=d$.
| {
"pile_set_name": "StackExchange"
} |
Q:
IOError: [Errno 22] invalid mode ('r') or filename
def read_texts():
quotes = open("C:\\movie_quotes.txt")
content_of_file = quotes.read()
print(content_of_file)
quotes.close()
before running it this appears:
appearing
I keep on running this code and this error appears:
Traceback (most recent call last):
File "C:\Python27\check_profanity.py", line 7, in <module>
read_texts()
File "C:\Python27\check_profanity.py", line 2, in read_texts
quotes = open("‪C:\\movie_quotes.txt")
IOError: [Errno 22] invalid mode ('r') or filename: '\xe2\x80\xaaC:\\movie_quotes.txt'
i use python 2.7.14
please i need answers!!!
A:
You have an invisible character in your code. Use a hex editor or hex dumper to see it:
$ echo 'open("C:\\' | hd
00000000 6f 70 65 6e 28 22 e2 80 aa 43 3a 5c 5c 0a |open("...C:\\.|
The character in question is U+202a, the left-to-right embedding character, encoded as UTF-8 as e2 80 aa.
Remove the character from your source code by deleting ("C: and retyping it.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to find ids of record from array of records using Ruby 2.0
consider here is array of records below
[#<IpAddress id: 26, ip: "12.10.20.11", latitude: '0.3155460609', longitude: '0.74357158' ,
#<IpAddress id: 27, ip: "12.10.20.12", latitude: '0.3155460609', longitude: '0.74357158',
#<IpAddress id: 29, ip: "12.10.20.30", latitude: '0.3155460609', longitude: '0.74357158',
#<IpAddress id: 44, ip: "127.0.0.1", latitude: '0.3155460609', longitude: '0.7435715',
#<IpAddress id: 52, ip: "127.0.0.3", latitude: '0.3155460609', longitude: '0.743571' ,
#<IpAddress id: 55, ip: "14.30.20.13", latitude: '0.3155460609', longitude: '0.74357']
I want to get ids of same ip's in this array by not considering last dot value of ip address in form of hash like below.
{12.10.20 => [26,27,29] , 127.0.0 => [44,52], 14.30.20 => [55]}
Any trick?
Thanks
A:
h = Hash.new {[]}
records.each { |ipaddr| ip = ipaddr.ip; h[ip[0...ip.rindex(".")]] <<= ipaddr.id }
puts h
# => {"12.10.20"=>[26, 27, 29], "127.0.0"=>[44, 52], "14.30.20"=>[55]}
| {
"pile_set_name": "StackExchange"
} |
Q:
Communications : Ground wave propagation
I was studying ground wave propagation, my book writes the lines about it without explaining it. I really do not know any explanation for these queries coming in my mind. I've Googled it, and you will get nothing so good for these queries on Ground wave propagation.
When the radio signal travels along the earth's surface, how it
induces current in it? (I read somewhere that the electric field
part of the wave will make electrons go out of association with the
nucleus, all this happening in earth, hence currents)
How will the wave tilt towards the earth after the induction of
current in the earth?
The attenuation of the surface increases very rapidly with increase
in frequency of the signal. How?
Note: Answer only for the level of Class 12 students required.
I seriously do not know anything about the last two questions. Any help would be praised for the one who will solve all these three questions.
A:
So, I'll take this very smoothly. The idea is to take you from ray optics gradually to an understanding of radiomagnetic waves as actual waves, and show that it all makes sense.
1st idea: Refraction on a material interface (high->low density)
We remember what happens when we have ray of light, leaving a optically denser medium (e.g., water) into a less dense one (e.g. air):
The ray is refracted away from the normal of the interface (image taken from wikipedia's refraction article & cropped).
We can actually calculate how $\theta_1$ and $\theta_2$ are related; it's Snell's law that you might already know:
$$\frac{\sin(\theta_1)}{\sin(\theta_2)}= \frac{n_2}{n_1}$$
with $n_i$ being the refractive index of the medium (air or water).
2nd idea: Water on a sphere
Now, imagine you're standing on sphere (like, a planet). Your planet is completely covered in very very salty water, and above that, is air.
You're of the water-dwelling kind, and you hold an orange laser pointer nicely horizontally:
So, in this drawing, you stand at point $B$, and hold your laser pointer straight vertically (that is, perpendicularly to the planet radius $\bar{BA}$. At point $C$, the ray hits the saltwater-air interface in the angle $\delta$.
Our job is now to find $\delta$, because we know the refractive indices of air and saltwater, and we can then calculate under which angle the ray will leave the saltwater¹.
We know that on the saltwater-air-interface, the ray will be refracted away from the normal, that is, closer to the ocean surface. So, the ray will already have one "bend", that looks like it "hugs" the ocean surface curvature a bit.
3rd idea: Water in layers.
Now we realize that this ocean is pretty deep, and that the water isn't constantly salty – the deeper waters are way more salty than the waters close to the surface.
Let's even think these different degrees of saltiness come in layers. Then, we can imagine there being a lot of interfaces like the water-air interface from the second idea :)
Since salty water is at the bottom and has a higher refractive index than less salty water, we get such a bend at every interface. The ray is getting bend more and more to "hug" the spheres, until, at the end, it practically "rides" on a circle-like shape that it really can't leave (because it's always refracted back a little bit more).
4th idea: From rays to waves
Now, the first big thing to simply swallow is: Laser light and, let's say, mediumwave radio broadcast, are really just the same thing: electromagnetic waves. There's zero difference between them, other than that an orange laser has maybe a wavelength of 600 nm, whereas your medium wave broadcast might have a wavelength of 600 m, that is, one billion of the wavelength.
So, whereas the saltwater layers seem "huge" to a ray of light, which you might have already learned to model as "plane wave front", these layers might be "small" compared to the wavelength of a medium wave transmission.
Now, imagine that instead of a small, cute laser pointer, you used a giant lamp consisting of thousands of laser pointers, mounted atop of each other: A large "tower" that shines kind of a beam (consisting of many laser rays). Now, the lower laser pointers are in deeper, saltier waters, and get bent more within shorter distance than the upper ones.
There's an old analogy that physics teachers often employ: imagine this group of rays being a marching band, nicely arranged to all start marching at the exact same instant. While the upper-water band members move relatively straight and only rarely meet a water-water level interface, the band members close to the ground are often making a bend in their path. The overall front of the marching band seems to "slouch" around the curvature of the earth.
This analogy isn't as bad as it sounds at first: The refractive index $n$ is actually just a measure for how much slower than in vacuum the light is in that medium. So, the "deepwater rays" simply are slower than the "not as saltywater rays". That means that the whole wavefront (marching band front) does follow a curve.
5th idea: we don't have salty water, but earth will do.
Obviously, you're not a water-dwelling alien controlling a giant marching band consisting of laser beams.
Instead, you have an antenna. But that antenna very much sends out an electromagnetic wavefront. As electromagnetic waves permeate air, trees, hills, dry earth, not-so-dry-earth, small animals, large animals, buildings, tapestries and people, they are, just like the special case of visible light, slowed down in media.
In the case of ground waves, the lower parts of the wave front permeates earth. Earth has a higher conductivity as air – and that means it slows down the electromagnetic wave. How that slowing down happens isn't actually very easy to explain - in the end, earth has physical properties that increase its $n$.
¹ I haven't had the time to properly test my calculations, but if they are correct, that angle is, if we set the earth radius to 1, $\delta=90° - 2\arcsin\left(\pm \sqrt{\frac l{2+2l}}\right)$, but that's actually not that important here. If you want to have some geometry in your presentation, deriving that angle from the ratio of earth radius (set arbitrarily to 1) and water height would definitely be a cool thing.
For the things I want to explain, it's not important what this angle is, exactly.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why does this pattern take a long time to match in java?
The following regex pattern, when applied to very long strings (60KB), causes java to seem to "hang".
.*\Q|\E.*\Q|\E.*\Q|\E.*bundle.*
I don't understand why.
A:
You have 5 eager/greedy quantifiers in that regex, so you could well be doing a huge amount of backtracking.
This article explains this behaviour at length and has suggestions for making your regex performance better.
In this case, the answer may be to replace the greedy quantifiers with non-greedy ones, or better still to use non-backtracking subpatterns.
A:
First, I think you could simplify your regex as follows:
.*\Q|\E.*\Q|\E.*\Q|\E.*bundle.*
could become
.*\|.*\|.*\|.*bundle.*
Second, to sorta answer your question, the fact that you have so many ".*"s in your regex means that there are a TON of possibilities that the regex solution must work through. The following might work faster if this would work for your situation.
(?:[^\|]*\|){3}[^|]*bundle.*
by changing "." to "[^|]" you narrow the focus of the engine since the first ".*" will not eagerly grab the first "|".
A:
Basically, the ".*" (match any number of anything) means try to match the entire string, if it doesn't match, then go back and try again, etc. using one of these is not too much of a problem, but the time necessary to use more than one increases exponentially. This is a fairly in-depth (and much-more accurate) discussion of this sort of thing: http://discovery.bmc.com/confluence/display/Configipedia/Writing+Efficient+Regex
EDIT: (I hope you really wanted to know WHY)
Example Source String:
aaffg, ";;p[p09978|ksjfsadfas|2936827634876|2345.4564a bundle of sticks
ONE WAY OF LOOKING AT IT:
The process takes so long because the .* matches the entire source string (aaffg, ";;p[p09978|ksjfsadfas|2936827634876|2345.4564a bundle of sticks), only to find that it does not end in a | symbol, then backtracks to the last case of a | symbol (...4876|2345...), then tries to match the next .* all the way to the end of the string.
It starts looking for the next | symbol specified in your expression, and not finding it, it then backtracks to the first | symbol that was matched (the one in ...4876|2345...), discards that match and finds the closest | before it (...dfas|2936...), so that it will be able to match the second | symbol in your match expression.
It will then proceed to match the .* to 2936827634876 and the second | to the one in ...4876|2345... and the next .* to the remaining text, only to find that you wanted yet another |. It will then continue to backtrack again and again, until it matches all of the symbols you specified.
ANOTHER WAY OF LOOKING AT IT:
(Original expression):
.*\Q|\E.*\Q|\E.*\Q|\E.*bundle.*
this roughly translates to
match:
any number of anything,
followed by a single '|',
followed by any number of anything,
followed by a single '|',
followed by any number of anything,
followed by a single '|',
followed by any number of anything,
followed by the literal string 'bundle',
followed by any number of anything
the problem is that any number of anything includes | symbols, requiring parsing of the entire string over and over again where what you really mean is any number of anything that is not a '|'
To fix or improve the expression, I would recommend three things:
First (and most significant), replace the majority of the "match anything"s (.*) with negated character classes ([^|]) like so:
[^|]*\Q|\E[^|]*\Q|\E[^|]*\Q|\E.*bundle.*
...this will prevent it from matching to the end of the string over and over again, but instead matching all the non-| symbols up to the first character that is not a "not a | symbol" (that double negative means up to the first | symbol), then matching the | symbol, then going to the next, etc...
The second change (somewhat significant, depending upon your source string) should be making the second-to-last "match any number of anything" (.*) into a "lazy" or "reluctant" type of "any number of" (.*?). This will make it try to match anything with the idea of looking out for bundle instead of skipping over bundle and matching the rest of the string, only to realize that there is more to match once it gets there, having to backtrack. This would result in:
[^|]*\Q|\E[^|]*\Q|\E[^|]*\Q|\E.*?bundle.*
The third change I would recommend is for readability - replace the \Q\E blocks with a single escape, as in \|, like so:
[^|]*\|[^|]*\|[^|]*\|[^|].*?bundle.*
This is how the expression is internally processed anyways - there is literally a function that converts the expression to "escape all the special characters in between \Q and \E" - \Q\E is a shorthand only, and if it does not make your expression shorter or easier to read, it should not be used. Period.
The negated character classes have an un-escaped | because | is not a special character within the context of character classes - but let's not digress too much. You can escape them if you'd like, but you don't have to.
The final expression translates roughly to:
match:
any number of anything that is not a '|',
followed by a single '|',
followed by any number of anything that is not a '|',
followed by a single '|',
followed by any number of anything that is not a '|',
followed by a single '|',
followed by any number of anything, up until the next expression can be matched,
followed by the literal string 'bundle',
followed by any number of anything
A good tool that I use (but costs some money) is called RegexBuddy - a companion/free website for understanding regex's is http://www.regular-expressions.info, and the particular page that explains repetition is http://www.regular-expressions.info/repeat.html
RegexBuddy emulates other regex engines and says that your original regex would take 544 'steps' to match as opposed to 35 'steps' for the version I provided.
SLIGHTLY LONGER Example Source String A:
aaffg, ";;p[p09978|ksjfsadfas|12936827634876|2345.4564a bundle of sticks
SLIGHTLY LONGER Example Source String B:
aaffg, ";;p[p09978|ksjfsadfas|2936827634876|2345.4564a bundle of sticks4me
Longer source string 'A' (added 1 before 2936827634876) did not affect my suggested replacement, but increased the original by 6 steps
Longer source string 'B' (added '4me' at the end of the expression) again did not affect my suggested replacement, but added 48 steps to the original
Thus, depending on how a string is different from the examples above, a 60K string could only take 544 steps, or it could take more than a million steps
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use XmlElement.InnerXml WITHOUT any formatting?
I need to communicate with a WebService through XML. This service is using a saml:Assertion to authenticate the connection. I can communicate with the server, but the validation always fails. I searched for hours what the problem is, because when I use soapUI with the exact same parameters and saml ticket, it works. I tried to "manually" remove any formatting from the saml:Assertion because it was signed, so with a single-byte change, it won't work anymore.
Here's my code:
// Insert saml:Assertion string into soapenv:Header
private static void InsertSAML(ref XmlDocument soapXML, ref XmlNamespaceManager nsmgr, string saml)
{
// Remove all formatting
saml = saml.Replace("\r", "");
saml = saml.Replace("\n", "");
while(saml.IndexOf(" ") > -1)
{
saml = saml.Replace(" ", " ");
}
saml = saml.Replace("> <", "><");
saml = saml.Replace("\" />", "\"/>");
XmlElement soapHeader = (XmlElement)soapXML.SelectSingleNode("//soapenv:Envelope/soapenv:Header/wsse:Security", nsmgr);
if (soapHeader == null)
{
throw new Exception("Can't find \"//soapenv:Envelope/soapenv:Header/wsse:Security\"");
}
soapHeader.InnerXml += saml;
}
But it seems like when I use soapHeader.InnerXml += saml; it causes some kind of formatting. A whitespace will appear before the closing tags of elements without inner content:
So, I need to add this:
<dsig:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
But in the final XML looks like this, even if I replaced these occurences before inserting:
<dsig:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
How can I get rid of this behaviour?
A:
As I said, the problem was with the additional bytes XmlDocument added to my xml when I append content to the InnerXml. I tried so hard to remove all formatting, and it was a good direction. But instead of "un-formatting" the saml:Assertion part, I magaged to un-format the whole request body, right before it was sent to the service. And now it works. I call this method right before sending the request:
// Insert XML to request body
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (var stringWriter = new StringWriter())
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
using (Stream stream = webRequest.GetRequestStream())
{
// Get XML contents as string
soapEnvelopeXml.WriteTo(xmlTextWriter);
xmlTextWriter.Flush();
string str = stringWriter.GetStringBuilder().ToString();
// Remove all formatting
str = str.Replace("\r", "");
str = str.Replace("\n", "");
while (str.IndexOf(" ") > -1)
{
str = str.Replace(" ", " ");
}
str = str.Replace("> <", "><");
str = str.Replace("\" />", "\"/>");
// Write the unbeutified text to the request stream
MemoryStream ms = new MemoryStream(UTF8Encoding.Default.GetBytes(str));
ms.WriteTo(stream);
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Using sed to check make sure each line only has numbers and a comma?
I have a text file that looks like this:
0,16777215
16807368,16807368
621357328,621357328
621357403,621357403
1380962773,1380962773
1768589474,1768589474
Is there a way to use sed to make sure that each line ONLY has numbers and one comma? If a line is missing the comma, contains letters, is blank, has spaces, etc. - then I want to delete it.
A:
With sed:
sed -nr '/^[0-9]+,[0-9]+$/p' File
To edit the file in-place:
sed -nri '/^[0-9]+,[0-9]+$/p' File
A portable solution:
sed -nE '/^[0-9]+,[0-9]+$/p' File
| {
"pile_set_name": "StackExchange"
} |
Q:
Postgresql Split single row to multiple rows
I'm new to postgresql. I'm getting below results from a query and now I need to split single row to obtain multiple rows.
I have gone through below links, but still couldn't manage it. Please help.
unpivot and PostgreSQL
How to split a row into multiple rows with a single query?
Current result
id,name,sub1code,sub1level,sub1hrs,sub2code,sub2level,sub2hrs,sub3code,sub3level,sub3hrs --continue till sub15
1,Silva,CHIN,L1,12,MATH,L2,20,AGRW,L2,35
2,Perera,MATH,L3,30,ENGL,L1,10,CHIN,L2,50
What we want
id,name,subcode,sublevel,subhrs
1,Silva,CHIN,L1,12
1,Silva,MATH,L2,20
1,Silva,AGRW,L2,35
2,Perera,MATH,L3,30
2,Perera,ENGL,L1,10
2,Perera,CHIN,L2,50
A:
Use union:
select id, 1 as "#", name, sub1code, sub1level, sub1hrs
from a_table
union all
select id, 2 as "#", name, sub2code, sub2level, sub2hrs
from a_table
union all
select id, 3 as "#", name, sub3code, sub3level, sub3hrs
from a_table
order by 1, 2;
id | # | name | sub1code | sub1level | sub1hrs
----+---+--------+----------+-----------+---------
1 | 1 | Silva | CHIN | L1 | 12
1 | 2 | Silva | MATH | L2 | 20
1 | 3 | Silva | AGRW | L2 | 35
2 | 1 | Perera | MATH | L3 | 30
2 | 2 | Perera | ENGL | L1 | 10
2 | 3 | Perera | CHIN | L2 | 50
(6 rows)
The # column is not necessary if you want to get the result sorted by subcode or sublevel.
You should consider normalization of the model by splitting the data into two tables, e.g.:
create table students (
id int primary key,
name text);
create table hours (
id int primary key,
student_id int references students(id),
code text,
level text,
hrs int);
| {
"pile_set_name": "StackExchange"
} |
Q:
Should I use Prometheus as a log aggregator?
Can/should prometheus be used as a log aggregator? We are deploying apps into a kubernetes cluster. All containers already log to stdout/err and we want all devs to instrument their code with logs to stdout/err. Fluentd will then collate all logs across the whole cluster and send to an aggregator. We have thought about using Elasticsearch/kibana however we will already have Prometheus for node metric gathering so if we can have fluentd send all logs to Prometheus it keeps everything in one place.
So, can/should Prometheus be used as a logging aggregator? Would it still have to poll the fluentd server? Really, it would be great to be able to use the alerting features of Prometheus so that if a certain log is made it (for instance) dumps the log message into a slack channel etc.
Appreciate some pointers on this one, thanks.
A:
Prometheus is a metrics system rather than a logs system. There's the mtail and grok exporters to process logs, but really that's only for cases where instrumenting your code with metrics is not possible.
For logs something like Elasticsearch is far more appropriate.
A:
Update: Loki is a new project that claims "like Prometheus, but for logs."
| {
"pile_set_name": "StackExchange"
} |
Q:
DeflaterOutputStream: write beyond end of stream
I get dealt a "write beyond end of stream" error by deflaterstream. I tracked the error down, and it shows the stream is apparently finished already. However, at the beginning of my function is create the stream as brand new and do not call close or finish at the very end ..
Error:
SEVERE: null
java.io.IOException: write beyond end of stream
at java.util.zip.DeflaterOutputStream.write(DeflaterOutputStream.java:102)
at evidence.SaveStateManager.saveIncremental(SaveStateManager.java:82)
Code:
public static void saveIncremental(int textureId, int layer, int shot) {
try {
bOut = new FileOutputStream("saves/p-" + layer + "-" + shot + ".gz");
gzipOut = new DeflaterOutputStream (bOut, deflater);
glPushAttrib(GL_ALL_ATTRIB_BITS);
glBindTexture(GL_TEXTURE_2D, textureId);
int bpp = 4;
ByteBuffer buffer = BufferUtils.createByteBuffer(SAVE_WIDTH * SAVE_HEIGHT * bpp);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer );
byte[] bytes = new byte[1024];
while (buffer.hasRemaining()) {
int len = Math.min(buffer.remaining(), bytes.length);
buffer.get(bytes, 0, len);
try {
gzipOut.write(bytes, 0, len);
} catch (IOException ex) {
Logger.getLogger(SaveStateManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
glBindTexture(GL_TEXTURE_2D, 0);
glPopAttrib();
gzipOut.finish();
gzipOut.close();
bOut.close();
} catch (Exception ex) {
Logger.getLogger(SaveStateManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
A:
The Deflator is stateful and you are reusing it.
gzipOut = new DeflaterOutputStream (bOut, deflater);
from the source for DeflaterOutputStream
public void write(byte[] b, int off, int len) throws IOException {
if (def.finished()) {
throw new IOException("write beyond end of stream");
| {
"pile_set_name": "StackExchange"
} |
Q:
jQuery .size() question
When you click the "Add Div" button, why doesn't the number increment?
http://jsfiddle.net/cN2zR/
A:
http://jsfiddle.net/cN2zR/3/ It does now :)
make d a function so it can be run each add.
var d = function(){
return '<div class="historyItem">Test ' + ($("#history > div").size() + 1) + '</div>';
}
Also I noticed your problem with the scroll link. A quick trick to scroll to the bottom of a container is using the .scrollTop([arbitrary high number])
| {
"pile_set_name": "StackExchange"
} |
Q:
Best way to avoid stale *.pyc files?
What's the best way to avoid stale *.pyc files? Sometimes, especially when switching branches in version control, some *.pyc files are left there and are used by Python instead of the source files I have.
What's the best strategy for making sure I don't create or unknowingly use stale *.pyc files?
A:
Similar to khampson, git and mercurial (and likely others) allow client side hooks. You can sprinkle around scripts that do
find -iname "*.pyc" -exec rm -f {} \;
on linux at least. Search "git hooks" and "mercurial hooks" for more details.
A:
There is a useful environment variable for that: PYTHONDONTWRITEBYTECODE
export PYTHONDONTWRITEBYTECODE=true
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove a record from shapefile with python
I have an ESRI shapefile .shp (with all associated files like .shx, .dbf and many more) which I want to edit - I need to remove the first record and save the file.
For this purpose I installed pyshp and tried to parse and edit the shapefile. This is what I have tried:
import shapefile
e = shapefile.Editor('location/of/my/shp')
e.shapes()
# example output
>>> [<shapefile._Shape instance at 0x7fc5e18d93f8>,
<shapefile._Shape instance at 0x7fc5e18d9440>,
<shapefile._Shape instance at 0x7fc5e18d9488>,
<shapefile._Shape instance at 0x7fc5e18d94d0>,
<shapefile._Shape instance at 0x7fc5e18d9518>]
From here I want to delete the first entry <shapefile._Shape instance at 0x7fc5e18d93f8> and then save the file:
e.delete(0) # I tried e.delete(shape=0) too
e.save()
However the record is still available in the newly saved file.
Unfortunately the documentation doesn't go in depth about these things.
How can I accomplish my goal? How to check that the deletion has been successful before saving the file?
A:
I'm not familiarized with pyshp but this can be easily solved using ogr, which allows to work with vector data and makes part of the gdal library.
from osgeo import ogr
fn = r"file.shp" # The path of your shapefile
ds = ogr.Open(fn, True) # True allows to edit the shapefile
lyr = ds.GetLayer()
print("Features before: {}".format(lyr.GetFeatureCount()))
lyr.DeleteFeature(0) # Deletes the first feature in the Layer
# Repack and recompute extent
# This is not mandatory but it organizes the FID's (so they start at 0 again and not 1)
# and recalculates the spatial extent.
ds.ExecuteSQL('REPACK ' + lyr.GetName())
ds.ExecuteSQL('RECOMPUTE EXTENT ON ' + lyr.GetName())
print("Features after: {}".format(lyr.GetFeatureCount()))
del ds
| {
"pile_set_name": "StackExchange"
} |
Q:
Why didn't the 4th Doctor come back for Sarah Jane?
School Reunion was an accident. The Doctor said he'd come back and he had many chances, so why didn't he do it?
A:
Let's allow the Doctor to explain it himself. From the transcript of School Reunion:
SARAH: Did I do something wrong, because you never came back for me. You just dumped me.
DOCTOR: I told you. I was called back home and in those days humans weren't allowed.
SARAH: I waited for you. I missed you.
DOCTOR: Oh, you didn't need me. You were getting on with your life.
[...]
SARAH: You could have come back.
DOCTOR: I couldn't.
SARAH: Why not?
(The Doctor keeps working on K9.)
And later on:
DOCTOR: I don't age. I regenerate. But humans decay. You wither and you die. Imagine watching that happen to someone who you ...
ROSE: What, Doctor?
DOCTOR: You can spend the rest of your life with me, but I can't spend the rest of mine with you. I have to live on. Alone. That's the curse of the Time Lords.
So it seems to be a mixture of a few reasons, although the first two may be untrue while the fourth is what he doesn't want to admit:
he was called back to Gallifrey and couldn't take her with him
he wanted to let her get on with her life
he couldn't keep her with him forever and saw it as a good opportunity to split up
he simply forgot about her.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to run a program when connecting to a specific network in Windows 7
I want to have an executable run every time I connect to my wireless network at home. The purpose is to sync a folder on my laptop with my desktop machine.
Is there any way run a program or script when you join a wireless network?
I'm running Windows 7, and I'd also be happy to use a program that takes care of this kind of task.
A:
I had this exact question, and Darren's answer was on the right track, but didn't get me all the way there. Here's what I ended up doing.
First determine which event you want to use to trigger the task. Run the Event Viewer program and navigate to:
Applications and Services Logs > Microsoft > Windows > WLAN-AutoConfig > Operational
In my case, I didn't want my task to run until I was actually connected to a specific WiFi network, so the Event ID I needed was 8001. The quick way to create a task based on this event is to right-click on the event and select "Attach Task To This Event..."
In the window that pops up, name your task something clever and add a description so you'll remember what it is later. Go through the wizard, selecting the program you want to run, etc., and when it gets to the last screen, check the box that says "Open the Properties dialog for this task when I click Finish".
At this point, the task will run when the computer successfully connects to any wireless network. To limit it to one particular network, you'll have to modify the task to filter for something unique in the meta data, like the network's SSID. In the properties dialog for the new task, go to the Triggers tab and edit the trigger.
Now, make note of the values for the Basic trigger. You're going to switch to a Custom trigger, and when you do, it'll start blank and you'll need to fill the values in again. After clicking "New Event Filter..." recreate the basic filter by selecting the necessary Event log, Event source, and entering the Event ID.
Note that there's no place to specify meta data from a particular event (such as the SSID of the wireless network). You'll need to edit the raw XML to make this happen, as I discovered in this article.
To figure out which meta data you need to filter in the Event Log, go back to the Event Viewer and click the Details tab for the event. Switch to the XML view. For this particular case, the relevant bit looks something like this:
<EventData>
...
<Data Name="SSID">Your WiFi Network</Data>
...
</EventData>
Back on the New Event Filter dialog, switch to the XML tab and check the box next to "Edit query manually".
Referring back to the article linked above, you'll see that the string you need to add will look something like this:
and *[EventData[Data[@Name='SSID']='Your WiFi Network']]
Paste this right before the </Select>
Boom. You're done.
Just a note that might make this easier, rather than editing the XML for the trigger, you can switch to the Conditions tab when bringing up the properties for the task. Here there is an option to 'Start only if the following network connection is available:' and provides a drop down list of networks that you have previously connected to. I suspect this would filter the trigger appropriately as well. Justin
A:
You can use Windows 7 Task Scheduler for this.
Under Triggers Tab, Begin the task On an event
I don't run Windows 7 on a laptop, but I believe the Event ID can be found in Microsoft-Windows-WLAN-AutoConfig.
Under Conditions Tab, Start Only if the following network connection is available, and specific the Wireless network you want.
Then call the program under Actions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Where are some good resources for learning the new features of Perl 5.10?
I didn't realize until recently that Perl 5.10 had significant new features and I was wondering if anyone could give me some good resources for learning about those. I searched for them on Google and all I found was some slides and a quick overview. Some of the features (to me at least) would be nice if they had more explanation.
Any links would be appreciated.
-fREW
A:
The perldelta manpage has all the nitty-gritty details. There's a brief (but informative) slide presentation, Perl 5.10 for people who aren't totally insane. And a good PerlMonks discussion on the issue.
A:
I found this article useful.
This one is more focused on 5.10 Advanced Regular Expressions.
And also A beginners' Introduction to Perl 5.10.
Finally, this excellent summary on why you should start using Perl 5.10 and from which I extracted the following:
state variables No more scoping variables with an outer curly block, or the naughty my $f if 0 trick (the latter is now a syntax error).
defined-or No more $x = defined $y ? $y : $z, you may write $x = $y // $z instead.
regexp improvements Lots of work done by dave_the_m to clean up the internals, which paved the way for demerphq to add all sorts of new cool stuff.
smaller variable footprints Nicholas Clark worked on the implementations of SVs, AVs, HVs and other data structures to reduce their size to a point that happens to hit a sweet spot on 32-bit architectures
smaller constant sub footprints Nicholas Clark reduced the size of constant subs (like use constant FOO => 2). The result when loading a module like POSIX is significant.
stacked filetests you can now say if (-e -f -x $file). Perl 6 was supposed to allow this, but they moved in a different direction. Oh well.
lexical $_ allows you to nest $_ (without using local).
_ prototype you can now declare a sub with prototype . If called with no arguments, gets fed with $ (allows you to replace builtins more cleanly).
x operator on a list you can now say my @arr = qw(x y z) x 4. (Update: this feature was backported to the 5.8 codebase after having been implemented in blead, which is how Somni notices that it is available in 5.8.8).
switch a true switch/given construct, inspired by Perl 6
smart match operator (~~) to go with the switch
closure improvements dave_the_m thoroughly revamped the closure handling code to fix a number of buggy behaviours and memory leaks.
faster Unicode lc, uc and /i are faster on Unicode strings. Improvements to the UTF-8 cache.
improved sorts inplace sorts performed when possible, rather than using a temporary. Sort functions can be called recursively: you can sort a tree
map in void context is no longer evil. Only morally.
less opcodes used in the creation of anonymous lists and hashes. Faster pussycat!
tainting improvements More things that could be tainted are marked as such (such as sprintf formats)
$# and $* removed Less action at a distance
perlcc and JPL removed These things were just bug magnets, and no-one cared enough about them.
A:
There's been a string of articles in Perl Tips about Perl 5.10:
Regular Expressions in Perl 5.10
Perl 5.10: Defined-or and state
Switch (given and when)
Perl 5.10 and Hash::Util::FieldHash
Smart-match in Perl 5.10
There are also my What's new in Perl 5.10 slides on Perl Training Australia's presentations page, but since they were written before 5.10 was released, some things may have changed slightly. I believe that rjbs' Perl 5.10 for people who aren't totally insane now covers everything my slides used to.
All the best,
Paul
Mandatory bias disclosure: I wrote almost all of the resources mentioned in this post,
| {
"pile_set_name": "StackExchange"
} |
Q:
How to plot 2 subplots that share the same x-axis
So currently i have a scatterplot and a kdeplot that i used seaborn library to plot out.
Here is how i plotted the graphs:
# plot a graph to see the zipcodes vs the density
plt.figure(figsize=(16,8))
sns.kdeplot(king['zipcode'], shade=True, legend=False)
plt.xlabel('Zipcode')
plt.ylabel('Density')
plt.figure(figsize=(16,8))
sns.scatterplot(king['zipcode'],king['price'])
But when i try to do a subplot, my kdeplot seems to be gone:
I tried to do in such a way:
f, axarr = plt.subplots(2, sharex=True)
sns.kdeplot(king['zipcode'], shade=True, legend=False)
sns.scatterplot(king['zipcode'],king['price'])
Is it possible to render both graph in subplots properly?
A:
Yep! Credits to @DavidG, i managed to plot out the subplots properly. So i added the axes object into the respective graphs. Here it goes.
f, axarr = plt.subplots(2, figsize=(16,8), sharex=True)
sns.kdeplot(king['zipcode'], shade=True, legend=False,ax=axarr[0])
axarr[0].set_ylabel('Density')
sns.scatterplot(x=king['zipcode'],y=king['price'],ax=axarr[1])
plt.show()
And it results in this:
| {
"pile_set_name": "StackExchange"
} |
Q:
How to retain number of digits for the variable in a for-loop
I wish to keep three digits for the variable in a for loop. E.g.
for (int i = 002; i <= 033; i++)
{
string localFilename = @"\\psf\Home\Pictures\Maulavi\" + i + ".jpg";
using (WebClient client = new WebClient())
{
MessageBox.Show(i.ToString());
client.DownloadFile("http://eap.bl.uk/EAPDigitalItems/EAP566/EAP566_1_1_19_2-EAP566_Maulvi_January_1946_v43_no2_" + i + "_L.jpg", localFilename);
}
}
However I changes to being just 2 and 3 etc. I want it to stay as 002 and 003 etc. How do I do that?
A:
You can do i.ToString("D3") or i.ToString("000").
For more information on number to string conversions, have a look at Standard Numeric Format Strings.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to specify a ranking for NHibernate search results, based on location of search term in results?
I have a paged list of search results. A user can search for 'derp' and anything with that sequence of characters anywhere in the name is returned.
I've been asked to change this so that this set of results will initially be ranked by relevance. So if normally the list would be returned as
a derp abc // everything is alphabetical
a derp xyz
b derp abc
derp abc
derp def
herp derp a
herp derp b
now the list needs to be sorted as
derp abc // these guys are given prominence
derp def
a derp abc // the rest of results alphabetical as normal
a derp xyz
b derp abc
herp derp a
herp derp b
keeping in mind that this list has to be paged (i.e. I can't just take the search result and manually remove occurrences of 'derp' from the middle and move them to the front), Is there any way with NHibernate that I can specify a required ranking?
Or do I have to do 2 queries, first searching for anything that starts with 'derp' and the second that contains 'derp' but doesn't start with it?
A:
OrderBy can use Projections, so this will work just fine:
var list = session.QueryOver<Store>()
.Where(s => s.Name.IsLike("My", MatchMode.Anywhere))
.OrderBy(NHibernate.Criterion.Projections.Conditional(
NHibernate.Criterion.Restrictions.Like(
NHibernate.Criterion.Projections.Property<Store>(s => s.Name), "My",
MatchMode.Start),
NHibernate.Criterion.Projections.Constant(0),
NHibernate.Criterion.Projections.Constant(1))).Asc
.ThenBy(s => s.Name).Asc
.List();
What we are doing here is using a Projection that basically translates to the following SQL:
ORDER BY (case when this_.Name like 'My%' then 0 else 1 end)
| {
"pile_set_name": "StackExchange"
} |
Q:
Migrating Oracle DB to another operating system from Red Hat Enterprise by using a disk image
I have a Red Hat Enterprise server disk image that Oracle DB is installed on it. My question is : Is it even possible to use this disk image in order to setup same DB on another Oracle supported operating system? If possible, how can it be done?
(I have no access to the mentioned Red Hat Enterprise server (because it's damaged). So I have only all disk files of previous installation on Red Hat Enterprise.)
A:
As I recall, Oracle database files (and binary backups) are OS dependent. You could access that DB if you dropped those disks into another Linux server, but you won't be able to utilize them on any non-Linux OS.
If you need them on a different Operating System, I'd recommend putting the disks into a different server or another Linux box, bring Oracle up, run an ASCII backup, then migrate that to your other Operating System.
| {
"pile_set_name": "StackExchange"
} |
Q:
iCal Not Recognized By Google
I've created an iCal which I'm trying to use in Google Calendar, but no events are being displayed. The feed is at here. Each event looks like the following, and two iCal validators are telling me it's a valid file. Does google need an extra field for each entry?
A:
I created my own iCal dumper at https://views.scraperwiki.com/run/days_of_the_year_1/ , which builds the source piece by piece. It won't work when I subscribe online via Google calendar, but if I save, then import the source the events are added. I guess there must be an out of place character in feed2ical's ouput.
| {
"pile_set_name": "StackExchange"
} |
Q:
Silverlight Grid Row Height NOT Taking full height
We're using the grid to layout a navigation bar on top of 75px and a content area below that should take up the rest of the height (we're using the frame navigation approach).
The content section though is being squashed to just short of 100px and the a horizontal scroll bar is added. I've added text wrap, which didn't help. I put a border around the content section and I can see it's not taking up the full space below the nav bar, which should all the screen realestate left.
The code looks as follows:
<UserControl
x:Class="DocRupert.Ui.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
xmlns:uriMapper="clr-namespace:System.Windows.Navigation;assembly=System.Windows.Controls.Navigation"
xmlns:dataControls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.DataForm.Toolkit"
xmlns:login="clr-namespace:DocRupert.Ui.LoginUI"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
<Grid x:Name="LayoutRoot" Style="{StaticResource LayoutRootGridStyle}" ShowGridLines="True">
<Grid.RowDefinitions>
<RowDefinition Height="75" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid Style="{StaticResource NavigationOuterGridStyle}" Grid.Row="0">
<Border>
<Grid x:Name="NavigationGrid" Style="{StaticResource NavigationGridStyle}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="1*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="35" />
<RowDefinition Height="35" />
</Grid.RowDefinitions>
<Border x:Name="BrandingBorder" Grid.Column="0" Grid.Row="0" Grid.RowSpan="2" Style="{StaticResource BrandingBorderStyle}">
<StackPanel x:Name="BrandingStackPanel" Style="{StaticResource BrandingStackPanelStyle}">
<ContentControl Style="{StaticResource LogoIcon}"/>
<TextBlock x:Name="ApplicationNameTextBlock" Style="{StaticResource ApplicationNameStyle}" Text="{Binding Strings.ApplicationName, Source={StaticResource ApplicationResources}}"/>
</StackPanel>
</Border>
<Border x:Name="LinksBorder" Grid.Column="1" Grid.Row="0" Style="{StaticResource LinksBorderStyle}" VerticalAlignment="Top">
<StackPanel x:Name="LinksStackPanel" Style="{StaticResource LinksStackPanelStyle}">
<HyperlinkButton x:Name="MenuHome" Style="{StaticResource LinkStyle}" NavigateUri="/Home" TargetName="ContentFrame" Content="{Binding Path=Strings.HomePageTitle, Source={StaticResource ApplicationResources}}"/>
<Rectangle x:Name="Divider1" Style="{StaticResource DividerStyle}"/>
<HyperlinkButton x:Name="MenuAboutUs" Style="{StaticResource LinkStyle}" NavigateUri="/About" TargetName="ContentFrame" Content="{Binding Path=Strings.AboutPageTitle, Source={StaticResource ApplicationResources}}"/>
</StackPanel>
</Border>
<Border Grid.Column="1" Grid.Row="1">
<StackPanel x:Name="AuthenticationStatusPanel" Style="{StaticResource AuthenticationStatusPanelStyle}">
<login:LoginStatus/>
</StackPanel>
</Border>
</Grid>
</Border>
</Grid>
<Border x:Name="ContentBorder" Grid.Row="1" Style="{StaticResource ContentBorderStyle}" VerticalAlignment="Top">
<navigation:Frame x:Name="ContentFrame" Style="{StaticResource ContentFrameStyle}" Source="/Home" Navigated="ContentFrame_Navigated" NavigationFailed="ContentFrame_NavigationFailed">
<navigation:Frame.UriMapper>
<uriMapper:UriMapper>
<uriMapper:UriMapping Uri="" MappedUri="/Views/Home.xaml"/>
<uriMapper:UriMapping Uri="/{pageName}" MappedUri="/Views/{pageName}.xaml"/>
</uriMapper:UriMapper>
</navigation:Frame.UriMapper>
</navigation:Frame>
</Border>
</Grid>
</UserControl>
[EDIT] - Add Home page XAML
Here's the XAML for the home page that is loaded into the frame:
<Grid x:Name="LayoutRoot">
<ScrollViewer x:Name="PageScrollViewer" Style="{StaticResource PageScrollViewerStyle}">
<StackPanel x:Name="ContentStackPanel" Style="{StaticResource ContentStackPanelStyle}">
<TextBlock x:Name="HeaderText" Style="{StaticResource HeaderTextStyle}"
Text="{Binding Path=Strings.HomePageTitle, Source={StaticResource ApplicationResources}}"/>
<TextBlock TextWrapping="Wrap" Text="Nulla tincidunt, arcu quis ultrices viverra, sapien enim gravida massa, aliquet mollis dolor neque in orci. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent blandit diam quis massa iaculis ut lobortis dui ornare. Morbi pulvinar rutrum justo, ut lacinia elit feugiat bibendum. Duis pharetra dictum mauris sit amet egestas. Suspendisse potenti. Vestibulum posuere velit a enim sollicitudin varius interdum erat scelerisque. Pellentesque blandit felis a diam euismod adipiscing. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vestibulum nunc erat; rutrum vel mattis tincidunt, tincidunt id leo. Suspendisse a accumsan urna. Etiam felis nisi, vulputate vel volutpat nec, ultrices nec quam. Maecenas viverra, sapien consequat pharetra vehicula, est erat pretium ipsum, at tempus nunc justo a mauris. Quisque ac auctor eros.
Sed id sollicitudin ligula. Phasellus dictum mauris vel libero imperdiet dictum. Donec bibendum, magna sit amet vestibulum hendrerit, mi turpis tincidunt arcu, eget pellentesque mauris lacus luctus mi. Quisque id justo turpis. Curabitur sollicitudin massa fermentum nunc adipiscing tincidunt vitae non diam. Praesent venenatis aliquet orci sed tincidunt? Etiam tincidunt ligula nec felis dictum condimentum nec egestas urna. Pellentesque blandit diam quis lacus suscipit pharetra. Nunc diam ante, vestibulum ac bibendum venenatis, laoreet blandit eros. Proin eleifend felis velit, a varius leo. Aliquam erat volutpat. Maecenas varius nisl a arcu malesuada convallis. Vestibulum at ipsum turpis, nec pharetra ipsum.
Sed blandit ultrices pulvinar! Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Mauris aliquam scelerisque sem sed tempor. Sed erat risus, tincidunt vitae pellentesque et, semper eu odio! Cras accumsan cursus urna a elementum. Vestibulum quam velit, sollicitudin sed posuere quis, ullamcorper ut purus. Pellentesque sollicitudin nibh vitae diam elementum eu convallis velit viverra. Maecenas convallis cursus porttitor. Pellentesque purus urna, ultricies sit amet tempor et, hendrerit at sem. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nunc in felis massa, ut congue leo. Maecenas in cursus massa!"></TextBlock>
<TextBlock>hello world</TextBlock>
</StackPanel>
</ScrollViewer>
</Grid>
A:
What GUI elements are you using in your navigation content pages? I would suggest having a Grid as the main GUI element, and ensuring its stretched to take all the available space. To make sure you do this correctly for all of your pages, I would suggest using a style, something like this:
<Style x:Key="NavigationContentGrid" TargetType="Grid">
<Setter Property="VerticalAlignment" Value="Stretch"/>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
</Style>
for your navigation root:
<Grid x:Name="LayoutRoot" Style="{StaticResource NavigationContentGrid}">
<ScrollViewer x:Name="PageScrollViewer" Style="{StaticResource PageScrollViewerStyle}">
...
</ScrollViewer>
</Grid>
Also, I would suggest that your LayoutRootGridStyle and NavigationOuterGridStyle styles both have these same VerticalAlignment & HorizontalAlignment properties set.
| {
"pile_set_name": "StackExchange"
} |
Q:
Declare function after template defined
Let's say I have a template function:
template <class T>
void tfoo( T t )
{
foo( t );
}
later I want to use it with a type, so I declare/define a function and try to call it:
void foo( int );
int main()
{
tfoo(1);
}
and I am getting error from g++:
‘foo’ was not declared in this scope, and no declarations were found by argument-dependent lookup at the point of instantiation [-fpermissive]
foo( t );
why it cannot find void foo(int) at the point of instantiation? It is declared at that point. Is there a way to make it work (without moving declaration of foo before template)?
A:
foo in your case is a dependent name, since function choice depends on the type if the argument and the argument type depends on the template parameter. This means that foo is looked up in accordance with the rules of dependent lookup.
The difference between dependent and non-dependent lookup is that in case of dependent lookup ADL-nominated namespaces are seen as extended: they are extended with extra names visible from the point of template instantiation (tfoo call in your case). That includes the names, which appeared after the template declaration. The key point here is that only ADL-nominated namespaces are extended in this way.
(By ADL-nominated namespace I refer to namespace associated with function argument type and therefore brought into consideration by the rules of dependent name lookup. See "3.4.2 Argument-dependent name lookup")
In your case the argument has type int. int is a fundamental type. Fundamental types do not have associated namespaces (see "3.4.2 Argument-dependent name lookup"), which means that it does not nominate any namespace through ADL. In your example ADL is not involved at all. Dependent name lookup for foo in this case is no different from non-dependent lookup. It will not be able to see your foo, since it is declared below the template.
Note the difference with the following example
template <class T> void tfoo( T t )
{
foo( t );
}
struct S {};
void foo(S s) {}
int main()
{
S s;
tfoo(s);
}
This code will compile since argument type S is a class type. It has an associated namespace - the global one - and it adds (nominates) that global namespace for dependent name lookup. Such ADL-nominated namespaces are seen by dependent lookup in their updated form (as seen from the point of the call). This is why the lookup can see foo and completes successfully.
It is a rather widespread misconception when people believe that the second phase of so called "two-phase lookup" should be able to see everything that was additionally declared below template definition all the way to the point of instantiation (point of the call in this case).
No, the second phase does not see everything. It can see the extra stuff only in namespaces associated with function arguments. All other namespaces do not get updated. They are seen as if observed from the point of template definition.
| {
"pile_set_name": "StackExchange"
} |
Q:
Access sharepoint search rest api
I have a problem. I use Azure AD to authenticate my asp.net app. Authentication works fine. Then I from this app trying to access OneDrive for Business using sharepoint search rest api. But the server always receives a response with a 401 error. I understand that the problem is in the access token which I use (Now I use the token received from Azure AD). But I never found the normal description of how to obtain an access token for the sharepoint search rest api.
Thanks in advance
A:
Answer
You need to give your ASP.NET Application permission to use your OneDrive for Business application.
Here is an overview of how to do this using the Azure Management Portal. (Note that your OneDrive for Business account is a type of Office 365 SharePoint Online account.)
Go to manage.windowsazure.com > Active Directory > Your Tenant. If your tenant has an associated OneDrive for Business account, then its list of applications will include Office 365 SharePoint Online.
If your tenant's list of application does include Office 365 SharePoint Online, then your next step is to give your ASP.NET Web Application permission to access it.
Open up your Web Application's page in the Azure Active Directory area. Then choose CONFIGURE > Add Application. Add the Office 365 SharePoint Online application. Give it all necessary permissions and save.
The following screenshot is for a Native Client Application, because that is what my demo code is using. You can do a similar thing for a Web Application, though you will need to use an X509 Certificate for authentication instead of a username/password.
Your access token will now work with your Office 365 for Business account. Hooray!
Demo
Here is some sample code that works on my machine with a Native Client App. You can do the same thing with a Web Application, though you will need to use an X509 Certificate instead of a username/password.
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Net;
namespace AAD_SharePointOnlineApp
{
class Program
{
static void Main(string[] args)
{
var authContext =
new AuthenticationContext(Constants.AUTHORITY);
var userCredential =
new UserCredential(Constants.USER_NAME, Constants.USER_PASSWORD);
var result = authContext
.AcquireTokenAsync(Constants.RESOURCE, Constants.CLIENT_ID_NATIVE, userCredential)
.Result;
var token = result.AccessToken;
var url = "https://mvp0.sharepoint.com/_api/search/query?querytext=%27timesheets%27";
var request = WebRequest.Create(url);
request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);
var response = request.GetResponse() as HttpWebResponse;
}
}
class Constants
{
public const string AUTHORITY =
"https://login.microsoftonline.com/mvp0.onmicrosoft.com/";
public const string RESOURCE =
"https://mvp0.sharepoint.com";
public const string CLIENT_ID_NATIVE =
"xxxxx-xxxx-xxxxx-xxxx-xxxxx-xxxx";
public const string USER_NAME =
"[email protected]";
public const string USER_PASSWORD =
"MY_PASSWORD";
}
}
Comments
If you are trying to do the above with a Web Application instead of a Native Client Application, then you will need to use an X509 Certificate, otherwise you will receive the following error.
Unsupported app only token.
See also: http://blogs.msdn.com/b/richard_dizeregas_blog/archive/2015/05/03/performing-app-only-operations-on-sharepoint-online-through-azure-ad.aspx
| {
"pile_set_name": "StackExchange"
} |
Q:
Non-uniqueness of the solution of the equation for a plucked string
I'm a bit confused about what is written in this PDF (in page 2). The author asserts that the differential equation $y'' +y = 0$ with boundary conditions $y(0)=0=y(\pi)$ has infinitely many solutions. Namely that $y(x) = A \sin(kx)$ is a solution for any $A\in\mathbb{R}$ and $k\in\mathbb{Z}$. Is he right? It seems to me that it works only for $k=1$ or $k=-1$.
Furthermore, for the more physically-oriented of you, this equation should represent "small oscillations of a plucked string", but I do not understand how it can be, because there is no dependence on time. I'd like to see where does this equation come from.
Thanks in advance for any response
A:
There is an error in the document.
The solution to $y''+y=0$ with the boundary conditions $y(0) = y(\pi) = 0$ is unique up to a multiplicative factor, $y = A \sin x$. This is also not the wave equation.
The partial differential equation describing the motion of a vibrating string is
$$\frac{\partial^2 \psi}{\partial x^2} = \frac{1}{c^2} \frac{\partial^2 \psi}{\partial t^2}$$
where $\psi = \psi(x,t)$ is the height of the string at position $x$ and time $t$,
and where $c$ is the speed of the waves on the string.
($c = T/\rho$, where $T$ is the tension and $\rho$ is the linear density.)
For convenience, set $c = 1$.
Separate variables, $\psi(x,t) = y(x)T(t)$.
We find
$$\frac{y''}{y} = \frac{T''}{T}.$$
Since the LHS depends only on $x$ and the RHS only on $t$, each ratio must be equal to some constant (sometimes called the separation constant).
Call it $-k^2$.
Thus,
$$\begin{eqnarray*}
y'' + k^2 y &=& 0 \\
T'' + k^2 T &=& 0.
\end{eqnarray*}$$
The solutions $y(x)$ are of the form $y(x) = A \sin k x + B\cos k x$.
Impose the boundary conditions, $y(0) =y(\pi) = 0$.
Thus,
$$y(x) = A\sin n x$$
where $k = n = 1,2,\ldots$.
This is the origin of our infinity of solutions.
The solutions to the differential equation for $T$ will be of the form $T(t) = C \sin n t + D\cos n t$.
(Notice the angular frequency is $k = n$, so the frequency of the $n$th solution is $n/(2\pi)$.)
Since we have not been given boundary conditions in time, the solution to the wave equation will be of the form
\begin{equation}
\psi(x,t) = \sum_{n=1}^\infty (a_n \sin n x \sin n t + b_n \sin n x \cos n t).\tag{1}
\end{equation}
There is an infinite tower of solutions.
The $n=1$ solution is the fundamental mode of vibration of the string.
The solutions for $n = 2, 3, \ldots$ correspond to the higher modes.
Addendum: There is another way to see nonuniqueness.
The general solution to the wave equation is
$$\psi(x,t) = f(x-t) + g(x+t)$$
where $f$ and $g$ are arbitrary twice differentiable functions.
($f(x-t)$ is a right-moving wave and $g(x+t)$ is left-moving.)
The boundary conditions imply
$$\begin{eqnarray*}
f(-t) + g(t) &=& 0 \\
f(\pi-t) + g(\pi + t) &=& 0.
\end{eqnarray*}$$
Thus, the solution to the specified partial differential equation is
$$\psi(x,t) = f(x-t) - f(-x-t)$$
where $f(x)$ is any periodic function with period $2\pi$, $f(x+2\pi) = f(x)$.
This solution corresponds, of course, to those functions attainable by the sum in equation (1).
| {
"pile_set_name": "StackExchange"
} |
Q:
Algorithm Time Complexity: i/=2 in loops
int fun(int n) {
int count = 0;
for (int i = n; i > 0; i /= 2)
for (int j = 0; j < i; j++)
count += 1;
return count;
}
I'm a very new to the time complexities calculations. For this algorithm, I get the answer to be O(nlogn), but the answer is apparently O(n).
My logic was the outer loop has an exponential decline and will occur log_base2_(N) times. The inner loop will run a total of N times as it becomes a geometric sum (first iteration it is N/2 times, then N/4, then N/8 ...). If I put these together and multiply them as a result of the nested loop, that's where I'm coming up with O(NlogN).
Am I missing something obvious?
A:
The outer loop would run a total of log(n) times. Now if you observe the inner loop it first time it runs n times, next n/2 times and so on, so it makes the series
n(1 + 1/2 + 1/4 + 1/8 + 1/16 + ...)
the sum of this would be (2*n), That means it is O(n)
Hence the time complexity is O(n) since outer loop runs O(logn) times and inner loop runs O(n) times.
It is not O(nlogn) since the inner loop does not take n steps each time, in fact the sum of all steps taken would be O(n)
| {
"pile_set_name": "StackExchange"
} |
Q:
Shared memory class
I wrote a class that opens a shared memory communication to use in my project, and would like a review.
mylib_com.hpp
#ifndef __MYLIB_COM_HPP
#define __MYLIB_COM_HPP
#include <sys/mman.h> /* For mmap */
#include <fcntl.h> /* For O_* in shm_open */
#include <unistd.h> /* For ftruncate and close*/
#include <string.h> /* For strcpy*/
#include <string>
namespace Myns{
class Channel{
public:
Channel(std::string name, size_t size = sizeof(char)*50);
~Channel();
void write(const char * msg);
std::string read();
private:
int memFd;
int res;
u_char * buffer;
};
}
#endif
mylib_com.cpp
#include "mylib_com.hpp"
#include <errno.h>
#include <system_error>
Myns::Channel::Channel(std::string name, size_t size){
memFd = shm_open(name.c_str(), O_CREAT | O_RDWR, S_IRWXU);
if (memFd == -1)
{
perror("Can't open file");
throw std::system_error(errno, std::generic_category(), "Couldn't open shared memory");
}
res = ftruncate(memFd, size);
if (res == -1)
{
perror("Can't truncate file");
close(memFd);
throw std::system_error(errno, std::generic_category(), "Couldn't truncate shared memory");
}
buffer = (u_char *) mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, memFd, 0);
if (buffer == NULL)
{
perror("Can't mmap");
close(memFd);
throw std::system_error(errno, std::generic_category(), "Couldn't mmap shared memory");
}
}
Myns::Channel::~Channel(){
close(memFd);
}
void Myns::Channel::write(const char * msg){
strcpy((char*)buffer,msg);
}
```
A:
__MYLIB_COM_HPP is a reserved identifier, you're not allowed to use these in your code.
Instead of including both <string> and <string.h>, you could also use std::strcpy(). Also, you don't need that in the header, move it to the implementation file.
sizeof (char) is by definition one, because sizeof gives you the size in multiples of that of a char. That part is basically redundant.
Outputting an error with perror() and throwing it as an exception is kind-of redundant as well. If you don't log an error when you catch it, you're a fool or have reason to ignore it, but you can't make that decision at the place where the error occurs.
You are using C-style casts. Don't, use the C++ casts (static_cast in the cases here) instead.
I'm not sure what u_char is, that may not be portable.
Avoid casting altogether: mmap() returns void*, which you cast to u_char* and store in buffer. In the only case where you use buffer, you cast it to char* first. Don't, just keep it a void* and only cast when you need.
You have no error checking when writing. You just take the char const* and feed it to strcpy(), without any bounds check.
A:
Just a couple of additional points...
I've not used c++17, but when performing tests against constants, consider putting the constants on the left, rather than the right. This prevents typos from having unexpected consequences. if (res = -1) changes the value of res, whereas if(-1 = res) doesn't compile.
You're keeping variables in your class that seem like they aren't needed. If they're only needed for the constructor, then use local variables. Maybe you have other plans for it, but res looks particularly suspect, since it's always going to be 0 if the class has been constructed and in the code you've supplied it's never read again.
| {
"pile_set_name": "StackExchange"
} |
Q:
Lie derivative commutes with interior product
Let $i_X : \Omega^k M \to \Omega^{k-1} M$ be the interior product for a smooth manifold $M$ and a smooth vector field $X$ with flow $\Phi$ and
$$L_X : \Omega^k \to \Omega^k, \; \omega \mapsto L_X \omega := \frac{\text d}{\text d t} \Big| _{t=0} \Phi^*_t \omega$$
the Lie derivative of a $k$-form. Show that
$$i_X \circ L_X = L_X \circ i_X.$$
To be honest, I have no clue. What I have proven so far is that the Lie derivative commutes with the exterior derivative ($d \circ L_X = L_X \circ d$), and I have also proven Cartan's magic formula ($L_X = i_X \circ d + d \circ i_X$) by induction. Is there an easy way to use both of these to prove the upper statement?
A:
$i_X\circ L_X=i_X\circ (i_X\circ d+d\circ i_X)=i_X\circ d\circ i_X$ since $i_X\circ i_X=0$.
$L_X\circ i_X=(i_X\circ d +d\circ i_X)\circ i_X=i_X\circ d\circ i_X$. You deduce that $i_X\circ L_X=L_X\circ i_X$.
| {
"pile_set_name": "StackExchange"
} |
Q:
is it possible to write a directive to match "any other query params"?
To ensure people don't append random query parameters (e.g. appending &r=234522.123 or similar) to avoid hitting our cache I want to have a way to reject any queries that are not handled explicitly. I can of course create one that contains a whitelist, but that would have to be separately maintained and I hate maintaining two things that needs to stay in synch. (Though, it would aid in failing faster.) Is this possible with Spray routing?
A:
I ended up with this:
// This contains a white-list of allowed query parameters. This is useful to
// ensure people don't try to use &r=234234 to bust your caches.
def allowedParameters(params: String*): Directive0 = parameterSeq.flatMap {
case xs =>
val illegal = xs.collect {
case (k, _) if !params.contains(k) => k
}
if (illegal.nonEmpty)
reject(ValidationRejection("Illegal query parameters: " + illegal.mkString("", ", ", "\nAllowed ones are: ") + params.mkString(", ")))
else
pass
}
For usage, have a look at the unit tests:
val allowedRoute = {
allowedParameters("foo", "bar") {
complete("OK")
}
}
"Allowed Parameter Directive" should "reject parameters not in its whitelist" in {
Get("/?foo&bar&quux") ~> allowedRoute ~> check {
handled should equal(false)
rejection should be(ValidationRejection("Illegal query parameters: quux\nAllowed ones are: foo, bar"))
}
}
it should "allow properly sorted parameters through" in {
Get("/?bar&foo") ~> allowedRoute ~> check {
handled should equal(true)
responseAs[String] should equal("OK")
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to add a list to a data frame in R?
I have 2 tables as below:
a = read.table(text=' a b
1 c
1 d
2 c
2 a
2 b
3 a
', head=T)
b = read.table(text=' a c
1 x i
2 y j
3 z k
', head=T)
And I want result to be like this:
1 x i c d
2 y j c a b
3 z k a
Originally I thought to use tapply to transform them to lists (eg. aa = tapply(a[,2], a[,1], function(x) paste(x,collapse=","))), then append it back to table b, but I got stuck...
Any suggestion to do this?
Thanks a million.
A:
One way to do it:
mapply(FUN = c,
lapply(split(b, row.names(b)), function(x) as.character(unlist(x, use.names = FALSE))),
split(as.character(a$b), a$a),
SIMPLIFY = FALSE)
# $`1`
# [1] "x" "i" "c" "d"
#
# $`2`
# [1] "y" "j" "c" "a" "b"
#
# $`3`
# [1] "z" "k" "a"
| {
"pile_set_name": "StackExchange"
} |
Q:
Fragments in ViewPager not loaded when the containing Fragment is recreated
I have a Fragment MyFragment vith a ViewPager containing more Fragment. It works properly the first time I load MyFragment, but if I go back and recreate it, the Fragments in the ViewPager are not shown because the method FragmentPagerAdapter.getItem is not called.
I'm using
What's wrong?
import android.app.Fragment;
import android.app.FragmentManager;
import android.support.v13.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
...
public class MyFragment extends Fragment {
private ViewPager pager;
private MyPagerAdapter adapter;
private List<Fragment> fragmentList = new ArrayList<Fragment>();
public MyFragment() {}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_fragment_layout, container, false);
}
public void onViewCreated(View v, Bundle savedInstanceState) {
super.onViewCreated(v, savedInstanceState);
indicators = (PagerSlidingIndicator) v.findViewById(R.id.indicators);
pager = (ViewPager) v.findViewById(R.id.pager);
Fragment fragment1 = new Fragment1();
fragmentList.add(fragment1);
Fragment fragment2 = new Fragment2();
fragmentList.add(fragment2);
Fragment fragment3 = new Fragment3();
fragmentList.add(fragment3);
adapter = new IndicatorPagerAdapter(getFragmentManager());
pager.setAdapter(adapter);
}
public class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return fragmentList.size();
}
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
}
}
A:
If you are using nested fragments ("I have a Fragment MyFragment vith a ViewPager containing more Fragment"), you need to use getChildFragmentManager(), not getFragmentManager(), when setting up your FragmentPagerAdapter.
| {
"pile_set_name": "StackExchange"
} |
Q:
What are the possible values of determinant of a nxn matrix if n odd vs even
Assume that A is an n x n matrix with complex entries such that $$A^TA = -I_n$$What are the possible values of det(A) if (i) n is even, (ii) n odd?
Justify your answers, clearly stating any properties of determinants that you use in your solution.
I have been struggling with this question for a long time and still can't make a start. I have been toying with $$det(A^t) = det(A)$$
$$det(A)(B) = det(A) det(B)$$
but I cannot make a plausible start. Please guide a bit. Thanks in advance.
A:
I cannot make a plausible start
I'd say you're nearly finished. Of course, you haven't gotten anywhere on writing a solution yet, but that's just the final step. Finding the solution is the largest and most important step (sadly, it's mostly invisible if you read books or attend lectures), and here you have done plenty of progress.
You've found that $\det(A^t) = \det(A)$, and you've found that $\det(AB) = \det(A)\det(B)$. Combining these, we get that $\det(A^tA) = \det(A)^2$.
The determinant of $-I_n$ is $(-1)^n$, which differs depending on whether $n$ is even or odd.
If $n$ is even, the determinant of $-I_n$ is $1$, and we have $\det(A)^2 = 1$. What are the two possible values of $\det(A)$ in this case? If, on the other hand, $n$ is odd, the determinant of $-I_n$ is $-1$, and we get $\det(A)^2 = -1$. What are the two possible values in this case?
| {
"pile_set_name": "StackExchange"
} |
Q:
Location-aware applications on WP7.5
I would like to create a location-aware application on WP7.5
Is it possible to automatically get a trigger on location change without our application running on background?
For example:
I would like to know if a user has moved in a new location. If the user has moved I would like to trigger a specific event from my application. My only concern is that if I do that from my application I will consume a significant amount of battery. Is it a specific WP7 service which can inform my application that the user has changed his location and trigger an event from my application?
If it is possible can you please point me an example?
A:
You can make 2 thinks:
Use Periodic Agent to get geoposition every 30 minuts
Use GeoCoordinateWatcher inside your app and set MovementThreshold to get data only when position really changed. This way will work only if your app is actually running on the device - when user left the application watcher will stop working.
| {
"pile_set_name": "StackExchange"
} |
Q:
Disabling auto adjusment to image in CSS when zooming in/out
<div class="footer">
<img class="fisk" src="fisk1.jpg" alt="fisk">
</div>
I have a img inside a div and i want this image to keep the same size when zooming in and out, but i can't get this to work. I feel like i have tried everything and it feels like this is not possible?
I get the text to stay the same size but not the image.
A:
This should be the solution, it seems to stay the same even during resize!
Note: tested in my local html file, while zooming in/out!
html,
body {
width: 100%;
margin: 0px;
}
<div class="footer">
<img class="fisk" src="http://via.placeholder.com/350x150" alt="fisk" width="100%">
</div>
| {
"pile_set_name": "StackExchange"
} |
Q:
Test missing when using AutoFixture with NSubstitute auto data attribute
A test class with the following test is discovered as expected:
[Theory]
[AutoData]
public void MyDiscoveredTest() { }
However, the following test is missing:
[Theory]
[AutoNSubstituteData]
public void MyMissingTest() { }
Interestingly, if I put MyDiscoveredTest after MyMissingTest, then MyDiscoveredTest is also now missing. I have tried both the xUnit visual studio runner and xUnit console runner with the same results.
My AutoNSubstituteData attribute is defined here:
internal class AutoNSubstituteDataAttribute : AutoDataAttribute
{
internal AutoNSubstituteDataAttribute()
: base(new Fixture().Customize(new AutoNSubstituteCustomization()))
{
}
}
A related question: since the AutoNSubstituteDataAttribute above seems like a fairly common attribute, I'm wondering why it's not included with AutoFixture.AutoNSubstitute. Similarly useful would be an InlineAutoNSubstituteDataAttribute. Should I submit a pull request for these?
Nuget package versions used:
AutoFixture 3.30.8
AutoFixture.Xunit2 3.30.8
AutoFixture.AutoNSubstitute 3.30.8
xunit 2.0.0
xunit.runner.visualstudio 2.0.0
xunit.runner.console 2.0.0
NSubstitute 1.8.2.0
I am using Visual Studio 2013 Update 4 and targeting the .NET 4.5.1 Framework
Update: As recommended I tried TestDriven.NET-3.9.2897 Beta 2. The missing test now runs, however it still seems there is some bug. New example:
[Theory]
[AutoData]
public void MyWorkingTest(string s)
{
Assert.NotNull(s); // Pass
}
[Theory]
[AutoNSubstituteData]
public void MyBrokenTest(string s)
{
Assert.NotNull(s); // Fail
}
[Theory]
[AutoData]
public void MyWorkingTestThatIsNowBroken(string s)
{
Assert.NotNull(s); // Fail even though identical to MyWorkingTest above!
}
Both MyBrokenTest and MyWorkingTestThatIsNowBroken fail at Assert.NotNull, while MyWorkingTest passes even though it is identical to MyWorkingTestThatIsNowBroken. So not only does the AutoNSubstituteData attribute not work properly, but it is causing the downstream test to misbehave!
Update2: Changing the definition of AutoNSubstituteDataAttribute to public instead of internal fixes everything. xunit runner now discovers and passes all the tests as does TestDriven.Net. Any idea about this behavior? Is it expected?
A:
Both xUnit visual studio runner and TestDriven.Net runner are causing these weird issues because the AutoNSubstituteDataAttribute class and constructor are internal. Changing these to public resolves all the issues. If the attribute is being ignored I would expect an error like this: System.InvalidOperationException : No data found for ...
This doesn't explain why the downstream tests are affected by the offending AutoNSubstituteData attribute from a totally different test. It seems like the unit test runners should be more robust in this case.
For completeness here is the working implementation of AutoNSubstituteDataAttribute:
public class AutoNSubstituteDataAttribute : AutoDataAttribute
{
public AutoNSubstituteDataAttribute()
: base(new Fixture().Customize(new AutoNSubstituteCustomization()))
{
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
No wired connection from router when waking up from suspend/reboot/reconnect
So up until recently my 5 year old Linksys WRT54GL router was working fine, but for a few days now everytime I wake up Ubuntu from suspend I have no wired internet (wireless devices still have internet), and the only way to fix it is to turn off and turn on the router.
If I don't do that I can't even access administrator page at 192.168.1.1. It's the same if I disconnect ethernet cable and plug it in again to laptop, I won't have internet unless reboot router once again.
How can I fix it, because it was working perfectly before.
A:
I checked my /etc/network/interfaces and it was like this (I never changed anything before):
auto lo
iface lo inet loopback
So I modified it:
auto lo eth0
iface lo inet loopback
iface eth0 inet dhcp
And now it automatically connects when I reboot or plug the ethernet cable. Not sure why was this the solution because I never touched interfaces file.
| {
"pile_set_name": "StackExchange"
} |
Q:
Flagged as Low Quality - can't flag as Dupe
I already flagged this question as Low Quality, and posted a comment to that effect.
But then the OP asked why it was low quality, so I searched and found an exact duplicate.
When trying to flag as a dupe, I get the Post already flagged error.
I don't know whether this is something that can be changed when flagging for a different reason?
Or is there something else I should have done?
A:
No, once you've flagged to close for any reason there's no going back.
Here's the feature request to allow you to change that vote (it's currently the number one status-declined feature request on Meta).
Here's one to allow you to swap close reasons.
| {
"pile_set_name": "StackExchange"
} |
Q:
Distinguish between types using SFINAE and void_t
I faced some situation where I have to write two functions, one of them should be invoked with primitive types and std::string. The other one should be called with other types.
So far I ended with working solution:
template <typename...>
struct Void_t_helper {
using type = void;
};
template <typename... Ts>
using Void_t = typename Void_t_helper<Ts...>::type;
template <typename T, typename = void>
struct Is_string : std::false_type {};
template <typename T>
struct Is_string<T, Void_t<decltype (std::declval<T> ().c_str ())>> : std::is_same<decltype (std::declval<T> ().c_str ()), const char*>::type {};
template <typename T>
std::enable_if_t<Is_string<T>::value || std::is_arithmetic<T>::value, void> foo (T) {
std::cout << "string or primitive\n";
}
template <typename T>
std::enable_if_t<!Is_string<T>::value && !std::is_arithmetic<T>::value, void> foo (T) {
std::cout << "other type\n";
}
And the usage:
foo (1);
foo (1.2);
foo (std::string {"fsdf"});
foo (std::vector<int> {1, 2, 3});
foo (std::vector<std::string> {"a", "v", "c"});
produces as expected:
string or primitive
string or primitive
string or primitive
other type
other type
My question is: Do you know better solution to this kind of problem?
I am not really sure if checking if c_str() exists is the better option I can get. I am aware that I could probably write some wrapper class that for primitive types and std::string would have some category_t defined with value X, and for other types value Y and distinguish between these groups using this category, but still I think that c_str() checking is more convenient.
A:
I am not really sure if checking if c_str() exists is the better option I can get.
Ideally you'll be checking for what you actually want.
That can either be a set of known types or templates, or it can be a concept.
At the moment, you're checking for "the concept of having a c_str() member function which returns a pointer to constant chars".
The question is, what concept does your SFINAE'd function need?
If it will use the c_str() member, that's reasonable. But if it's going to use other members or types of the string, you probably want to build a compound concept to describe the parts of the interface you're going to exercise.
Of course, you may just want to confirm that it is actually a specialisation of std::string. It's difficult (impossible) to tell unless you state the use case.
| {
"pile_set_name": "StackExchange"
} |
Q:
Set Task type to Empty
How to set the type of the Task to empty value using SOAP API?
While creating Task when I set the empty string - SF just takes the default value for the organization.
A:
You need to set fieldsToNull to include the fields that have a null value specified, otherwise the default value will be taken. This is due to a limitation in how WSDL describes the service; fields with null attributes will be silently discarded by default.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is this distribution called?
For every positive integer $n$,
$nx^{n-1}$
is a probability density function in $[0,1]$. What is it called?
A:
The distribution with pdf
$$
f(x) = \frac{\beta x^{\beta-1}}{\alpha^\beta}
$$
is known as the "power distribution" (unfortunately, it’s a very google-unfriendly name). It is alternatively parametrized by $k = 1/\alpha$. It has the $(0, \alpha]$ support.
| {
"pile_set_name": "StackExchange"
} |
Q:
ImageView not showing image in activity
I made an app where you use the default camera to take a photo then displays it on the image view.Problem is, image does not show in the image view. Tried many ways but no solution.
mainactivity.java:
public class MainActivity extends Activity {
private static final int ACTIVITY_START_CAMERA_APP = 0;
static final int REQUEST_IMAGE_CAPTURE = 1;
private ImageView mPhotoCapturedImageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPhotoCapturedImageView = (ImageView) findViewById(R.id.capturePhotoImageView);
}
public void takePhoto(View view){
Intent callCameraApplicationIntent = new Intent();
callCameraApplicationIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(callCameraApplicationIntent, ACTIVITY_START_CAMERA_APP);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Toast.makeText(this, "Picture taken sucessfully!", Toast.LENGTH_SHORT).show();
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mPhotoCapturedImageView.setImageBitmap(imageBitmap);
}
}
}
main_activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.taufiq.ocrdemo.MainActivity">
<ImageView
android:id="@+id/capturePhotoImageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/photoButton"
android:layout_marginBottom="19dp"
android:layout_marginEnd="43dp"
android:layout_marginLeft="43dp"
android:layout_marginRight="43dp"
android:layout_marginStart="43dp"
android:layout_marginTop="16dp"
android:contentDescription="@string/preview"
android:minHeight="300dp"
app:layout_constraintBottom_toTopOf="@+id/photoButton"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="MissingConstraints"
tools:layout_constraintBottom_creator="1"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintTop_creator="1"
tools:minHeight="300dp" />
<Button
android:id="@+id/photoButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="takePhoto"
android:text="@string/capture_photo"
android:layout_weight="1"
tools:ignore="MissingConstraints"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
tools:layout_constraintLeft_creator="1"
android:layout_marginBottom="27dp"
app:layout_constraintLeft_toLeftOf="parent" />
</android.support.constraint.ConstraintLayout>
A:
Problem is here :
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
you are starting the Activity with requestCode ACTIVITY_START_CAMERA_APP
startActivityForResult(callCameraApplicationIntent, ACTIVITY_START_CAMERA_APP);
so you need to modify the if condition like:
if (requestCode == ACTIVITY_START_CAMERA_APP && resultCode == RESULT_OK) {
| {
"pile_set_name": "StackExchange"
} |
Q:
Merge two map of strings in JavaScript
In React Native JSX, how can join two map of strings like this?
const map1 = { title: 'Avengers: Infinity War', genre: 'Action, Adventure, Fantasy' };
const map2 = { directors: 'Anthony Russo, Joe Russo', stars: ' Robert Downey Jr., Chris Hemsworth, Mark Ruffalo' };
The result I want:
{ title: 'Avengers: Infinity War', genre: 'Action, Adventure, Fantasy', directors: 'Anthony Russo, Joe Russo', stars: ' Robert Downey Jr., Chris Hemsworth, Mark Ruffalo' }
Thanks for your help!
A:
const map1 = { title: 'Avengers: Infinity War', genre: 'Action, Adventure, Fantasy' };
const map2 = { directors: 'Anthony Russo, Joe Russo', stars: ' Robert Downey Jr., Chris Hemsworth, Mark Ruffalo' };
console.log(Object.assign({}, map1, map2));
Object.assign({}, map1, map2);
| {
"pile_set_name": "StackExchange"
} |
Q:
Volatile in C++11
In C++11 standard the machine model changed from a single thread machine to a multi threaded machine.
Does this mean that the typical static int x; void func() { x = 0; while (x == 0) {} } example of optimized out read will no longer happen in C++11?
EDIT: for those who don't know this example (I'm seriously astonished), please read this: https://en.wikipedia.org/wiki/Volatile_variable
EDIT2:
OK, I was really expecting that everyone who knew what volatile is has seen this example.
If you use the code in the example the variable read in the cycle will be optimized out, making the cycle endless.
The solution of course is to use volatile which will force the compiler to read the variable on each access.
My question is if this is a deprecated problem in C++11, since the machine model is multi-threaded, therefore the compiler should consider concurrent access to variable to be present in the system.
A:
Whether it is optimized out depends entirely on compilers and what they choose to optimize away. The C++98/03 memory model does not recognize the possibility that x could change between the setting of it and the retrieval of the value.
The C++11 memory model does recognize that x could be changed. However, it doesn't care. Non-atomic access to variables (ie: not using std::atomics or proper mutexes) yields undefined behavior. So it's perfectly fine for a C++11 compiler to assume that x never changes between the write and reads, since undefined behavior can mean, "the function never sees x change ever."
Now, let's look at what C++11 says about volatile int x;. If you put that in there, and you have some other thread mess with x, you still have undefined behavior. Volatile does not affect threading behavior. C++11's memory model does not define reads or writes from/to x to be atomic, nor does it require the memory barriers needed for non-atomic reads/writes to be properly ordered. volatile has nothing to do with it one way or the other.
Oh, your code might work. But C++11 doesn't guarantee it.
What volatile tells the compiler is that it can't optimize memory reads from that variable. However, CPU cores have different caches, and most memory writes do not immediately go out to main memory. They get stored in that core's local cache, and may be written... eventually.
CPUs have ways to force cache lines out into memory and to synchronize memory access among different cores. These memory barriers allow two threads to communicate effectively. Merely reading from memory in one core that was written in another core isn't enough; the core that wrote the memory needs to issue a barrier, and the core that's reading it needs to have had that barrier complete before reading it to actually get the data.
volatile guarantees none of this. Volatile works with "hardware, mapped memory and stuff" because the hardware that writes that memory makes sure that the cache issue is taken care of. If CPU cores issued a memory barrier after every write, you can basically kiss any hope of performance goodbye. So C++11 has specific language saying when constructs are required to issue a barrier.
volatile is about memory access (when to read); threading is about memory integrity (what is actually stored there).
The C++11 memory model is specific about what operations will cause writes in one thread to become visible in another. It's about memory integrity, which is not something volatile handles. And memory integrity generally requires both threads to do something.
For example, if thread A locks a mutex, does a write, and then unlocks it, the C++11 memory model only requires that write to become visible to thread B if thread B later locks it. Until it actually acquires that particular lock, it's undefined what value is there. This stuff is laid out in great detail in section 1.10 of the standard.
Let's look at the code you cite, with respect to the standard. Section 1.10, p8 speaks of the ability of certain library calls to cause a thread to "synchronize with" another thread. Most of the other paragraphs explain how synchronization (and other things) build an order of operations between threads. Of course, your code doesn't invoke any of this. There is no synchronization point, no dependency ordering, nothing.
Without such protection, without some form of synchronization or ordering, 1.10 p21 comes in:
The execution of a program contains a data race if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other. Any such data race results in undefined behavior.
Your program contains two conflicting actions (reading from x and writing to x). Neither is atomic, and neither is ordered by synchronization to happen before the other.
Thus, you have achieved undefined behavior.
So the only case where you get guaranteed multithreaded behavior by the C++11 memory model is if you use a proper mutex or std::atomic<int> x with the proper atomic load/store calls.
Oh, and you don't need to make x volatile too. Anytime you call a (non-inline) function, that function or something it calls could modify a global variable. So it cannot optimize away the read of x in the while loop. And every C++11 mechanism to synchronize requires calling a function. That just so happens to invoke a memory barrier.
| {
"pile_set_name": "StackExchange"
} |
Q:
A word or expression to describe someone who don't think for themselves
People who don't have a critical mind. They repeat what they heard without questioning or analyzing the subject matter. What would you call these kind of individuals??
Thank you .
A:
Such a person would be a parrot:
a person who, without thought or understanding, merely repeats the words or imitates the actions of another.
to repeat or imitate without thought or understanding.
Though one hears the verb form more often (he just parrots back what they tell him).
For a more common noun, there is also the closely related sheep:
a meek, unimaginative, or easily led person.
| {
"pile_set_name": "StackExchange"
} |
Q:
Invalid datetime format in laravel while sending data from angular
Can anyone help me how to solve this issue? I have a request data from angular that I had passed to the laravel backend for inserting multiple rows at a time. But I got below error. I tried running the below query in Mysql, it is working fine there but not from laravel.
How can I fix this??
Request data from Angular (API):
[
{
"customer_id": 3,
"check_in_date": "2020-07-30T00:00:00.000Z",
"check_out_date": "2020-07-31T00:00:00.000Z",
"room_id": 2
},
{
"customer_id": 3,
"check_in_date": "2020-07-29T00:00:00.000Z",
"check_out_date": "2020-07-31T00:00:00.000Z",
"room_id": 3
}
]
Migration Table
public function up()
{
Schema::create('reservations', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('room_id');
$table->foreign('room_id')->references('id')->on('rooms');
$table->unsignedBigInteger('customer_id');
$table->foreign('customer_id')->references('id')->on('customers');
$table->unsignedBigInteger('booking_id')->nullable();
$table->foreign('booking_id')->references('id')->on('bookings');
$table->dateTime('check_in_date');
$table->dateTime('check_out_date');
$table->timestamps();
});
}
Controller of reservation:
public function store(Request $request)
{
$reservation = Reservation::insert($request->all());
return $this->jsonResponse(true, 'Reservation has been created successfully.', $reservation);
}
private function jsonResponse($success = false, $message = '', $data = null)
{
return response()->json([
'success' => $success,
'message' => $message,
'data' => $data
]);
}
Error:
"message": "SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2020-07-
29T00:00:00.000Z' for column 'check_in_date' at row 1
(SQL: insert into `reservations` (`check_in_date`, `check_out_date`, `customer_id`, `room_id`)
values (2020-07-30T00:00:00.000Z, 2020-07-31T00:00:00.000Z, 3, 2),
(2020-07-29T00:00:00.000Z, 2020- 07-31T00:00:00.000Z, 3, 3))",
"exception": "Illuminate\\Database\\QueryException",
A:
the dates have the wrong format, try casting them using Carbon, it should serialize automatically to the correct form that your DBMS wants:
use Carbon\Carbon;
...
function store(Request $request)
{
$all = array_map(function($el){
$el->check_in_date = Carbon::createFromFormat('Y-m-d\TH:i:s+', $el->check_in_date);
$el->check_out_date = Carbon::createFromFormat('Y-m-d\TH:i:s+', $el->check_out_date);
return $el;
}, $request->all());
$reservation = Reservation::insert($all);
return $this->jsonResponse(true, 'Reservation has been created successfully.', $reservation);
}
Edit: seems like there was some issue about accessing the object fields, solved using $el['check_in_date'] instead of $el->check_in_date
| {
"pile_set_name": "StackExchange"
} |
Q:
Proposal: Add a filter "My tags" to all the question lists
When I check the different Questions lists (Newest, featured, etc...) without specifying a specific tag, I am flooded with non-relevant (for me of course!!!) questions.
I've got a decent amount of tags.
So I always have to filter the questions tags by tags, by clicking on my own tags list on the right side. This takes time and is not fun. When I am on the mobile app, the experience is even worse.
Maybe I have missed something, but apparently the feature to filter on "All my tags" at once doesn't exist, which is weird considering that it is for me an essential feature for people mastering a lot of different technologies.
Would you consider adding this, or point me to a simple way to do it that I would have missed?
A:
Well... I've got 3 browsers, 10 computers, 3 different workplaces... the bookmark is NOT a solution.
Details about your (beta new navigation) tabs are saved on the server, so any custom tabs you happen to save on one browser or computer will be available on any other browser or computer.
Can you setup a tab for all your favorites?
Yes. I've done this in the new navigation beta, but I have so many favorite tags (most not shown in the tag field as they're scrolled off to the left in the UI), I find it more productive to setup separate (Swift, watchOS, ...) tabs for specific language or platform questions.
Once you've enabled the new beta navigation, use these steps to create your own custom tag tabs:
Select + new tab.
Enter a list of tags for that tab.
Select whether you want to filter by any tags that match or whether all tags must match. (This implicitly separates your tags with OR or AND.)
Right-click on the tab's dropdown arrow to give your tab a specific name.
Click the Save button to make that tab permanent.
Is there a mobile app solution for this issue?
And this is not applicable to the mobile app.
Not sure if Android also does this, but the latest update for the iOS app just added a way to save a custom filter for questions.
| {
"pile_set_name": "StackExchange"
} |
Q:
Select a point of a curve
I am doing some caclulations with extreme velocities and the only way to solve my system equations is to do it graphically. Once I have plotted my curve, I would like to develop a function that enter an x-value and the function itself plots a line from this x-value up to the corresponding point of the curve and from this point, another line over y-value. Like this I would get my y-value that would be the solution of my system equations.
Here is my code. The function Vr_Vmed is the expression of my final equation. In fact, n=4 and Tr=50 and x is the variable.
par(font=10,font.axis=10,font.lab=10,font.main=11,font.sub=10)
curve(Vr_Vmed(x,n,Tr),xlim=c(1,2.5),ylim=c(1,17),
xaxs="i",yaxs="i",xaxt="n",yaxt="n",lwd=2,
xlab="K Weibull",ylab="Vref / Vmed",usr=c(1,2.5,1,17),
main="Vref Estimation")
axis(1,at=c(seq(1,2.5,0.1)),xaxp=c(1,2.5,1))
axis(2,at=c(seq(1,17,1)))
A:
If you just want to add lines to your plot,
you can use lines or segments.
f <- function(x) {
y <- Vr_Vmed(x,n,Tr)
lines(c(x,x,0),c(0,y,y))
}
f(2)
(But that does not "solve" anything: your Vr_med function
aparently does all the work.)
| {
"pile_set_name": "StackExchange"
} |
Q:
C# Expression change body (Property to SubProperty)
I create custom helper and need change expression body.
Models
public class Customer
{
public string Name { get; set; }
}
public class Report
{
public Customer Customer { get; set; }
}
Using helper
@Html.TextBoxForAdv(report => report.Customer)
public static MvcHtmlString TextBoxForAdv<TModel, TProperty>(
this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> value)
{
//value = { report.Customer };
//At this place i want change Customer to Customer.Name
string property = SomeFunction(typeof(Report)) return "Name";
//value = { report.Customer.Name (from property) };
return helper.TextBoxFor(helper, value);
}
I get property
Expression expr = Expression.Property(expression, "Name");
But new expression not valid to call helper.TextBoxFor(...)
How do it?
A:
This should do what you are looking for:
public static MvcHtmlString TextBoxForAdv<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> value)
{
var body = Expression.Property(value.Body, "Name");
var expression = Expression.Lambda<Func<TModel, string>>(body, value.Parameters[0]);
return helper.TextBoxFor(expression);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Updating App in Mac App Store with a higher OS requirement
Currently my app requires snow leopard and above.. Can I send an update to the Mac App Store that requires Lion and above?
A:
I got my answer from Apple.
Yes, I can submit an update with a higher OS requirement.
Drawback: users with previous OS will not be able to download any version.
| {
"pile_set_name": "StackExchange"
} |
Q:
How cold air is less dense in one case and more dense in another case when compared with warm air?
There are two different and contradicting explanations given. Which one is correct?
Explanation 1: Cold air is more denser than hot air because ,when cold air of some density, say 'd' is heated, the molecules/atoms move apart from each other and so the volume expands. As mass of the air hasn't changes and the volume has increased, hot air is less denser than cold air.
Explanation 2: Hot air is more denser than cold air because ,air mostly comprises Oxygen(~20%) and Nitrogen(~78%). So this air, when starts holding water (i.e when it starts becoming cold), few O2(atomic mass 16 units) and N2(atomic mass 14 units) molecules are replaced by H20 (atomic mass 10 units). So, by Avogadro's law, for given volume of air at same temp and pressure and same number of molecules, cold air has lesser weight(H20 has lesser atomic mass) than hot air.
Which of the above two is correct? What causes sea breeze??
Is it that the second explanation is a special case of water acting as cooling agent, otherwise first case is true.
A:
The equations for the density of air are available on the engineering toolbox site. The density of dry air is approximately given by:
$$ \rho_{dry} = \frac{0.0035\,P_0}{T} $$
where $P_0$ is the pressure and $T$ is the temperature. The density of moist air is approaximately given by:
$$ \rho_{wet} = \rho_{dry}\,\frac{1 + x}{1 + 1.609 x} $$
where $x$ is the mass fraction of water. Just for fun I calculated these in Excel assuming that $P_0 = 101325$ Pa and got:
The first table shows the density in kg/m$^3$ while the second table is the same data but as a fraction of the density of dry air at $0$ºC.
The reason for the blanks in the table is that for any temperature there is a maximum amount of water that the air will hold. Again this is available from the engineering toolbox site. I have chosen the values of $x$ to be the maximum values at the temperatures 273K, 278K, and so on, so the bottom left portion of the table is empty.
I found the results rather surprising. The effect of humidity and temperature are almost equal in their effect - I had not expected humidity to have that big an effect.
This is all good fun, but it doesn't have any great bearing on the sea breeze. because the land is hotter than the sea the density of the air on the land is lower so it rises and pulls in air from the sea - hence the sea breeze. The moisture content of the air remains constant as the air flows, so all that changes is the temperature not the moisture content.
| {
"pile_set_name": "StackExchange"
} |
Q:
Error while Setting up Angular 2 environment on Windows 7/64 bit
I was setting up the environment for angular 2 on my local machine running Windows 7 64 bit OS. I successfully installed the node JS v6.11.0 LTS on my machine but when I'm trying to install Angular cli using npm by this command-
npm install -g @angular/cli
It throws following error-
Your environment has been set up for using Node.js 6.11.0 (x64) and
npm.
C:\Users\XYZ>npm install -g @angular/cli
URIError: URI malformed
at decodeURIComponent (native)
at Url.parse (url.js:269:19)
at Object.urlParse [as parse] (url.js:75:5)
at Object.validateUrl [as validate] (C:\Program Files\nodejs\node_modules\npm\node_modules\nopt\lib\nopt.js:164:13)
at validate (C:\Program Files\nodejs\node_modules\npm\node_modules\nopt\lib\nopt.js:213:24)
at validate (C:\Program Files\nodejs\node_modules\npm\node_modules\nopt\lib\nopt.js:179:11)
at C:\Program Files\nodejs\node_modules\npm\node_modules\nopt\lib\nopt.js:101:12
at Array.map (native)
at C:\Program Files\nodejs\node_modules\npm\node_modules\nopt\lib\nopt.js:67:15
at Array.forEach (native)
C:\Program Files\nodejs\node_modules\npm\lib\npm.js:39
throw new Error('npm.load() required')
^
Error: npm.load() required
at Object.get (C:\Program Files\nodejs\node_modules\npm\lib\npm.js:39:13)
at exit (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:60:40)
at process.errorHandler (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:180:3)
at emitOne (events.js:96:13)
at process.emit (events.js:188:7)
at processEmit (C:\Program Files\nodejs\node_modules\npm\node_modules\npmlog\node_modules\gauge\node_modules\signal-exit\index.js:146:32)
at processEmit [as emit] (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-registry-client\node_modules\npmlog\node_modules\gauge\node_modules\signal-exit\index.js:146:32)
at process._fatalException (bootstrap_node.js:296:26) URIError: URI malformed
at decodeURIComponent (native)
at Url.parse (url.js:269:19)
at Object.urlParse [as parse] (url.js:75:5)
at Object.validateUrl [as validate] (C:\Program Files\nodejs\node_modules\npm\node_modules\nopt\lib\nopt.js:164:13)
at validate (C:\Program Files\nodejs\node_modules\npm\node_modules\nopt\lib\nopt.js:213:24)
at validate (C:\Program Files\nodejs\node_modules\npm\node_modules\nopt\lib\nopt.js:179:11)
at C:\Program Files\nodejs\node_modules\npm\node_modules\nopt\lib\nopt.js:101:12
at Array.map (native)
at C:\Program Files\nodejs\node_modules\npm\node_modules\nopt\lib\nopt.js:67:15
at Array.forEach (native)
C:\Program Files\nodejs\node_modules\npm\lib\npm.js:39
throw new Error('npm.load() required')
^
Error: npm.load() required
at Object.get (C:\Program Files\nodejs\node_modules\npm\lib\npm.js:39:13)
at exit (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:60:40)
at process.errorHandler (C:\Program Files\nodejs\node_modules\npm\lib\utils\error-handler.js:180:3)
at emitOne (events.js:96:13)
at process.emit (events.js:188:7)
at processEmit (C:\Program Files\nodejs\node_modules\npm\node_modules\npmlog\node_modules\gauge\node_modules\signal-exit\index.js:146:32)
at processEmit [as emit] (C:\Program Files\nodejs\node_modules\npm\node_modules\npm-registry-client\node_modules\npmlog\node_modules\gauge\node_modules\signal-exit\index.js:146:32)
at process._fatalException (bootstrap_node.js:296:26)
C:\Users\XYZ>
How to get rid of this error?
A:
Issue solved by changing the PROXY and HTTPS-PROXY URLs contained in the .NPMRC file.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on
Im pretty new to C# but I have been playing around with it to learn. So far I have a nice app that does things like starts up the screen saver and controls the windows system volume.
However I'm having some trouble and I'm not sure what is wrong. I have already gone through a bunch of similar questions on the site but I don't think any of them apply to my specific case.
So I wanted to control the app from the web. My plan is to have the app check a webpage on my site for a command every couple seconds. Depending on what the site returns the app will do different things(mute, vol up, etc.) and reset the command on the website to blank. The website command part is all done in PHP and is quite simple, there is no problem with that part of it.
I created a button that calls a function that checks the page and performs the action. It worked fine. But when I tried to make it automatically check the site I'm getting errors. I'm pretty sure it is because I moved the check and perform action to a new thread. So lets move on to the code. These are not the full files but what I think you need to know to help. If you need anything more just let me know.
Form1.cs
public Form1(Boolean init = true)
{
if (init)
{
InitializeComponent(); //initialize UI
startWebMonitor(); //starts web monitor thread for remote web commands
}
}
private void startWebMonitor()
{
Thread t = new Thread(WebMonitor.doWork);
t.Start();
}
public IntPtr getWindowHandle()
{
return this.Handle;
}
WebMonitor.cs
public static void doWork()
{
while(true)
{
checkForUpdate();
Thread.Sleep(1000);
}
}
private static void checkForUpdate()
{
lastCommand = getLastCommand();
if (lastCommand.Equals(""))
{
//No Update
}
else
{
processCommand(lastCommand);
}
}
public static void processCommand(String command)
{
if(command.Equals("mute"))
{
VolumeCtrl.mute(Program.form1.getWindowHandle());
}
HTTPGet req2 = new HTTPGet();
req2.Request("http://mywebsite.com/commands.php?do=clearcommand");
}
VolumeCtrl.cs
private static IntPtr getWindowHandle()
{
Form1 form1 = new Form1(false); //false = do not initialize UI again
return form1.getWindowHandle();
}
public static void mute(IntPtr handle)
{
SendMessageW(getWindowHandle(), WM_APPCOMMAND, getWindowHandle(), (IntPtr)APPCOMMAND_VOLUME_MUTE);
}
Alright so basically the mute function requires the window handle in order to work. But when I try to get the window handle from the new thread it throws the error:
Cross-thread operation not valid: Control 'Form1' accessed from a
thread other than the thread it was created on.
So how do I get around this? I have read other answers on here saying you need to use Invoke or Delegate but I'm not sure how those work or where to use them. I tried to follow one of the answers but I got even more errors.
A:
In this case, write invoke operation inside of method. Then you can access both from control's thread and other threads.
delegate IntPtr GetWindowHandleDelegate();
private IntPtr GetWindowHandle() {
if (this.InvokeRequired) {
return (IntPtr)this.Invoke((GetWindowHandleDelegate)delegate() {
return GetWindowHandle();
});
}
return this.Handle;
}
or, if you want to avoid delegate hell, you could write in more few code with built-in delegate and lambda.
private IntPtr GetWindowHandle() {
if (this.InvokeRequired)
return (IntPtr)this.Invoke((Func<IntPtr>)(GetWindowHandle));
return this.Handle;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Modifying the conditional build expression in RoboHelp using Extendscript
I'm trying to automate a process for our documentation team. They have a pretty big batch of framemaker files across several books and use RoboHelp to generate EclipseHelp for two different versions of our project.
Each framemaker file has the appropriate tags set to indicate which version a particular piece of documentation applies to. Currently the writers modify the conditional build expression to specify the correct set of tags and run File->Generate->EclipseHelp each time. I can run the generation process just fine, but I can't figure out how to change which tags it's using.
I've read through RoboHelp's scripting guide and the only references I can find to Conditional Build Tags is the ability to create and delete them. I can't find any references to Conditional Build Expressions. Does anyone know any way to modify it from a script? Alternatively, if someone can suggest a different way of organizing RoboHelp/Framemaker that is more conducive, I'm all ears, though I have basically zero familiarity with either.
A:
I'm going to answer with what I found - even though it's only a partial answer - just in case it can help someone, or possibly give someone enough to figure out a more proper answer.
Basically I found that each Single Source Layout has a corresponding *.ssl file. If your layout is called OnlineHelp, it will be (in my experience) OnlineHelp.ssl and will be in the same directory as your .xpj file. The ssl file is just a bunch of xml and has some number of sections. One of the sections will have the same name as the content category where you would go in the UI to change the Conditional Build Expression. In that section is an element named "BuildExpression". Set that to whatever you need and reopen your RoboHelp project. It's a bit of a hack, but I set up a groovy script to do that before running my ExtendScript and it gets the job done.
| {
"pile_set_name": "StackExchange"
} |
Q:
How can I increment a number at the end of a string in bash?
Basically i need to create a function where an argument is passed, and i need to update the number so for example the argument would be
version_2 and after the function it would change it to version_3
just increments by one
in java I would just create a new string, and grab the last character update by one and append but not sure how to do it in bash.
updateVersion() {
version=$1
}
the prefix can be anything for example it can be dog12 or dog_12 and always has one number to update.
after the update it would be dog13 or dog_13 respectively.
A:
updateVersion()
{
[[ $1 =~ ([^0-9]*)([0-9]+) ]] || { echo 'invalid input'; exit; }
echo "${BASH_REMATCH[1]}$(( ${BASH_REMATCH[2]} + 1 ))"
}
# Usage
updateVersion version_11 # output: version_12
updateVersion version11 # output: version12
updateVersion something_else123 # output: something_else124
updateVersion "with spaces 99" # output: with spaces 100
# Putting it in a variable
v2="$(updateVersion version2)"
echo "$v2" # output: version3
| {
"pile_set_name": "StackExchange"
} |
Q:
Check if JQuery object exists in DOM
I have a function which expect from parameter JQuery object. I need to find if JQuery object exists in DOM or not (in $('<div></div>') case).
I check for duplicates and found several answers (link1, link2, link3). Can some expert shine some light witch is the best (fastest) way to do it.
Options are:
$.contains //not working
$a.find
$a.parent()
$a.closes()
document.contains()
$a[0].isConnected
Snippet:
var a = $("#test"); //length 1
var b = $('<div></div>'); //length 1
console.log("contains: ", $.contains(document, a), $.contains(document, b)); //false, false
console.log("find: ", !!$(document).find(a).length, !!$(document).find(b).length); // true, false
console.log("parent: ", !!a.parent().length, !!b.parent().length); // true, false
console.log("closest: ", !!a.closest('body').length, !!b.closest('body').length); //true, false
console.log("document.contains: ", document.contains(a[0]), document.contains(b[0])); //true, false
console.log("isConnected: ", a[0].isConnected, b[0].isConnected); //true, false
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="test"></div>
</body>
</html>
Thank you.
A:
If performance is a really big concern for you, native methods are generally the way to go.
document.contains($myJQueryEl[0])
Outperforms the next fastest jQuery operation, $elem.closest('body'), by around 4 times according to this answer and its comment.
If you're really looking for performance for non-document elements, however, Shadow DOM is definitely your best option.
| {
"pile_set_name": "StackExchange"
} |
Q:
store binary of decimal in char array
I want to store binary equivalent of decimal number in char array by applying below code, but the problem is I am not able to hold the last bit of the decimal number. I am getting garbage values.
int k,j;
char c[40];
j=32;
scanf("%d",&k);
while(k)
{
k=k>>1;
c[j]=k|1;
j--;
}
puts("number is");
puts(c);
A:
Besides the problems noted by @SouravGhosh, you need to
(5) convert from the digits 0/1 to the character values for '0' and '1' by adding in the value of the character '0' [actually Sourav noted that too], and
(6) pick off the low-order bit before shifting k right by 1 bit.
Here's a working version:
char c[40];
int j=39;
c[j--]='\0';
while(k)
{
c[j]=(k&1)+'0';
j--;
k=k>>1;
}
puts("number is ");
puts(&c[j+1]);
| {
"pile_set_name": "StackExchange"
} |
Q:
Assigning base class object to derived class object
class Base{};
class Derived: public Base{};
int main()
{
Base B;
Derived D;
Base B1 = D;//OK
Derived D1 = B;//error: conversion from ‘Base’ to non-scalar
//type ‘Derived’ requested
return 1;
}
I know derived class has a is-a relationship with base class.
What stops the Derived D1 having values from B and remaining member variables(if any) with some garbage value?
Or
What does the error message
conversion from ‘Base’ to non-scalar type ‘Derived’ requested Derived D1 = B;
say? What is a scalar type?
A:
The statement
Derived D1 = B;
is an initialization, not an assignment (even if it looks like an assignment).
It attempts to use the Derived copy constructor, but that copy constructor takes an argument Derived const&. And the B instance can't be automatically converted down to a full Derived.
If you really want a slice assignment – assigning only to the Base slice of D1 – then you can explicitly use the Base::operator=:
Derived D1;
D1.Base::operator=( B );
Another way to express that:
Derived D1;
static_cast<Base&>( D1 ) = B;
But it smells bad. ;-)
Re
” What is a scalar type?
That's the same word as in “scale”. A scalar type provides a single magnitude value, so that values of the type can be compared with == (and ideally also <). However, in C++ pointers and even member pointers are regarded as scalar types:
C++11 §3.9/9 [basic.types]:
” Arithmetic types (3.9.1), enumeration types, pointer types, pointer to member types (3.9.2), std::nullptr_t, and cv-qualified versions of these types (3.9.3) are collectively called scalar types.
| {
"pile_set_name": "StackExchange"
} |
Q:
get all second highest values from a mysql table
I have a table with two fields as follows,
name score
xyz 300
pqr 200
abc 300
mno 100
erp 200
yut 200
How can I retrieve all second highest score from above table using MySQL query. Tried as follows,
SELECT name, MAX( `score` )
FROM score
WHERE score < (
SELECT MAX( score )
FROM score )
but it returns single value.
Expected result ,
name score
pqr 200
erp 200
yut 200
Any help please
A:
You can use:
SELECT
`name`,
`score`
FROM
`score`
WHERE
`score`=(SELECT DISTINCT `score` FROM `score` ORDER BY `score` DESC LIMIT 1,1)
Tip: naming table and it's column with same names will cause troubles in complicated queries (for you, not for DBMS)
| {
"pile_set_name": "StackExchange"
} |
Q:
Having trouble redirecting URLs with .htaccess
I have a link that looks like this:
http://www.example.com/football/nfl
which I want to redirect to this:
http://www.example.com/nfl-lines/
I tried this:
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^http://www.example.com/football/nfl.*$ http://www.example.com/nfl-lines/ [R=301,L]
Doesn't work..
and in a cupple of minuites I will change it to:
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^/football/nfl.*$ http://www.example.com/nfl-lines/ [R=301,L]
because I think it's the right way to write this. And ofcourse I will update here if it works.
Is this the right way to do this?
A:
Try this
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^/football/nfl$ nfl-lines [R=301,L]
| {
"pile_set_name": "StackExchange"
} |
Q:
javascript keydown combination activates with one key after first use
So, I've got a Keydown combination working to move between divs in a section of my form, but after using the combination the first time, I can only press the ALT key (Keycode 18) and it runs both if statements in the function, and therefore is calling my other function twice.
It should be checking for the second keydown event before entering the if, or at least that's what I believed.
Is there some Clear command for the keydown I need to do, or a way to reset the listening of the keydown event?
var keys = [];
document.onkeydown = function(evt){
var key = evt.keyCode;
keys[key] = true;
if(keys[18] && keys[78]){
NewFocus('#Notes');
console.log("Notes");
}
if(keys[18] && keys[67]){
NewFocus('#Callers');
console.log("Callers");
}
return false;
}
function NewFocus(newNav)
{
$('.navActive').hide().removeClass('navActive');
console.log("made it to New Focus event.");
var id = $(newNav);
console.log("This is the id " + $(id));
$(id).show().addClass('navActive');
return false;;
}
BTW, I'm running this in Safari and Chrome, and you can see what happens just watching the console.
I must be missing something, but don't know what.
A:
You need to listen for onkeyup and use delete keys[key] to clear the state of that key.
A:
You need to clear the keys array when the key is released:
document.onkeyup = function (evt) {
var key = evt.keyCode;
keys[key] = false;
};
| {
"pile_set_name": "StackExchange"
} |
Q:
What are the software technologies behind real time web apps?
What are some of the software technologies behind "real-time" web apps, like Twitter, Trello, or even Gmail? I know there's a webserver and probably a database on the backend, but what are the software pieces that make for that rich web interaction that I'm seeing more of today?
A:
Comet plays an important role in these applications.
Comet is a web application model in which a long-held HTTP request allows a web server to push data to a browser, without the browser explicitly requesting it.
http://en.wikipedia.org/wiki/Comet_%28programming%29
JavaScript is the glue between the comet servers and the browsers. Server software like Node.js are used to implement these comet servers that will have to handle many long-held connections.
Besides comet, these applications also need a good backend. The solutions may be very specific to the problem.
Twitter, for example, has to stream tweets to all your followers for each of your tweets. Facebook has to run machine learning algorithms to select which stories to stream on your News Feed.
Although different, these applications have many things in common: heavy use of cache, data denormalization, asynchronous jobs, are highly distributed.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does \listfiles work on Overleaf?
I don't have my notebook available for some days, hence I was trying to answer to a TeX.SE question using Overleaf.
I've realized, unfortunately, that Overleaf hasn't the most recent release of the packages (for example, biblatex).
I would like to see the versions used, adding \listfiles at the top of my code but it doesn't work.
\listfiles
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[british]{babel}
\begin{document}
\just to create an error and get the log on Overleaf
\end{document}
A:
This is quite a pain, but if you download a ZIP-file of the project, then you can choose Input and Output files. The .log file will be included in the ZIP when using that option.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to share classes between DLLs
I have an unmanaged Win32 C++ application that uses multiple C++ DLLs. The DLLs each need to use class Foo - definition and implementation.
Where do Foo.h and Foo.cpp live so that the DLLs link and don't end up duplicating code in memory?
Is this a reasonable thing to do?
[Edit]
There is a lot of good info in all the answers and comments below - not just the one I've marked as the answer. Thanks for everyone's input.
A:
Providing functionality in the form of classes via a DLL is itself fine. You need to be careful that you seperate the interrface from the implementation, however. How careful depends on how your DLL will be used. For toy projects or utilities that remain internal, you may not need to even think about it. For DLLs that will be used by multiple clients under who-knows-which compiler, you need to be very careful.
Consider:
class MyGizmo
{
public:
std::string get_name() const;
private:
std::string name_;
};
If MyGizmo is going to be used by 3rd parties, this class will cause you no end of headaches. Obviously, the private member variables are a problem, but the return type for get_name() is just as much of a problem. The reason is because std::string's implementation details are part of it's definition. The Standard dictates a minimum functionality set for std::string, but compiler writers are free to implement that however they choose. One might have a function named realloc() to handle the internal reallocation, while another may have a function named buy_node() or something. Same is true with data members. One implementation may use 3 size_t's and a char*, while another might use std::vector. The point is your compiler might think std::string is n bytes and has such-and-so members, while another compiler (or even another patch level of the same compiler) might think it looks totally different.
One solution to this is to use interfaces. In your DLL's public header, you declare an abstract class representing the useful facilities your DLL provides, and a means to create the class, such as:
DLL.H :
class MyGizmo
{
public:
static MyGizmo* Create();
virtual void get_name(char* buffer_alloc_by_caller, size_t size_of_buffer) const = 0;
virtual ~MyGizmo();
private:
MyGizmo(); // nobody can create this except myself
};
...and then in your DLL's internals, you define a class that actually implements MyGizmo:
mygizmo.cpp :
class MyConcreteGizmo : public MyGizmo
{
public:
void get_name(char* buf, size_t sz) const { /*...*/ }
~MyGizmo() { /*...*/ }
private:
std::string name_;
};
MyGizmo* MyGizmo::Create()
{
return new MyConcreteGizmo;
}
This might seem like a pain and, well, it is. If your DLL is going to be only used internally by only one compiler, there may be no reason to go to the trouble. But if your DLL is going to be used my multiple compilers internally, or by external clients, doing this saves major headaches down the road.
| {
"pile_set_name": "StackExchange"
} |
Q:
Concatenating props within Inline CSS (React)
I'm currently trying to use props within my inline CSS. I'm curious to know why can't I concatenate this.props.color when using linear-gradient on the background-image property. Is there possibly another way I could go about achieving this or am I missing something?
render() {
let background = {
width: "100%",
height: "100%",
position: "fixed",
left: 0,
top: 0,
backgroundImage: "linear-gradient(to right," + this.props.color + "0%, #0072ff 100%)"
};
return (
<div style={background}></div>
);
}
Component in use:
<Background color='red'/>
A:
You need a space before 0%
Do like the following:
render() {
let background = {
width: "100%",
height: "100%",
position: "fixed",
left: 0,
top: 0,
backgroundImage: `linear-gradient(to right,${this.props.color} 0%, #0072ff 100%)`
};
return (
<div style={background}></div>
);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How does RabbitMQ decide when it is time to delete a message?
I am trying to understand the logic for message deletion in RabbitMQ.
My goal is to make messages persist even if there is not a client connected to read them, so that when clients reconnect the messages are waiting for them. I can use durable, lazy queues so that messages are persisted to disk, and I can use HA replication to ensure that multiple nodes get a copy of all queued messages.
I want to have messages go to two or more queues, using topic or header routing, and have one or more clients reading each queue.
I have two queues, A and B, fed by a header exchange. Queue A gets all messages. Queue B gets only messages with the "archive" header. Queue A has 3 consumers reading. Queue B has 1 consumer. If the consumer of B dies, but the consumers of A continue acknowledging messages, will RabbitMQ delete the messages or continue to store them? Queue B will not have anyone consuming it until B is restarted, and I want the messages to remain available for later consumption.
I have read a bunch of documentation so far, but still have not found a clear answer to this.
A:
RabbitMQ will decide when to delete the messages upon acknowledgement.
Let's say you have a message sender:
var factory = new ConnectionFactory() { HostName = "localhost", Port = 5672, UserName = "guest", Password = "guest" };
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "hello",
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
string message = "Hello World!";
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "",
routingKey: "hello",
basicProperties: null,
body: body);
Console.WriteLine(" [x] Sent {0}", message);
}
This will create a durable queue "hello" and send the message "Hello World!" to it. This is what the queue would look like after sending one message to it.
Now let's set up two consumers, one that acknowledges the message was received and one that doesn't.
channel.BasicConsume(queue: "hello",
autoAck: false,
consumer: consumer);
and
channel.BasicConsume(queue: "hello",
autoAck: true,
consumer: consumer);
If you only run the first consumer, the message will never be deleted from the queue, because the consumer states that the messages will only disappear from the queue if the client manually acknowledges them: https://www.rabbitmq.com/confirms.html
The second consumer however will tell the queue that it can safely delete all the messages it received, automatically/immediately.
If you don't want to automatically delete these messages, you must disable autoAck and do some manual acknowledgement using the documentation:
http://codingvision.net/tips-and-tricks/c-send-data-between-processes-w-memory-mapped-file (Scroll down to "Manual Acknowledgement").
channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
A:
The simple answer is that messages consumed from one queue have no bearing on messages in another. Once you publish a message, the broker distributes copies to as many queues as appropriate - but they are true copies of the message and are absolutely unrelated from that point forward so far as the broker is concerned.
Messages enqueued into a durable queue remain until they are pulled by a consumer on the queue, and optionally acknowledged.
Note that there are specific queue-level and message-level TTL settings that could affect this. For example, if the queue has a TTL, and the consumer does not reconnect before it expires, the queue will evaporate along with all its messages. Similarly, if a message has been enqueued with a specific TTL (which can also be set as a default for all messages on a particular queue), then once that TTL passes, the message will not be delivered to the consumer.
Secondary Note In the case where a message expires on the queue due to TTL, it will actually remain on the queue until it is next up to be delivered.
| {
"pile_set_name": "StackExchange"
} |
Q:
After killing on VATS mode, I'm waiting for the kill cam to end, but my enemies aren't!
The situation is this:
I'm attacked by a bunch of enemies, so I go in VATS mode and plan a sequence of shots for a few ones. When I kill one, by the time I target the next one, I'm in slow motion kill cam. But, my enemies are still moving so they can attack me when I'm waiting for the slow motion kill cam to end.
I don't know if there is a setting to avoid this. So my question is:
Is there a way to avoid my character waiting?
A:
If you're in VATS mode, both you and the enemies should be in slow motion. If not, then there's a glitch occurring.
But, it sounds like you're just having a problem waiting for the kill cam to end so you can kill the next thing.
This is fixable. If you tap the VATS button during the kill cam, it will exit and you can continue doing things. The cancel button (B on Xbox) will also exit VATS. I often skip out of that kill cam and line up the next shot before the bullet gets there. This is because, even if no glitch is occurring, the enemies keep moving in slow motion while you sit there and do nothing watching your bullet.
To minimize the time spent out of VATS, tap the button to exit, then immediately hold the button to re-enter it. If you keep tapping the button, you're liable to enter and immediately re-exit, which can be bad news. Remember that you have 90% damage reduction while in VATS.
One specific time I do this on every playthrough is when fighting Kellog. I line up a crit with the fat man from the armory, fire it, and then cancel out and set up VATS shots on the synths before the mini-nuke hits Kellog.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it helpful to stay single if I am not going to become a monk?
In most Buddhist traditions, monks are expected to follow an austere life without being married or involved with another person, but what about lay people who are not going to become monks?
Personally, I've reached what most people consider mid-life and I'm getting too old for any monastery to accept me, but I'm sure this question applies to lay people both older and younger.
I am under the impression, monks are required to be single because of the attachment and desire that arises when being involved. However, a good number of monks do not live among lay people which I imagine would make it easier. It seems like lay people would benefit though, and when their time on Earth has expired also make it easier to let go.
However, I don't have a teacher nor do I have access to one so I wanted to reach out to the community to see what their impressions were. My guess is that it is helpful but a personal choice that differs from individual to individual. I mean 'helpful' in the sense of being closer to Nirvana or Enlightenment.
A:
What matters is what you do when you are single. If being single means using prostitutes to satisfy one's sensual desires, it could lead one further away from the path as compared to a person who restrains himself to one woman and practices loyalty, kindness, doing good deeds together etc.
But if being single means being celibate and using one's free time for meditation etc., one would generally have a higher chance of progressing in the path as compared to the average family man.
In the time of the Buddha, there were monks who went to forest for seclusion and ended up having sex with monkeys. So what really matters is what you do when you are single.
A:
As you've said, it all varies from individual to individual. The bottom line is one should not do what other people expects one to do. Instead, do whatever is best for oneself in terms of peace, happiness, and most important, suitable and favorable conditions to the learning, contemplation, and practice of the Buddha Dhamma. Please see DN 29, where the Buddha taught about the 10 kinds of disciples that make up His spiritual community. Out of those 10, 4 are from lay folks like us: celibate laymen, householder laymen, celibate laywomen, and householder laywomen. Give it a careful read and it could be a useful guide to help with your inquiry. Good luck..
| {
"pile_set_name": "StackExchange"
} |
Q:
Prove the congruence $ \sum_{r=1}^{p-1}{(r|p) * r } \equiv 0 \pmod p.$
Prove that if $p$ is prime and $p\equiv 1 \pmod4$, then $$ \sum_{r=1}^{p-1}{(r|p) * r } \equiv 0 \pmod p.$$
( $(r|p)$ is a Legendre Symbol )
I know that $\sum_{1 \le r \le p}{(\frac{r}{p})} = 0$, but I don't know what to do with the multiplication by r.
A:
Denote your sum by $S$. Note: you don't need a congruence on $p$, but you do need $p>3$.
Proof I:
Let $s\neq 1$ be a fixed non-zero square $\pmod p$ (this requires that $p>3$.)
As $r$ spans the non-zero residues, so does $sr$. Thus (working $\pmod p$): $$S=\sum_{r=1}^{p-1}\left(\frac {sr}p\right)sr=s\sum_{r=1}^{p-1}\left(\frac {r}p\right)r=s\times S\implies S=0$$
Proof II:
Let $g$ be a primitive root $\pmod p$. Assume $p>3$ so $g\neq -1$. Then $$S=\sum_{i=1}^{p-1} (-1)^ig^i=-g\times \frac {(-g)^{p-1}-1}{(-g)-1}$$ That last sum is $0\pmod p$ by Fermat's little Theorem.
A:
$\newcommand{\jaco}[2]{\left(\frac{#1}{#2}\right)}$Since $-1$ is a quadratic residue modulo $p$ you have $\jaco{-1}p=1$ and $\jaco ap = \jaco{-a}p$. This gives you
$$\jaco ap =\jaco{p-a}p$$
and $$a\jaco ap + (p-a)\jaco{p-a}p = p \equiv 0 \pmod p.$$
So you can see that the numbers $1,2,\dots,p-1$ can be divided into $\frac{p-1}2$ pairs, such that the contribution of each pair to the sum is a multiple of $p$.
In fact, in this way we can show that
\begin{align*}
\sum\limits_{\substack{a=1\\(a|p)=1}}^{p-1} a &= \frac{p(p-1)}4\\
\sum\limits_{\substack{a=1\\(a|p)=-1}}^{p-1} a &= \frac{p(p-1)}4
\end{align*}
and
\begin{align*}
\sum\limits_{a=1}^{p-1} a\jaco ap
&= \sum\limits_{\substack{a=1\\(a|p)=1}}^{p-1} a - \sum\limits_{\substack{a=1\\(a|p)=-1}}^{p-1} a \\
&= \frac{p(p-1)}4 - \frac{p(p-1)}4 = 0
\end{align*}
A:
Here is another proof. Note that, for an odd prime $p$,
\begin{align*}
\sum_{r=1}^{p-1} \bigg(\frac rp\bigg) r &= \sum_{r=1}^{p-1} \bigg( \bigg(\frac rp\bigg) + 1 \bigg) r - \sum_{r=1}^{p-1} r \\
&= \bigg( \sum_{r=1}^{p-1} \#\{ m \text{ (mod }p)\colon m^2\equiv r\text{ (mod }p)\} \cdot r \bigg) - \frac{p(p-1)}2 \\
&\equiv \bigg( \sum_{m=1}^{p-1} m^2 \bigg) - 0 \pmod p \\
&= \frac{(p-1)p(2p-1)}6 .
\end{align*}
When $p>3$, this last expression is $0$ (mod $p$).
This proof highlights the often-overlooked method of converting a sum involving Legendre symbols into a sum taken directly over the squares (mod $p$). The second equality is easy but is worth remembering; the third step might take some thoughtful reflection, but I think that time is well worth it.
| {
"pile_set_name": "StackExchange"
} |
Q:
What are some good questions for this trick, if $\frac{a}{b}=\frac{c}{d}=\frac{e}{f}=\dots=\alpha$ then $\alpha=\frac{a+c+e+...}{b+d+f+...}$?
I need some good algebra questions that are applications of this trick, often in a non obvious and elegant way: $$\text{If } \frac{a}{b}=\frac{c}{d}=\frac{e}{f}=\dots=\alpha \text{ then } \alpha=\frac{a+c+e+...}{b+d+f+...}$$
A:
If $\displaystyle\frac a{b+c}=\frac b{c+a}=\frac c{a+b};$ prove that each ratio $\displaystyle=\frac12$ if $\displaystyle a+b+c\ne0$
If $\displaystyle\frac{a-b}{x^2}=\frac{b-c}{y^2}=\frac{c-a}{z^2}$ prove that $\displaystyle a=b=c$
If $\displaystyle\frac{a-b}{a^2+ab+b^2}=\frac{b-c}{b^2+bc+c^2}=\frac{c-a}{c^2+ca+a^2}$ prove that $\displaystyle a=b=c$ (for a special condition)
If $\displaystyle\frac{a+b}{a^2+ab+b^2}=\frac{b+c}{b^2+bc+c^2}$ and $a\ne b\ne c$ prove that each ratio $=\displaystyle\frac{c+a}{c^2+ca+a^2}$
| {
"pile_set_name": "StackExchange"
} |
Q:
Questions about database performances and more
For school I had to create a AJAX/PHP based chatbox where someone can just join in by entering their username and presses click.
I got it all working but I got some questions whether the way I did this is the right way to do it.
One question by example is that I am using a setInterval from javascript to fetch the latest 5 records out of the database every second. But what if someone changes this interval on the website itself? And makes it so it queries the database every second? I was thinking of storing the last executed query date and check if it actually is the 1 second that I had set. But where would I store this? I wouldn't want to store it in my database most likely as I will have to query the database then also.
Another question is, do professional chat boxes actually use a interval to check for new records in the database in an x amount of time? If not, how do they go about it?
ATM I am at a point that I don't exactly know how I should go about this, is there an experienced PHP developer out there that could give answers on any of these?
A:
Request the server once every 5 second (with or without database query) is expensive and does not scale. Instead of having client requesting every fixed interval, let the server notify the client whenever there is new message. To do so, you need a more persistence connection. There are two popular approaches:
Ajax Long Polling: usually, web server will close its connection once it has successfully serve the content. The idea behind long polling is to keep the connection open for long period of time and serve content by chucked. Once there is new message, it feed to client. Once the connection timeout, it re-open a new connection.
WebSocket: WebSocket allows web browser and server to have persistence connection via its WebSocket protocol (similiar to HTTP protocol). Some browsers does not support this feature yet.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a 64-bit Ruby?
It seems like people are compiling MRI Ruby (1.8.7) for 64-bit platforms. I've been searching and reading for a while now without really getting the answers I want. What I want to know is if any of you guys actually used more than 4GB of memory in Ruby? Is Ruby truly 64-bits if you compile it that way?
I've found comments in the source code indicating that it's not tested on 64-bits. For instance it says "BigDecimal has not yet been compiled and tested on 64 bit integer system." in the comments for BigDecimal.
It would also be interesting to know how the other implementations of Ruby do in 64-bits.
A:
MRI (both the 1.8.x and 1.9.x line) can be compiled as 64 bits.
For example, Snow Leopard comes bundled with 1.8.7 compiled as 64 bits. This can be seen in the activity monitor, or from irb by asking, for example 42.size. You'll get 8 (bytes) if it is compiled in 64 bits, 4 (bytes) otherwise.
Ruby will be able to access over 4G of ram. For example:
$ irb
>> n = (1 << 29) + 8
=> 536870920
>> x = Array.new(n, 42); x.size
=> 536870921 # one greater because it holds elements from 0 to n inclusive
Getting the last line will take a while if you don't have more than 4 G or ram because the OS will swap a lot, but even on my machine with 4 GB it works. Virtual ram size for the process was 4.02 G.
I updated the comment in the bigdecimal html file which was outdated (from march 2003...)
| {
"pile_set_name": "StackExchange"
} |
Q:
Upgrade to Visual Studio 2015 and now can't hit break points in debugging
I have a multi-project solution that I was building in Visual Studio 2013 and it was working fine but now that I have upgraded to Visual Studio 2015 I can no longer hit break points in debug mode for any project exect the main project selected as the Startup project in the Project Properties page. I used to be able to click on the other projects and just choose Debug -> Start New Instance. I am getting the error The breakpoint will not currently be hit. No symbols have been loaded for this document. I have tried a lot of things found on Google including:
Clean/Rebuild
Delete the OBJ and BIN folder form the projects
Did VS repair
Rebooted
Uninstalled/Reinstalled
Confirmed Define DEBUG constraint is enabled for Properties -> Build
Confirmed Optimize Code is unchecked for Properties -> Build
Confirmed Properties -> Build => Platform target was set to Any CPU for all projects
Tried running VS using "Run as Administrator"
Deleted all the files in /AppData/Local/Temp/Temporary ASP.Net Files/
Made sure Debug -> Attack to Process -> Select had "Automatically determine the type of code to debug" was selected
Made sure the Properties -> Web -> Debuggerts had ASP.Net checked (my properties has ASP.NEt and Enable Edit and Continue Checked, Natvie Code SQL Server and Silverlight unchecked)
Confirmed Target framework in Properties -> Application was set to the same version (4.6) as in the Web.Config/App.Config files.
So what am I missing here? Why can I no longer debug the other projects?
A:
I had a similar problem, when I created a new build configuration. After hunting around settings in VS2015, I noticed that there were no *.pdb files in my build output. Obviously, debugging would not work if there were *.pdb files.
The fix for me was to go into every project's properties -> 'build' page -> click the "advanced" button at the bottom of the page -> In the dialog's 'Output' section, I set "debug info" to equal "full".
Basically, I created a new solution and project and copied all the build properties into the solution that the debugger was not stopping at break points anymore. In addition to the setting above, I also changed the following setting to match the default debug settings:
I set on the same advanced page "Internal Compiler Error Reporting" to "prompt"
In the main 'build' page, I checked in the 'general' section "Define DEBUG constant" and "Define TRACE constant"
A:
I solved this problem when checked Options->Debugging->General->Suppress jit optimization on module load. Before I did that I have also unchecked Tools->Options "Projects and Solutions" "Build and Run" "Only build startup projects and dependencies on run". Don't know if that has any reason why it works after suppress jit is unchecked.
A:
My situation was that I have enabled "Optimize code" in the project properties.
| {
"pile_set_name": "StackExchange"
} |
Q:
Show form fields conditionally based on user input
In my Laravel app, I have a select form field that lists a set of countries:
<select id="js-countrySiteSelect">
<option>Select Your Country</option>
<option>United States</option>
<option>Australia</option>
<option>Germany</option>
<option>Switzerland</option>
<option>United Kingdom</option>
</select>
Beneath that, I also have a series of select form fields. Each select shows a series of locations within that country.
{!! Form::select('site_id', $australia, null, ['class' => 'js-siteSelect select-australia', null => 'Select a user...']) !!}
{!! Form::select('site_id', $germany, null, ['class' => 'js-siteSelect select-germany']) !!}
{!! Form::select('site_id', $switzerland, null, ['class' => 'js-siteSelect select-switzerland']) !!}
{!! Form::select('site_id', $us, null, ['class' => 'js-siteSelect select-us']) !!}
{!! Form::select('site_id', $uk, null, ['class' => 'js-siteSelect select-uk']) !!}
Based on which country the user selects, I want to show or hide the corresponding form fields:
$('#js-countrySiteSelect').change(function(e) {
e.preventDefault();
$('.js-siteSelectLabel').addClass('js-show');
if ( $(this).val() == 'United States' ) {
$('.js-siteSelect').removeClass('js-show');
$('.select-us').addClass('js-show');
} else if ( $(this).val() == 'Australia' ) {
$('.js-siteSelect').removeClass('js-show');
$('.select-australia').addClass('js-show');
} else if ( $(this).val() == 'Germany' ) {
$('.js-siteSelect').removeClass('js-show');
$('.select-germany').addClass('js-show');
} else if ( $(this).val() == 'Switzerland' ) {
$('.js-siteSelect').removeClass('js-show');
$('.select-switzerland').addClass('js-show');
} else if ( $(this).val() == 'United Kingdom' ) {
$('.js-siteSelect').removeClass('js-show');
$('.select-uk').addClass('js-show');
}
});
However, since each location dropdown is still loaded into the DOM, the form always submits the first option of the last select—in this example, the UK dropdown.
How can I refactor this so that only the visible select element submits data?
A:
this is because you just hide the not used selects, if you mark them as disabled, then the elements wont be send to the server.
Try in place to set
$select.hide()
use
$select.prop('disabled', true)
| {
"pile_set_name": "StackExchange"
} |
Q:
Remove Windows Live
Is there anyway to remove windows live and all the other windows products that I don't use from my computer without making vista go crazy?
A:
Windows Live is just a program, just as any other program. You can remove it in the software configuration screen.
And what other windows products do you mean?
A:
I'm assuming you mean the software such as Photo Gallery, Movie Maker, Messenger, Mail, etc?
Start > Control Panel > Program and Features
On the side bar is an option to "Turn Windows features on or off"
Here you can disable Gadgets and Games, and under Media Features are options for Media Centre, DVD maker and Media player.
Photo Gallery, Movie Maker, Messenger, Mail may be listed here in Vista. I'm on Windows 7 so I can't be sure. (These programs are not included in Win7)
| {
"pile_set_name": "StackExchange"
} |
Q:
A clickable using an tag - no JS to be used. Is it legal HTML?
Ok, I have read a lot of times that inline elements should never contain block elements. I agree, there are problems with that and it can get messy after. But I find it the only solution to do the following:
I'm trying to create an HTML template that imitates the Metro UI "tiles" (yeah, the one that is in windows 8). The tiles are made using <li> elements. Now, the problem is that I want the tiles (the whole <li> tag) clickable, but proper HTML tells me you can't surround a block element with an inline element. Besides, you can't surround an <li> with an <a>. Is there any method of doing this without going against the rules of html?
A:
A legal and clean way of accomplishing this is to use a style of inline-block for the A tags and let them fill the complete LI.
LI > A
{
display: inline-block;
}
OR
LI > A
{
display: block;
}
This will work in IE7+, and all recent versions of Firefox, Chrome, Safari, Opera, etc.
Note that in the current draft of HTML 5, it is legal to put a greater variety of elements inside an anchor tag than was previously allowed (see "permitted content" and examples): http://dev.w3.org/html5/markup/a.html
Additional article: http://html5doctor.com/block-level-links-in-html-5/
| {
"pile_set_name": "StackExchange"
} |
Q:
Algorithm for auto-indenting brackets in code
im working on a code-editor (WinForms) and i want to know how to do function of { and } specifically the auto-indention using brackets (open and close) like in actual code editor .
---|> { and }
like this 1:
Editor was a richtextbox named rtb.
A:
ok my solution is buggy but it's enough that you get the idea of how it works
my result:
{
{
{
}
}
}
and here my Code
public partial class Form1 : Form
{
private bool FLAG_Selftimer = false;
private bool FLAG_KeyPressed = false;
private int pos = 0;
public Form1()
{
InitializeComponent();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
var rtb = sender as RichTextBox;
var point = rtb.SelectionStart;
if (!FLAG_Selftimer)
{
rtb.Text = ReGenerateRTBText(rtb.Text);
FLAG_KeyPressed = false;
}
else
{
point ++;
FLAG_Selftimer = false;
}
rtb.SelectionStart = point;
}
private string ReGenerateRTBText(string Text)
{
string[] text = Regex.Split(Text,"\n");
int lvl = 0;
string newString = "";
foreach (string line in text)
{
line.TrimStart(' ');
newString += indentation(lvl) + line.TrimStart(' ') + "\n";
if (line.Contains("{"))
lvl++;
if (line.Contains("}"))
lvl--;
}
FLAG_Selftimer = true;
return (!FLAG_KeyPressed) ? newString : newString.TrimEnd('\n');
}
private string indentation(int IndentLevel)
{
string space = "";
if(IndentLevel>0)
for (int lvl = 0; lvl < IndentLevel; lvl++)
{
space += " ".PadLeft(8);
}
return space;
}
private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
FLAG_KeyPressed = true;
}
}
i hope this will help you
A:
Please read the following texts before reading and using codes:
I've not enough time for writing better codes. I have only tried to write a sample for you.
I have only written the codes in a simple way, not in OOP.
You can improve the codes with using Enums, Properties, Classes and other things of OOP.
You can improve the logic of the codes; and you can use Multi-Threading for achieve to better performance.
This sample isn't thorough. I has only implemented an Auto-Indention example for "semicolon (;)" character.
I should say some tips for using the codes:
rtbCodes is the name of the RichTextBox control on the form in the sample project.
frmCodeEditor is the name of the form in the sample project.
You can download the sample project from the following addresses:
4Shared -> Auto-Indention for Code Editor
SendSpace -> Auto-Indention for Code Editor
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class frmCodeEditor : Form
{
char[] chrTracingKeyChars = new char[] { ';', '}', '\n' };
char[] chrCheckingKeyChars = new char[] { '{', '(' };
Point ptCurrentCharPosition;
bool bolCheckCalling = false;
int intInitialCursorPosition = 0;
int intRemainingCharsOfInitialText = 0;
int intNextCharIndex = 0;
int intPrevCharIndex = 0;
public frmCodeEditor()
{
InitializeComponent();
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
AutoIndention(rtbCodes);
}
/// <summary>
/// Implements Auto-Indention.
/// </summary>
/// <param name="rtb">A RichTextBox control</param>
private void AutoIndention(RichTextBox rtb)
{
char chrLastChar = GetChar(rtb);
if (chrLastChar == chrTracingKeyChars[0])
{
intRemainingCharsOfInitialText = rtb.TextLength - rtb.SelectionStart;
intInitialCursorPosition = rtb.SelectionStart;
ImplementIndentionForSemicolon(rtb);
}
else if (chrLastChar == chrTracingKeyChars[1])
{
ImplementIndentionForRightCurlyBracket(rtb);
}
else if (chrLastChar == chrTracingKeyChars[2])
{
ImplementIndentionForNewLineCharacter(rtb);
}
}
/// <summary>
/// Specifies current char based on the cursor position.
/// </summary>
/// <param name="rtb">A RichTextBox control</param>
/// <returns>Returns a char.</returns>
private char GetChar(RichTextBox rtb)
{
return GetChar(rtb.SelectionStart, rtb);
}
/// <summary>
/// Specifies a char based on the specified index.
/// </summary>
/// <param name="intCharIndex">A char index</param>
/// <param name="rtb">A RichTextBox control</param>
/// <returns>Returns a char.</returns>
private char GetChar(int intCharIndex, RichTextBox rtb)
{
if (intCharIndex != rtb.TextLength)
{
ptCurrentCharPosition = rtb.GetPositionFromCharIndex(intCharIndex - 1);
}
else
{
ptCurrentCharPosition = rtb.GetPositionFromCharIndex(intCharIndex);
}
return rtb.GetCharFromPosition(ptCurrentCharPosition);
}
/// <summary>
/// Specifies current line number based on the cursor position.
/// </summary>
/// <param name="rtb">A RichTextBox control</param>
/// <returns>Returns the line number.</returns>
private int GetLineNumber(RichTextBox rtb)
{
return GetLineNumber(rtb.GetFirstCharIndexOfCurrentLine(), rtb);
}
/// <summary>
/// Specifies the line number based on the specified index.
/// </summary>
/// <param name="intCharIndex">A char index</param>
/// <param name="rtb">A RichTextBox control</param>
/// <returns>Returns the line number.</returns>
private int GetLineNumber(int intCharIndex, RichTextBox rtb)
{
return rtb.GetLineFromCharIndex(intCharIndex);
}
/// <summary>
/// Implements indention for semicolon ";" character.
/// </summary>
/// <param name="rtb">A RichTextBox control</param>
private void ImplementIndentionForSemicolon(RichTextBox rtb)
{
Dictionary<char, int> dicResult = IsExistCheckingKeyChars(rtb);
if (dicResult[chrCheckingKeyChars[0]] != -1)
{
int intIndentionLevel = CheckingIndentionLevel(dicResult[chrCheckingKeyChars[0]], rtb);
ImplementIndention(dicResult[chrCheckingKeyChars[0]], intIndentionLevel, rtb);
}
}
private void ImplementIndentionForRightCurlyBracket(RichTextBox rtb)
{
}
private void ImplementIndentionForNewLineCharacter(RichTextBox rtb)
{
}
/// <summary>
/// Checks current and previous lines for finding key-chars.
/// </summary>
/// <param name="rtb">A RichTextBox control</param>
/// <param name="bolSearchCurrentLine">The search state</param>
/// <returns>Returns first occurrences of key-chars before current char.</returns>
private Dictionary<char, int> IsExistCheckingKeyChars(RichTextBox rtb, bool bolSearchCurrentLine = false)
{
GetChar(rtb);
Dictionary<char, int> dicCheckingKeyCharsIndexes = new Dictionary<char, int>();
for (int intCntr = 0; intCntr < chrCheckingKeyChars.Length; intCntr++)
{
dicCheckingKeyCharsIndexes.Add(chrCheckingKeyChars[intCntr], 0);
}
for (int intCntr = 0; intCntr < chrCheckingKeyChars.Length; intCntr++)
{
int intFirstIndexForChecking = 0;
int intLastIndexForChecking = 0;
for (int intLineCounter = GetLineNumber(rtb); intLineCounter >= 0; intLineCounter--)
{
if (intLineCounter == GetLineNumber(rtb))
{
intLastIndexForChecking = rtb.GetCharIndexFromPosition(ptCurrentCharPosition);
}
else
{
intLastIndexForChecking = intFirstIndexForChecking - 1;
}
intFirstIndexForChecking = rtb.GetFirstCharIndexFromLine(intLineCounter);
try
{
dicCheckingKeyCharsIndexes[chrCheckingKeyChars[intCntr]] = rtb.Find(chrCheckingKeyChars[intCntr].ToString(), intFirstIndexForChecking,
rtb.GetCharIndexFromPosition(ptCurrentCharPosition), RichTextBoxFinds.NoHighlight | RichTextBoxFinds.None);
if (dicCheckingKeyCharsIndexes[chrCheckingKeyChars[intCntr]] != -1)
{
do
{
if (rtb.Find(chrCheckingKeyChars[intCntr].ToString(), intFirstIndexForChecking, rtb.GetCharIndexFromPosition(ptCurrentCharPosition),
RichTextBoxFinds.NoHighlight | RichTextBoxFinds.None) != -1)
{
dicCheckingKeyCharsIndexes[chrCheckingKeyChars[intCntr]] = rtb.Find(chrCheckingKeyChars[intCntr].ToString(), intFirstIndexForChecking,
rtb.GetCharIndexFromPosition(ptCurrentCharPosition), RichTextBoxFinds.NoHighlight | RichTextBoxFinds.None);
}
intFirstIndexForChecking++;
} while (intFirstIndexForChecking != rtb.GetCharIndexFromPosition(ptCurrentCharPosition));
break;
}
}
catch
{
dicCheckingKeyCharsIndexes[chrCheckingKeyChars[intCntr]] = -1;
break;
}
if (bolSearchCurrentLine)
{
break;
}
}
}
return dicCheckingKeyCharsIndexes;
}
/// <summary>
/// Checks a line for calculating its indention level.
/// </summary>
/// <param name="intCharIndex">A char index</param>
/// <param name="rtb">A RichTextBox control</param>
/// <returns>Returns indention level of the line.</returns>
private int CheckingIndentionLevel(int intCharIndex, RichTextBox rtb)
{
int intLineNumber = GetLineNumber(intCharIndex, rtb);
int intIndentionLevelNumber = 0;
intCharIndex = rtb.GetFirstCharIndexFromLine(intLineNumber);
char chrChar = GetChar(intCharIndex, rtb);
if (chrChar == '\n')
{
chrChar = GetChar(++intCharIndex, rtb);
}
if (chrChar != ' ')
{
return 0;
}
else
{
int intSpaceCntr = 0;
while(chrChar == ' ')
{
chrChar = GetChar(++intCharIndex, rtb);
if (chrChar == ' ')
{
intSpaceCntr++;
}
if (intSpaceCntr % 4 == 0 && intSpaceCntr != 0)
{
intIndentionLevelNumber++;
intSpaceCntr = 0;
}
}
if (intSpaceCntr % 4 != 0)
{
intIndentionLevelNumber++;
}
}
return intIndentionLevelNumber;
}
/// <summary>
/// Implements Indention to the codes
/// </summary>
/// <param name="intCharIndex">A char index</param>
/// <param name="intIndentionLevel">The number of indention level</param>
/// <param name="rtb">A RichTextBox control</param>
private void ImplementIndention(int intCharIndex, int intIndentionLevel, RichTextBox rtb)
{
intNextCharIndex = intCharIndex;
intPrevCharIndex = intCharIndex;
int intKeyCharsNumberInLine = 1;
int intCurrentLineNumber = GetLineNumber(rtb);
int intKeyCharLineNumber = GetLineNumber(intNextCharIndex, rtb);
string[] strLinesTexts;
Dictionary<char, int> dicResult;
do
{
rtb.SelectionStart = intPrevCharIndex;
dicResult = IsExistCheckingKeyChars(rtb);
if (dicResult[chrCheckingKeyChars[0]] != -1)
{
intKeyCharsNumberInLine++;
intPrevCharIndex = dicResult[chrCheckingKeyChars[0]];
}
} while (dicResult[chrCheckingKeyChars[0]] != -1);
if (!bolCheckCalling)
{
if (intCurrentLineNumber == intKeyCharLineNumber)
{
for (int intCntr = 1; intCntr <= intKeyCharsNumberInLine; intCntr++)
{
do
{
rtb.SelectionStart = intPrevCharIndex;
dicResult = IsExistCheckingKeyChars(rtb, true);
if (dicResult[chrCheckingKeyChars[0]] != -1)
{
intPrevCharIndex = dicResult[chrCheckingKeyChars[0]];
}
} while (dicResult[chrCheckingKeyChars[0]] != -1);
bolCheckCalling = true;
ImplementIndention(intPrevCharIndex, rtb);
}
return;
}
}
bolCheckCalling = false;
rtb.SelectionStart = intNextCharIndex;
rtb.SelectionLength = 1;
rtb.SelectedText = "\n" + rtb.SelectedText;
intCurrentLineNumber = GetLineNumber(rtb);
strLinesTexts = rtb.Lines;
strLinesTexts[intCurrentLineNumber] = strLinesTexts[intCurrentLineNumber].Trim();
for (int intIndentionCntr = 1; intIndentionCntr <= intIndentionLevel; intIndentionCntr++)
{
for (int intSpaceCntr = 1; intSpaceCntr <= 4; intSpaceCntr++)
{
strLinesTexts[intCurrentLineNumber] = ' ' + strLinesTexts[intCurrentLineNumber];
}
}
rtb.Lines = strLinesTexts;
rtb.SelectionStart = intNextCharIndex + ((intIndentionLevel * 4) + 1);
intNextCharIndex = rtb.SelectionStart;
rtb.SelectionLength = 1;
rtb.SelectedText = rtb.SelectedText + "\n";
intCurrentLineNumber = GetLineNumber(rtb);
strLinesTexts = rtb.Lines;
strLinesTexts[intCurrentLineNumber] = strLinesTexts[intCurrentLineNumber].Trim();
for (int intIndentionCntr = 1; intIndentionCntr <= intIndentionLevel + 1; intIndentionCntr++)
{
for (int intSpaceCntr = 1; intSpaceCntr <= 4; intSpaceCntr++)
{
strLinesTexts[intCurrentLineNumber] = ' ' + strLinesTexts[intCurrentLineNumber];
}
}
rtb.Lines = strLinesTexts;
rtb.SelectionStart = intInitialCursorPosition + ((rtb.TextLength - intInitialCursorPosition) - intRemainingCharsOfInitialText);
intNextCharIndex = rtb.SelectionStart;
intPrevCharIndex = intNextCharIndex;
}
/// <summary>
/// Implements Indention to the codes
/// </summary>
/// <param name="intCharIndex">A char index</param>
/// <param name="rtb">A RichTextBox control</param>
private void ImplementIndention(int intCharIndex, RichTextBox rtb)
{
int intIndentionLevel = CheckingIndentionLevel(intCharIndex, rtb);
ImplementIndention(intCharIndex, intIndentionLevel, rtb);
}
}
}
I hope that this sample codes can help you.
Please update and share codes, if you improve them.
| {
"pile_set_name": "StackExchange"
} |
Q:
With Rails 5, how do I add a database record after a new User has been created?
In my application, I have Accounts, Users, and Permissions. When a new user is created, I have gotten as far as automatically creating an Account record with the new User foreign_key set as an "owner_id" in the Account table. At the same time this is done, I want to add a record to my Permissions table with the new account_id and new user_id set in their respective columns, as well as the resource column set to "Account" and the role column set to "owner".
Here is how my models look:
account.rb
class Account < ApplicationRecord
belongs_to :owner, class_name: "User"
has_many :permissions
end
user.rb
class User < ApplicationRecord
...
has_one :account, foreign_key: "owner_id"
has_many :permissions
after_initialize :set_account
...
private
def set_account
build_account unless account.present?
end
end
permissions.rb
class Permission < ApplicationRecord
belongs_to :account
belongs_to :user
end
I was hoping that by modifying the "set_account" to the following would at least populate the account_id and user_id columns of the Permissions table, but I get an "undefined local variable or method 'build_permission' error.
def set_account
build_account and build_permission unless account.present?
end
here is my schema file to show tables/columns:
ActiveRecord::Schema.define(version: 2018_04_02_040606) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "accounts", force: :cascade do |t|
t.integer "hash_id"
t.integer "owner_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["hash_id"], name: "index_accounts_on_hash_id", unique: true
t.index ["owner_id"], name: "index_accounts_on_owner_id"
end
create_table "permissions", force: :cascade do |t|
t.integer "account_id"
t.integer "user_id"
t.string "resource"
t.string "role"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["account_id", "user_id"], name: "index_permissions_on_account_id_and_user_id", unique: true
end
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.inet "current_sign_in_ip"
t.inet "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.jsonb "settings"
t.index ["email"], name: "index_users_on_email", unique: true
t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
end
add_foreign_key "users"
end
I would appreciate any insight on what I might be missing or where I go from here to have it work how I want.
A:
Unless account object is created, you can not get account_id to update it in permissions table. One option would be to have an after_create call back to set account and permissions.
class User < ApplicationRecord
...
has_one :account, foreign_key: "owner_id"
has_many :permissions
after_create :set_account_and_permission
...
private
def set_account_and_permission
account = create_account
permissions.create(role: 'owner', account_id: account.id, resource: 'Account')
end
end
Hope it helps !
| {
"pile_set_name": "StackExchange"
} |
Q:
How properly calculate cornerRadius depending on the button frame
How to calculate cornerRadius property based on frame of the button to create rounded corners.
I do not like to redefine each time corner cornerRadius for each button item.
I create extension for the UIButton.
extension UIButton {
func setRoundedCorners(){
self.layer.cornerRadius = 10
self.layer.borderWidth = 1
}
}
And i would like to know how too calculate dynamically cornerRadius each time i use this function.
The main issue to find function that will calculate .cornerRadius for different button sizes. Example below will show small difference.
Example:
Corner radius is 10:
:
Corner radius is 15:
Is it possible to find function that will calculate proper value that will give corner radius?
A:
The main idea to get flexible function that will calculate proper
corner radius for different buttons based on their frame
I think it's up to you what you pass as the arguments:
extension UIButton {
func setRoundedCorners(ratio: Double?) {
if let r = ratio {
self.layer.cornerRadius = self.frame.size.width*r // for specific corner ratio
} else {
// circle
// i would put a condition, as width and height differ:
if(self.frame.size.width == self.frame.size.height) {
self.layer.cornerRadius = self.frame.size.width/2 // for circles
} else {
//
}
}
self.layer.borderWidth = 1
}
}
Usage
let button = UIButton()
button.setRoundedCorners(ratio: 0.25) // shape with rounded corners
button.setRoundedCorners() // circle
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I prove the correctness of my greedy algorithm for vertex cover on a tree?
The vertex cover problem on trees is as follows.
Input: an acyclic simple undirected graph G Output: a set of vertices W such that, for every edge uv, u &in W or v &in W. We want to minimize the size of W.
My greedy algorithm is to initialize W = &emptyset, then, while G is not empty, repeat the following steps. Let L be the leaf vertices of G. Let N(L) be the set of vertices adjacent to some vertex in L. Update W = W ∪ N(L). Delete the vertices L ∪ N(L) and their incident edges from G.
This algorithm works in all of the cases that I have tried so far. How do I go about proving it correct? Here's what I have so far.
Assume that there is another set S that is an optimal solution. By contradiction, I want to establish either that S does not cover all of the edges or that S is the same set as the one produced by my greedy algorithm.
A:
That's a reasonable start, but I see two issues. First, the optimal solution may not be unique. Consider the four-vertex path a-b-c-d, which has three optimal solutions: {a,c}, {b,c}, {b,d}. Second (and you're probably doing this already, but you didn't say so), it's necessary to consider the tree to be rooted. Otherwise, on the graph a-b for example, we have L = {a,b} and N(L) = {b,a}, and the vertex cover produced is W = {b,a}, which is not optimal. By designating a as a root, it is by definition excluded from the set of leaves.
To prove formally the correctness of a program involving a loop, it is often a good idea to use induction to establish a loop invariant. Allow me to suggest two.
For all times t (where time = number of loop iterations), let G(t) be what's left of G at time t and let W(t) be the value of W at time t. For every vertex cover X of G(t), the set W(t) ∪ X is a vertex cover of G(0), where 0 is the starting time.
For all times t, there exists an optimal solution that contains W(t) as a subset.
Let T be the ending time. Since G(T) is the empty graph, X = &emptyset is a valid vertex cover of G(T), so Invariant #1 establishes that W(T) is a vertex cover of G(0). Invariant #2 establishes that W(T) is contained in some optimal solution. Since W(T) itself is a vertex cover, W(T) itself must be that optimal solution.
The inductive step in proving Invariant #2 is, given an optimal solution that contains W(t-1) but not W(t), to massage it into another optimal solution that contains W(t). This involves formalizing your intuition that it's always at least as productive to take a leaf's neighbor over the leaf.
| {
"pile_set_name": "StackExchange"
} |
Q:
What does it mean when a paper is copyrighted by an organization?
While I was searching for materials for my research topic, I found a research paper which is signed as copyright by "Some organization". Does that mean that I could not use the content of this paper nor the ideas it presents until the paper owner gives me permissions?
A:
Not necessarily. Copyright prohibits you from presenting the work as yours under any circumstances. In addition, it prohibits you from publishing or recopying large segments of the work, without securing the permission of the owner of the copyright.
However, the existence of copyright does not exclude you from citing the work of others, nor mentioning what their key ideas are. Such use of copyright is covered by fair-use guidelines. Under these circumstances, though, you are still responsible for following the proper citation procedures of your university or the journal to which you are submitting the work under question. Note, however, that this is a tricky balance, and you should be careful to directly quote only the material you absolutely need to duplicate, as fair use is not an absolute guideline.
A:
No. Copyright covers the verbatim text and figures, not the ideas.
A:
The short answer: unless the document is marked "confidential" you can probably quote short passages verbatim and you can certainly make use of the ideas.
To expand on some of the other responses given here: In most jurisdictions, copyright allows the protection of the expression of an idea (e.g. as written down in a book or article) but not the idea itself. Legal protection of ideas is covered by patent law, which is much more restrictive than copyright, with much shorter periods of protection.
It's also worth knowing that phrases like "All rights reserved" are partly redundant these days in most countries – all works are copyrighted automatically, whether or not they include this phrase or similar. However, it's still useful to know who owns the copyright to a particular work.
What is referred to as "Fair Use" under US copyright law may not exist or may be very different in other jurisdictions. For example, in the United Kingdom there is a rather more restrictive version called "Fair Dealing".
If you have some time to kill, Bound by Law is a useful comicbook-style introduction to copyright.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to Insert Date (as Date DataType) In Mongo from 'Mongo Command Prompt' & From 'mongoimport'
MongoDB shell version: 2.0.4
Want to insert date as 'date datatype' from mongo command line.
db.my_date_collection.insert(
{"user_id" : 91,
"event_timestamp" :new Date("09-AUG-12 05.30.28.402000 AM")
});
Above query add record but change date from "09-AUG-12 05.30.28.402000 AM" to "1970-01-01T00:00:00Z"
> db.my_date_collection.findOne()
{
"_id" : ObjectId("54168ddc289a635d725d86fb"),
"user_id" : 91,
"event_timestamp" : ISODate("1970-01-01T00:00:00Z")
}
Plus it also didn't save 'date data' as date 'datatype'
typeof db.my_date_collection.findOne().event_timestamp;
object
Can someone help me insert data as date type from mongo prompt?
Additionally can some one tell me how to insert the 'date as date datatype type' from a tsv file? as i got the same issue in loading tsv from mongoimport.
Thanks
A:
The date is not in a valid format to be parsed by the date constructor. Try the equivalent value in a valid format (I'm assuming UTC time since you didn't include a timezone):
"09-AUG-12 05.30.28.402000 AM" => "2012-08-09T05:30:28.402"
> var my_date = ISODate("2012-08-09T05:30:28.402")
> db.my_dates.insert({ "x" : my_date })
> var doc = db.my_dates.findOne()
> doc.x instanceof Date
true
The return value is of Date type, but Javascript isn't object oriented so the meaning of that and how to determine if something is of Date type are different than you are expecting, apparently. Use instanceof to check is something is of a certain type or "inherits" from that type.
| {
"pile_set_name": "StackExchange"
} |
Q:
Will dipping in to savings affect mortgage possibillities?
I currently have 2 accounts; a savings, and a current.
Each month I have an amount transferred over to the savings.
Since I have saved for a number of years now I have enough for a reasonable deposit on a house, but I am worried my spending habits will lower my chances of getting a good mortgage.
Each month I transfer a small amount from my savings back to my current account. It would usually be around £100, which I pay back with my next transfer to my savings.
I always put the money back in, but I wondered if this would look bad on a mortgage application in the UK.
A:
If you apply for a mortgage with someone other than your current / savings account provider, they will not have access to this level of information.
They will pull your credit report, which contains information about debts and credit cards (repayments, amount borrowed etc.) and overdrafts, as well as anything like CCJs against you, but has no information about current or savings accounts other than who your main current account provider is.
You can (and should) check your credit report yourself, to make sure there's nothing incorrect on there. This only costs a few pounds and you can find out about how to do this from the 3 main agencies here: https://www.moneyadviceservice.org.uk/en/articles/how-to-check-your-credit-report
If you apply for a mortgage with the same provider that you use for your current account and savings account, they could theoretically look at your account usage history in this level of detail. However, I would be very surprised if they had a problem with the type of activity you describe. They'll be looking more at whether you have regular income into your account, whether you have frequently gone overdrawn without permission, etc. Moving money around between accounts or having a fluctuating savings account balance is not even slightly a red flag.
| {
"pile_set_name": "StackExchange"
} |
Q:
Efficient way of Element lookup in a Python List?
I have a list of files in a directory. I have to process only certain files from that directory. filelist is my desired file-list. How do I go about achieving this? Not interested in a bash solution since I have to do it all in this one Python script. Thanks much!
for record in result:
filelist.append(record[0])
print filelist
for file in os.listdir(sys.argv[1].strip() + "/"):
for file in filelist: #This doesn't work, how else do I do this? If file equals to my desired file-list, then do something.
print file
Sorry guys, not sure how I missed this! Early morning coding I guess!! Mods, please close it unless someone wants to chip in with an efficient way of doing it.
for file in os.listdir(sys.argv[1].strip() + "/"):
if file in filelist:
print file
A:
Sounds like you want to do a test:
for file in os.listdir(sys.argv[1].strip() + "/"):
if file in filelist:
# Found a file in the wanted-list.
print file
A:
If order and uniqueness don't matter, you can use a set intersection, which will be much more efficient.
import set
os_list = os.listdir(sys.argv[1].strip() + "/")
for file in set(os_list) & set(filelist):
#...
Example of improvement:
import random
import timeit
l = [random.randint(1,10000) for i in range(1000)]
l2 = [random.randint(1,10000) for i in range(1000)]
def f1():
l3 = []
for i in l:
if i in l2:
l3.append(i)
return l3
def f2():
l3 = []
for i in set(l) & set(l2):
l3.append(i)
return l3
t1 = timeit.Timer('f1()', 'from __main__ import f1')
print t1.timeit(100) #2.0850549985
t2 = timeit.Timer('f2()', 'from __main__ import f2')
print t2.timeit(100) #0.0162533142857
| {
"pile_set_name": "StackExchange"
} |
Q:
Powershell -renaming a file after copying
I'm having ongoing trouble with a script I've written that is (supposed) to do the following.
I have one folder with a number of csv files, and I want to copy the latest file with the company name into another folder, and rename it.
It is in the current format:
21Feb17070051_CompanyName_Sent21022017
I want it in the following format:
CompanyName21022017
So I have the following powershell script to do this:
## Declare variables ##
$DateStamp = get-date -uformat "%Y%m%d"
$csv_dest = "C:\Dest"
$csv_path = "C:\Location"
## Copy latest Company CSV file ##
get-childitem -path $csv_path -Filter "*Company*.csv" |
where-object { -not $_.PSIsContainer } |
sort-object -Property $_.CreationTime |
select-object -last 1 |
copy-item -Destination $csv_dest
## Rename the file that has been moved ##
get-childitem -path $csv_dest -Filter "*Company*.csv" |
where-object { -not $_.PSIsContainer } |
sort-object -Property $_.CreationTime |
select-object -last 1 | rename-item $file -NewName {"Company" + $DateStamp + ".csv"}
The file seems to copy ok, but the rename fails -
Rename-Item : Cannot bind argument to parameter 'Path' because it is null.
At C:\Powershell Scripts\MoveCompanyFiles.ps1:20 char:41
+ select-object -last 1 | rename-item $file -NewName {"CompanyName" + $DateSt ...
I think it is something to do with the order in which powershell works, or the fact it can't see the .csv in the $file variable. There are other files (text files, batch files) in the destination, in case that affects things.
Any help in where I'm going wrong would be appreciated.
A:
As wOxxOm answered, you need to remove $file from Rename-Item as it is not defined and the cmdlet already receives the inputobject through the pipeline.
I would also suggest that you combine the two operations by passing through the fileinfo-object for the copied file to Rename-Item. Ex:
## Declare variables ##
$DateStamp = get-date -uformat "%Y%m%d"
$csv_dest = "C:\Dest"
$csv_path = "C:\Location"
## Copy and rename latest Company CSV file ##
Get-ChildItem -Path $csv_path -Filter "*Company*.csv" |
Where-Object { -not $_.PSIsContainer } |
Sort-Object -Property CreationTime |
Select-Object -Last 1 |
Copy-Item -Destination $csv_dest -PassThru |
Rename-Item -NewName {"Company" + $DateStamp + ".csv"}
| {
"pile_set_name": "StackExchange"
} |
Q:
Passing a list of strings from Python to Rust
I've been learning Rust for about two weeks now and today, I got into its FFI. I used Python to play with Rust, using ctypes and libc. I passed integers, strings and even learned to pass a list of integers (thanks to this wonderful answer).
Then, I tried to pass a list of strings (following the reasoning behind the that answer), but I failed, as I couldn't get a lead on it. In Python, I have something like this to pass the array of strings.
def testRust():
lib = ctypes.cdll.LoadLibrary(rustLib)
list_to_send = ['blah', 'blah', 'blah', 'blah']
c_array = (ctypes.c_char_p * len(list_to_send))()
lib.get_strings(c_array, len(list_to_send))
In Rust, I thought that there should be something (like a STRING_RECEIVER) to collect the incoming strings, but I can't find one.
#![feature(libc)]
extern crate libc;
use std::slice;
use libc::{size_t, STRING_RECEIVER};
#[no_mangle]
pub extern fn get_strings(array: *const STRING_RECEIVER, length: size_t) {
let values = unsafe { slice::from_raw_parts(array, length as usize) };
println!("{:?}", values);
}
Is there any alternative way to achieve this?
A:
There is absolutely no difference with the case of array of numbers. C strings are zero-terminated arrays of bytes, so their representation in Rust will be *const c_char, which could then be converted to &CStr which then can be used to obtain &[u8] and then &str.
Python:
import ctypes
rustLib = "libtest.dylib"
def testRust():
lib = ctypes.cdll.LoadLibrary(rustLib)
list_to_send = ['blah', 'blah', 'blah', 'blah']
c_array = (ctypes.c_char_p * len(list_to_send))(*list_to_send)
lib.get_strings(c_array, len(list_to_send))
if __name__=="__main__":
testRust()
Rust:
#![feature(libc)]
extern crate libc;
use std::slice;
use std::ffi::CStr;
use std::str;
use libc::{size_t, c_char};
#[no_mangle]
pub extern fn get_strings(array: *const *const c_char, length: size_t) {
let values = unsafe { slice::from_raw_parts(array, length as usize) };
let strs: Vec<&str> = values.iter()
.map(|&p| unsafe { CStr::from_ptr(p) }) // iterator of &CStr
.map(|cs| cs.to_bytes()) // iterator of &[u8]
.map(|bs| str::from_utf8(bs).unwrap()) // iterator of &str
.collect();
println!("{:?}", strs);
}
Running:
% rustc --crate-type=dylib test.rs
% python test.py
["blah", "blah", "blah", "blah"]
And again, you should be careful with lifetimes and ensure that Vec<&str> does not outlive the original value on the Python side.
| {
"pile_set_name": "StackExchange"
} |
Q:
Как поменять режим через checkbox
Я хочу когда была галочка на checkbox я мог вести мячик, а когда нет галочки не мог.
let ball = document.querySelector('.ball');
let check = document.querySelector('.check');
check.addEventListener('change', function ( ) {
if (check.checked === true) {
ball.onmousedown = function(event) { // (1) отследить нажатие
ball.style.transitionProperty = '';
// (2) подготовить к перемещению:
// разместить поверх остального содержимого и в абсолютных координатах
ball.style.position = 'absolute';
ball.style.zIndex = 1000;
// переместим в body, чтобы мяч был точно не внутри position:relative
document.body.append( ball );
// и установим абсолютно спозиционированный мяч под курсор
moveAt( event.pageX , event.pageY );
// передвинуть мяч под координаты курсора
// и сдвинуть на половину ширины/высоты для центрирования
function moveAt( pageX , pageY ) {
ball.style.left = pageX - ball.offsetWidth / 2 + 'px';
ball.style.top = pageY - ball.offsetHeight / 2 + 'px';
}
function onMouseMove( event ) {
moveAt( event.pageX , event.pageY );
}
// (3) перемещать по экрану
document.addEventListener( 'mousemove' , onMouseMove );
// (4) положить мяч, удалить более ненужные обработчики событий
ball.onmouseup = function () {
document.removeEventListener( 'mousemove' , onMouseMove );
ball.onmouseup = null;
ball.ondragstart = function () {
return false;
};
};
};
};
});
.ground {
position: relative;
width: 700px; height: 700px;
margin: 20px 0;
background-image: linear-gradient(to top right, rgb(37, 53, 222), rgb(64, 55, 203), rgb(91, 57, 185), rgb(119, 58, 166), rgb(146, 60, 148), rgb(173, 62, 129), rgb(174, 58, 143), rgb(174, 54, 157), rgb(175, 50, 171), rgb(176, 46, 184), rgb(176, 42, 198), rgb(177, 38, 212));
box-shadow: inset 0 0 10px 2px rgba(0,0,0,0.7);
border: 3px cornflowerblue solid;
}
.ball {
top: 0;
left: 0;
position: absolute;
width: 100px; height: 100px;
transition: none 1s ease-out;
transition-property: background-color;
border-radius: 50%;
background-image: linear-gradient(to top right, rgb(115, 240, 19), rgb(138, 222, 22), rgb(161, 204, 24), rgb(184, 187, 27), rgb(207, 169, 29), rgb(230, 151, 32), rgb(230, 129, 30), rgb(231, 107, 27), rgb(231, 85, 25), rgb(231, 62, 23), rgb(232, 40, 20), rgb(232, 18, 18));
cursor: pointer;
margin: 5px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.8);
}
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="container">
<div class="lol"><input type="checkbox" class="check"> <span><sup>*</sup> Режим свободного ведения (Вы можете водить круг куда вам хочется )</span></div> <br>
<div class="ground">
<div class="ball" id="ball">
</div>
</div>
<script src="main.js"></script>
</body>
</html>
A:
Перенесите просто проверку на поле check в функцию нажатия кнопки.
Пример:
let ball = document.querySelector('.ball');
let check = document.querySelector('.check');
check.addEventListener('change', function ( ) {
ball.onmousedown = function(event) { // (1) отследить нажатие
if (check.checked === true) {
ball.style.transitionProperty = '';
// (2) подготовить к перемещению:
// разместить поверх остального содержимого и в абсолютных координатах
ball.style.position = 'absolute';
ball.style.zIndex = 1000;
// переместим в body, чтобы мяч был точно не внутри position:relative
document.body.append(ball);
// и установим абсолютно спозиционированный мяч под курсор
moveAt(event.pageX, event.pageY);
// передвинуть мяч под координаты курсора
// и сдвинуть на половину ширины/высоты для центрирования
function moveAt(pageX, pageY) {
ball.style.left = pageX - ball.offsetWidth / 2 + 'px';
ball.style.top = pageY - ball.offsetHeight / 2 + 'px';
}
function onMouseMove(event) {
moveAt(event.pageX, event.pageY);
}
// (3) перемещать по экрану
document.addEventListener('mousemove', onMouseMove);
// (4) положить мяч, удалить более ненужные обработчики событий
ball.onmouseup = function () {
document.removeEventListener('mousemove', onMouseMove);
ball.onmouseup = null;
ball.ondragstart = function () {
return false;
};
};
}
};
});
.ground {
position: relative;
width: 700px; height: 700px;
margin: 20px 0;
background-image: linear-gradient(to top right, rgb(37, 53, 222), rgb(64, 55, 203), rgb(91, 57, 185), rgb(119, 58, 166), rgb(146, 60, 148), rgb(173, 62, 129), rgb(174, 58, 143), rgb(174, 54, 157), rgb(175, 50, 171), rgb(176, 46, 184), rgb(176, 42, 198), rgb(177, 38, 212));
box-shadow: inset 0 0 10px 2px rgba(0,0,0,0.7);
border: 3px cornflowerblue solid;
}
.ball {
top: 0;
left: 0;
position: absolute;
width: 100px; height: 100px;
transition: none 1s ease-out;
transition-property: background-color;
border-radius: 50%;
background-image: linear-gradient(to top right, rgb(115, 240, 19), rgb(138, 222, 22), rgb(161, 204, 24), rgb(184, 187, 27), rgb(207, 169, 29), rgb(230, 151, 32), rgb(230, 129, 30), rgb(231, 107, 27), rgb(231, 85, 25), rgb(231, 62, 23), rgb(232, 40, 20), rgb(232, 18, 18));
cursor: pointer;
margin: 5px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.8);
}
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="main.css">
</head>
<body>
<div class="container">
<div class="lol"><input type="checkbox" class="check"> <span><sup>*</sup> Режим свободного ведения (Вы можете водить круг куда вам хочется )</span></div> <br>
<div class="ground">
<div class="ball" id="ball">
</div>
</div>
<script src="main.js"></script>
</body>
</html>
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I maximize an application first instance when trying to start a new one
I would like to limit an application to having only one instance running on a machine. So far I have this :
Mutex m = new Mutex(true, Name, out IsOwned);
if (!IsOwned)
{
string message = "There is already a copy of the application '" +
Name +
"' running. Please close that application before starting a new one.";
MessageBox.Show(message, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Information);
Environment.Exit(0);
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
And it exits, but is there a way to maximise the first instance before this one closes?
A:
This isn't the way you want to handle multiple instances of the application. The accepted practice is to just switch to the running instance of the application.
That being said, you can easily create a class that derives from WindowsFormsApplicationBase (in the Microsoft.VisualBasic namespace). This answer outlines how you would do it, and indicate that you want a single instance, as well as how to handle what happens when you try and run a new instance:
Opening a "known file type" into running instance of custom app - .NET
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.