INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
http_proxy setting
I know this is simple.. I am jus missing something.. I give up!!
#!/bin/sh
export http_proxy='
rm -f index.html*
strace -Ff -o /tmp/mm.log -s 200 wget '
I have used different proxy servers.. to no avail.. I get some default page.. In /etc/wgetrc use_proxy = on
Actually I am trying to use this setting(http_proxy) with python's urllib2. It access some default page as well..
strace - does a dns lookup of the proxy server GET < HTTP/1.0\r\nUser-Agent: Wget/1.11.4\r\nAccept: _/_ \r\nHost: slashdot.org\r\n\r\n
Any pointers??
|
The problem was I was using proxy sites. These sites expect you to send GET request to the proxy site (with the target site as parameter in URL or whatever site specific mechanisms they implement).
I was looking for proxy sites like <
I connect to their respective ports and send a get request to the original target site..
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "urllib2, wget, http proxy"
}
|
Our coach forbids (us) 'drinking'/'to drink'
In my grammar book "Grammatica Inglese Facile (Simple English Grammar)" I read that the following sentences are both correct:
> * Our coach _forbids drinking_.
>
> * Our coach _forbids us to drink_.
>
>
But the book adds that the latter cannot rewritten in this way:
> * Our coach _forbids us drinking_.
>
However the book doesn't explain its last statement, thus I'm asking if someone can explain whether what the book states true is. If so, why?
|
The reason is that the verb _forbid_ is transitive but not doubly transitive. That is, it needs one object, but cannot take two objects. The object, however, can be either the thing forbidden or the person to which it is forbidden.
> I forbid it.
> I forbid you.
(You can't just say "I forbid"; you need the "it" or "you", but either one works).
> Our coach forbids alcohol to the team.
> Our coach forbids the team to drink alcohol.
I believe some dialects permit a doubly transitive _forbid_ , but most dialects don't:
> *Our coach forbids the team alcohol.
Those people who do permit it would allow your last example.
This happens with other verbs as well, like _provide,_ which is only doubly transitive in America--see this question.
|
stackexchange-english
|
{
"answer_score": 4,
"question_score": 5,
"tags": "grammar"
}
|
jQuery- Making variable available inside function
I am trying to use a predefined variable inside a number of functions (its an API key that I use in several functions on the page):
var key = '12345';
function get_dom(query) {
$.ajax({
type: 'GET',
url: '
success: function (data) {
// do stuff...
}
});
}
How do I get `key` available inside the function? I keep getting `undefined`
|
In the comments you state that the get_dom() function is called on document ready. Often, when scoping issues then arise it is because that you forget that the event callbacks for things like document ready are executed in the global scope, and the variable you are trying to access is not in the global scope. Is it defined in some kind of inner scope, say, a wrapper function? People often do that to make the script unobtrusive. To mitigate this, you can wrap the callback in a proxy function that makes sure the scope is what you want it to be. I've personally messed this up countless times, it's so easy to do wrong.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "jquery"
}
|
Problemas de conexão do PHP com MySQL.(Access denied for user)
sou iniciante na área que se refere à programação e computadores. Estou com um problema que não consigo a solução em lugar algum.
Tenho uma máquina virtual Linux com um servidor MySQL para suprir a ferramenta de monitoramento Zabbix Server (que já está instalada na máquina virtual). A partir da minha máquina física (Windows) criei um túnel SSH através do Putty, dessa forma consigo conectar o PHP (que instalei via Xampp) ao MySQL da máquina virtual:
<?php
$link = mysql_connect('127.0.0.1:3310','root','senha');
?>
A conexão é feita, porém o MySQL me retorna que a senha ou usuário está errado:
> Warning: mysql_connect(): Access denied for user 'root'@'srv-gui' (using password: YES) in C:\xampp\htdocs\zabbix\index.php on line 2
O usuário e senha estão corretos, isto é fato, já que consigo acessar o console do MySQL com os mesmos.
Agradeço a ajuda!
|
Tenta dar acesso para o usuário acessar remotamente
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'
IDENTIFIED BY 'YOUR_PASS'
WITH GRANT OPTION;
FLUSH PRIVILEGES;
|
stackexchange-pt_stackoverflow
|
{
"answer_score": -1,
"question_score": 1,
"tags": "php, mysql, mysqli"
}
|
Require user to enter password to delete Facebook app
Is there any way to (some dialog maybe?) that can require a user to enter his password for Facebook, in order to confirm his identity (again)...
I have a webpage, which is using Facebook login. But I would like to require the user to enter his password in order to delete his membership of the page.
|
There is no built-in functionality to handle this. If you have them enter a password for your site after they login via fb, then you can build a simple confirmation yourself.
_And my personal opinion:_ Just use a captcha to prevent a bot from doing it. Besides that, until your site becomes "big enough" to get attention, its not as big of a really a security hole as you're probably thinking it is. If it would be _disastrous_ for them to lose membership, then users should probably have a separate password for that website anyway. And if you're still stuck on this idea, just do what Facebook does: don't actually "delete" the user, just move it into an "inactive" state. If they come back, make it all "active" again.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "facebook, facebook graph api"
}
|
How can "strange" ROP gadgets be found in a normal DLL? Compilers would never do this. (Return-oriented programming)
The gadget:
pushad
ret
from a certain DLL makes no sense to me in a legit program.
Assuming the DLL is legit, how is it possible for the gadget to be found by automatic search? An example of a function uses it may be helpful.
|
The instruction encoding is:
60 pushad
c3 ret
So wherever these two bytes occur, a `pushad; ret` gadget obtains. For example, this instruction could reasonably exist in SSE code:
66 0f 60 c3 punpcklbw xmm0, xmm3
See the `60 c3` gadget in it? Alternatively, the gadget could obtain from some immediate. For example, suppose there is some variable at `0x4800c360` and we try to load its address:
b8 60 c3 00 48 mov eax, 0x4800c360
See the gadget again?
There are tons of other ways this gadget could appear in perfectly normal code.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "assembly, dll, x86, reverse engineering, machine code"
}
|
Is it possible to obtain a transit visa at Heathrow Airport?
I am an Iranian national travelling with British Airways from Tehran, Iran via Heathrow Airport, London to Shanghai, China. I will arrive at LHR on 28th at 11:55am and depart at 14:10pm without changing terminals.
If I need a transit visa, can I obtain one at Heathrow Airport?
I am scared that British Airways have stopped a few people from boarding flights.
Also, do I need a transit visa to enter the UK?
I want to do some sightseeing.
What are the chances of getting past officials using transit without visa concession?
|
You need a "direct airside transit visa" (DATV) to connect at Heathrow, and visas are **never** issued at UK airports, **ever**.
While theoretically you could get through the international connections corridor at Heathrow undetected without a DATV, the check-in staff in Tehran is particularly responsible to make sure they don't transport you without the proper documentation. So if you don't have a DATV, you're not getting on the flight to London.
So, again, **you need a DATV**.
|
stackexchange-travel
|
{
"answer_score": 2,
"question_score": 0,
"tags": "visas, air travel, uk, transit visas, lhr"
}
|
Using the Euler-Lagrange equation to evaluate an integral
I think this is a very basic question. I'm just not sure how to use $\frac{\mathrm{d}}{\mathrm{d}x}\left(\frac{\partial F}{\partial y'}\right)=\frac{\partial F}{\partial y}$ to find the general solution to: $$\int \left(y^2 − y'^{\\\2}- 2y \cos( 2x)\right) \:\mathrm{d}x$$
Thanks
|
If you simply apply the equation $$\frac{\partial F}{\partial y} - \frac{d}{dx}(\frac{\partial F}{\partial y'}) = 0$$ for $F(x , y , y') = y^2 - y'^2 - 2y\cos(2x)$, you shall get $y'' - y = \cos(2x)$ (Please check the calculation).
Hope you can solve the second order ODE.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "calculus of variations"
}
|
regex sets of 5 digits followed by a comma (trailing comma optional)
I've got the following regex:
(\d{5}[,])
This matches the following:
12005,11111,11111,
but how do I make the trailing comma optional?
**EDIT:**
Acceptable results would be:
12005,
11111,11111,
12005
11111,11111
Unacceptable:
123456
123456,
12345,123456
123456,123456
|
(\d{5}[,]?)
Will match
12005,11111,11111,
or
12005,11111,11111
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "javascript, regex"
}
|
DS3231 Module Circuit Teardown
I recently purchased a DS3231 RTC module to use in one of my prototypes. Now that it is complete I would like to integrate the RTC directly into my PCB instead of using a plug in module. To that effect I have been trying to figure out the circuit using continuity testing on the module and the recommended circuit in the DS3231 datasheet. I have figured out all of it, except 2 things.
1. There are 2 capacitors in parallel connected between VCC and GND. There are no marking on them so how do I figure out their value?
2. There is a diode - resistor (210 ohm) pair between VCC and ground. Can't figure out the use of these since they are not in the manufacture suggested circuit diagram as well.
Any help is appreciated !
Edit: The diode in question can be seen in this closeup picture at the bottom side of the RTC here
!enter image description here
|
Found it. As per the posts here and here, the diode/resistor are connected between VCC and VBAT (that was my bad, I though they were connected to GND). This apparently is used to trickle charge the module with LIR2032 rechargeable battery. So in my case, I can ignore it.
Thanks all for the help !
|
stackexchange-electronics
|
{
"answer_score": 1,
"question_score": 0,
"tags": "embedded, rtc"
}
|
A problem with FormClosing property
i want to set a property that when the user clicks on X button in the title bar it check for some condition if all conditions are true then exit if no then do nothing and return to the form ..
but i noticed that FormClosing property exit the application howevere are my conditions ... so how to do my scenario ?!?
i'm using visual studio 2005 - C#
|
If you have already created the handler for the FormClosing event, just set the `FormClosingEventArgs.Cancel` property to True to cancel the closure of the form.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if(myConditionsAreMet == false)
e.Cancel = true;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "c#, winforms, events"
}
|
Getting the current iframe's body reference in JavaScript
I'm working on modal windows. When I click on a hyperlink in the main page, I need to show a modal window. This modal window I prepared using divs and one iframe. iFrame is used to show the source. Now in this modal window, I have another hyperlink to click which again opens a new modal window. This goes on.
Every time when I click on hyperlink, i want to create a new modal window in that provided iframe's src file itself. How to achieve this ?
TIA.
!modal windows to built
|
You can achieve this by using a simple java script file which creates div and iframe in your pages and frames. This script file will have all the necessary methods and a class to access these methods separately in each of the frame.
For example you can have the script file like
MyClass = function(){
this.var1, this.var2; // To store values separately in each frame.
this.myMethod = function(){
// Function body
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, iframe"
}
|
visualforce list button not working in Napili Community
Visualforce list button is working in lightning experience whereas the same button is not working in Napili Community.I have enabled **Available for Lightning Experience, Salesforce1, and Lightning Communities** on Visualforce page settings and also added a visualforce page to Community Profile.
List Button shows up in Community but nothing happens on click on list button and no debug logs for community user.
I do see below error on console.
. someone can show me how i can set the maximum width , height for image.
**Sollution**
create two ul li in html mockup one in left with image and second with text in right side. that's easier to follow.
|
<ul id="ilist">
<li>
<img src="img/icon1.png" alt="" **width="500" height="400"**/>
<p>some text here</p>
</li>
</ul>
Or do it with css:
#ilist li img{
max-height: 400px;
max-width: 500px
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "html, css"
}
|
Adding double quotes to NSString
I have reading everything and \" does NOT work.
I am trying to create a string that looks like this:
"SomeString" = "AnotherString"
Here is the code that I have to insert the double quotes:
NSString *newOutput = [NSString stringWithFormat:@"%@ \" = \" %@", output, [englishDic objectForKey:str]];
All that it outputs is:
"RateThisAppDontAsk \" = \" Don't ask again"
I thought maybe the "=" was causing problems but removing still gives me an output of this:
"RateThisAppDontAsk \" \" Don't ask again"
Any help would be very much appreciated!
|
Works for me in a little MacOS X command line test program. Here's all the code:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSString *newOutput = [NSString stringWithFormat:@"%@ \" = \" %@", @"foo", @"bar"];
NSLog(newOutput);
}
return 0;
}
Output is:
test[54844:403] foo " = " bar
If you want quotes before _foo_ and after _bar_ , add those:
NSString *newOutput = [NSString stringWithFormat:@"\"%@\" = \"%@\"", @"foo", @"bar"];
New output is:
test[54873:403] "foo" = "bar"
|
stackexchange-stackoverflow
|
{
"answer_score": 28,
"question_score": 7,
"tags": "objective c, nsstring, formatting"
}
|
Closed form of power series
First day on the site and this is an amazing place!
this is my question:
knowing that: $$1+\frac{x^2}{2}+\frac{x^4}{4}+\frac{x^6}{6}+\frac{x^8}{8}+\cdots $$
is a power series, how can I obtain its closed form?
Thank you.
|
Let $$f(x)=1+\frac{x^2}2+\frac{x^4}4+\frac{x^6}6+\cdots\ .$$ Then $$f'(x)=x+x^3+x^5+\cdots=\frac{x}{1-x^2}\ ,$$ so $$f(x)=\int\frac{x}{1-x^2}\,dx=-\frac12\ln(1-x^2)+C\ .$$ And since $f(0)=1$ we have $C=1$.
* * *
Alternatively, if you know the standard series $$\ln(1+t)=t-\frac{t^2}2+\frac{t^3}3-\cdots\ ,$$ you can substitute $t=-x^2$ and then do some simple algebra.
|
stackexchange-math
|
{
"answer_score": 9,
"question_score": 5,
"tags": "sequences and series"
}
|
SQLite FullText Index search on 2 terms with AND & OR
I have created a Full Text Index and can search terms like this:
SELECT * FROM mytable where myfield MATCH 'Food'
How do I add an AND clause to return records with the word FOOD and DOG ?
I've tried this:
SELECT * FROM mytable where myfield MATCH 'Food' and myfield MATCH 'Dog'
|
Read the documentation:
SELECT * FROM mytable WHERE myfield MATCH 'Food Dog'
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sqlite, full text search"
}
|
Integrate $\int{\frac{1}{x\sqrt{1-x^3}}dx}$
How do I integrate $$\int{\frac{1}{x\sqrt{1-x^3}}dx}$$
Not able to think of a method. Any hint is appreciated. Thanks
|
Hint:
Generalization:
$$\dfrac1{x\sqrt[n]{1-x^m}}=\dfrac{mx^{m-1}}{mx^m\sqrt[n]{1-x^m}}$$
Now choose $\sqrt[n]{1-x^m}=v\implies dv=?$
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 1,
"tags": "calculus, integration, indefinite integrals"
}
|
Copy files with renaming
I have a huge file tree. Some files have same name but in different case, e.g., `some_code.c` and `Some_Code.c`.
So when I'm trying to copy it to an NTFS/FAT filesystem, it asks me about whether I want it to replace the file or skip it.
Is there any way to automatically rename such files, for example, by adding ` (1)` to the name of conflict file (as Windows 7 does)?
|
Many GNU tools such as `cp`, `mv` and `tar` support creating backup files when the target exists. That is, when copying `foo` to `bar`, if there is already a file called `bar`, the _existing_ `bar` will be renamed, and after the copy `bar` will contain the contents of `foo`. By default, `bar` is renamed to `bar~`, but the behavior can be modified:
# If a file foo exists in the target, then…
cp -r --backup source target # rename foo → foo~
cp -r --backup=t source target # rename foo → foo.~1~ (or foo.~2~, etc)
There are other variants, such as creating numbered backups only when one already exists. See the coreutils manual for more details.
|
stackexchange-unix
|
{
"answer_score": 45,
"question_score": 30,
"tags": "rename, file copy"
}
|
Large request when sending TIFF image via SOAP
We have a WebService with a method to upload images, this method accepts a byte array which is a TIFF.
On the client side the TIFF is loaded with `Image.FromFile(path)` and then saved into a `MemoryStream`. Then `memoryStream.ToArray()` is called which results in a byte array which is used in the WebService request.
Currently we have a TIFF which is 130 KB big, but the total request size is almost 10 MB. How can this happen? Is this because the `Image.FromFile` method converts (deflates) the TIFF to a standard format, so compression etc is lost? Is there a better way of doing this?
Thanks.
|
Loading the tiff into an Image does remove all of the compression of the TIFF.
If you don't really have a need to load it into the Image, I'd just read it into memory as an arbitrary file and send the byte array that way.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": ".net, performance, web services, soap"
}
|
How to decrease SQL Query from last 30 days until now?
I am trying to get the amount of data for the last 30 days.
SELECT ( Now() - interval 1 month ),
Count(flightid) AS count
FROM flight
WHERE flightstatus = 0
AND flightvisibility = 1
AND flightvaliddate > Now()
AND flightvaliddate >= ( Now() - interval 1 month )
Right now this is working ok and it's giving me only 1 row that corresponds to the same day of last month.
What I would like is to get the remaining data from each day until now. How can I do this?
I am using MySQL.
|
The condition in the `WHERE` clause is wrong.
And since you want day wise data of last thirty days till now then you must have to use `GROUP BY`.
SELECT
DATE(flightvalidate) AS flightValidateDate,
Count(flightid) AS count
FROM
flight
WHERE
flightstatus = 0
AND flightvisibility = 1
AND DATE(flightvaliddate) >= CURDATE() - INTERVAL 1 MONTH
GROUP BY flightValidateDate
ORDER BY flightvalidate
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "mysql"
}
|
Drilling holes behind existing walls/ceilings
We are remodeling a 1914 house, and want to keep damage to the walls and ceiling to a minimum. We had to take a few walls down already, and as a result have the ability to drill new holes behind the existing wall/ceiling.
We would like to drill through 3 to 4 joists without removing the ceiling for new wiring.
The span of the 3-4 joists is about 5 feet, and we have about a foot worth of space to fit this 5 foot spade bit plus the drill.
We were thinking about using extension bars to incrementally get the spade bit across. The only issue that I can think about is how would we keep the spade bit straight.
Would this be a "hope it works" kind of situation, or is there a better way of doing it?
|
I personally wouldn't go this route, as it would definitely be a "hope it works" situation. For starters, I would hesitate to drill through stud bays that I didn't have access to both sides of because there is really no way to be sure you wouldn't be drilling through something important, like existing wiring for example. Second, drilling the holes is only the first challenge - fishing a wire through 4 blind holes over 5 feet is no small task. About the only way I would see this is feasible is using the bit (plus extensions) to pull the wire back through after it is drilled.
If you decide to try this, don't use a spade bit. Five feet worth of extensions going through 100 year old seasoned floor joists is going to be practically impossible due to the amount of pressure you would have to put on the drill bit and the number of joints in the system. I would use an auger bit instead - that way you would have the bit itself pulling the extensions taut.
|
stackexchange-diy
|
{
"answer_score": 1,
"question_score": 0,
"tags": "electrical"
}
|
call javascript function from c# page
I am using the below code to call a javascript function from aspx page load. But it's not working.
protected void Page_Load(object sender, EventArgs e)
{
btn_add_more_pack.Attributes.Add("OnClick", "openform()");
}
The javascript :
function openform()
{
try {
alert('enter');
}
catch (ex) {
}
}
|
I think the problem could be `OnClick` it should be `onclick` though it doesn't matter (not case sensitive) but you can try like below.
So on page load it should be as follows
protected void Page_Load(object sender, EventArgs e)
{
btn_add_more_pack.Attributes.Add("onclick", "openform()");
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "c#, javascript, asp.net, c# 4.0"
}
|
can I find the limit in this way?
I have to check if the sequence $b_{n}=\frac{n+cos(n^2)}{n+sin(n)}$ converges.I thought that I could find it like that: $$-1 \leq sin(n) \leq 1 \Rightarrow n-1 \leq n+sin(n) \leq 1+n \Rightarrow \frac{1}{1+n} \leq \frac{1}{n+sin(n)} \leq \frac{1}{n-1} \Rightarrow \frac{n+cos(n^2)}{1+n} \leq \frac{n+cos(n^2)}{n+sin(n)} \leq \frac{n+cos(n^2)}{n-1} $$ Can I use this relation to find the limit of the sequence?
|
I would extend your inequalities to this:
$$ 1-\frac{2}{n+1}=\frac{n-1}{1+n}\leq\frac{n+cos(n^2)}{1+n} \leq \frac{n+cos(n^2)}{n+sin(n)} \leq \frac{n+cos(n^2)}{n-1} \leq\frac{n+1}{n-1}=1+\frac{2}{n-1}$$
and now use the Squeeze Theorem.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "analysis"
}
|
How to fix laravel v6.18.38 after mistake in cache driver selection?
After a mistake in the laravel .env (cache_driver was set incorrectly to "data") the complete systems is broken. I have changed the driver name back to a valid value ("file") but still literally any "php artisan ..." command replys with "InvalidArgumentException : Cache store [data] is not defined.". So it seems the change in the .env is simply ignored. Also composer dump-autoload fails with the same error.
|
If you run into an issue where you have a cached configuration and you have errors that stop artisan from running you can delete this cached configuration file manually, the file is:
bootstrap/cache/config.php
As a side note, if you are developing locally, there isn't much need to cache your configuration or routes. Doing so will often get in your way as you will update things and not see the changes until you cache the configuration/routes again or clear the cached configuration/routes. Obviously if you are deploying this to your server caching these things is a benefit.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "php, laravel"
}
|
How to configure django-uploadify for videos upload only?
I want to use django-uploadify to upload for videos only, I just want it to upload videos only, all kind of videos, or at least all kind of popular video formats.
So far, i added `uploadify` in `settings.py` and in `urls.py` I added this
`(r'^uploadify/',include('uploadify.urls')),`
But didn't go through every step described in the docs just yet, I'll do the other steps when you tell me how to configure django-uploadify for videos only.
django-uploadify is not well documented so i'm relying on your experience to configure it.
if you have a better way to create a video uploading form, please tell me.
|
django-uploadify does not come with a custom filefield you are still going to use the django FileField that AFAIK does not have this kind of validation (filename extension checking).
You have to implement yourself this validation, you can do that using model validation or you can extend the django-uploadify form and add some validation there.
you can see a code example here
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "django, django models, django forms"
}
|
In Scala, how to find an elemein in CSV by a pair of key values?
For example, from a following file:
Name,Surname,E-mail
John,Smith,[email protected]
Nancy,Smith,[email protected]
Jane,Doe,[email protected]
John,Doe,[email protected]
how do I get e-mail address of John Doe?
I use the following code now, but can specify only one key field now:
val src = Source.fromFile(file)
val iter = src.getLines().drop(1).map(_.split(","))
var quote = ""
iter.find( _(1) == "Doe" ) foreach (a => println(a(2)))
src.close()
I've tried writing "iter.find( _(0) == "John" && _(1) == "Doe" )", but this raises an error saying that only one parameter is expected (enclosing the condition into extra pair of parentheses does not help).
|
The underscore as a placeholder for a parameter to a lambda doesn't work the way that you think.
a => println(a)
// is equivalent to
println(_)
(a,b) => a + b
// is equivalent to
_ + _
a => a + a
// is not equivalent to
_ + _
That is, the first underscore means the first parameter and the second one means the second parameter and so on. So that's the reason for the error that you're seeing -- you're using two underscores but have only one parameter. The fix is to use the explicit version:
iter.find( a=> a(0) == "John" && a(1) == "Doe" )
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 5,
"tags": "scala, file io, csv"
}
|
get YouTube videoID from gdata.youtube.com/feeds/api/videos (YouTube api)
Using jQuery and YouTube api.
I've been trying for a while to simply get the ID's of the searched videos, seems like or either i'm blind or the guys from youtube wants us to work more than necessary ;-)
#search = 'mad max';
$.ajax({
url: " + escape($("#search").val()) + "&alt=json&max-results=30&format=5",
dataType: "jsonp",
success: function (data) {showVideoList(data)}
});
function showVideoList(data) {
console.log(data);
}
I get lots of information but the videos ID's. Ok I can get it from:
data.feed.entry[0].entrymedia$group.media$player[0].url
But will have to use regExp and might change in the future. There is no property in this object where I can get just the videoID ?
|
Try this:
var id = data.feed.entry[0].id.$t.split('/').reverse()[0];
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, jquery, youtube api"
}
|
Which folders and files needed 777 mode in joomla 1.5?
After joomla upload to ftp . how many folder needed mode 777 need enable to working joomla without any error.
|
Depending on the security configuration of your Web server the recommended default permissions of 755 for directories and 644 for files should be reasonably secure.
source: <
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "joomla, joomla1.5"
}
|
How to use vga palettes
I switched to VESA mode 105h which is a 256 color mode. When I checked the palette data using AX = 4F09h, I got values that matched the colors displayed on the screen.
When I switched the mode to 118h, a 16.8M color mode, I checked the palette table and the same values are still there even though the colors displayed are different.
How do I get the palette data for the new mode I switched to? Or maybe I am not getting the whole concept right. Can someone explain to me how to get the palette values for a specific mode?
|
With 256 colors, only an 8-bit color index is specified. the color to be displayed is then looked up in a color palette.
But `118h` is a 24-bit bit color mode and it's a little different there: No color palettes are used there, the color value is given directly as a 24-bit value (8 bits for the red component, 8 bits for the green component and 8 bits for the blue component). One could also say that the values that were previously in the color palette are now written directly into the screen buffer.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "assembly, graphics, osdev, vesa"
}
|
Proof of $m \times a + n \times a = (m + n) \times a$ in rings
I am trying to prove that
$$m \times a + n \times a = (m + n) \times a$$
while $m, n \in N$ and $a,b \in (Z, +, \times)$.
This is what I have got:
$a \times 0 = 0$ $\Rightarrow$ $a \times 0 + a \times 0 = a \times 0$, because $0 + 0 = 0$
assumption: $\underbrace{a + a + ... + a}_{\text{m}} = m \times a$
induction: $\underbrace{a + a + ... + a}_{\text{m}} + a = (m + 1) \times a$
therefore: $m \times a + a = (m + 1) \times a$ $\Rightarrow$ $m \times a + 1 \times a = (m + 1) \times a$, because $a \times 1 = a$ $\Rightarrow$ $m \times a + n \times a = (m + n) \times a$
is this right ?
|
The problem seems to be missing the definition of $n\times a$, which is - I assume - inductive.
Namely:
$0\times a=0$
$(n+1)\times a=n\times a+a$.
Once we know the definition, it is not difficult to show this using induction on $n$.
$1^\circ$ For $n=0$ we have $$m\times a+0\times a\overset{(*)}=m\times a=(m+0)\times a$$ where the equality $(*)$ follows from $0\times a=0$, which is part of the definition.
$2^\circ$ _Inductive step._
You know that $m\times a+n\times a=(m+n)\times a$.
What can you say - using the definition - about
$m\times a + (n+1)\times a=?$
$(m+n+1)\times a=?$
> $m\times a + (n+1)\times a= m\times a + n\times a + a \overset{(\triangle)}= (m+n)\times a + a$
> $(m+n+1)\times a= (m+n)\times a +a$
> The equality marked as $(\triangle)$ is the place where we are using the inductive hypothesis. The first equality in both cases follows from the definition.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 3,
"tags": "ring theory, field theory"
}
|
How to add rolling filters in dashboard
I want to add custom filters to dashboards, that means from 05-02-2014 to 31-12-2014 can any one please guide me
|
You can use Last 2 months, Last 3 Months Rolling filter, as you said we cannot add the custom filters like date range through UI but may possible using VF pages/ components
|
stackexchange-salesforce
|
{
"answer_score": 2,
"question_score": 2,
"tags": "dashboard"
}
|
Best translation for "Quality over quantity"
What is the best translation into Russian of the common English expression "Quality over quantity"?
I have not found any answers on the internet.
(Bear in mind that I'm a native Russian speaker.)
|
Лучше меньше, да лучше. (В. И. Ленин)
|
stackexchange-russian
|
{
"answer_score": 11,
"question_score": 5,
"tags": "перевод, выражения, english"
}
|
SpaceX and propulsive landing on Mars -- what just happened? (and why?)
There is some news that I've just read about in the Pod Bay SE chat room:
* Wired: SpaceX's Mars Plan Hits a Pothole. Up Next: The Moon?
* Ars Technica: Elon Musk’s Mars rocket may be about to lose half of its engines
* YouTube: Elon Musk, ISS R&D Conference, July 19, 2017
The news items include a lot of background and interpretation and speculation and future-predicting and it's hard for me to roll all of that back and identify just the bare technical facts.
Is propulsive landing of a Red Dragon capsule on Mars _more difficult than originally thought for some technical reason_ , or is it just that _the goal is less attractive_ for logistic, business, or long-range planning types of reasons?
|
Red Dragon was intended to piggyback on the effort to develop _and qualify_ Dragon for propulsive landings on Earth. The qualification hit a snag: NASA requirements for human-rating the propulsive landing system were so stringent that SpaceX decided they didn't want to spend the time and money to meet those requirements.
That left development of the landing system incomplete. They'd have to finish the landing system for Red Dragon alone, which would make Red Dragon a much more expensive mission.
Reading between the lines, SpaceX wants to focus its development resources on their Interplanetary Transport System (ITS/BFR) as soon as possible, and not spend time on one-off missions like Red Dragon.
|
stackexchange-space
|
{
"answer_score": 58,
"question_score": 35,
"tags": "spacex, red dragon, propulsive deceleration"
}
|
C++ write a number on two bytes
I am new to the low level c++, and I find it a bit hard to understand how to manipulate bits. I am trying to do the following to use in a compression algorithm I am trying to make:
unsigned int num = ...;//we want to store this number
unsigned int num_size = 3;//this is the maximum size of the number in bits, and
//can be anything from 1 bit to 32
unsigned int pos = 7;//the starting pos on the 1st bit.
//this can be anything from 1 to 8
char a;
char b;
if the `num_size` is 3 and pos is 7 for example, we must store `num`, on the **7th** and **8th** bit of `a` and on the **1st** bit of `b`.
|
How about just?
a = num << (pos-1);
b = ((num << (pos-1)) & 0xFF00) >> 8;
To read num back just
num = ((unsigned int)a + ((unsigned int b) << 8)) >> (pos - 1);
Note, this doesn't do any sanity checks, such as whether all the relevant bits fit in a and b, you'll have to do that yourself.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c++"
}
|
Solve Non-Homogeneous Equations In Order 3
I would like to solve the following: $$ y'''-10y''+32y'-32y=(2x-3)e^{4x}$$ $$y(0)=1,y'(0)=5,y''(0)=22$$ what I did:
1. $y=y_{Homogeneous }+y_{Private} \rightarrow y_{h}+y_{p}$
LHS : $y'''-10y''+32y'-32y=0 \rightarrow K^3-10K^2+32K-32 \rightarrow (K-4)^2(K-2)$
we get: $y_{h}=C_{1}e^{4X}+C_{2}Xe^{4X}+C_{3}e^{2X}$
RHS: $f(x)=(2x-3)e^{4X}\rightarrow y_{p}=AX^2e^{4X}+BX^3e^{4X}$
this is the level that I dont know how to continue, I need to differentiate $y_{p}\rightarrow y'p,y''p,y'''p$ then to compare coefficients?
thanks.
|
The particular solution should not have arbitrary constants. That is you when find the particular solution ($y_p$) you should have found the values of $A$ and $B$. The correct answer is,
$$y_p(x)=\frac{1}{6}x^3 e^{4x}-x^2 e^{4x}$$
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 1,
"tags": "ordinary differential equations"
}
|
Improved Insertion Method for Linear Probing
Currently, I am asked to devise an _O(n log n)_ algorithm for inserting _n_ elements into a hash table with _n_ slots using linear probing.
Originally, it would take up to _O(n^2)_ time for inserting _n_ elements, if the hash values generated by the hash function end up being a single number.
Therefore, I am thinking about preventing the collisions before hashing any elements, by predicting them using a certain type of data structure.
For example: calculate all the hash values for each element (which is _O(n)_ ), search for possible collisions, change the hash values of the colliding keys, and then do insertion.
My question: is it possible to find a data structure that solves my problem in _O(n log n)_ time?
Many thanks.
|
To start, initialize a vEB tree to contain 0..n-1, representing the open slots of the hash table. To insert an element into the hash table, call the FindNext method of the vEB tree once or twice (if there is wraparound) to determine the next free slot and then call Delete to remove it from the vEB tree. The total running time is O(n log log n).
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "algorithm, hash, time complexity"
}
|
Angular ngRepeat html content
I have the following:
<div class="columns large-12">
<p ng-repeat="desc in joinUs.description">{{desc}}</p>
</div>
How can I display html content inside the repeated paragraph? Basically I want to repeat:
<p ng-bind-html="{{desc}}"></p>
joinUs.description is an array of strings, some containing anchor tags.
Edit
I have tried this the following (as suggested angular.js ng-repeat li items with html content) but the html is still shown as plain text.
<div class="row">
<div class="columns large-12">
<p ng-repeat="desc in joinUs.description" ng-bind-html-unsafe="desc">{{desc}}</p>
</div>
</div>
|
try this:
<p ng-repeat="desc in joinUs.description" ng-bind-html="desc"></p>
plunkr with similar use is here: <
(it might help, if you add a working sample as plunkr/fiddle or similar)
edit:
ng-bind-html-unsafe has been deprecated. see this stackoverflow question: With ng-bind-html-unsafe removed, how do I inject HTML?
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, c#, html, angularjs"
}
|
Installing dll file into GAC by drag and drop
I had build and compile a class project in Visual Studio, I would like to deploy the dll file into Global Assembly Cache (GAC) by drag and drop.
My question is...
1) Is there any side effect of drag and drop of dll into GAC instead of using gacutil.exe?
2) After installing of dll into GAC, I required to do iisreset in order my class project to take effect, why?
thank you in advanced.
|
1) I use drag and drop and it's fine for me.
2) No, iis reset is not needed, but you have to restart application pool, where dll used.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "visual studio, dll, gac"
}
|
How to check if the record updated or inserted successfully Angular
I have Angular 7-8 project back end is Node.JS, I could not found a solution on how to check if my record inserted or updated successfully in database.
here is my service.ts file
UpdateData(data, id) {
try {
return this.http.post(this.baseurl + "/update/" + id, data)
.subscribe(result => console.log(result));
} catch (err) {
console.log("-------Error occurred update posting----" + err);
this.handleError(err);
}
}
I want to check in my component.ts if the insert/update completed successfully or not after calling this service function.
|
This can be done within the subscribe method like below:
return this.http.post(this.baseurl + "/update/" + id, data)
.subscribe(result => console.log(result),
(error) => {
// error logic here
},
() => {
// request success logic here
});
However if you want to check for the error/success in your component you shouldn't subscribe in your service and perform the actual subscribe in your component like below:
service:
return this.http.post(this.baseurl + "/update/" + id, data);
In your component.ts
this.serviceInstance.UpdateData(data, id).subscribe(result => console.log(result),
(error) => { /* error logic */ }, () => { /* success logic */})
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "node.js, angular"
}
|
Formula or upper bound for $\sum_{i=1}^n i^3 {n\choose i} a^i b^{n-i}$
I want to upper bound (or find a closed form for): $$ \sum_{i=1}^n i^3 {n\choose i} a^i b^{n-i} $$ This seems really close to the binomial formula $\sum_{i=1}^n {n\choose i} a^ib^{n-i} = (a+b)^n$, so I was wondering if there's an easy way to deal with sums of this type.
|
Since $\sum_{i=0}^n\binom{n}{i}(ax)^ib^{n-i}=(ax+b)^n$, you can apply $x\tfrac{d}{dx}$ three times, then set $x=1$. The $i=0$ lower limit has the same effect as taking $i=1$, because $0^3=0$.
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 0,
"tags": "combinatorics, summation, binomial coefficients"
}
|
how to modify a column datatype in mysql so that it saves the previous records in the newly saved format
I just need to change the datatype of my column however, I used the command `alter *table_name* modify column *column_name* *datatype*` and it update the datatype but the previously saved result are in the same previous datatype . I want them to be modified too. Any help? And am I clear with my query?
|
It's been a while and I've been bouncing between database engines a lot lately so my syntax may be off, but the general idea will still be valid:
SELECT * INTO <table_name>_bak FROM <table_name>;
-- alter your table, leaving nulls in the column
UPDATE <table_name>
SET <column_name> = b.<column_name>
FROM <table_name> t
INNER JOIN <table_name>_bak ON <primary-key-join-clause-here>;
-- disable nulls in your modified column if needed
DROP TABLE <table_name>_bak;
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "mysql"
}
|
When to use Count(PK_ID) and when to use system tables?
We can use either `count(<column_name>)` or system tables to get the number of rows in a table. Then where to use which one?
Thanks Devi
|
When `COUNT(*)` (without any `WHERE` conditions) starts to take more than about 10 seconds, that's when I usually cancel the query, and start using the system tables from then onwards. Obviously, if there are `WHERE` conditions, then you can only obtain the answer via `COUNT(*)` (or `COUNT(<column>)`)
Once a table is large enough that `COUNT(*)` isn't performing well, you don't generally need an exact answer anyway.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "sql, sql server"
}
|
Efficient Way to Determine Union of Sets
I have a (a very large) list of sets, containing pairs of values such as:
SetList = [{1,2},{2,3},{4,5},{5,6},{1,7}]
I'd like to efficiently determine the sets of values that are disjoint as implied by the transitivity of the relationships in the pairs above. For example, 1 is associated with 2, and 2 with 3 and so 1,2,3 are associated. Similarly 1 is associated with 7, so 1,2,3, and 7 are associated. In the above, 4, 5, and 6 are associated, but not with the remaining values. The result should look like the following:
DisjointSets = [{1,2,3,7},{4,5,6}]
Is there are simple, and efficient, way to perform this operation that I'm missing? Thank you!
|
Converting my original list to tuples:
TupleList = [(1,2),(2,3),(4,5),(5,6),(1,7)]
I used networkx via (thanks @user2357112):
import networkx as nx
G = nx.path_graph(0)
G.add_edges_from(TupleList)
DisjointSets = list(nx.connected_components(G))
Is this the most efficient way to solve the problem? Any other ideas?
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "python, python 3.x, set"
}
|
Check if exists or not in the same line PHP
How can i check if exists or not in the same line something like that but it dosen't work :
<td><?= isset([$a['type1']]) ? [$a['type1']] : "0"; ?></td>
This's my code :
<td align="center" valign="top" class="textContent">
<h2 style="text-align:center;font-weight:normal;font- family:Helvetica,Arial,sans-serif;font-size:23px;margin-bottom:10px;color:#72C8F3;line-height:135%;">Error1 : '.($a["type1"]).' <br/>Error2 : '.($a["type2"]).'<br/>Error3 : '.($a["type3"]).'</h3>
</td>
Thanks for any help.
|
You can use the ternary operator as followed. Note you don't need to wrap the array in '[]'
<?php echo (isset($a['type1']) ? $a['type1'] : 0); ?>
If you want to check all are set you could use;
<?php echo ( isset($a['type1']) && isset($a['type2']) && isset($a['type3'] ) ? $a['type1'] : 0 ); ?>
To simplify further as suggested by Magnus Eriksson:
<?php echo ( isset($a['type1'], $a['type2'], $a['type3']) ? $a['type1'] : 0 ); ?>
If you wish to check for just one use the or/double pipe `||` expression
<?php echo ( isset($a['type1']) || isset($a['type2']) || isset($a['type3'] ) ? $a['type1'] : 0 ); ?>
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "php"
}
|
Sequencing inaccurate at the primer site
The times I have sent a sample to sequence, both the forward and the reverse primer sites, show high inaccuracy while the rest of the gene is correctly sequenced. Because of this, the sequences of my _in silico_ construct and the sequenced sample do not align in this section; but they do align at the rest of the gene almost 100%.
Is there a reason for this? Is this simply a sequencing artifact or is should I trust the sequenced sample and assume that the primer sites have mutated?
|
The very extremities of sequencing reads obtained by most if not all sequencing technologies are usually of lower quality, though more often so in the 5' region. You should disregard this data, or better yet design additional primers further away to encapsulate that region too if you desperately need it.
Below is a fairly typical output from FASTQC analysis of Illumina sequencing data. You can see how the quality is at its peak in the middle of the read (base index on the x axis. You'd likely see a similar thing for Sanger sequencing which is presumably what you're using.
(x_{n-1}-3)<0\Rightarrow 3<4x_{n-1}-x_{n-1}^2 $$ so $$ x_n=\frac{3}{4-x_{n-1}}<x_{n-1} $$ So $2.$ holds as well. Now by the monotone convergence theorem, $x_n$ converges. With a little more work, we can show that this limit is actually $1$.
|
stackexchange-math
|
{
"answer_score": 9,
"question_score": 9,
"tags": "calculus, sequences and series, limits, convergence divergence"
}
|
In Box2D, how do I make a flexible pole?
I would like to replicate the behavior of a flexible pole as used for pole vault.
Can somebody give me some inspiration how to simulate that with Box2D? Should I connect multiple objects with flexible joints, or is there another way?
|
If you don't want to worry about the pole-vault colliding with anything during the vault, you can simulate it using a simple spring-mass-damper system, and you can just animate the pole deforming artificially. The pole can be considered to be a (very stiff) spring. The rest length of the spring is the length of the pole. This is actually a mathematical model
When the player is about to pole-vault, find a point on the ground in front of the player for the pole to attach to. Then, create a spring joint between the player and the ground point. If the player has enough forward momentum, he/she will vault through the air. Tune the stiffness of the spring until you get a result that you like.
As for animating the pole, you can check the length of the spring against its rest length. If the length is significantly shorter, then the pole is compressing, and you can draw a "compressed pole" sprite or curve. Otherwise, the pole is straight.
|
stackexchange-gamedev
|
{
"answer_score": 1,
"question_score": 3,
"tags": "box2d, spring"
}
|
Prove $g(x)=\sum_{n=0}^{\infty}b_n x^n$ $(x\in\mathbb{R})$ converges (Two power series, whose ratio goes to $0$ and convergence)
Let $f(x) = \sum_{n=0}^{\infty}a_n x^n$ $(x \in \mathbb{R})$ be a power series and $a_n$ be positive real numbers. Suppose $f(x)$ converges when $\lvert x \rvert < 1$, and $f$ is bounded in $[0,1)$, then it is known that
$$\sum_{n=0}^{\infty}a_n $$
converges.
Now, let $\\{b_n\\}$ satisfy $b_n/a_n \to 0$ when $n \to \infty$. Then, I would like to prove $g(x) = \sum_{n=0}^{\infty}b_n x^n$ $(x\in\mathbb{R})$ converges on $\lvert x \rvert < 1$.
**My try:**
① For $\varepsilon = 1$, there exists $N$ such that for all $n \geq N$, $b_n < a_n$. So,
$$\sum_{n=0}^{\infty}b_n x^n \leq \sum_{n=0}^{\infty}a_n x^n .$$
Thus, $\sum_{n=0}^{\infty}b_n x^n$ is bounded. But $b_n$ is not supposed to be positive, so we should try another method.
② I tried to use ratio test, but in vain.
|
Since $b_{n}/a_{n}\rightarrow0$, there exists $M>0$ such that $|b_{n}|\leq M|a_{n}|$ for all $n$. It is given that $\sum_{n=1}^{\infty}a_{n}x^{n}$ is convergent for $|x|<1$. Hence the radius of convergence $R$ is at least $1$. Recall that for any $x$ with $|x|<R$, the power series $\sum_{n=1}^{\infty}a_{n}x^{n}$ is absolutely convergent.
Let $x\in\mathbb{R}$ with $|x|<1$. We have that \begin{eqnarray*} \sum_{n=1}^{\infty}|b_{n}x^{n}| & \leq & \sum_{n=1}^{\infty}M|a_{n}x^{n}|\\\ & < & \infty. \end{eqnarray*} Hence, $\sum_{n=1}^{\infty}b_{n}x^{n}$ converges.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "real analysis, sequences and series, limits, convergence divergence, power series"
}
|
Compute $P(X^2+Y^2 \leq 1 \mid X= x) $
> $X$ and $Y$ are rv jointly continuous with pdf $f(x,y) = \frac{1}{x}$ for $0\leq y \leq x \leq 1$ and $0$ otherwise. I want to evaluate $P(X^2+Y^2 \leq 1 \mid X= x) $.
First of all, What confuses me is that value $X=x$. We know for continuous rv $P(X=x)= 0$. But if we try to evaluate the mentioned probabililty we have
$$ P(X^2+Y^2 \leq 1 \mid X= x) = \frac{P(x^2+Y^2 \leq 1 )}{P(X=x)} $$
by definition. But this is undenfined expression. is there a typo on the problem?
|
Conditional density of $Y|X=x, $ $f_{Y|X=x}(x)=\frac{f(x,y)}{f_X(x)}=\frac{f(x,y)}{\int_0^x f(x,y)dy}=\frac{1/x}{\int_0^x 1/xdy}=1/x $ for $0<y<x,$ and $f_{Y|X=x}(x)=0$ otherwise. $P(X^2+Y^2\leq 1|X=x)=P(Y^2\leq 1-x^2|X=x)=P(0< Y\leq \sqrt{1-x^2}|X=x)=\frac{\min\\{x,\sqrt{1-x^2}\\}}{x}.$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "probability"
}
|
Django class based generic views: cannot import name TemplateView
Django fires exception `cannot import name TemplateView` how to fix this?
**view.py** :
from django.views.generic import TemplateView
class Monitor(TemplateView):
template_name = 'helo.html'
* * *
**urls.py** :
from monitor.views import Monitor
urlpatterns = patterns('',
(r'^admin/', Monitor.as_view()),
)
|
I don't know what Django version you are using, but only in Django 1.3 a class called TemplateView exists. Its import should be:
from django.views.generic.base import TemplateView
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, django, django templates"
}
|
Google Sheets IMPORTXML Text Field from Website
I am trying to dynamically pull in car values for cars matching specific criteria on Kelley Blue Book. I have this `IMPORTXML` query that has a link to the specific page that shows the trade-in value of the car.
=IMPORTXML(" "//text[@y='-8']")
In this URL, there is a text field that has the y coordinate as -8. I was hoping that it would be sufficient to identify the data I want to pull in (The trade-in value). I get the standard Can't fetch URL error and can't figure out why.
|
the issue is not within your XPath `"//text[@y='-8']"` but with the website itself.
basically you have two options to test if the website can be scraped:
=IMPORTXML("URL", "//*")
where XPath `//*` means "everything that's possible to scrape"
and direct source code scrape method:
=IMPORTDATA("URL")
sometimes is source code just huge and Google Sheets can't handle it so this needs to be restricted a bit like:
=ARRAY_CONSTRAIN(IMPORTDATA("URL"), 10000, 10)
anyway, non of these can scrape anything from your URL
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "xpath, web scraping, google sheets, google sheets formula"
}
|
Makefile: Conditionals in foreach
Is it possible to add multiple commands in a foreach loop? I'm trying to add a simple if-else conditional but unfortunately I cannot find a good explanation for that.
Foreach lib in TARGET_LIBS, I would like to check if lib contains the word "test". If yes, call TEST_COPY_RULE. Otherwise, call LIB_COPY_RULE.
Thank you
|
This Makefile answers your question positively:
TARGET_LIBS := a testb ctest d e
TEST_COPY_RULE = $(info TEST_COPY $1)
LIB_COPY_RULE = $(info LIB_COPY $1)
IS_TEST = $(findstring test, $L)
$(foreach L, $(TARGET_LIBS), $(if $(call IS_TEST,$L),$(call TEST_COPY_RULE, $L),$(call LIB_COPY_RULE, $L)) )
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "makefile"
}
|
How to replace multiple spaces by one tab
I have some text files which contain some columns separated by a various number of spaces, but instead I need one single tab as a separator. Is it possible to do in Bash?
|
To convert sequences of **more than one space** to a tab, but **leave individual spaces alone** :
sed 's/ \+ /\t/g' inputfile > outputfile
To do this for a number of files:
for inputfile in *
do
sed 's/ \+ /\t/g' "$inputfile" > tmpfile && mv tmpfile "$inputfile"
done
or
for inputfile in *
do
sed -i.bak 's/ \+ /\t/g' "$inputfile"
done
or
find . -type f -exec sed -i.bak 's/ \+ /\t/g' {} \;
|
stackexchange-superuser
|
{
"answer_score": 41,
"question_score": 33,
"tags": "linux, bash, text manipulation"
}
|
Verifying IP address using regex in Python
I am trying to validate an IP address. Following is the code. Can anyone please tell me what is wrong in the code?
import re
ip = '355.4'
m = re.match('^((?:1?\d{0,2}|2[0-4]\d{1}|25[0-5]).){3}(?:1?\d{0,2}|2[0-4]\d{1}|25[0-5])$', ip)
if m:
print "correct"
print m.groups()
else:
print "wrong"
According to the IP given, it should print `wrong` as output but it prints `correct ('4',)` as the output.
|
I was making a mistake by not giving `\` before `.` which was resulting in it matching any character.
import re
ip = '255.25.2.256'
m = re.match('^((?:1?\d{0,2}|2[0-4]\d{1}|25[0-5])\.){3}(?:1?\d{0,2}|2[0-4]\d{1}|25[0-5])$', ip)
if m:
print "correct"
print m.groups()
else:
print "wrong"
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, regex"
}
|
How to use Method function getParamterTypes()?
I am trying to print out the parameter types for the methods of a generic class, but I am getting garbage values. I am sure I am just making a simple error somewhere, but I am really new to programming so I can't figure out where.
static void displayMethodInfo(Object obj){
Class c = obj.getClass();
Method methods[] = c.getDeclaredMethods();
for(Method m : methods){
if(!Modifier.isPrivate(m.getModifiers()))
System.out.print(m.getName() + "(");
System.out.print(m.getParameterTypes() + " -> ");
System.out.println(m.getReturnType());
}
}
When I run the program, the parameters types are not printing out, only their memory locations. It should be printing out int and char. Do I need to override something to get them to print out right, or am I just using the function wrong?
|
Java does not implement a human-readable version of `toString()` for an array which is being returned by `m.getParameterTypes()`. You could wrap it into a list to print:
System.out.print(Arrays.asList(m.getParameterTypes()) + " -> ");
The result which is returned by this call would be verbose, so you could convert it into `String[]` using `Class.getSimpleName` for each of the return parameter types:
public static String[] toSimpleNames(Class... classes){
String[] names = new String[classes.length];
for (int i = 0; i < classes.length; i++) {
names[i] = classes[i].getSimpleName();
}
return names;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java"
}
|
Como validar se o TextField esta vazia?
Boa noite, meus caros
Estou com a dificuldade no seguinte, pretendo que o usuário receba um aviso quando a textfield estiver vazia e se o mesmo apertou no botão.
tentei com a condição if (textFiel.text == "") mais não deu certo, agradeço a nossa ajuda.
@IBAction func botton(_ sender: Any) {
let celcius = Float(textFiel.text!)!
let Fahrenheit:Float = (9 * celcius + 160) / 5
label.text = "\(Fahrenheit)"
if (textFiel.text == "") {
label.text = "Por favor digite algo"
}
}
|
Outra sugestão é usar o comando _guard_ :
@IBAction func botton(_ sender: Any) {
guard !((textField.text ?? "").isEmpty) else {
label.text = "Por favor digite algo"
return
}
let celcius = NSString(string: textField.text!).floatValue
let Fahrenheit:Float = (9 * celcius + 160) / 5
label.text = "\(Fahrenheit)"
}
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "ios, swift"
}
|
Is there any C++ library to work with WMI?
I'm working on a big project that have to poll remote WMI counter. I have to code a Win32 app in C++ to query WMI from remote Windows systems. So, Is there any C++ library (free or paid) help me to work with WMI ? Please help me.
Thanks so much :)
|
You can use the `WMI Delphi Code Creator` to generate C++ code to access the WMI (Windows Management Instrumentation) classes, events and methods.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c++, wmi, static libraries"
}
|
www. в доменном имени
Как можно сделать, чтобы при наборе домена без www. впереди например < он менялся на < то есть впереди само подставлялось www.?
|
Пропишите в .htaccess:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule (.*) < [R=301,L]
домен соответственно Ваш.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "домен"
}
|
Select dots on image and modify the color of some of them
I make a dotted map just like the one on the image below. I am using Illustrator and Photoshop.
How can I select and re-color some of the dots on this image?
!
|
In Photoshop, select one of the dots with the Magic Wand tool, then choose _Select > Similar_. This will select all the dots.
Use _Layer > New > Layer via Copy_ to make a new layer from these dots, then in the Layers Panel, click the checkerboard icon next to the word Lock. This will prevent painting from leaking out of the dot area.
All you have to do now is to choose a colour, switch to the Brush tool and select a hard-edged brush, and paint the dots on the new layer. Only the dot area will be coloured.
|
stackexchange-graphicdesign
|
{
"answer_score": 3,
"question_score": 0,
"tags": "adobe photoshop, adobe illustrator"
}
|
Let $f:A→B$ be an onto function and let $T⊆B$. Prove that $(f◦f^{-1})(T) =T$
Let $f:A→B$ be an onto function and let $T⊆B$. Prove that $(ff^{−1})(T) = T$
How would I go about proving this?
> Let $x$ be an element of $(ff^{−1})(T)$.
>
> By the definition of composition/composite functions, $\text{Dom}(ff^{−1}) = \text{Dom}(f)$ and the $\text{Ran}(ff^{−1}) = \text{Ran}(f^{-1})$.
>
> By the definition of the inverse, the range of $f^{-1}$ is the domain of $f$.
>
> Thus $(ff^{−1})(T)$ is a function from $A$ to $A$. (?)
I can't get much past this. My prof hinted to using double containment but I can't get past the first part.
|
An important point here is that $f^{-1}(z)$ must be treated as a _set_ , whereas $f(w)$ is a single _element_.
Note that
$(f \circ f^{-1})(T) = f(f^{-1}(T)). \tag 0$
Let
$z \in (f \circ f^{-1})(T) = f(f^{-1}(T)); \tag 1$
then in accord with (0) there is some
$w \in f^{-1}(T) \subset A \tag 2$
with
$z = f(w); \tag 3$
but (2) implies
$f(w) \in T; \tag 4$
thus,
$z \in T, \tag 5$
and
$f(f^{-1}(T)) \subset T; \tag{5.5}$
to go the other way, observe that
$z \in T \tag 6$
with
$w \in f^{-1}(z) \subset f^{-1}(T) \tag 7$
yields
$z = f(w) \in f(f^{-1}(T)) \subset T; \tag 8$
this shows
$T \subset f(f^{-1}(T)); \tag 9$
(5.5) and (9) together imply
$T = f(f^{-1}(T)), \tag{10}$
the requisite result.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 2,
"tags": "real analysis, discrete mathematics, elementary set theory"
}
|
Расширение chrome на сервере
Вопрос, можно ли как-то запустить расширение, чтобы оно 24/7 работало, если есть Ubuntu сервер, может есть варианты через PHP или JS например? Нужно чтобы расширение постоянно парсило страничку, так как через PHP до нее не добраться по неизвестным причинам. Вот этот json нужен <
|
Что вы имеете ввиду под фразой "не добраться"?
$data = json_decode(file_get_contents(' true);
print_r($data);
никаких проблем
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "php, javascript, ubuntu, сервер, расширения"
}
|
Encrypted string to Byte Array
I'm encrypting a string using this function;
$encrypted_body = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, utf8_encode($body), MCRYPT_MODE_CBC, $iv);
//Encrypting using MCRYPT_RIJNDAEL_256 algorithm
I then get my encrypted string.
What i need to do next is convert this string into a Byte Array. How do I do this? I've played with the pack/unpack features but am not having any luck!
Any help would be great.
Thanks in Advance!
|
PHP does not have byte arrays. What other languages call byte arrays are just a string of bytes one after the other, which can be accessed by their offset. PHP _strings_ in fact do the same thing:
$encrypted_body[0] -> first byte
$encrypted_body[1] -> second byte
$encrypted_body[n] -> n+1th byte
So, just use PHP strings for the same purpose.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php"
}
|
convert string to object with number of occurances
I have tried to write a function to do this:
return the number of occurances of each letter of a string in an object case insensitive // eg. numOfOccurances('This is great') => { t: 2, h: 1, i: 2, s: 2, g: 1, r: 1, e: 1, a: 1 }
function numOfOccurances(string) {
const stringLower = string.replace(/ /g, '').toLocaleLowerCase();
const counts = {};
let ch;
let count;
let i;
for (i = 0; i < stringLower.length; i++) {
ch = stringLower.charAt(i);
count = counts[ch];
counts[ch] = count ? count + 1: 1;
}
console.log(stringLower);
console.log(counts);
}
(it currently outputs console so i can see the output).
the output i get is:
Object {t: 2, h: 1, i: 2, s: 2, g: 1…}
a:1
e:1
g:1
h:1
i:2
r:1
s:2
t:2
|
What you're getting should be the expected result. I get the same thing in chrome devtools.
`Object {t: 2, h: 1, i: 2, s: 2, g: 1…}` Objects with many properties get abbreviated, thus the ellipsis. You are then able to click to expand the object and view the full list of properties.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, object"
}
|
Difference between 会いに vs 会って
What's the difference between these two ways of saying "I'm driving to meet a friend"?
> ****
>
> ****
Is this the difference between between V-stem and V-te conjunctives, one is written and the other colloquial?
|
In the form (continuative form)++(motion verb), the can be , , , , , , , etc.
> "go to see" "come to see" "come back to see" ...
> sounds incorrect.
Related threads:
* [Is it true that only movement verbs can take [V-stem] to express a purpose?](
* When can you use (masu stem) + (another verb)
* Usage of after verbs
* * *
would be interpreted as "I met my friend and am driving."
To say "I'm driving to meet my friend", I would probably say...
> () _lit._ I'm (on my way) going to meet a friend by car.
|
stackexchange-japanese
|
{
"answer_score": 4,
"question_score": 4,
"tags": "usage"
}
|
Массовый UPDATE в MySQL для нескольких условий
Пытаюсь реализовать массовый UPDATE, но не могу понять как его сделать для нескольких условий. Сейчас данный запрос выполняется в цикле.
UPDATE product_tara_test
SET price = ?, date_import = UNIX_TIMESTAMP(NOW())
WHERE id_product = ? AND id_stockroom = ?
Т.к. на каждую итерацию происходит запрос, время выполнения скрипта существенно торомзит из-за этого.
Пытаюсь реализовать через **CASE** Собрав динамически запрос, но не могу понять как его сделать по нескольким условиям:
**WHERE id_product = ? AND id_stockroom = ?**
UPDATE `product_tara_test` SET price = CASE
WHEN id_product = 1 THEN 100
...
END,
date_import = CASE
WHEN id = 1 THEN UNIX_TIMESTAMP(NOW())
....
END,
WHERE id_product in (1,2,3....) AND id_stockroom IN (1, 1, 1....)
|
UPDATE product_tara_test P
JOIN (
select ? as id_product, ? as id_stockroom, ? as price
union all
select ? as id_product, ? as id_stockroom, ? as price
...
) D
ON P.id_product=D.id_product and P.id_stockroom=D.id_stockroom
SET price=D.price, date_import = UNIX_TIMESTAMP(NOW())
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "mysql"
}
|
Speed comparison between DRAM, HDD, and flash memory
The question:
> Assume that cache memory is ten times faster than DRAM memory, that DRAM is 100,000 times faster than magnetic disk, and that flash memory is 1,000 times faster than disk. If it takes 2 microseconds while reading from cache memory, how long does it take to read the same file from DRAM, disk, and flash memory?
Does this require only simple algebra, or are there any complex computations needed?
|
Given time equivalencies:
1,000 flash = disk
100,000 dram = disk
1,000,000 cache = disk (substituted from 10 cache = dram)
Now given cache = 2µs:
disk = 1,000,000 * 2µs = 2s
dram = 2s / 100,000 = 20µs
flash = 2s / 1,000 = 2ms
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "memory, ram"
}
|
Boto3 - Create S3 'object created' notification to trigger a lambda function
How do I use boto3 to simulate the `Add Event Source` action on the AWS GUI Console in the `Event Sources` tab.
I want to programatically create a trigger such that if an object is created in `MyBucket`, it will call `MyLambda` function(qualified with an alias).
The relevant api call that I see in the Boto3 documentation is `create_event_source_mapping` but it states explicitly that it is only for AWS Pull Model while I think that S3 belongs to the Push Model. Anyways, I tried using it but it didn't work.
Scenarios:
* Passing a prefix filter would be nice too.
|
I was looking at the wrong side. This is configured on S3
s3 = boto3.resource('s3')
bucket_name = 'mybucket'
bucket_notification = s3.BucketNotification(bucket_name)
response = bucket_notification.put(
NotificationConfiguration={'LambdaFunctionConfigurations': [
{
'LambdaFunctionArn': 'arn:aws:lambda:us-east-1:033333333:function:mylambda:staging',
'Events': [
's3:ObjectCreated:*'
],
},
]})
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 5,
"tags": "amazon web services, amazon s3, lambda, boto3"
}
|
XSS, encoding a return url
Here is the vulnerable code
<?php header("Location: ".$_POST['target']); ?>
What is the appropriate way to make sure nasty things that come in to target are cleaned?
|
**First up, this is a vulnerability**
OWASP categorizes it as "Unvalidated Redirects and Forwards". See OWASP's guide for more information.
A few interesting attacks are possible. See this thread on sla.ckers.org for ideas on how this can be abused.
**How do you protect yourself?**
* Verify the scheme of the URL. You usually only want to support http and https. Abort the request for any other scheme.
* Parse the URL, and extract the domain. Only allow redirects to known list of domains. For other domains, abort the request.
That's about it.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 4,
"tags": "php, html, security, xss"
}
|
select value from object in javascript
Hi I am getting dificulties to select value from this dictionary,
my object
[{id: "063f48d0-1452-4dad-8421-145820ddf0f8",
storeName: "birr",
cost: {
4fd5ee28-835d-42dc-85a6-699a37bc1948: "54",
f45827c8-1b1a-48c3-831b-56dab9bcaf3b: "543"
},
saved: true}]
I need to get cost of 54 somehow.
please help
|
<script>
var arraylist = [{'id': "063f48d0-1452-4dad-8421-145820ddf0f8",
'storeName': "birr",
'cost': {
'4fd5ee28-835d-42dc-85a6-699a37bc1948': "54",
'f45827c8-1b1a-48c3-831b-56dab9bcaf3b': "543"
},
'saved': true}];
var costKey = '4fd5ee28-835d-42dc-85a6-699a37bc1948'
var selectedCost = arraylist[0]['cost'][costKey];
alert(selectedCost);
</script>
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -3,
"tags": "javascript"
}
|
Proportion with ggplot geom_bar
What is the simplest way to do with ggplot the same as done here:

y <- c("exercise1", "exercise2", "exercise3", "exercise1", "exercise2", "exercise3", "exercise1", "exercise2", "exercise3")
dt <- data.frame(x, y)
ggplot(dt, aes(x, fill = y)) + geom_bar()
|
This is a similar question to this previous one here. You can use the `position = "fill"` argument within ggplot to scale bars to 100% height. The `scale_y_continuous(labels = scales::percent)` command changes the frequency scale from 0-1 to 0-100%.
library(ggplot2)
x <- c("good", "good", "bad", "bad", "bad", "bad", "perfect", "perfect", "perfect")
y <- c("exercise1", "exercise2", "exercise3", "exercise1", "exercise2", "exercise3", "exercise1", "exercise2", "exercise3")
dt <- data.frame(x, y)
# Build plot
ggplot(dt, aes(x, fill = y)) +
geom_bar(position = "fill") +
scale_y_continuous(labels = scales::percent)
 route for view specs?
As a side note, is there any way to specify a nested resource to the Rails 3 controller scaffold generator?
|
The test looks ok to me...
By any chance do you have a form on your eggs/index.html.erb for creating new eggs that might not yet be wired up correctly? It seems it may be trying to render the index view but failing because the view is trying build a route that doesn't exist? You'd want to make sure that the form is using the correct nested resource route. Does the view render when you load it up in the browser?
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 7,
"tags": "ruby on rails 3, rspec2"
}
|
Converting some columns into indicator variables after grouping by another column
I'm creating a _k-nn_ model and I need to reorganize my dataset into a nice euclidean vectors.
My dataset looks like the one below
data = pd.DataFrame({'orderID': [1, 1, 2, 2],
'productID': [1, 3, 1, 2]})
which yields
orderID productID
0 1 1
1 1 3
2 2 1
3 2 2
I would like to group my data by _orderID_ and then create a vector which would store the information the products which were bought in each order. So I need something like this dataframe
orderID prod_1 prod_2 prod_3
0 1 1 0 1
1 2 1 1 0
Is there any "built-in" method to achieve that?
Regards!
|
Try this:
In [84]: data['prod_name'] = 'prod_' + data.productID.astype('str')
In [105]: data.pivot_table(index='orderID', columns='prod_name', values='productID', aggfunc=len).fillna(0).reset_index().rename_axis(None, axis=1)
Out[105]:
orderID prod_1 prod_2 prod_3
0 1 1.0 0.0 1.0
1 2 1.0 1.0 0.0
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python, pandas, dataframe"
}
|
AspectJ: how to get a Thread name?
I need to get Thread names and log them in AspectJ class. This solution does't work
`@Around("call(void method*())")
public Object condition(ProceedingJoinPoint joinPoint) throws Throwable
{
PropertyConfigurator.configure("log4j.properties");
long before = System.currentTimeMillis();
Object res = joinPoint.proceed();
long diff = System.currentTimeMillis() - before;
logger.info(Thread.currentThread().getName() + "\t" + diff );
return res;
}
` because the result is e.g.:
`main 717`
My aspect is `around` some methods. How to get name of thread where method is executed (not thread created by aspect)?
|
**1.** First of all its **Not the thread where method is execute** , But **the thread that executes the method.**
**2.** Here what you can do to **identify** the thread that **executed** that method:
**\- Initialize the thread.**
Thread t = new Thread(MyClass);
// MyClass is the class which extends or implements Thread or Runnable respectively.
**\- Naming the thread of execution.**
t.setName("T1");
**\- Inside the method getting the thread that is executing it.**
public void go(){
Thread.currentThread().getName();
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "java, multithreading, logging, log4j, aspectj"
}
|
Glassfish: How to do asadmin commands without password?
every time I enter a CLI-command for glassfish like this `asadmin start-instance i1` I am prompted to enter the admin-username and admin-password.
How can I disable the need for entering these credentials?
I plan to write scripts for running commands like this and I think it's not possible to enter the credentials in a bash script.
Thanks
|
You can set the password from a file instead of entering the password at the command line.
The --passwordfile option takes the file containing the passwords:
AS_ADMIN_PASSWORD=value
AS_ADMIN_ADMINPASSWORD=value
AS_ADMIN_USERPASSWORD=value
AS_ADMIN_MASTERPASSWORD=value
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 6,
"tags": "linux, glassfish"
}
|
Listing stackoverflow questions with most views for a given tag (ex: maven)?
> **Possible Duplicate:**
> How do I sort the questions by the number of views?
Is it possible to create/obtain a list of stackoverflow questions having the most views for a given tag? I know it is possible to get a list with most votes, but that is not the same thing. Thanks.
|
You can get a list of questions using a tag, and with a minimum number of views, for example with [[maven] views:10000]( It doesn't allow you to sort the answers by the number of views, and it doesn't allow you to set a range, though.
|
stackexchange-meta
|
{
"answer_score": 6,
"question_score": 2,
"tags": "discussion"
}
|
Env vars for Visual Studio command prompt
I'm doing an RDP into a machine that has just the CLR installed, and doesn't have Visual Studio on it. Can I somehow load all the Visual Studio-specific environment variables on to the regular command prompt and convert it into the VS command prompt so that I'm able to build my projects via command line?
I looked at the `vcvarsall.bat` file. That calls the appropriate processor-specific batch file. Couldn't get any inputs from there.
|
Short of installing all VS, or tracing thru all the various batch files to find out what's getting set, you may be able to simply capture the env vars that are set.
Open up a VS command prompt, and run `set > vars.bat`
Then open up vars.bat, and put a set command in front of each line.
Not sure how much this will help, since you're going to be missing all the utilities that come with Visual Studio, but it does answer your question.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "visual studio"
}
|
Maximum transmission range with SimpleObstacleShadowing in Veins
I would like to understand which is the maximum transmission range (maximum distance beetween two vehicles exchanging messages) having set the SimpleObstacleShadowing analogue model.
So I read this article and I would like to exploit formula (6) to reach my purpose. Unlikely I didn't understand if the attenuation got by obstacles (Lobs[dB]) is given in Veins or through which parameters I can actually compute it.
I also read this post but I think those formulas do not hold for this model.
Thanks so much
|
The maximum distance between two nodes in the network is calculated by the _SimplePathLoss_ model. It calculates the distance according to the used transmission frequency and MCS.
The _SimpleObstacleShadowing_ additionally adds attenuation if the transmitted message hits an obstacle.
Both are analogue models and can be configured via the config.xml which is read by the _Decider_ module of the physical layer.
**_Update:_** Also there is the _maxInterfDist_ parameter which determines the distance an ideal communication can have at most.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "veins"
}
|
Jsoup, parse html table
This is probably dumb question, but I can't really figure it out. I'm trying to parse html output from page: <
So basically I need to extract values from table, from left side (blue text) as keys(headers) and from right side (brown text) as values. Additionaly, header labels ("Aktualna pogoda/Weather conditions: ")
My intention is to get html table from html output and then parse its row, but I can't figure it out, because html output is rather complicated. I'm starting from it:
doc = Jsoup.connect("
Elements tables = doc.select("table");
for (Element row : table.select("tr"))
{
Elements tds = row.select("td:not([rowspan])");
System.out.println(tds.get(0).text() + "->" + tds.get(1).text());
}
But still my result is a mess. Do you have any ideas how to parse it correctly?
|
keys data from first table can be retrieved by this code:
doc.select("table").get(1).select("tbody").get(1).select("tr").get(1).select("td").get(0).select("b")
and value by this:
doc.select("table").get(1).select("tbody").get(1).select("tr").get(1).select("td").get(1).select("b")
**for second table**
doc.select("table").get(2).select("tbody").get(0).select("tr").get(1).select("td").get(0).select("b")
and
doc.select("table").get(2).select("tbody").get(0).select("tr").get(1).select("td").get(1).select("b")
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "java, web scraping, html table, jsoup"
}
|
Set VM's $PATH via Puppet config.yaml or Vagrantfile?
I would like to add an additional path to my VM's $PATH environment variable through use of my puppet `config.yaml` or `Vagrant` file (or some other VM external mechanism that I don't know).
Is this possible? If so, how?
|
In Vagrant you can easilly provision stuff with a shell script. So first, create a script (in the same folder than your Vagrantfile) that add additional path to `$PATH`. By exemple, create a file called `bootstrap.sh` with this content :
export PATH=$PATH:/foo/bar
# Or if you want it for all users :
echo 'PATH=$PATH:/foo/bar' >> /etc/profile
Then in your `Vagrantfile`, add this line to execute this script when the VM is booted :
config.vm.provision :shell, path: "bootstrap.sh"
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "vagrant, puppet, vagrantfile"
}
|
Handling expected supervisord exit codes
I am using `supervisord` inside a Docker container to manage my running processes and would like to also use it to trigger certain commands - run them once and expect them to exit with `0`.
Here's one example:
[program:central-seed-posts]
command = /usr/bin/php /var/www/app/artisan post
autostart = false
autorestart = false
startsecs = 3
startretries = 0
exitcodes = 0
stderr_logfile=/tmp/central/posts-stderr-supervisor.log
stdout_logfile=/tmp/central/posts-stdout-supervisor.log
And I'm using nsenter's `docker-enter` with `supervisorctl start central-seed-posts` to trigger it but I would also like to handle a successful exit instead of supervisor telling me `ERROR (abnormal termination)`
Does it have to do with supervisor events ?
|
Problem you are encountering seems to be with the following option you use:
startsecs = 3
If you read manual of supervisord, you can see that startsecs sets for how long the process has to stay alive after a startup for Supervisord to consider the start successful. Your process is probably exiting before 3 secs, which suggests to supervisord that startup was not successful.
Try lowering that to 0, unless you have a real reason to keep it 3 sec.
|
stackexchange-serverfault
|
{
"answer_score": 6,
"question_score": 3,
"tags": "centos, supervisord"
}
|
Add Developers in Xcode
Assume I have an Xcode project running on Github and multiple developers. I have a new developer who will clone the git repository and start working on the app. I want to add his iOS devices as devices that can run the builds without having to reissue certificates and do all that long process on the iOS Dev Center. How can I do that? I want him to clone the repo, connect his device to Xcode and be able to run the app on his device.
Thanks
|
If he is a paid iOS developer and there is no reason to use a specific provisioning profile you won't need to do anything. Xcode can automatically provision his device when he compiles it. Just use the automatic profile selection for your development builds in the build settings.
If it is important that you both use the correct provisioning profile (for example to test push notifications) there is no way around adding his device to the profile on the developer portal. Plus you will need to let him sign the binary as you, using your developer certificate and private key (which you will have to export from Keychain on your development machine).
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ios, xcode, provisioning, beta testing"
}
|
Why isn't assertRaises catching my Attribute Error using python unittest?
I'm trying to run this test: `self.assertRaises(AttributeError, branch[0].childrennodes)`, and `branch[0`] does not have an attribute `childrennodes`, so it should be throwing an `AttributeError`, which the `assertRaises` should catch, but when I run the test, the test fails because it is throwing an `AttributeError`.
Traceback (most recent call last):
File "/home/tttt/../tttt/tests.py", line 504, in test_get_categories_branch
self.assertRaises(AttributeError, branch[0].children_nodes)
AttributeError: 'Category' object has no attribute 'children_nodes'
Any ideas?
|
I think its because assert raises only accepts a callable. It evalutes to see if the callable raises an exception, not if the statement itself does.
self.assertRaises(AttributeError, getattr, branch[0], "childrennodes")
should work.
EDIT:
As THC4k correctly says it gathers the statements at collection time and will error then, not at testing time.
Also this is a reason why I like nose, it has a decorator (raises) that is useful and clearer for these kind of tests.
@raises(AttributeError)
def test_1(self)
branch[0].childrennodes
|
stackexchange-stackoverflow
|
{
"answer_score": 22,
"question_score": 25,
"tags": "python, django, unit testing"
}
|
How do I set the windows default printer in C#?
How do I set the windows default printer in C#.NET?
|
Using the SetDefaultPrinter Windows API.
Here's how to pInvoke that.
|
stackexchange-stackoverflow
|
{
"answer_score": 20,
"question_score": 24,
"tags": "c#, windows, printing"
}
|
Set up java environment variable value using bat command permanently
I write a bat script to set java path in envirnment variable. I use following command to set path -
setx PATH=%jdkDirDest%\bin;%PATH%.
setx PATH=%playDirDest%;%PATH%.
set PATH=%jdkDirDest%\bin;%PATH%.
set PATH=%playDirDest%;%PATH%.
It works fine when I am working with current session But what happen if I closed current command prompt and again open and run following command
java -version
javac etc.
It shows no java version is intall in this system
Can any one sugest me what code I use to set these environment path permanently to my matchine using bat command.
** I need bat command.
|
You have to use **setx** without the ' **=** ', and **set** with it. Also use quotes for the values of the environment variables
setx PATH "%jdkDirDest%\bin;%PATH%"
setx PATH "%playDirDest%;%PATH%"
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "java, batch file, cmd, command"
}
|
How do you give an .exe an ico image in Visual Studio?
I have the application using an .ico image for the taskbar and window, but how do you set up the .exe to use an icon?
While on this subject does anyone have any resources on how to work with ico images? As in what size does the start bar use, and so forth?
From what I can find there are tools out there to assign .exe's icon images but this is surely not the correct way of doing things.
Thanks in advance.
|
You can change the application icon from Common Properties -> General -> Application Icon
|
stackexchange-stackoverflow
|
{
"answer_score": 22,
"question_score": 10,
"tags": "c#, .net, visual studio, icons"
}
|
Is this ammeter and power reading correct?
Is the ammeter reading 2A and the power absorption 100W or did I calculate this incorrectly?
;
$args2 = array('var3', 'var4', 'var5', 'var6');
foreach ($args2 as $arg) {
$args[] = $arg;
}
|
Yes, **`array_merge()`**.
>
> array array_merge ( array $array1 [, array $... ] )
>
>
> Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array.
>
> If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
>
> Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "php"
}
|
Replace character in string in specific position (ie not first, not all)
I would like to replace one character in a string with an uppercase of the same character. Is there an elegant way to do this? Eg I have 'Donald Mcdonald' and I would like to uppercase the first 'd' in 'Mcdonald' so I end up with 'McDonald'
The string.replace function only gives the option to replace first or all. If I use the code below it obviously won't work.
if(name.containsIgnoreCase(' mc')){
integer mc = name.indexOfIgnoreCase(' mc') + 3;
name = name.replaceFirst(name.mid(mc, 1), name.mid(mc,1).toUpperCase());
}
|
Thanks to @sfdcfox for the platform to build on. This is what I eventually ended up with which works perfectly for a string with multiple occurrences.
Pattern mcprefix = Pattern.compile('(?i)( ?ma?c)(\\p{L}+|\\P{L}+)');
list<string> names = name.split(' ');
list<string> fixednames = new list<string>();
for(string n : names){
Matcher m2 = mcprefix.matcher(n);
while(m2.find()) {
String g1 = m2.group(1), g2 = m2.group(2);
Integer start = n.indexOf(g1 + g2);
if (start == 0 || n.substring(start - 1, start).isWhitespace())
n = n.replaceFirst(g1 + g2, g1 + g2.capitalize());
}
fixednames.add(n);
}
name = String.join(fixednames, ' ');
|
stackexchange-salesforce
|
{
"answer_score": 0,
"question_score": 1,
"tags": "apex, string, substring, replace"
}
|
Инициализация вектора в структуре
Есть такая структура:
typedef unsigned char byte;
struct A
{
int a;
byte b;
std::vector<int>z;
}
Хочу написать метод для инициализации нулём полей структуры.
void setZero()
{
memset(this,0,sizeof(A));
}
Вот только с вектором проблема. Нельзя так делать. А как можно, не понимаю.
|
Нужно просто добавить конструктор, в котором все поля занулить. Вектор занулять никак не нужно, т.к. он по умолчанию пустой и готовый к работе.
A::A() : a(0), b(0) {}
Если конструктор не приемлем, если нужно именно внешней функцией занулить, тогда просто нужно занулить каждое примитивное поле:
void Zeroize(A & a) {
a.a = 0;
a.b = 0;
}
Также в C++11 можно писать инициализацию полей прямо в структуре.
struct A {
int a = 0;
byte b = 0;
std::vector<int> z;
};
По поводу `memset()`, таким методом можно занулять структуры, у которых все поля примитивные (числа, Си массивы). Если хоть одно поле представляет сложный класс, например _STL_ класс, тогда занулять всё нельзя. В этом случае через `memset` можно занулять отдельные члены, которые примитивные.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c++"
}
|
Loading webview (to display website) in iOS application
I'm new to iOS development.
Inside my app (iOS native app), on clicking one tab, I need to load a website using webview inside the application just like using browserField in Blackberry. The website will be used to make some transactions/payments.
If this is done, will there be any problem publishing the app in iStore as the website included will be used for secure transactions.
|
You should use In-App purchase for payments which intend to purchase content, functionality, or services in your app.
If your app implements any external payment system/services for purchasing any of above, your app will violate the app-store guidelines and hence will be rejected.
For more info please read through App Store Review Guidelines section 11 "Purchasing and currencies". You will need to login with your AppleId.
Hope that helps!
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "ios, iphone, webview, app store"
}
|
Creating a string array in jsfl for flash cs6
I have a simple problem while creating array.Below is the example.
var names:Array = new Array();
trace(names.length); // output: 0
While running the code I am getting the following error
SyntaxError: missing ; before statement
Plz guide me.I am running this code in Flash cs6
|
Your code looks like a regular AS3 code, but JSFL has its own features, which are different from AS3. Here an example of the same code, but for JSFL:
var names = [];
fl.trace(names.length);
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "flash, flash cs6, jsfl"
}
|
Integrate NPS in an email and retrieve data
I would like to send a triggered email with NPS inside it. As I understand it is not possible to integrate Javascript into an email. The solution would then be to have 10 different images. My question is, what is the best way to retrieve data? Can I make one unique cloud pages which can recover the image clicked by the user? And do I have to make 10 different cloud pages depending on the image clicked? Or maybe there is other solutions?
Thanks!
|
You can add a parameter to the URL, e.g. `?nps=1` which differs between images. You will then just need a single Cloud Page, and use RequestParameter function, to get the value from nps parameter.
Then it's up to you whether you want to differentiate content on the landing page accordingly, or just store the value.
|
stackexchange-salesforce
|
{
"answer_score": 3,
"question_score": 1,
"tags": "marketing cloud, email, cloudpage, email studio, survey"
}
|
Regex automation for replace javascript hex string into HTML entities string
I have some strings like the following one:
\x63\x68\x69\x6C\x64\x72\x65\x6E
and I like to convert that string in the following form:
children
by using a single regex.
Currently I am using this one:
\\
and I am doing the replacement of the `\` with the value `;&#`.
Unfortunatelly, this returns the following result:
;children
_Note that the result starting with the greek question mark and ends without the greek question mark_
So, is there any better way to replace the `\` with `;&#` but without the result starting with the `;` and finally the result ending with `;` ?
|
Match the following regex:
`\\(\w+)`
and replace with:
`&#\1;`
Result: `children`
## Demo
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, php, regex, string"
}
|
Are FTP accounts available in VestaCP for free?
I'm planning to deploy VestaCP on a VPS hosted in OVH. I know that VestaCP needs a license for the file manager. Does it include free FTP accounts to manage my future site in WordPress? Do I need to pay for the use of FTP accounts?
|
The pricing page says:
> All core functionality is free.
and only lists a chroot sFTP package for sale. The features page lists VsFTPD or ProFTPD under the core features.
I take this to mean that VsFTPD and ProFTPD are included as part of the free core features. You would only need to pay for the chroot sFTP if you want to give users access to sFTP without allowing them to see content outside their home directory.
|
stackexchange-webmasters
|
{
"answer_score": 0,
"question_score": 2,
"tags": "web hosting, vps"
}
|
Frequency response based on a transfer function
The transform function: $$T(s) = \frac{1-sRC}{1+sRC}$$ Polynomial form: $$-\frac{s-\frac{1}{RC}}{s + \frac{1}{RC}}$$ Since magnitudes of the zero _Sn = 1/RC_ and pole _Sp = -1/RC_ are equal,amplitude gain is 0. What about the phase? How does '-' sign affect the phase?
Without the minus: **Sn** i positive and real and has a \$\Pi\$ phase while the negative **Sp** has a \$0\$, at \$\omega=0\$.
As \$\omega\rightarrow\infty\$, \$\pi \rightarrow \pi/2\$ and \$ 0\rightarrow\pi/2\$. After subtracting the phases from zero and poles we have that phase changes from \$\pi\rightarrow0\$.
What does the minus affect?
|
!schematic
simulate this circuit - Schematic created using CircuitLab
Here is a schematic of a first-order allpass. As one can see, the phase starts at 0 deg (cap is open circuit) and goes to negative values (low pass response). For very large frequencies, the non-inv. input is grounded and we have negative unity gain (inverter) - equivalent to -180deg phase shift.
The transfer function is
**H(s)=(1+R/R)/(1+sRC) -R/R; H(s)=(1-sRC)/(1+sRC)**
|
stackexchange-electronics
|
{
"answer_score": 1,
"question_score": 1,
"tags": "frequency, transfer function"
}
|
Partial sum of dataframe
If I have
year veg number
2017 aubergine 3
2017 tomato 13
2017 eggplant 4
2018 aubergine 1
2018 tomato 17
2018 eggplant 3
how can I sum the data for `aubergine` and `eggplant` for each year to get
year veg number
2017 aubergine 7
2017 tomato 13
2018 aubergine 4
2018 tomato 17
?
|
One way would be to `replace` `"eggplant"` to `"aubergine"`, then `group_by` `year` and `veg` and take `sum`.
library(dplyr)
df %>%
mutate(veg = replace(veg, veg == "eggplant", "aubergine")) %>%
group_by(year, veg) %>%
summarise(number = sum(number))
# year veg number
# <int> <fct> <int>
#1 2017 aubergine 7
#2 2017 tomato 13
#3 2018 aubergine 4
#4 2018 tomato 17
In base R, that can be done with `transform` and `aggregate`
aggregate(number~year + veg,
transform(df, veg = replace(veg, veg == "eggplant", "aubergine")), sum)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "r, dataframe, sum"
}
|
PostGIS create table with multiple geometry
I want to create a table with a geometry field in it. e.g.:
CREATE TABLE ptgeogwgs(gid serial PRIMARY KEY, geog geography(POINT) );
In my case, this geometry field can either be a POINT, a LINESTRING or a POLYGON. I couldn't find any examples where that unique column could take three different types. So I guess the type of geometry should be fixed in advance. Nonetheless, is is better to create one table for each geometry type or create multiple columns, one for each geometry type.
Furthermore, if I choose for the second option, are the two empty geometry fields stored as "null" and therefore taking some memory space or doesn't empty fields in PostGIS table take any space?
|
You can define a generic _geometry_ type `GEOMETRY` (not to be confused with the actual _column data type_!), i.e.
CREATE TABLE ptgeogwgs (
gid SERIAL PRIMARY KEY,
geog GEOGRAPHY(GEOMETRY, 4326)
);
to let the `geog` column accept all _geometry types_. Note that for `GEOGRAPHY`, if left blank, the CRS will be set to `EPSG:4326` by default.
* * *
Client applications usually deny the work with a single generic _geometry type_ column as well as multiple geometry columns in one table!
|
stackexchange-gis
|
{
"answer_score": 4,
"question_score": 1,
"tags": "postgis, postgresql, sql, geometry"
}
|
tomcat 6 taking a long time to shutdown
tomcat 6.32 on linux takes a long time to shutdown, why? A webapp might be resource intensive, but still doesn't justify a 10 minute shut down time. what can be done to fix it?
|
Tomcat will keep running while until all non-daemon threads die.
Do a `kill -3 pid` (on Unix) to see what threads are running.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "tomcat"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.