INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Could not load file or assembly 'MySql.Data' the parameter is incorrect
I keep getting this exception when I start my program.
`System.IO.FileLoadException: Could not load file or assembly 'MySql.Data, Version=8.0.13.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d'. The parameter is incorrect. `
Somewhere I read it could be caused by a corrupted package: I have tried to reinstall the NuGet package, but it's still not working.
NOTE: I'm not using Visual Studio, I'm coding a .NET Core class library using Jetbrains Riders on a Linux computer. | Try using an older version of MySql. Use the NuGet-Manager and download version 6.8.8 of MySql.Data, always worked for me. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "c#, mysql, .net"
} |
How to rank a record with same weight in MySQL
Suppose I have a data say:
Name | Marks
StudentA | 90
StudentB | 85
StudentC | 85
StudentD | 70
now StudentA will get 1st Rank, StudentB and StudentC will get 2nd Rank and Student D will get 4th Rank.
I know the basic rank computation if there are no duplicate weights, but how to handle if we encounter 2 similar weights as in this case there are two 85 marks which will share rank 2. | Using Giorgos's fiddle...
SELECT name
, marks
, FIND_IN_SET(marks, (SELECT GROUP_CONCAT(marks ORDER BY marks DESC) FROM mytable)) rank
FROM mytable;
| Name | Marks | rank |
|----------|-------|------|
| StudentA | 90 | 1 |
| StudentB | 85 | 2 |
| StudentC | 85 | 2 |
| StudentD | 70 | 4 |
<
or
SELECT name, marks, rank
FROM (SELECT name
, marks
, @prev := @curr
, @curr := marks
, @i:=@i+1 temp
, @rank := IF(@prev = @curr, @rank, @i) AS rank
FROM mytable
, ( SELECT @curr := null, @prev := null, @rank := 0, @i:=0) vars
ORDER
BY marks DESC,name
) x
ORDER
BY marks DESC,name
< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "mysql, mysql variables"
} |
How to do subtractions in a list in R?
I have a list of 25 data frames. My goal is to do a subtraction of one column from another in each list. For example:
a1 <- list(mtcars[1:5,], mtcars[6:10,])
I have to calculate `drat` \- `wt` and make a new column to show to results. Like this:
[[1]]
mpg cyl disp hp drat wt qsec vs am gear carb Results
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 1.28
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 1.025
[[2]]
mpg cyl disp hp drat wt qsec vs am gear carb Results
Valiant 18.1 6 225.0 105 2.76 3.46 20.22 1 0 3 1 -0.70
Duster 360 14.3 8 360.0 245 3.21 3.57 15.84 0 0 3 4 -0.36
I could not figure it out. Could someone help? Thanks! | `a2` is a list with all the same data frame in `a1` except that one column `Results` is updated.
a1 <- list(mtcars[1:5,], mtcars[6:10,])
a2 <- lapply(a1, function(dt){
dt$Results <- dt$drat - dt$wt
return(dt)}) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "r, list"
} |
port mac application to ios
Is it possible to port mac source code to ios (iphone and ipad) easily. The mac application is using both C and Objective C languages. What i asssume is to create xib files for mac nib files, and port the code for ios. Any suggestions??? Cheers | Yes, it's possible. How hard it is depends on how heavily your desktop app relies on a keyboard, mouse and a large screen. In general, porting an app from the desktop to a mobile device is far from trivial, for reasons that have nothing to do with the portability of APIs and project files. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "iphone, objective c, ipad, macos"
} |
Hover on span inside div, show other element
I wanted the div id='cancelReq' to be displayed when the mouse hover at span id='requestSent'
I've tried this code, but it's not working.
<style>
#cancelReq {
display: none;
}
#requestSent:hover + #cancelReq {
display: block;
}
</style>
<div id='addUser'>
<span id='requestSent'>Add Friend</span>
</div>
<div id='cancelReq' >hello there</div> | You can use the javascript for that. Here is the code for your problem:
<script type="text/javascript">
function fun(){
document.getElementById("cancelReq").style.display = "block";
}
function fun1(){
document.getElementById("cancelReq").style.display = "none";
}
</script>
And make your HTML code like following:
<div id='addUser'><span id='requestSent' onmouseover="fun();" onmouseout="fun1();" >Add Friend</span></div>
<div id='cancelReq' >hello there</div> | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "css, hover"
} |
Looping array for largest number using forEach()
I am trying to pull the largest number of an array using a forEach Javascript method. This is what I have so far, but I know it's not correct.
var arr = [2,3,4];
var largest = 0;
arr.forEach(function(elem){
if(largest < elem)
largest = elem;
console.log(largest);
}); | This will work
var arr = [2,3,4];
var largest = 0;
arr.forEach(function(elem){
if(largest < elem)
largest = elem;
});
console.log(largest);
but why would you even do that? Why not use Math max?
var largest = Math.max.apply(Math, arr); | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 1,
"tags": "javascript, arrays, loops, foreach"
} |
Question about auto-versioned static content
From my understanding, auto-versioning as a method of forcing updates of static content will cause unique files to be cached every time the content is updated, potentially leading to many "copies" of the content saved, all but one of which will never be used.
Is this ever a problem? | No. Caches expire data when they get full as well as when the time runs out on them. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, css, static content, auto versioning"
} |
No Internet Connection on Boot with Windows 8
After Doing a (cold) boot I have no internet connection.
But I actually can restore the connection with Window's Network Diagnostics:
According to the diagnostics the problem is
> "No valid IP-Configuration"
and is solved by "resetting the LAN-Connection".
However, the problem persists and I have to run the diagnostics after every boot. Is there a way to fix this permanently?
**EDIT** : While trying some commands I found that 'ipconfig /renew' gives a time out error:
"DHCP-Server not found" | Solved by:
_Computer -> Manage -> Device Manager -> Network Adapter -> [Your Adapter] -> Power Management -> uncheck all boxes here_
Kudos to Viking_667. | stackexchange-superuser | {
"answer_score": 0,
"question_score": 1,
"tags": "windows 8, internet"
} |
Key Pressed Event
I want add a **KeyEventListener** to **JButton** which responds to Enter key, using following code segment:
private void jButton3KeyPressed(java.awt.event.KeyEvent evt) {
if (evt.getKeyCode() == 10) {
eventRegister();
}
}
I pressed space bar instead of enter and the if condition set to true and the `eventRegister` invoked. Why? How could I prevent this manner? | * don't to use `KeyListener` or `MouseListener` for `JButton` or `JButtons JComponent`, those events are implemented in API, or `ButtonsModel`, every can be testable, with to `consume()` of `KeyEvent`
* `JButton` has implemented ENTER and SPACE key as accelator in KeyBindings
* remove `SPACE` from `KeyBindings`, but not suggest that, I'm wouldn'd be confuse users, sure depends of | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 4,
"tags": "java, swing, jbutton, keylistener"
} |
Python Web Services
> **Possible Duplicate:**
> Python Web Services
> What's the best SOAP client library for Python, and where is the documentation for it?
What tool would you recommend to use with Python to consume Web Services?
I have thought about using SOAP.py, but some of the libraries it relies on (PyXML) are out of date. Plus, it seems as if it is not in active dev/support anymore.
FYI: I am consuming a SOAP web service. | I'd recommend suds. It is very simple and easy to use.
* * *
Simple example:
from suds.client import Client
url = '
client = Client(url)
result = client.service.MyMethod(args)
For more examples / tutorial see their documentation page.. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, soap, service"
} |
Systematically resolve conflicting styles in css
I have some stylesheets from different sources in my web project. I want to harmonize them. Some styles I need from the one, some from the other. Is there a tool or method how to systematically resolve style conflicts? I tried IE8 developer tool, and yes, it is possible to view conflicts at the level of each element. But I have many elemens, so if I do it element by element I think this takes too long. Theoretically there could be a tool that shows conflicts of two css files at design time?!? I think this would save me a lot of time. | Have you tried this Firefox extension, Dust-Me Selectors (< It makes removing redundant styles much easier.
Otherwise, I'd probably pop all the styles into one file, trying to group together similar rules, and then use Dust-Me to remove the unused ones. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 11,
"tags": "css, conflict, resolve"
} |
tkinter messagebox always appears behind main pygame window
I am trying to make my messagebox appear in front of my `pygame` window, but it keeps appearing behind it. Here's my code:
from tkinter import messagebox
# pygame loop here
messagebox.showinfo("Title", "Message here")
Do I need to do add some lines of code to bring it to the front? Any help would be appreciated. | I got it to work. I had to add `root.withdraw()` as well.
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.withdraw()
# pygame loop here
messagebox.showinfo("Title", "Message here")
root.lift()
Not sure why hiding the root tkinter window makes it work... | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "python, tkinter, pygame"
} |
Is it possible to disable django related_name for a specific field?
Example:
class Route(models.Model):
last_waypoint_visited = models.ForeignKey('WayPoint')
class WayPoint(models.Model):
route = models.ForeignKey(Route)
Since WayPoint already has a reference to Route through the route field, I don't really need the field last_waypoint_visited to generate a back reference to Route.
Is it possible do just disable the back reference creation for the "last_waypoint_visited" field? | Yes, disabling backward relations is a documented feature:
last_waypoint_visited = models.ForeignKey('WayPoint', related_name='+') | stackexchange-stackoverflow | {
"answer_score": 23,
"question_score": 16,
"tags": "django"
} |
Integrating Custom Database with Wordpress
I Have a Wordpress Site with few users who are my college students
They Registered using their RollNumbers/HallTicket Numbers as their usernames in Wordpress site
Now I Have Another Database with Their Personal Details like Marks, Rank etc
Now I want to Integrate this Database to Wordpress so that when student/user logins , then he/her could see their respective marks and other details
I Just want your suggestions/ideas to implement this, Not asking for a Complete solution
Thankyou | A simple Google search for wp custom query has turned out a couple of interesting results.
I chose this one for you: <
It should provide sufficient information if you can put it together with what you wnat to have done. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "php, mysql, wordpress"
} |
What is the Watson card's ability?
On page 12 of the Rulebook, it says
> At the start of the Investigation Phase of this round, the holder of this card may choose the Location card of another player which is read out loud
Does this mean the player can direct someone to read his card out loud to the entire table? | Yes, whenever I've played it, the player who chose that location must read it out loud to the table.
Group policies differ as to how slowly and audibly the choosing player should be required to read it, though there is a convention that listeners may not ask for bits to be repeated. | stackexchange-boardgames | {
"answer_score": 2,
"question_score": 0,
"tags": "watson and holmes"
} |
Confusion regarding boundedness & Equicontinuity
It is given that $ |f_{n} ' (x) | \le \frac {1}{x^{\frac {1}{3}}} \forall 0 \lt x \le 1$ , where {$f_{n}$} is a sequence of real valued $C^{1}$ function on $[0,1]$ and each {$f_{n}$} has a zero in $[0,1]$ . Now to prove that the sequence has a uniformly convergent subsequence; somehow I have to try with Ascoli Arzela Theorem.
What I have done: .... To go with Ascoli-Arzela, I have to show pointwise boundedness & equicontinuity... Now, by the condition that: each {$f_{n}$} has a zero in $[0,1]$ , pointwise boundedness is shown. But,
1) I could not show Equicontinuity,
2) & one doubt is: since {$f_{n}$} is a sequence of real valued $C^{1}$ function on $[0,1]$ derivative should be bounded.. isn't it?? | Hint: I guess you are using the following argument to show that $f_n$ are uniformly bounded:
Let $x_n\in [0,1]$ such that $f_n(x_n) = 0$, then for all $x\in [0,1]$, $$ |f_n(x)| = |f_n(x) - f_n(x_n)| = \bigg|\int^x_{x_n} f_n'(t) dt \bigg| \leq \int^x_{x_n} t^{-1/3} dt \leq \frac{3}{2} \big| x^{1-1/2} - x_n^{1-1/2}\big| \leq 3.$$
What happens if you use a general $y$ instead of $x_n$? | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "real analysis"
} |
PySpark : How to convert minutes to hours : minutes?
I will convert col in minutes to hours : minutes
col(min)
---
685
I will obtain
col(min) | col1(h:min)
---|---
685 | 11:25 | Use the sql functions `div` and `mod` to get the quotient and remainder respectively, and then concatenate them.
df = df.withColumn('col1', F.expr('concat(div(col, 60), ":", mod(col, 60))')) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "dataframe, pyspark"
} |
Android debug certificate
I read at android site that "The self-signed certificate used to sign your application in debug mode (the default on Eclipse/ADT and Ant builds) will have an expiration date of 365 days from its creation date."
but when i use jarsigner to take inforamtion about my certificate and write at command line
jarsigner -verify -verbose -certs myapp.apk
i get information that my debug certificate valid time is from 29.08.11 16:07 to 21.08.41 16:07
It's mean that my debug certificate valid 30 years, but it must be valid only 1 years. Maybe this is problem of jarsigner or all is correct? Why so it turns? | Sometime last year Google changed the validity period of the debug certificate generated by the ADT to 30 years from 1 year. I don't know what version of the SDK/ADT the change appeared in but when my debug certificate recently expired after 1 year and I generated a new one with the latest ADT I noticed that's it's valid for 30 years. So there is no problem with your set up. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "android, jarsigner"
} |
what is * return type in as3
I saw a method in Action script that has a return type of *
public function f(s:String):*
what does this [*] means ? | The `*` symbol means "untyped", meaning that the type can be anything (and that the value can be `undefined`). Using the asterisk has the same effect as not specifying the type at all, but it's good form to use it in order to be explicit about your intention. See the language reference for more info. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 3,
"tags": "apache flex, actionscript 3, adobe"
} |
MySQL call a stored procedure every x minutes
Is there a way in MySQL to call a stored procedure from within SQL every x minutes?
I want to use this in a session-environment, where the database keeps track of all the sessions and automatically deletes sessions older than x minutes. | Use MySQL Events, it was introduced in version 5.1. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 2,
"tags": "sql, mysql, events, stored procedures, session"
} |
Open Interest on Options on Futures
Is there anywhere that reports open interests or the max pain on futures such as Crude (CL), Natural Gas (NG), or E-Minis (ES)? I cannot seem to find this data, though I have seen it listed on trading screens. The closest I have found is on the CME's website: < but how can I get it in a report or data format of each strike's OI for all expiries? . ICE has reports such as < | Every day the CME publishes daily settlement information, which includes Open Interest
Go here < and click on for example COMEX Options. There are two formats for the file, .csv or plain text. In the .csv file look for the column 'prev int' which refers to Previous Day's Open Interest
The file(s) can also be downloaded automatically via ftp if you wish | stackexchange-quant | {
"answer_score": 1,
"question_score": 0,
"tags": "futures, open interest"
} |
Regex: extracting matches preceding a pattern in R
I'm trying to extract matches preceding a pattern in R. Lets say that I have a vector consisting of the next elements:
my_vector
> [1] "ABCC12|94160" "ABCC13|150000" "ABCC1|4363" "ACTA1|58"
[5] "ADNP2|22850" "ADNP|23394" "ARID1B|57492" "ARID2|196528"
I'm looking for a regular expression to extract all characters preceding the **" |"**. The expected result must be something like this:
my_new_vector
> [1] "ABCC12" "ABCC13" "ABCC1" "ACTA1"
and so on.
I have already tried using `stringr` functions and regular expressions based on look arounds, but I failed.
I really appreciate your advices and help to solve my issue.
Thanks in advance! | We could use `trimws` and specify the `whitespace` as a regex that matches the `|` (metacharacter - so escape `\\` followed by one or more character (`.*`)
trimws(my_vector, whitespace = "\\|.*") | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "r, regex, string"
} |
Integral with Branch Cut
While evaluating the integral $\int_{0}^{\infty}\frac{\sqrt{z}}{1+z^2}$ we use branch cut.Such a shame that I couldn't draw the complex plane with diagram, but I hope you would understand my explanation to the problem. The two horizontal parallel lines above branch cut would result the same integral which we can add, the bigger circle (contour) would vanish because of jordan's lemma if we take the limit as radius tends to infinity, but why the smaller circle with centre at branch point 0 would vanish as its radius tends to 0. | For the smaller circle about the origin, set $z=\epsilon \, e^{i \phi}$. Then the integral about the smaller circle is
$$i \epsilon \int_{2 \pi}^0 d\phi \, e^{i \phi} \frac{\sqrt{\epsilon} \, e^{i \phi/2}}{1+\epsilon^2 e^{i 2 \phi}}$$
As $\epsilon \to 0$, this integral goes to zero as $\frac{4}{3} \epsilon^{3/2}$. | stackexchange-math | {
"answer_score": 4,
"question_score": 3,
"tags": "complex analysis"
} |
Magento set product as variable
I want to use `array_map()` method in my code, but i need to pass an array and the ' **product** ' object. There's solutions to do it but **my question** here is : if it's a good practice, or how horrible is to do something like:
[...]
private $myproduct;
[...]
$this->setMyproduct($product);
[...]
$product = $this->getMyproduct();
[...]
My doubt is if php save the object again, what looks like a lot of work for the code, or if only save a reference to it and it's fast and a good manner to have my product where i want.
Thanks | That should work fine, Magento/PHP will store the reference to the product, and will not load it everytime you access the variable, if that's what you're asking.
Another way to pass a persistent variable is to use Magento's register functionality:
`Mage::register('current_product', $product);`
and use this to retrieve it again:
`Mage::registry('current_product');` | stackexchange-magento | {
"answer_score": 2,
"question_score": 1,
"tags": "magento 1.9"
} |
What's the difference between ruby-1.9.3-p194 and ruby-1.9.3-p194@global gemsets?
I am currently running the following on OSX 10.6.8 and am trying to understand gemsets and gems.
Ruby 1.9.3-p194
Rails 3.2.8
RVM 1.15.6
When I look in .rvm/gems/ I see several gemset directories. Inside each one there is a gems directory. Now, whats the relationship between the non-'@' gemset and the @global gemset? | From the documentation:
> ### Interpreter global gemsets
>
> RVM provides (>= 0.1.8) a `@global` gemset per ruby interpreter.
>
> Gems you install to the `@global` gemset for a given ruby are available to all other gemsets you create in association with that ruby.
>
> This is a good way to allow all of your projects to share the same installed gem for a specific ruby interpreter installation.
To expand on this, the gemset without the `@global` is the default gemset for that Ruby version. It is essentially a gemset with no name. The `@global` gemset, however, is special for the reasons outlined in the docs above. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "ruby, rvm, gemset"
} |
Display <div> inline with list item
Given a following structure:
<div class="index">a</div>
<div class="li">
<div class="index">b</div>
<div class="li">
some text
</div>
</div>
Is there a way to display it as this:
a b some text
and not:
a
b
some text
The problem is that I am **not** allowed to change HTML markup, so it's a pure CSS question.
**EDIT:** "li" must have `display` set to `list-item` or follow the list hierarchy in terms of margins on the left side | You can `float` `.index` and `.li`
.li { display: list-item; }
.index, .li {
float: left;
}
<div class="index">a</div>
<div class="li">
<div class="index">b</div>
<div class="li">
some text
</div>
</div> | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "html, css"
} |
Renaming large amount of files
i need a script which will rename large amount of files. I got a folder with a lot of files. Every file is named by ID. Then i have a CSV file like this:
> oldID;newID
>
> oldID;newID
>
> etc...
Every old and new id is specific and original. I'd like to ask what should be the best way to do it or little help in bash/batch. | If you are using **bash** (the shell used in world of Linux, UNIX, etc.), you can use the following short script based on this internal field separator answer. This assumes that you are using a semicolon (`;`) as the delimiter of your "CSV" file and that there is only one such delimiter.
#!/bin/bash
while IFS=';' read -ra names; do
mv "${names[0]}" "${names[1]}";
done < translation.csv
where `translation.csv` is your file containing the name translations with an `oldname;newname` format.
If you are instead asking for a **batch** file (i.e. for Windows, DOS, etc.) then that is a different animal in a different world. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -3,
"tags": "bash, file, batch file, rename"
} |
Word for 'make more frequent'
For example, how would you convert
> He made cunning remarks more frequently.
to
> He **____** his cunning remarks. | Perhaps some of these might work:
* accelerated
* increased the pace of
* ramped up
* sped up | stackexchange-english | {
"answer_score": 3,
"question_score": 3,
"tags": "synonyms"
} |
Cuenta caducada en Ubuntu 16.04
Es una pregunta de lo mas novata que hay, pero no se conseguir desbloquear la cuenta.
Y la pregunta es que he puesto la caducidad de una cuenta justamente este mes (mayo) el 1 de 2021, y esa cuenta era una cuenta administrador. Necesito la cuenta ahora porque si no, no puede ejercer modificaciones.
He usado `Sudo usermod -e 2021-05-01 administrador` y para desbloquear he usado `usermod -U administrador`. Después de haber hecho esto dije, pues se "desbloqueara", pero en modo texto pongo su nombre de cuenta y contraseña, y vuelve a salirme la pantalla de login.
Y en modo grafico pone que tengo la cuenta caducada.
Lo que he hecho, para al menos desbloquear, es ir a una cuenta creada usar `su root` y poner `usermod -U administrador`. Pero como os digo la cuenta sigue caducada, y no entiendo porque sigue caducada y ya no se como desbloquearla. | Haz un status, para saber si realmente está caducada la cuenta:
passwd --status cuenta
Si estuviera bloqueada aparecería la indicación "L" o "LK" de "locked"
cuenta L 05/01/2021 0 99999 7 -1
Con el comando "change" veremos la información de la fecha
chage -l cuenta
Saldría algo así como:
Last password change : May 01, 2021
Password expires : never
Password inactive : never
Account expires : May 01, 2021
Minimum number of days between password change : 0
Maximum number of days between password change : 1
Number of days of warning before password expires : 12
En el caso de que haya expirado, puedes ampliar los días que necesites o desees (30 por ejemplo)
chage -E $(date -d +30days +%Y-%m-%d) cuenta
Y compruebas si los cambios han dado resultado
chage -l cuenta | stackexchange-es_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "linux, cuenta usuario"
} |
why are functions defined inside play framework template not allowed to state return type?
the following inside a play framework template works fine:
@cdnPath(productID: String) = @{
" + productID + ".png"
}
but the following - with the return type explicitly stated does not work:
@cdnPath(productID: String):String = @{
" + productID + ".png"
}
I am curious why this is so? Thanks | It is not part of template parser spec. We have a new template compiler at works which will fix some of these issues.
< | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "playframework 2.0"
} |
Is it OK to extract datasets from somebody's paper and work with it in your own papers?
Let's say David Smith has published a paper a while ago. In this paper there are some results plotted in a graph. I want to use this dataset in my own research and extend it with my own results. Unfortunately, it is not possible to contact David Smith. So I use some of tools mentioned for example in this question to extract the dataset from the plot (which, of course, might introduce some kind of small errors).
Do you consider it as OK if I now publish a paper which includes the old dataset from David Smith + my new data in a new plot? I would, of course, cite the old paper by David Smith. (I might deduce some results from the old+new data that a somewhat different that the original conclusion by David Smith.) | If you cite the original authors in your plots and when comparing results/conclusions (or simply everywhere you use their data/work) you should be fine. Also make it clear that the data is "reverse engineered" from their graphs/plots and not the "original" data. | stackexchange-academia | {
"answer_score": 6,
"question_score": 4,
"tags": "publications, data"
} |
What websites can I use to sort my unlisted followers, into a new Twitter list?
Does it exist online already, or do I have to make it myself? | I just tried < which does this job perfectly fine for me. | stackexchange-webapps | {
"answer_score": -1,
"question_score": 0,
"tags": "twitter"
} |
Linking a shared object into other shared object C++ project
I am working in a very big C++ project to create a big shared object where we are using an external SDK which have several header files and several shared libraries which belong to each other. This means that the declaration of SDK classes are in the header files but their definitions are in the shared objects.
I understand that because of the declarations in header files I can compile this code.
But what I do not understand exactly is **when do I have to specify the used shared objects for the linker explicitly?**
Namely if I specify it (e.g. in cmake with _target_link_libraries_ command) then the linker can check that a symbol will be in the shared library or not. But what happens if I do not specify it (i.e. there is not any -l[shared_object_name] flags in linkage)? My experience is (which surprised me) that is work properly (i.e. the whole building process finished). How can it possible? | In POSIX shared libraries, you can have undefined symbols in a shared library, and all will link just fine. As long as the executable is fully linked, there will be no linker errors.
That's done this way because dynamic libraries mimic the behaviour of static libraries, and static libraries can have undefined symbols (static libraries are not linked, to begin with).
If you come from a Windows background, then it will surprise you, because Windows DLLs cannot have undefined symbols.
If you are worried about this, you can check the linker options `--no-undefined` and `--no-allow-shlib-undefined`. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "c++, linker, cmake"
} |
Boosting massless particles
How does one calculate the boost matrix to go from a photon of (standard) four-momentum $k^\mu = (k,0,0,k)$ to $p^\mu = (p,0,0,p)$? (in terms of $|p|/|k|$)
Weinberg in his Quantum Field Theory Vol.1 has written an expression, which I suspect involves some Taylor expansion involving the $m \to 0$. | Just boost with the Lorentz matrix: $$ \begin{bmatrix} p\\\0\\\0\\\p \end{bmatrix}=\begin{bmatrix} cosh(\lambda) & 0 & 0 & sinh(\lambda) \\\ 0&1&0&0 \\\ 0&0&1&0 \\\ sinh(\lambda) & 0 & 0 & cosh(\lambda) \end{bmatrix} \begin{bmatrix} k\\\0\\\0\\\k \end{bmatrix}=\begin{bmatrix} (cosh(\lambda)+sinh(\lambda))k\\\0\\\0\\\\(cosh(\lambda)+sinh(\lambda))k \end{bmatrix}=e^{\lambda}\begin{bmatrix} k\\\0\\\0\\\k \end{bmatrix} $$ where ${v\over c}=tanh(\lambda)$. The $\lambda$ is the Lorentz Boost Parameter (aka rapidity). | stackexchange-physics | {
"answer_score": 3,
"question_score": 1,
"tags": "quantum field theory, special relativity"
} |
Checking package versions in a miniconda environment
I hava a conda environment called test and a requirements file-requirements.txt.
What i need to achieve is that i need to check the versions of different packages against those in requirements.txt and display which are upto date and which are not.
I need to write a python script for the task. For eg: if requirements.txt has django==2.0.6, i have to check against the installed version of django in the test environment and display accordingly.
The steps that i thought are :
1. Activating the environment inside script
2. running "conda list" command and saving all the packages along with their versions in a map as key-value pairs
3. matching against the requirements.txt
How to activate the environment inside a python script using "conda activate test" and run the command "conda list"? | `conda list` accepts the argument `-n` to specify an environment like this:
conda list -n test
so no need to activate the conda env | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python 3.6, conda, virtual environment"
} |
Guzzle/Goutte - Basic scrape - passing variable to request
I am currently using a simple php crawler called Goutte. It uses Guzzle to perform the http `GET` requests. I am able to perform scrape actions. However, I am trying to pass/echo a variable inside `filter` but get the error `Undefined variable: x`. The variable is defined. What would be the correct way to pass a variable to filter?
$client = new Goutte\Client();
$crawler = $client->request('GET', '
$crawler = $client->click($crawler->selectLink('Sign in')->link());
$form = $crawler->selectButton('Sign in')->form();
$x = "hello";
$crawler = $client->submit($form, array('login' => 'xxxxx', 'password' => 'xxxxx'));
$crawler->filter('.flash-error')->each(function ($node) {
echo $x;
print $node->text() . "\n";
}); | Try:
$crawler->filter('.flash-error')->each(function ($node) use (&$x) {
echo $x;
print $node->text() . "\n";
});
You can remove `&` if you don't need to alter it in that function. For reference to inheriting parent variables inside anonymous functions. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "php, guzzle, goutte"
} |
JSON Path Extractor in JMeter
I am new to jmeter. Can anyone help me to use a response object of one request to be passed as a request header of next HTTP request ?
Let me explain.
1. I am getting an access token along with the response of login in my app:
{: "responseCode":18, : "message":"Successfully logged in.", : "responseObject":"8zWExE4eSdhcJDwnW9MgIw=="}
2. No I want to use this access token (8zWExE4eSdhcJDwnW9MgIw) as one of the parameter of next request.
I used JSON Path Extractor for this.But its not working. | I am using JSON Path Extractor as well and it works great if it is properly configured. Just put it into request and fill fields:
* Variable Name: access_token (or any other you want to use later in request like this ${access_token})
* JSON Path: responseObject should be enough if the JSON you pasted is full response (thjose additional colons are just some mistakes when copy-pasting or the JSON is corrupted?)
* Default Value: I always use some value like 'NotUpdated!' here so I can assert in the next step or at least see it easily in request. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "jmeter"
} |
Erro de memória ao gerar planilha com o PHPExcel
Estou com problemas na geração de planilhas do Excel utilizando o PHPExcel quando o número de registros é muito grande a memória é insuficiente para processar a tarefa, existe alguma forma de melhorar a criação desse arquivo através de algum sistema de cache? | Sugiro que aumente a memória no `php.ini`. O meu é `php7.0` no `Ubuntu 14`, fica em `/etc/php/7.0/apache2/php.ini`
Na linha 389 coloquei assim:
Memory_limit = 768M
Pra editar o `php.ini` sugiro que use o `vi` no Ubuntu. | stackexchange-pt_stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, array, memória, cache, phpexcel"
} |
How to count the number of different items in a range without use a pivot table excel vba
I have a large range with various repeating id's. I want to know how many unique id's are in the range, but I don't want to use a pivot table. This question is related, but does not have the answer. Is there a simple way to do this using VBA?
I also saw this, but it doesn't work for me. | Here's the simplest way I've found:
Function Count_Uniques(cell_range As Range)
Dim n As Long
Dim cells1 As Range
Dim unique_count As Collection
Set unique_count = New Collection
On Error Resume Next
For Each cells1 In cell_range
unique_count.Add cells1.Value, CStr(cells1.Value)
Next cells1
On Error GoTo 0
Count_Uniques = unique_count.Count
End Function | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "excel, vba"
} |
Object #<HTMLDocument> has no method 'getElememtById'
Here's the html:
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="while.js"></script>
</head>
<body>
<div id="panel"><div>
</body>
</html>
Here's the script:
function init() {
var panel=document.getElememtById("panel");
var num=70;
while (num > 10) {
panel.innerHTML="Countdown value: "+num+"<br>";
num-=5;
}
}
window.onload=init;
Here's the resuts:
Google Console: Uncaught TypeError: Object # has no method 'getElememtById'
FireBug: document.getElememtById is not a function
IE: nothing
What's wrong with my script which I patched together from an example in a book? Also, an inner div is created inside the #panel div. What's that about?
Answers are so appreciated. | It's `getElementById`, not `getElememtById`. Looks like your issue is just a typo? :) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "getelementbyid"
} |
Foundation - The third container is pushed down
I am building a calendar web app that displays a list of events. On larger screen sizes the third event item gets pushed down so that it does not line up with the two events to the left of it. I inspected the CSS of the web app but could not find what was causing this. this also occurs when the screen size is a bit smaller and the events are in a two column layout.
URL: < | Its because you have white space in your container `portfolioContainer october` delete it and it will work fine : !enter image description here | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "css, responsive design, zurb foundation"
} |
If $f_n \rightarrow f$ in $L^p$, Does $f_n^p \rightarrow f^p$ in $L^1$?
If $f_n \rightarrow f$ in $L^p$, Does $f_n^p \rightarrow f^p$ in $L^1$?
This seems a very trivial fact, but just from looking at the norm definition of convergence, it does not seem entirely clear how $||f_n - f||_p \rightarrow 0$ would imply $||f_n^p - f^p||_1 \rightarrow 0$.
Does the statement hold? | I will assume that $ 1<p<\infty$. Let $q$ be the conjugate index. $|x^{p}-y^{p} |\leq p(|x|^{p-1}+|y|^{p-1}) |x-y|$ by MVT. To show that $\int |f|^{p-1} |f-f_n| \to 0$ apply Holder's inequality: $\int |f|^{p-1} |f-f_n| \leq \|f-f_n\|_p (\int |f|^{(p-1)q})^{1/q}$. Since $q(p-1)=p$ we see that $\int |f|^{p-1} |f-f_n| \to 0$. Similarly, $\int |f_n|^{p-1} |f-f_n| \to 0$. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "real analysis, functional analysis, convergence divergence, normed spaces, lp spaces"
} |
Android Age Spinner Item
Is it possible to build a for loop that goes to 100 to populate an Android spinner? As opposed to manually adding to the ArrayList.
Something like the below:
List<Integer> age = new ArrayList<>();
for (int i = 1; i < 101; i++) {
age.add(i);
} | It's perfectly fine to programmatically populate your `ArrayList`; you just need to use an `ArrayAdapter` like this:
List age = new ArrayList<Integer>();
for (int i = 1; i <= 100; i++) {
age.add(Integer.toString(i));
}
ArrayAdapter<Integer> spinnerArrayAdapter = new ArrayAdapter<Integer>(
this, android.R.layout.simple_spinner_item, age);
spinnerArrayAdapter.setDropDownViewResource( android.R.layout.simple_spinner_dropdown_item );
Spinner spinner = (Spinner)findViewById(R.id.spinner);
spinner.setAdapter(spinnerArrayAdapter);
Hope this helps! | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "android"
} |
How to store screen output of Scrapy into a file in Linux
I often use
self.logger.info('Parse function called on %s', response.url)
to debug Scrapy project. However, when there are lot of items crawled, those log information will be embedded inside a lot of non-useful information.
What I want is to store the screen output into a file, so that I can do search, do text editing, etc.
I tried:
scrapy crawl xxx_spider >> my_log
but it doesn't work | It seems that your script may be writing to something other than stdout, such as stderr. Try:
$ scrapy crawl xxx_spider &> test_log
If it is indeed writing script output to stderr, you may want to direct stderr to stdout in the future and might want to consider changing the location to which logger outputs text. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "linux, scrapy"
} |
Concatenation in scheme
I have the following code:
(define rest '(((di (a) (b c)) (sh (b) (e d))) ((al (a) (b)))))
(define first '((di (a) (5)) (sh (b) (3))))
I want to get the following list:
(((di (a) (5)) (sh (b) (3))) ((di (a) (b c)) (sh (b) (e d))) ((al (a) (b)))))
meaning, add the list `first`, to be the first element in rest.
When I do `append`, it gives me:
((di (a) (5)) (sh (b) (3)) ((di (a) (b c)) (sh (b) (e d))) ((al (a) (b))))
And any other library function, or function that I try to do, didn't help.
Thank you. | `Append` takes two _lists_ and puts them together. Given that you have a `first` and a `rest`, you probably want `cons`. `Cons` takes an _element_ and prepends it to a list. In this case, the element is `first` and the list is `rest`. So you want something like
(cons first rest) | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 6,
"tags": "scheme"
} |
React JS setInterval to API
I want to make a call to an API once an hour, every hour, using setInterval, how would I go about implementing that?
componentDidMount() {
fetch(fullURL)
.then((response) => response.json())
.then((responseJson) => {
// console.log(responseJson);
const resultyt = responseJson.items.map(obj => " + obj.id.videoId);
this.setState({resultyt});
})
.catch((error) => {
console.error(error);
});
}
the API call is stored inside a const called fullURL | Wrap that up in a function that can be called many times, then simply use setInterval:
componentDidMount() {
this.intervalId = setInterval(() => this.loadData(), 3600000);
this.loadData(); // also load one immediately
}
componentWillUnmount() {
clearInterval(this.intervalId);
}
loadData() {
fetch(fullURL).then(...);
} | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 2,
"tags": "javascript, reactjs, setinterval"
} |
Named aggregations with pandas group by agg are super slow. Why?
I have a df with many groups.
N = int(1E6)
df = pd.DataFrame({'A':np.random.randint(300_000, size=N),
'B': np.random.rand(N)})
df.loc[::2, ['B']] = np.nan
I want to calculate the sum of each group, given that the group has at least one non-Nan value. I encounter that the following is very slow:
df.groupby('A').agg(**{
'newname' : ('B', lambda x: x.sum(min_count=1))
})
(22 seconds)
while the following is fast:
df.groupby('A').sum(min_count=1)
(0.11 seconds).
However I would like to use named aggregations.
Am I doing something wrong in the named_aggregation approach, hereby reducing performance? I tried functools.partial as well (instead of the lambda function), but this yields the same performance. | Once you pass in `lambda`, the operation is no longer vectorized _across the groups_ even though it can be vectorized _within each group_. For example: `df.groupby('A').agg(**{'newname' : ('B', 'sum')})` is comparable to `df.groupby('A')['B'].sum()` and is largely faster than `lambda x: x.sum()`.
That said, I read somewhere that named agg can be a bit slower than straight up applying the built-in functions. For example, this would be a bit faster than `.agg`:
d = df.groupby('A')
pd.DataFrame({'new_name': d['B'].sum(min_count=1),
'other_name': d['B'].size()
})
but then, you code base looks not as clean as `.agg`. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "python, pandas, dataframe, aggregate"
} |
Is there a difference between glClearColor(0.0,0.0,0.0,0.0) and glClear(COLOR_BUFFER_BIT)?
Both clear the color buffer, right? Do they do it the same way? | `glClear` actually clears the buffer, while `glClearColor` just sets the colour to clear the buffer to. | stackexchange-stackoverflow | {
"answer_score": 25,
"question_score": 10,
"tags": "opengl"
} |
SocialEngine 4 cropped URLs
Nice to meet you, stackoverflow!
I have a little question about SocialEngine 4.. it is possible to have longer URLs?
I mean I need longer titles from topics is forum, so I edited Create.php and Edit.php files in application/modules/Forum/Topic dir and also edited title length in database..
But SE keeps cropping my URLs after 64 characters so I need topic URL to be as long as the title is.
Could you help me to solve that?
Many thanks! | You can provide the length in model getHref function where getSlug function called.
$this->getSlug(null, 100);
Or
parent::getSlug($title, 100);
100 is the length of title, you can change it as per your requirement. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 2,
"tags": "php, url, socialengine"
} |
Trying to send using PHP Mailer and getting following error
This is my configuration
$mail->isSMTP();
$mail->SMTPAuth = true;
$mail->SMTPSecure = "tls";
$mail->Host = "gator4102.hostgator.com";
$mail->Port = 465;
$mail->Username = '[email protected]';
$mail->Password ='jyghvbjyhj';
It throws following error
SMTP -> ERROR: HELO not accepted from server:
SMTP -> NOTICE: EOF caught while checking if connectedLanguage string failed to load: tls
Mail gets delivered though sometimes. Please help. | Change:
$mail->Port = 465;
To:
$mail->Port = 587;
For tls, 587 port is used. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 2,
"tags": "php, smtp, phpmailer"
} |
Pandas: How to find the low after a high within a rolling window
For a series of numbers, I am trying to find the low after the high within a rolling window. I am able to calculate the high within the window, but not the low after it within the same window. I'm using Pandas and have tried to get the index of the high and use that as some type of reference, but I can't get it to work.
Here is some code to set up the problem:
dates = pd.date_range("20130101", periods=15)
temps = {'Temperature' :[16, 3, 26, 56, 2, 92, 54, 98, 73, 68, 80, 18, 75, 24, 12]}
df = pd.DataFrame(temps, index=dates, columns = ['Temperature'])
df['RollMax'] = df['Temperature'].rolling(5).max()
# df['Low_After_High'] = ### Lowest value after high has been reached within the window
And here is what the output should look like:
.apply(lambda x : min(x[pd.Series(x).idxmax():]))
2013-01-01 NaN
2013-01-02 NaN
2013-01-03 NaN
2013-01-04 NaN
2013-01-05 2.0
2013-01-06 92.0
2013-01-07 54.0
2013-01-08 98.0
2013-01-09 73.0
2013-01-10 68.0
2013-01-11 68.0
2013-01-12 18.0
2013-01-13 18.0
2013-01-14 18.0
2013-01-15 12.0
Freq: D, Name: Temperature, dtype: float64 | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "python, pandas, max, min, rolling computation"
} |
Разделение строки
Здравствуйте, помогите пожалуйста с заданием. Требуется разделить строку на предложение, предложения на слова, а затем вывести с каждого предложения самое длинное слово. Важно использовать при этом массивы.
Смог сделать только так, чтобы искало самое большое слово со всей строки.
string str = "This is a test message. This is a test";
char* cstr = new char [str.length()+1];
strcpy(cstr, str.c_str());
char* p = strtok (cstr, " ,");
char* maxword = p;
while(p = strtok(NULL, " ,")) {
if(strlen(maxword) < strlen(p))
maxword = p;
}
cout << maxword << endl; | Использование в С++ старых добрых C-функций - не самая хорошая идея. Конечно, они будут работать. Но это приумножает мировую скорбь. В С++ есть свои средства для работы со строками. И они довольно неплохие.
#include <sstream>
#include <iostream>
using namespace std;
int main()
{
string str = "This is a test message. This is a test";
istringstream ss(str);
string sentence;
while (getline(ss, sentence, '.')) { // цикл по потоку предложений
istringstream ws(sentence);
string curr, longest;
while (ws >> curr) // цикл по потоку слов
if (curr.size() > longest.size()) longest = curr;
sentence = sentence.substr(sentence.find_first_not_of(" "));
cout << sentence << " => " << longest << endl;
}
char dummy[42]; // используем массивы, поскольку это очень важно :)
return 0;
} | stackexchange-ru_stackoverflow | {
"answer_score": 3,
"question_score": -2,
"tags": "c++, c, строки"
} |
Determining the null space of the matrix
> Determine the null space of the matrix:$$\begin{bmatrix} 1 & -1 \\\ 2 & 3 \\\ 1 & 1 \end{bmatrix}$$
**My try:** $$\begin{bmatrix} 1 & -1 \\\ 2 & 3 \\\ 1 & 1 \end{bmatrix}_{R_2\rightarrow R_2-2R_1\\\R_3\rightarrow R_3-R_1}$$ $$\begin{bmatrix} 1 & -1 \\\ 0 & 5 \\\ 0 & 2 \end{bmatrix}_{R_3\rightarrow 5R_3-2R_2}$$ $$\begin{bmatrix} 1 & -1 \\\ 0 & 5 \\\ 0 & 0 \end{bmatrix}_{R_2\rightarrow \frac{R_2}{5}}$$ $$\begin{bmatrix} 1 & -1 \\\ 0 & 1 \\\ 0 & 0 \end{bmatrix}$$
From this I got $$x-y=0\implies x=y\\\y=0$$ $$(x,y,z)^T=(y,0,z)^T=y(1,0,0)^T+z(0,0,1)^T$$ So, $(1,0,0)^T$ and $(0,0,1)^T$ is the null space. Is this correct? | Recall that by definition the nullspace is the subspace of all vectors $\vec x$ such that $A\vec x=\vec 0$ and in that case we have ony the trivial solution $(x_1,x_2)=(0,0)$ then $Null(A)=\\{\vec 0\\}$.
Notably to solve $Ax=0$ we can proceed by RREF to obtain
$$\begin{bmatrix} 1 & -1 \\\ 2 & 3 \\\ 1 & 1 \end{bmatrix}\to \begin{bmatrix} 1 & -1 \\\ 0 & 5 \\\ 0 & 2 \end{bmatrix}\to \begin{bmatrix} 1 & -1 \\\ 0 & 1 \\\ 0 & 0 \end{bmatrix}$$
that is
$$\begin{bmatrix} 1 & -1 \\\ 0 & 1 \\\ 0 & 0 \end{bmatrix}\begin{bmatrix} x_1 \\\ x_2 \end{bmatrix}=\begin{bmatrix} 0 \\\ 0 \end{bmatrix}$$
that is $x_1=x_2=0$. | stackexchange-math | {
"answer_score": 0,
"question_score": 1,
"tags": "linear algebra"
} |
Подскажите как отобразить аватарку email-отправителя
В общем есть почта на хостинге. при отправление на email пользователю ему приходит в таком виде:
.on("click", function () {
$("#inp").focus();
});
DEMO: <
If click on `button`, the above code just `selects` (and not happens `focusing`) the text in input field. this happens in safari and chrome, correctly works in opera and firefox.
Question: how to make input `focusing` in chrome and safari also ? | Maybe try this:
<
$("#button").on("click", function () {
$('#inp').focus().val($('#inp').val());
}); | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "javascript, jquery"
} |
Is it possible to manage different github account for different projects in android studio?
I am now using android studio to develop several applications.
And one of them exists in the repository of a different github account.
But, when I have two instance of android studio opened for two projects, and changed one github account in the VCS setting, the setting of the other instance also changed. which is quite inconvenient. For I want these two projects shared in different repo from different account.
Hope I made my point clearly. Anyone have some idea about that? | I guess you can simply use command line or terminal for any `push` or `pull`. Instead of using Android studio. If in case you do this way and SSH key is not configured you might be able to easily use two different account because it is just going to be varied `remote` | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "github, android studio"
} |
Excel: search for string in row and find column
I would like to search a row for a string and get the column number if there is such a string.
Is this possible by using worksheet functions in Excel? | You can use `MATCH` to give the position, e.g. you can search in row 2 for "xyz" like this
`=MATCH("xyz",2:2,0)`
If "xyz" is found first in J2 you get 10
if you want partial matches then you can use wildcards like
`=MATCH("*xyz*",2:2,0)`
so if F2 contains [abc **xyz** 344] you get a match with that and formula returns 6 | stackexchange-stackoverflow | {
"answer_score": 12,
"question_score": 3,
"tags": "excel, search, find, worksheet function"
} |
Confirmation that someone is listening to another person's speech
When someone is telling you a very long and detailed story he usually wants to hear some "confirmations" (or response) that you are listening to his story. In Russian we often use something like "tak" (which has a meaning of "ok" and "well, proceed further"), "a-ha" or "uh-huh".
What word serves the same purpose in English and American English? | The use of such verbal and non-verbal markers has a name ( **backchannelling** ), and has been the subject of studies ( see < ).
They form a subset of discourse (better, pragmatic) markers (< ), obviously of the 'oiling the wheels of discourse' variety - though they grade into replies containing semantic feedback ('I see!' 'Never!'). | stackexchange-english | {
"answer_score": 10,
"question_score": 7,
"tags": "word choice"
} |
In proving A = B, A, B are sets, do you always have to show $\subseteq$ and $\supseteq$?
I am trying to show the DeMorgan's Law
> $X \backslash \bigcup_{\alpha \in I} A_\alpha = \bigcap_{\alpha \in I} (X \backslash A_\alpha)$
It seems I could directly approach this as follows:
$X \backslash \bigcup_{\alpha \in I} A_\alpha = X \bigcap (\bigcup_{\alpha \in I} A_\alpha)^c = X \bigcap (\bigcap_{\alpha \in I} A_\alpha^c) = \bigcap_{\alpha \in I} X \backslash A_\alpha$
The last line follows from distributivity
But I thought in set theory proofs of the type **Prove $A = B$** , you have to show that $ A \subseteq B$ and $B \subseteq A$.
But in this case it seems I have directly proved that the two are equivalent without resorting to $A \subseteq B$ and $B \subseteq A$...
Can someone enlighten me as to whether my approach is correct? I am not very well versed in set theory proofs. | Your proof is just fine. :-)
The rule "to show $A = B$, verify that $A \subseteq B$ and that $B \subseteq A$" is quite nice, since it often gives you a fruitful starting point for your proving efforts.
However, it's not actually necessary to verify an equality using this rule. Any other sound method of proof can be used as well. In your case, you implicitly used the lemma "if $A = B$ and $B = C$ then $A = C$".
Let me add that calculational proofs proceeding by stringing equalities might be considered more elegant than element-wise proofs. However, in many cases, element-wise proofs are easier to accomplish. | stackexchange-math | {
"answer_score": 4,
"question_score": 4,
"tags": "general topology, elementary set theory, proof verification, proof writing, proof explanation"
} |
extjs function parameters - why not being used?
In ext js, I come across functions like this:
SearchWindow.WindowCloseButton.on('click',function(btn,e){
SearchWindow.hide();
});
So on click of close button, the window will be hidden. But why does the function need those two arguments (btn, e) when they are not being used inside the function? I am a java developer and I am unable to understand this syntax | It doesn't _need_ the arguments. These are the arguments that are passed into the function. You can use them or not. The function will work without them if you like this better:
SearchWindow.WindowCloseButton.on('click',function(){
SearchWindow.hide();
}); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "extjs"
} |
Ambiguous use of 'subscript' - NSMutableDictionary
My code worked perfectly in the version of Swift in May 2015, when I programmed the app. When I opened XCode 7.2 today I get an odd error message I can't understand: Ambiguous use of 'subscript'. In total I get this error 16 times in my code, do anyone know what I can change to fix this problem?
if let path = NSBundle.mainBundle().pathForResource("colorsAndAlternatives", ofType: "plist") {
if let dict = NSMutableDictionary(contentsOfFile: path) {
let randomNumber = Int(arc4random_uniform(UInt32(numberOfOptions)))
let correctColor = "#" + String(dict["\(randomNumber)"]![1] as! Int!, radix: 16, uppercase: true) // Ambiguous use of 'subscript'
The correctColor is determined by HEX using this code: < | The Swift compiler is much more strict now.
Here, it doesn't know for sure what type is the result of `dict["\(randomNumber)"]` so it bails and asks for precisions.
Help the compiler understand that the result is an array of Ints and that you can access it alright with subscript, for example:
if let result = dict["\(randomNumber)"] as? [Int] {
let correctColor = "#" + String(result[1], radix: 16, uppercase: true)
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "ios, swift, dictionary"
} |
how to iterate over this example
I have this variable "data" that is array of objects:
[{"id_questao":1,"id_tipoquestao":1,"conteudo":"Pergunta exemplo 1","id_formulario":1},{"id_questao":2,"id_tipoquestao":1,"conteudo":"Pergunta exemplo 2","id_formulario":1}]
I want to iterate over "data" and get the `id_questao` , `id_tipoquestao` and `conteudo` out of the objects, whats the correct way of doing so. | Use `Array.forEach` and `Object destructuring`
var arr = [{"id_questao":1,"id_tipoquestao":1,"conteudo":"Pergunta exemplo 1","id_formulario":1},{"id_questao":2,"id_tipoquestao":1,"conteudo":"Pergunta exemplo 2","id_formulario":1}];
arr.forEach(({id_questao, id_tipoquestao, conteudo})=>{
console.log(id_questao+" "+id_tipoquestao+ " "+conteudo);
});
` | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "javascript, json, ajax"
} |
Mysql 2 updates in the same trigger
I have 2 tables route and loc. When either the drivername or rt_num changes in the route table I need to update the loc table. I have tried all day playing with the following code. Each UPDATE statement works as a trigger by it self. I am not sure if it can be done at all.
DELIMITER |
CREATE TRIGGER `add2` AFTER UPDATE ON `route`
FOR EACH ROW
BEGIN
AFTER UPDATE ON `route`;
UPDATE loc
SET drivername = new.driver_d_name
WHERE rt_nanme = old.rt_num;
UPDATE loc
SET rt_nanme = new.rt_num
WHERE rt_nanme = old.rt_num;
END;
|
DELIMITER ; | Why are you repeating the `after update` statement?
In addition, you don't need two update statements. So:
DELIMITER $$
CREATE TRIGGER `add2` AFTER UPDATE ON `route`
FOR EACH ROW
BEGIN
UPDATE loc
SET drivername = new.driver_d_name,
rt_nanme = new.rt_num
WHERE rt_nanme = old.rt_num;
END;$$
DELIMITER ; | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "mysql, triggers"
} |
How to validate PowerShell Function Parameters allowing empty strings?
Please try this:
function f1
{
param(
[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[string]
$Text
)
$text
}
function f2
{
param(
[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
#[string]
$Text
)
$text
}
function f3
{
param(
[Parameter(Mandatory=$False,ValueFromPipelineByPropertyName=$true)]
[string]
$Text
)
$text
}
f1 ''
f2 ''
f3 ''
Here f1 throws an error. Now try
f2 $null
f3 $null
This time only f2 throws an error. What I want is a function f, so that
f '' # is accepted
f $null # returns an error | The Mandatory attribute blocks null and empty values and prompts you for a value. To allow empty values (including null) add the AllowEmptyString parameter attribute:
function f1
{
param(
[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
[AllowEmptyString()]
[string]$Text
)
$text
} | stackexchange-stackoverflow | {
"answer_score": 85,
"question_score": 43,
"tags": "powershell, parameters"
} |
Delphi4 XE / iOS / read XML file /
Am I correct in that Delphi 4 XE Pro does not supply any native way of reading XML documents? (TXMLDocument is Windows only) I have pondered about using TClientDataSet, but I am not sure if that is the right way to go.
Here is an example of what I want: Readonly XML file that defines a list of contacts. In the XML file, it also contains e.g. file path to photo of contact.
Ideally I then want to show the data in e.g. a TListBox (which might mean I need to write my own logic for loading images in/out of memory.) | If validation is not required (as in the linked answer above), try
NativeXml or OmniXML
Both are free open source libraries for Delphi, however I have not checked if they can be used on other platforms.
Update: see < and Windows & Mac XML library for delphi XE2 | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "ios, xml, delphi"
} |
How to know if a completion packet is for WSASend() or WSARecv() or AcceptEx()?
When I call `WSASend()` or `WSARecv()` or `AcceptEx()`, a completion packet will be placed in the completion port and I can dequeue it using `GetQueuedCompletionStatus()`. But how can I know what operation this completion packet represents? | You use an 'extended' `OVERLAPPED` structure which contains other information. Often this also contains the data buffer and some flags which tell the caller of `GetQueuedCompletionStatus()` what the completion type is.
There are lots of useful tutorials about IOCP on the web and I expect all of them explain this as it's fairly fundamental. My tutorials can be found here, along with some code which implements a some simple IOCP servers. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c++, sockets, winapi, network programming, iocp"
} |
How to detect users on an iPhone with "Private Browsing" enabled?
My jquerymobile App requires the use of localStorage and sessionstorage e.t.c, I've been giving a prompt to users without cookie support and telling them to enable cookies, but if a user has private browsing enable, this create cookie test I'm doing doesn't work and they just get a still erroneous screen, does anyone know how I could test if the user has private browsing enabled?
Thanks | I don't have an Iphone to test this on, but in the desktop Safari browser (in private mode) running the below function does catch the error and handles it as expected.
function storageEnabled() {
try {
localStorage.setItem("__test", "data");
} catch (e) {
if (/QUOTA_?EXCEEDED/i.test(e.name)) {
return false;
}
}
return true;
}
if (!storageEnabled()) alert('localStorage not enabled');
Jsfiddle: < | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 6,
"tags": "javascript, iphone, jquery mobile"
} |
Generate questions based on keyword in php
I am working on a project that must generate human readable questions based on a single keyword. I'm kind of lost on how to start though. Can anyone point me in the right direction? | A computer is no different from a human in this regard. If you ask a human to come up with random questions about "president", he or she will draw upon past experience and knowledge to formulate questions. For example, the question "Is the president doing a good job?" will probably be the first one produced, because in the past experiences of most people, it has been an interesting question about the keyword provided.
So you're basically walking into a very complex area of study. This is going to involve probably thousands of question templates, a neural net of some kind to select questions based on input, and a lot of trial-and-error.
In short, this isn't something you can just throw together in a few hours and be done with it. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "php, artificial intelligence"
} |
How to use custom array in yii2 dataprovider gridView?
I have the following array at the top of the view file:
$order_status = array(
'nocourier' => 'در حال جستجوی پیک',
'accepted' => 'پیک تعیین شد',
'picking' => 'در حال دریافت مرسوله',
'delivered' => 'تحویل داده شد'
);
And later in the page, I want to use it inside one of the columns of the dataprovider table as below:
[
'label' => 'Status',
'format' => 'raw',
'value' => function ($model, $order_status) {
return Html::a("<div class='col-sm-8 progress' style='padding: 0px; height: 10px;'>
<div class='progress-bar ".$model->status."'></div>
</div><label class='col-sm-4'>".$order_status[$model->status]."</label>", null);
},
'headerOptions' => ['style' => 'text-align: center;'],
'contentOptions' => ['style' => 'width: 300px;']
]
But I get empty label. What am I missing? | could be you need `use` for pass the content of the array to the anonymous function eg:
'value' => function ($model) use ($order_status){
return Html::a("<div class='col-sm-8 progress' style='padding: 0px; height: 10px;'>
<div class='progress-bar ".$model->status."'></div>
</div><label class='col-sm-4'>".$order_status[$model->status]."</label>", null);
}, | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "yii2"
} |
How to pass multiple values in a request in a get method
and during my studies I came across this problem:
Imagine this request body:
response = requests.get('
It is possible to pass several values in the key.
I'm trying to create a function where I can pass multiples values as an argument
def request(*data):
d = {}
d.update({'keys':data})
return ('
But, the output format is incompatible:
request(1,2,3)
" '2', '3')"
The ideal format would be this:
"
I don't know if I managed to be clear in my question. I'm still starting my studies, I appreciate the help | You have a tuple which you have to convert to a string:
def request(*data):
return ('
print (request(1,2,3)) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "python, request"
} |
perl: add to a path using substitution
My script takes in a filepath, and I want to append a directory to the end of the path. The issue is I want to be agnostic of whether the argument has a trailing slash or not. So for example:
$ perl myscript.pl /path/to/dir
/path/to/dir/new
$ perl myscript.pl /path/to/dir/
/path/to/dir/new
I tried `$path =~ s/\/?$/\/new/g`, but that results in a double `/new` if a slash is present:
$ perl myscript.pl /path/to/dir
/path/to/dir/new/new
$ perl myscript.pl /path/to/dir
/path/to/dir/new
What's wrong? | Drop the `/g` modifier:
$path =~ s/\/?$/\/new/
works fine.
You only want to modify add one "new" at the end, so having a `/g` modifier makes no sense.
* * *
Also, note that you can use different delimiters for your regex:
$path =~ s{ /? $}{/new}x;
is a little bit clearer. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "regex, perl, replace"
} |
Як правильно перекласти retail measurement?
Зіткнулась із необхідністю перекласти на українську мову **retail measurement**.
Cambridge dicionary дає лише тлумачення поняття _retail management_
> noun [ U ] UK US COMMERCE, MANAGEMENT the activity of managing stores that sell goods to the public:
>
> She has worked in retail management and customer service.
а також поняття work measurement .
Але жодне з цих не підходить, хоча можна сформувати загальне уявлення, що _retail_ \- роздрібна торгівля, а _measurement_ \- вимірювання, зважаючи на це і це джерело, наприклад.
**То як правильно у документації перекласти саме словосполучення retail measurement?** | **Вимірювання роздробу**.
> The retail measurement service (RMS) tracks the sales of goods from retailers to consumers, at specific outlets in a predefined geographical area.
Переклад:
> Служба вимірювання роздробу (СВР) відстежує продажі товарів роздрібними продавцями споживачам, у певних точках продажу в наперед визначеній зоні. | stackexchange-ukrainian | {
"answer_score": 1,
"question_score": 1,
"tags": "переклад, from english, документація"
} |
output repeated for each line
< this is my code. I have a question about the output so when i tried to print output to file it show me this ouput : < as you can see from this output that the total column was repeated for every line why is this happen the calcdata function seems good to me. If something was wrong in the caldata function can anyone explain what was wrong to me ? thanks | I go through your code and one thing seems to be weird. If i understand clearly, each table correspond to a skater.
For each row you have a base, some score and a total score. In your print function we can clearly see that:
skater[i].baseval[j] print the base val for skater i and row j
Then the score list is displayed with skater[i].score[j][k] where k is the score index in the array.
However when printing the total score you display skater[i].total_score which is a unique value. So it is normal that is the same for each row of the table for one given skater.
If you want a total score for each row, you just have to transform skater[i].total_score to an array then compute the total score and add it to the righ row (like you did for the base score)
Edit: changed wrong variable name
Regards | stackexchange-stackoverflow | {
"answer_score": -1,
"question_score": -1,
"tags": "c"
} |
How can I use arrays and JS to replace classes in a html element?
I am trying to make an interaction that replaces an element class with the next class in the array when the link is clicked. How can I do that?
Html
<a id="text" href="#">Change weights</a>
<h1>Hello world</h1>
Javascript
var weights = ["jHairline", "jThin", "jLight", "jRegular", "jMedium"];
$('text').addEventListener('click', function(e) {
$("h1").each("weights");
e.preventDefault();
});
Thank you in advance. | You can something like
$(function() {
var weights = ["jHairline", "jThin", "jLight", "jRegular", "jMedium"];
//Variable to store the current class being pointed
var currentIndex = 0;
//Bind click handler
$('#text').on('click', function(e) {
//Removes all classes and a
$("h1").removeClass().addClass(weights[currentIndex]);
//Reset to 0, if its last index
if (currentIndex == weights.length)
currentIndex = 0;
else
currentIndex++;
e.preventDefault();
});
});
DEMO | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -2,
"tags": "javascript, jquery, html"
} |
UML standards guide / Best Practices
Does anyone know of a decent UML standards guide?
My company currently relies on UML 2.0 (rightly or wrongly) to do the majority (read _all_ ) of their design work. I have been asked to come up with a draft 'best practice' guide to help other developers develop better models. The main problem I face is that Im slightly biased against UML... I feel that: if a diagram takes more than 5 mins to draw then its too complicated! Im looking for advice predominantly on what sort of standards I should be looking at. Also Im looking for an external source of information that can be used to balence out my irrational loathing of UML-heavy design and act as a 'sanitizer' for my suggestions.
Most of all Im looking to write a useful document rather than one that will sit moulding away in some obscure network directory.
Any ideas? | UML Distilled by Martin Fowler | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 4,
"tags": "uml, standards"
} |
FFMPEG : Two processes with a single action
I want to complete the command with 2 different source files in one operation, is that possible?
my codes :
ffmpeg -i 1.mp4 -i 1.png -filter_complex "[1:v]format=argb,geq=r='r(X,Y)':a='0.2*alpha(X,Y)'[zork]; [0:v][zork]overlay" -vcodec libx264 myresult.mp4
ffmpeg -y -i myresult.mp4 -i 2.png -filter_complex "[1:v]format=argb,geq=r='r(X,Y)':a='0.3*alpha(X,Y)'[zork]; [0:v][zork]overlay" -vcodec libx264 1.mp4 | Combined command:
ffmpeg -i 1.mp4 -i 1.png -i 2.png -filter_complex "[1:v]format=argb,geq=r='r(X,Y)':a='0.2*alpha(X,Y)'[zork1];[0:v][zork1]overlay[bg];[2]format=argb,geq=r='r(X,Y)':a='0.3*alpha(X,Y)'[zork2];[bg][zork2]overlay" -vcodec libx264 myresult.mp4 | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "video, ffmpeg"
} |
JavaFX: MediaPlayer cannot play the movie
I'm trying my first MediaPlayer javafx application. I followed a lot of how-to but i'm still not able to run a video on a new application.
What's wrong with this:
Media m = new Media ("file:///C:/Documents%20and%20Settings/User/Desktop/samples/kick.mp4");
MediaPlayer mp = new MediaPlayer(m);
MediaView mv = new MediaView(mp);
Group root = new Group();
root.getChildren().add(mv);
stage.setScene(new Scene(root,400,400));
stage.setTitle("Media Player");
stage.show();
mp.play();
The app builds correctly, no "file not found exception" is fired, but the player is stuck in the UNKNOWN status and the raised window is with a white, fixed background. Neither any kind of audio is provided. Any suggestion? | Got it! I'm running on Windows XP, therefore i'm missing some codec.
From here:
For Windows XP and Windows Vista, JavaFX Media 2.2 requires that one of the following
external modules be installed to play AAC audio and H.264/AVC video:
MainConcept H.264/AVC Pro Decoder Pack
DivX Plus Codec Pack
MainConcept Showcase (includes demo version codecs)
Installing DivX codecs did the trick! | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 1,
"tags": "java, video, media player, javafx 2, javafx"
} |
Nginx loses POST variable with http -> https redirect
I have a website set up that uses the redirect method...
server {
listen 80;
server_name example.org;
return 301
}
However when a page is posted to "< it redirects to "< and in the process, it strips the POST.
I recognize this is how it works, however I need to somehow do one of the following...
* Do a redirect from http -> https while keeping the POST variable intact
* Convert the POST variable to a GET variable during the redirect (which would work fine)
* Redirect everything EXCEPT for one folder
Any suggestions? I'm a bit lost... | If you are willing to forgo the "permanent" redirect status, I believe a 307 redirect instead of a 301 will preserve the POST. There actually is a redirect that is permanent and preserves the post, a 308, but it isn't well adopted yet by browsers and other user agents. | stackexchange-stackoverflow | {
"answer_score": 16,
"question_score": 10,
"tags": "apache, .htaccess, redirect, nginx, https"
} |
Redirect channel to another speaker
I'm not sure about the title but don't know how to say it in a clearer way.
My Soundcard is a Creative X-Fi and I'm using the Creative console starter.
Now I'd like to use my speakers not only for my normal screens but also when using a beamer. Due to my room's geometry, the only place for the beamer's projection is a wall which is right to my normal screens (so the projection would be between the front right and the rear right speaker).
Now I'm thinking about redirecting the channels to the correct speakers somehow. As far as I remember, in previous version of creative console starter there was an option to do this (e.g. redirect front left to rear right output channel).
Does anyone know how to do this with software? Of course I could install a cable switch, but if there's a way without I'd prefer this :)
Thanks in advance. | Virtual Audio Cable allows you to do this.
You can configure virtual cables with it and redirect audio in both ways.. | stackexchange-superuser | {
"answer_score": 0,
"question_score": 3,
"tags": "surround sound, creative"
} |
How do you get this div to wrap around an image link?
I have this image link:
<%= link_to image_tag(comment.user.profile.photo.url(:tiny)), profile_path(comment.user.profile), :class => "comment_image" %>
and I want to wrap a div containing 1. text and 2. a list with a link and text around that image link. I want the image to be on the left, and the div to be on the right wrapping around the image.
!enter image description here | Assuming you don't need any of the fancier features offered by the `link_to` helper, the easy answer is to just use an anchor tag directly.
<a href="<%= profile_path(comment.user.profile) %> class="comment_image">
<div>
Some stuff -- whatever
<%= image_tag(comment.user.profile.photo.url(:tiny)) %>
Some more stuff -- ya know...
</div>
</a> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "ruby on rails, css, ruby, ruby on rails 3, positioning"
} |
Publicly available webservice I can use
I am learning to write PHP client programs which call webservices with POST & GET. Is there any publicly available webservice I can use for trying out client programs? Basically, I don't want to get into writing a webservice first before I start trying out client programs - are there any such easy to use webservices I can use? | You can browse through ProgrammableWeb's API directory (REST protocol). What kind of webservice are you looking for in particular? | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 2,
"tags": "php, rest, webservice client, webservices client"
} |
How to get back button on a new page I added?
I am using navigation template and get a default home page. I add another page called home2, nothing changed yet everything what I get out of VS. From home, I can go to home2. Problem is from home2,I don’t see that back button to get back to home. In my home2.html, I have following
<button class="win-backbutton" aria-label="Back" disabled type="button"></button>
Not sure I can enable it so that I can see it in home2. If I remove the disabled from above line, I do get it but when I click on it, I still am on same page. I am not sure what I need to add to get back button functionality. | how are you getting to home2?
If you use WinJS.Navigation.navigate('/pages/home2/home2.html') this should all work automatically and your back button is available.
If you are using an href, then you'll need to hook into the href and in turn call navigate instead of letting the href work as it normally would, otherwise you aren't using the navigation framework. If you have questions on that - I'll post more but let's first see what you are doing. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "javascript, microsoft metro, winjs"
} |
How to get suggestions in NetBeans for included files
i have a problem to get suggestions for classes which are included in included files.
E.g. content of file 'Header.php' is:
//File 'Header.php':
include('User.php'); //Class file
When I now include the Header.php in my file 'Example.php', i do not get any suggestions:
//File 'Example.php':
include('Header.php');
User::
After typing User:: I exspect Methods and Vars of class User as suggestions, but there arent any. If I would include 'User.php' directly in my 'Example.php' it works, but that doesn't help me. How to solve this problem? | This works fine for me, but all the files have to be included in a Project file. You can't just open random files and include them. Also, if it's lagging, try pressing Crtl+Space. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "php, class, include, netbeans6.8, phpdoc"
} |
Finding the common eigenvectors of two matrices
I want to find the common eigenvectors of two symmetric matrices with the same dimension in R Assuming two matrices L1 and L2 I am looking for vector X such that L1*X = (landa)L2*X where landa is the eigen value | The term you are looking for is Generalized Eigenvalue Problem. This is a well researched linear algebra problem.
In terms of implementation, I suggest looking at a special Netlib section, where I think your matrices will satisfy Generalized Symmetric Definite Eigenproblems solver requirements.
Intel MKL provides the functionality directly available from C, Fortran, and, as far as I know, Python. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "eigenvalue, eigenvector"
} |
Does 1 >= 2 ? console.log("123"): null; create memory leak?
i have the question to this statement `1 >= 2 ? console.log("123"): null;`
Does the statement create a memory leak because of "null"? I can write the code like this instead of an if statement.
Best regards, | In JavaScript, values exists as long as you can _reference_ (access) them. A memory leak is, if you keep a reference to thigs that you actually don't need anymore. In your case however, `null` never gets stored somewhere, so it gets thrown away directly after that statement executed. There is no memory leak.
* * *
As a sidenote, there is no reason to use a ternary at all here. That can be written in a cleaner way using an if statement:
if(1 >= 2) console.log("123"); | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": -3,
"tags": "javascript, typescript"
} |
Defining a cell inside Google Sheets using a Script
I am writing a Google Sheets Script to save as Sheet file to a PDF. I want the File Name to be `Cell A11` (which is a combination of texts from other cells). So I wrote this:
file.setName(Cell + '.pdf');
My question is: how can I define "Cell" to pull data from A11 from inside the spreadsheet. | Here. Add this function to your script.
function getFilename() {
var spreadsheet = SpreadsheetApp.getActive();
var sheet = spreadsheet.getSheetByName('Sheet1');
// Edit the sheet name as necessary
var cell = sheet.getRange('A11');
var filename = cell.getValue();
return filename;
}
Then change
`file.setName(Cell + '.pdf');`
to
`file.setName(getFilename() + '.pdf');` | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "google sheets"
} |
Propositional Logic simplification
I was wondering if anyone could help me to understand how this is simplified:
P v (P ^ Q)
The answer is:
1) (P ^ T) v (P v Q) - apply Identity.
2) P ^ (T v Q) - apply Distributive.
3) (P ^ T) - apply Identity.
4) P - apply identity.
Steps 3, and 4 I get.
I don't see how step 1 is an application of Identity.
Identity states: `P v T = T`... `P v F = P`... `P ^ T = P`... `P ^ F = F`...
So from: `P v (P ^ Q)`
How is step 1 applying identity? I can't seem to understand how that uses identity.
Thanks. | Step one is taking $P$ and expressing it as $P\land T$ which as one of your identities states, is equivalent to $P$.
So $$\color{blue}{\bf P} \lor (P\land Q) \equiv \color{blue}{\bf (P \land T)} \lor (P\land Q)$$ | stackexchange-math | {
"answer_score": 3,
"question_score": 1,
"tags": "logic, propositional calculus"
} |
update textview from inside of thread?
There is an int value that continuously get updated inside a thread and I want to show the value in a textview but i m unable to use findviewbyid inside of thread ?
How to refer to that textview from inside that thread and update it accordingly?
Here is my code:
package com.example.raj.testview;
import android.widget.TextView;
public class TextChange implements Runnable
{
public void run()
{
TextView tv=(TextView)findViewById(R.id.tv);
for(int i=0;i<10000;i++)
{
tv.setText(String.valueOf(i));
}
}
} | You cannot change UI elements from a non-UI thread. Try using runOnUiThread).
runOnUiThread(new Runnable(){
@Override
public void run(){
// change UI elements here
}
}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -2,
"tags": "android, android layout, android activity"
} |
Split list into sub-lists based on integer in string
I have a list of strings as such:
['text_1.jpg', 'othertext_1.jpg', 'text_2.jpg', 'othertext_2.jpg', ...]
In reality, there are more entries than 2 per number but this is the general format. I would like to split this list into list of lists as such:
[['text_1.jpg', 'othertext_1.jpg'], ['text_2.jpg', 'othertext_2.jpg'], ...]
These sub-lists being based on the integer after the underscore. My current method to do so is to first sort the list based on the numbers as shown in the first list sample above and then iterate through each index and copy the values into new lists if it matches the value of the previous integer.
I am wondering if there is a simpler more pythonic way of performing this task. | Try:
import re
lst = ["text_1.jpg", "othertext_1.jpg", "text_2.jpg", "othertext_2.jpg"]
r = re.compile(r"_(\d+)\.jpg")
out = {}
for val in lst:
num = r.search(val).group(1)
out.setdefault(num, []).append(val)
print(list(out.values()))
Prints:
[['text_1.jpg', 'othertext_1.jpg'], ['text_2.jpg', 'othertext_2.jpg']] | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, list"
} |
How to disable remember last position (directory) in apps?
I noticed that every time I open a new window of Files and Terminal, it goes directly to the previous working directory. How can I disable this completely for all applications? | You can find answers for your question at these questions:
* Files: How to choose the default directory Pantheon-files starts in
* Terminal How to disable last working directory in pantheon-terminal? | stackexchange-elementaryos | {
"answer_score": 1,
"question_score": 0,
"tags": "release loki, pantheon terminal, files"
} |
Vector space with homogeneous system
The question states:
Which are the following are subspaces of M (nxn):
And the main problem I'm having trouble understanding is with this question:
The set of all n x n matrices A for which Ax=0 has only the trivial solution.
How would I go about proving if this is a subspace? | If we know $V$ is a vector space a priori, then a space $W$ contained in $V$ is a subspace of $V$ if there is closure under scalar multiplicaton and addition.
What does it mean for a square matrix $A$ such that $A\vec{x}=\vec{0}$ to have only the trivial solution?
This means that $A$ is invertible.
Can you find two invertible matrices such that when you add them together you do not get an invertible matrix?
Yes! Let $A=\begin{pmatrix} 2&1\\\ 1&1\\\ \end{pmatrix}$ and $B=\begin{pmatrix} -2&-1\\\ -1&-1\\\ \end{pmatrix}$
Thus $A+B=\begin{pmatrix} 0&0\\\ 0&0\\\ \end{pmatrix}$ which is not an invertible matrix since $\det(A+B)=0$.
Since we have demonstrated that adding two matrices together in our supposed subspace yields a matrix **not** in our subspace, the set of all $n\times n$ matrices $A$ for which $A\vec{x}=\vec{0}$ has only the trivial solution is not a subspace of $M_{nn}$ matrices. | stackexchange-math | {
"answer_score": 0,
"question_score": 1,
"tags": "linear algebra, vector spaces"
} |
String.Format in C#
I have an values like
1,000
25,000
500,000
Need to convert above values as like below without comma
1000
25000
500000
How to acheive this in C#?
how to get reverse output of this -
string.Format("{0:n}", 999999) | You can use the `Replace` function of the string class like so:
string str = "25,000";
str = str.Replace(",", "");
EDIT:
As suggested by `Matthew Watson` from the comments
> If the string is returned from string.Format("{0:n}", 999999) run on a machine in a locale that uses "." as the thousands separator, this will fail
updated answer:
string num = "25,000";
NumberFormatInfo currentInfo = CultureInfo.CurrentCulture.NumberFormat;
num = num.Replace(currentInfo.NumberGroupSeparator, ""); | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 1,
"tags": "c#, string.format"
} |
Grails: How to create a clear button?
Hello I have created a filter for my list. In a template named `_search.gsp` And I need a clear button that clears out all the fields in the filter. I have one textField named `proyectoRutaN` And four datePickers named `fechaCambioD` , `fechaCambioH` , `lastUpdatedD`, and `lastUpdatedH`
Any help would be greatly appreciated! Thanks!
-Fernando | I think you can just use the html tag:
<input type='reset' value='Reset' />
within your form. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "button, grails, groovy, filter"
} |
Pandas convert positive number to 1 and negative number to -1
I have a column of positive and negative number. How to convert this column to a new column to realize convert positive number to 1 and negative number to -1? | You need `numpy.sign`
df['new'] = np.sign(df['col'])
**Sample** :
df = pd.DataFrame({ 'col':[-1,3,-5,7,1,0]})
df['new'] = np.sign(df['col'])
print (df)
col new
0 -1 -1
1 3 1
2 -5 -1
3 7 1
4 1 1
5 0 0 | stackexchange-stackoverflow | {
"answer_score": 14,
"question_score": 7,
"tags": "python, pandas"
} |
How can I automatically insert values into a new column I made based on a column that already exists in mySQL
I had an `employee` table that stored some data which includes `salary`. I added another column `grade`.
If salary is between 0-2000 grade is 1.
If between 2000-3000 grade is 2.
If more than 3000 than 3.
Do I need to manually do this through `UPDATE` or is it possible to define this condition with `ALTER`. | It is possible to do this with an update. But, you might find it better to use a generated column:
alter table employee add grade int generated as
(case when salary < 2000 then 1 when salary < 3000 then 2 else 3 end);
This is handy, because you don't have to update the grade if the score changes or when new rows are added. `GRADE` is calculated when it is used. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "mysql, sql"
} |
weird inheritance for list item links
in the process of updating my html to html5, i noticed that the inheritance behaved a bit strange. i'm not sure why links in the ul li lists have matched css rules with blocks that have nothing to do with it.
!enter image description here eg in screenshot 1 (aside), it takes over styles from the footer (but out of the screenshot also from role=navigation)
!enter image description here in screenshot 2 (footer), it takes of styles from the aside (and also from the screenshot also from role=navigation)
why does it do so? | In you first screenshot the css that gets applied is used on #footer #footerGrid ul li a, a:link,a:visited. By seperating this with comas you are having 3 different css selectors:
* #footer #footerGrid ul li a
* a:link
* a:visited
So this gets applied to the footer section, but also triggers on a:link and a:visited. And the same goes to your 2nd screenshot vice versa !
documentation for that:
* <
> Note When grouping selectors, remember that the comma starts an entirely new selector from the beginning. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "css, html, inheritance"
} |
What does ``` var num = 200_200 ``` mean in kotlin?
I am learning kotlin through codecademy and came across this exercise where we were learning operators like `+ - % /` then I noticed this line of code and din't understand could someone please explain?
`var Num = 200_200`
That is the line of code. | The `_` is ignored by the compiler. It's only there for readability.
You can use `_` as a delimiter, dividing numbers into more readable parts. In your example, you use the `_` as a thousand delimiter. But if you want to work with bits at some point, you can also use `_` to delimit bytes, e.g., `0010_1010`.
Kotlin reference: < | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "kotlin"
} |
How to merge all exports from different files into one?
e.g.
./one.const.js ---------> module.exports = {};
./two.const.js ----------> module.exports = {};
./index.js---------------> module.exports = mergedExports; // mergedExports: {one: {}, two: {}};
In a folder say `xyz` I have two files with *.const.js filenames and there's one index.js. I want an automated code in index.js which merges all the exports from *.const.js | Assuming you want to do this on startup:
const fs = require('fs');
const regex = new RegExp('.const.js$')
const files = fs.readdirSync('.').filter((fileName) => regex.test(fileName))
const mergedExports = {};
for (let i =0; i < files.length; i++) {
const fileName = files[i].split('.const.js')[0]
mergedExports[fileName] = require(`./${files[i]}`)
}
module.exports = mergedExports
If you want to merge the exports into a single object, update the for loop to:
for (let i =0; i < files.length; i++) {
mergedExports = { ...mergedExports,
...require(`./${files[i]}`),
}
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "node.js, npm, node modules"
} |
Doubt on a Lipschitz Inequality
I am following this paper. Towards the top of page 23 the author has: $$|D(v,t) - D(v_i,t)| \leq \frac{f(a+tv) - f(a+tv_i)}{t}| + |(v-v_i)\cdot \nabla f(a)| \leq C \cdot |v - v_t|$$
where $D$ denotes the total deriative in the direction of $v$ and $C$ comes from the Lipschitz constant. However, how does the $t$ in the denominator vanish? | Since $f$ is Lipschitz: $$\left|\frac{f(a+tv)-f(a+tv_i)}{t}\right| = \left|\frac{f(a+tv)-f(a+tv_i)}{(a+tv)-(a+tv_i)}(v-v_i)\right|\le L|(v-v_i)|$$ where $L \ge 0$ is the Lipschitz constant.
He then puts $C = L +|\nabla f(a)|$, using Cauchy-Schwarz. Hope it is clear. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "real analysis, functional analysis, inequality"
} |
Confusion about a simple Fourier Transform
I was looking at a table of Fourier transform pairs, and one entry is really confusing me. There's one on the second page that states $$ \mathcal{F}(\cos(\omega_0t))(\omega) = \pi(\delta(\omega - \omega_0) + \delta(\omega + \omega_0)) $$ I know that a Fourier transform is supposed to map a function in the time domain to an equivalent function in the frequency domain, so lets see what that means in this case. The period of $\cos(\omega_0t)$ is $2\pi/\omega_0$, meaning the frequency in rad/s is $\omega_0$. Thus at $\omega = \pm\omega_0$, the frequency domain should be $1$, because the amplitude of $\cos$ is $1$. When we plug it in, however, we get $\pi$: $$ \pi(\delta(0) + \delta(2\omega_0)) = \pi(1 + 0) = \pi $$ Why is this true? Isn't the amplitude of the cosine $1$, not $\pi$? | The Dirac distribution needs an integration to lead to finite values.
And that might also explain the factor $\pi$, because that integration is the inverse Fourier transformation and that might have a compensating factor in your case.
Your text lists $$ f(t) = \frac{1}{2\pi} \int\limits_{-\infty}^{\infty} \\!\\! F(\omega)\,e^{j\omega t}\, d\omega $$
so this gives $$ f(t) = \frac{1}{2\pi} \int\limits_{-\infty}^{\infty} \\!\\! \pi \left[ \delta(\omega - \omega_0) + \delta(\omega + \omega_0) \right] \, e^{j\omega t}\, d\omega = \frac{1}{2}\left[ e^{j\omega_0 t} + e^{-j\omega_0 t}\right] = \cos(\omega_0 t) $$ so we could read the transform as $$ F(\omega) = 2\pi \, \frac{1}{2} \left[ \delta(\omega - \omega_0) + \delta(\omega + \omega_0) \right] $$ where the $2\pi$ is due to the specific constants choosen for the Fourier transformation pair. | stackexchange-math | {
"answer_score": 2,
"question_score": 0,
"tags": "fourier analysis"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.