INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Insert last Second of day
How do you use C# to insert into an SQL table the very end of a day?
Example:
2012-03-01 23:59:59
This field in my database (SQL SERVER) is `SmallDateTime`. When I edit this field in SQL Management Studio and up the seconds to 50 this changes to 00:00:00.
|
If you want to reference the last second of a day, you'll need to change your column from SmallDateTime to DateTime since SmallDateTime does not support seconds.
SmallDateTime
From MSDN:
smalldatetime
Date and time data from January 1, 1900, through June 6, 2079, with accuracy to the minute. smalldatetime values with 29.998 seconds or lower are rounded down to the nearest minute; values with 29.999 seconds or higher are rounded up to the nearest minute.
--returns time as 12:35
SELECT CAST('2000-05-08 12:35:29.998' AS smalldatetime)
GO
--returns time as 12:36
SELECT CAST('2000-05-08 12:35:29.999' AS smalldatetime)
GO
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 2,
"tags": "c#, sql server 2008"
}
|
search first x characters from excel range
I need to search an Excel range for specific text, and return how many are found, but want to search only on the first 4 characters. I have
=SUMPRODUCT(-- ISNUMBER(FIND("V",E4:E40)))
which does search the range, but it finds all `V`'s and not those just in the first 4 characters. The data starts with a 4 character acronym and then has free form text.
I'm unable to get `LEFT` to work in this formula.
|
=SUMPRODUCT(-- (LEFT(E4:E40,4) = "VOID"))
If you only want to see if `V` is in the first 4 letters:
=SUMPRODUCT(--(FIND("V",E4:E40 & "XXXXV")<=4))
concatenating the `& "XXXXV"` on the end removes the possiblity of the error. So the Find will return a number. We then test whether that `V` is found in the first 4 characters.
We added four`X` to the string to ensure that if the value has a length less than 4 we do not get false positives.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "excel, excel formula"
}
|
AWS API Gateway: Get or Post for querying
I am creating an API, which is going to list me products page by page with given filter conditions.
To give a brief description, it holds a AWS Lambda behind AWS API.
I am not able to decide whether to use GET or POST.
* Because querying is considered a **GET** operation, so this is natural choice. But having a GET operation with JSON body is not very convenient way. So basically, I am left with the choice of putting it in URL.
* About **POST** , I wont be able to use API cache in future if required.
Please suggest the right way.
|
Use `GET`.
Many clients do not support the body for `GET`, use URL params instead of the body. `GET` can be cached, bookmarked. Also `GET` is a natural choice as you are not updating any data.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "amazon web services, post, get, aws api gateway"
}
|
How to get top hit count pages programatically in SharePoint 2013
Can anyone help me how to get Top pages by Hit Count form my site collection?
In SharePoint 2010 it was easy. CSOM, REST, jsom, powershell methods also acceptable.
|
Here are three excellent sites with step-by-step instructions for what you want:
<
<
Is it possible to get the most popular pages using REST?
|
stackexchange-sharepoint
|
{
"answer_score": 0,
"question_score": 2,
"tags": "sharepoint online"
}
|
Codekit 2 doesn't resolve Bonjour Hostname after Yosemite 10.10 Upgrade
After upgrading to Yosemite 10.10 via the AppStore (no new/clean install), I get a blank page when previewing a website with Codekit 2. In the "Server" tab the Bonjour Hostname in my case "lukas.local" is missing since the upgrade <
Any ideas how to expose my Bonjour hostname correctly again? Thanks!
|
Check your HostName - I had the same issue;
sudo scutil --get HostName
If you don't get back an expected result (ie. lukas.local) change it... along with the ComputerName and LocalHostName if they need changing...
sudo scutil --set ComputerName Lukas
sudo scutil --set LocalHostName lukas
sudo scutil --set HostName lukas.local
Restart the CodeKit servers.
Hope that helps someone at least.
|
stackexchange-stackoverflow
|
{
"answer_score": 18,
"question_score": 8,
"tags": "bonjour, osx yosemite, codekit"
}
|
Filter out random username after string
I have a full list of API status with lots of information like that. I need to grep the name of the username so I can send it to another file or variable.
For example:
[{"id":"1onyc4b1otgmtrmw37h83rjs9w","create_at":1542718790947,"update_at":1542728017634,"delete_at":0,"username":"ivan.ivanov","auth_data":"".
I need to grep the string after "username": In the end to have only **ivan.ivanov** or whatever the name will be.
|
If this was a proper json string, you could parse it with `jq`:
your_api_call | jq -r '.[]["username"]'
or
jq -r '.[]["username"]' file
But the string you provided is not proper json. It's missing the closing brackets (`]}`) at the end and has a `.` instead.
`jq` should be available in most package managers, e.g. install it with:
sudo apt install jq
* * *
If you somehow **need** to use `grep` and have `pgrep` / `grep -P` available:
grep -Po '"username":"\K[^"]*'
|
stackexchange-unix
|
{
"answer_score": 2,
"question_score": 0,
"tags": "linux, grep, json"
}
|
Homomorphism on U(36)
**Question** Suppose that $f$ is homomorphism of $U(36)$, $\ker(f) = \\{1,13,25\\}$, and $f(5) =17$. Determine all the elements that map to 17.
**What I've tried so far** So I've determined that $U(36) = \\{1,5,7,11,13,17,19,23,25,29,31,35\\}$ so $|U(36)| = 12$. Because $\ker(f) \triangleleft U(36)$, and $|\ker(f)| = 3$, then we know that $U(36)/\ker(f)$ is a group of order 12/3 = 4.
However, I'm not sure any of this helps. Any suggestions on how to determine the elements that map to 17?
|
Note that if $k \in \ker(f)$, and $g \in U(36)$, then $f(kg) = f(k)f(g) = f(g)$.
To convince yourself that this is the full story of the preimage $f^{-1}(17)$, think about the first isomorphism theorem strictly in terms of sets: It tells you that the cosets $U(36)/\ker(f)$ are in bijection with $\operatorname{Im}(f)$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "abstract algebra, group theory, group homomorphism"
}
|
(Python) MVHR Covariance and OLS Beta difference
I calculated the minimum variance hedge ratio (MVHR) of two securities' returns by:
1\. Calculating the optimal h* = Cov(S,F) / Var(F) using samples
2\. Running an OLS regression and obtain the beta value
Both values differ slightly, for example I got h* = 0.9547 and beta = 0.9537. But they are supposed to be the same. Why is that so?
Below is my code:
import numpy as np
import statsmodels.api as sm
var = np.var(secRets, ddof = 1)
cov_denom = len(secRets) - 1
for i in range (0, len(secRets)):
cov_num += (indexRets[i] - indexAvg) * (secRets[i] - secAvg)
cov = cov_num / cov_denom
h = cov / var
ols_res = sm.OLS(indexRets, secRets).fit()
beta = ols_res.params[0]
print h, beta
indexRets and secRets are lists of daily returns of the index and the security (futures), respectively.
|
This is also a case of missing constant in OLS regression. The covariance and variance calculation subtracts the mean which is the same in the linear regression as including a constant. statsmodels doesn't include a constant by default unless you use the formulas.
For more details and an example see for example OLS of statsmodels does not work with inversely proportional data?
Also, you can replace the python loop to calculate the covariance by a call to `numpy.cov`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, numpy, statsmodels"
}
|
list conversion of jsonlite in R
I would like to have a list of matrices within R imported from a json file using jsonlite.
A <- matrix(rnorm(100),10,10)
B <- matrix(rnorm(100),10,10)
C <- matrix(rnorm(100),10,10)
l <- list(A,B,C)
import_l <- fromJSON(toJSON(l),simplifyMatrix = FALSE)
the above code doesnt work since it is R internally a list of list of numerics. However, I would like to have my list of `A,B,C` back, i.e. `l`. Is there a way to achieve getting back the correct list of matrices using jsonlite?
|
The issue here is that a column matrix and an unnamed list look the same if converted to JSON:
toJSON(list(1, 2, 3))
## [[1],[2],[3]]
toJSON(matrix(c(1, 2, 3), ncol = 1))
## [[1],[2],[3]]
However, a _named_ list looks different:
toJSON(list(A = 1, B = 2, C = 3))
## {"A":[1],"B":[2],"C":[3]}
If you use a named list in your example, `fromJSON()` does indeed reproduce the original list:
l <- list(A = A, B = B, C = C)
all.equal(fromJSON(toJSON(l)), l, tol = 1e-4)
## [1] TRUE
If this is not possible - for example because you don't create the JSON file yourself, but get it as an input - you can also convert the result you get with `fromJSON()`:
l <- list(A, B, C)
import_l <- fromJSON(toJSON(l))
l2 <- lapply(1:3, function(i) import_l[i, , ])
all.equal(l2, l, tol = 1e-4)
## [1] TRUE
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "r, jsonlite"
}
|
Hide GET request html/php
I'm not really sure what I'm looking for, but I know what I wanna do. Therefor it's kinda hard to search. Sorry for being stupid, the answer might be really simple.
I got a website, as of currently I take a get request like: <
What I want is to have it as <
The website then takes the value and does a bunch of stuff, but I'm not really sure how to get it like this. Is it from editing .htaccess or what?
How do I fix that? (again, sorry for being stupid)
|
Specifically for you condition try this..
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^([0-9]+)$ index.php?id=$1
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "php, html, .htaccess"
}
|
Check for specific combinations of values in an array
I have an array containing both lemons and pears. I want to check if there are exactly five pears and two lemons in that array without creating a separate array for the two. How could I do that?
|
You can use **Array** `count` method to get the count of a particular element in an array.
fruits = [:pears, :pears, :lemons, :figs, :pears, :figs, :lemons, :figs, :apples, :pears, :pears]
puts fruits.count(:pears) == 5 && fruits.count(:lemons) == 2 # will return true if the pears is 5 and lemons is 2 in fruit array
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -3,
"tags": "arrays, ruby"
}
|
Does declaring items on customs necessarily imply taxes owed?
If an item needs to be declared on customs for any country when arriving by airport, and you declare that item, does that necessarily mean that you will need to pay duty/taxes on that item?
|
No. Declaring an item simply means telling the customs authorities that you have it. Whether or not you have to pay duty will depend on the particular laws of that country and the situation.
For example, I purchased some cake at Demel in Vienna and brought it to the United States. I declared it to customs, because it is food, and the United States requires that you declare food. I didn't have to pay duty, because I did not exceed my allowance for goods that can be imported without duty.
Exactly what must be declared and when duty must be paid is a matter of national law.
|
stackexchange-travel
|
{
"answer_score": 15,
"question_score": 3,
"tags": "customs and immigration, airports, airport security, borders, import taxes"
}
|
How to remove duplicates in map()
How to remove duplicates in `[].map()` . `a.href` may contain the same `href` link, how can I stop this reoccuring data? EXAMPLE: www.example.com | www.example.com
const hrefs = await page.evaluate(() => {
const anchors = document.querySelectorAll('a');
return [].map.call(anchors, a => a.href);
});
|
Set hrefs = new Set([].map.call(anchors, a => a.href));
return [...hrefs];
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "javascript, node.js, web scraping"
}
|
Woher stammt der umgangssprachliche Ausdruck „Boah ey“?
Woher kommt der umgangssprachliche Ausdruck „Boah ey“? Für mich sieht er sehr seltsam aus.
|
Im Wikipedia-Artikel über den Ausruf _" Ey!"_ steht, der Ausdruck sei als Teil der sogenannten Jugendsprache, restringierter Soziolekte/Ethnolekte aufgekommen und hätte als anerkennende Form weite Verbreitung im Rahmen der in den späten 1980er Jahren beliebten Mantawitze gefunden.
Auch im Diagramm von Googles Ngram Viewer wird der Trend seit den achtziger Jahren angezeigt:
!Boah ey! Ngram
Es könnte sein, dass sich der Ausruf aus dem Begriff _" Bohei"_ entwickelt hat. Er bedeutet "Aufheben" im Sinne von _Aufstand_ und _Spektakel_ und hat sich vielleicht aus dem Westmitteldeutschen und Rheinischen aus den Ausrufen _bu(h)_ und _hei_ gebildet oder aus dem Niederländischen (älter niederländisch boeha [heute: poeha] = Lärm, Tumult; Aufheben) gebildet.
Es gibt einige interessante Artikel und Diskussionen, die sich um den Ausruf _Bohei_ drehen:
* <
* < (archiviert)
|
stackexchange-german
|
{
"answer_score": 5,
"question_score": 21,
"tags": "etymology, slang, interjection"
}
|
Windows 10 complete remove tablet mode
Windows 10 detect my workstation custom PC as a tablet device and the Tablet mode is visible in PC settings. 2 applications, Bluestacks, and Droid4X detect my PC as a tablet device. I tried to unplug some USB cable but it's not helping. My monitor is ASUS gaming monitor with Nvidia 3D vision. I had disabled Tablet mode in settings but some applications still detect my PC as a tablet device. How can i fully remove tablet mode from my PC and make Tablet mode disappear from PC settings?
|
As tablet mode is a part of Windows 10 for the new Universal Platform it would be impossible to remove it; however you do have the option to turn it off in Settings.
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 1,
"tags": "windows, windows 10, tablet mode"
}
|
GXT live grid not scrolling to bottom
I have a GXT LiveGridView grid - works great, loading fine, but will not scroll all the way to the bottom record using the scroll bar. The only way to see the last record is to select the last visible record and use the down arrow key to force the display down, one record at a time.
|
By overriding the 'getCalculatedRowHeight' method, since it was returning a wrong value (compared with the Firebug analysis) the issue was resolved.
private class MyLiveGridView<T> extends LiveGridView<T> {
// deal with wrong value of 22 from this method currently.
@Override
protected int getCalculatedRowHeight(){
return 28;
}
}
(A real fix would be to dynamically acquire the correct row height. For now this will suffice since I'm on the hook for a lot of code still).
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "gxt"
}
|
deviceorientation not working
Well I've got this little script:
<script>
window.addEventListener('deviceorientation', function(event) {
var a = event.alpha;
var b = event.beta;
var g = event.gamma;
}, false);
</script>
<script>
setInterval('alert(""+g+"");', '1000');
</script>
Which should add the `deviceorientation`, attach it to the page, and alert every 1 second what the orientation currently is, the gamma.
It's not working, though? Nothing alerts! any tips... ideas...?
**Edit: I get "Uncaught ReferenceError: g is not defined" in the console log... but it is defined!**
|
The `var` statement sets the scope of a variable to the function it is in.
You are trying to access a local variable in the global scope—where it doesn't exist.
Additionally, you don't set the variable until a `deviceorientation` occurs, but you try to read it all the time.
You would have to rewrite your code like this:
<script>
window.addEventListener('deviceorientation', function(event) {
var a = event.alpha;
var b = event.beta;
var g = event.gamma;
console.log( g.toString() ); // Better to use a non-blocking method like console.log to display results.
}, false);
</script>
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "javascript, html, device orientation, uideviceorientation"
}
|
2D pixel array rotation and scaling
I am working on a C# program to process images ( given as int[,] )..
I have a 2D array of pixels, and I need to rotate them around a point, then scale them down to fit the original array. I already found articles about using matrix to transform to a point and rotate then transform back. What remains is to scale the resultant image to fit an array of original size.
How that can be done? (preferably with 2 equations one for x and one for y )
|
Have a look here. That should give you all the math behind doing coordinate rotations.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, image, matrix, rotation, image scaling"
}
|
Python create path with file
Is there a way to create a file and automatically create its path?
for example:
with open("./path/to/file/data.txt", "w") as f:
f.write("hello")
I want it to create the path `./path/to/file` and then create the file `data.txt` and open it. instead it will give the error
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: './path/to/file/data.txt'
I don't want to have to manually create the path one folder at a time.
|
import os
os.makedirs(os.path.dirname(fullPath))
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, file io"
}
|
How To start/stop IIS 6.0/7.0 remotely using PowerShell Scripts?
I have two servers Server A and Server B. I want to stop server A from Server B remotely using Powershell script.
|
One of the simplest ways to do this is really with just a command line execution using PsExec. And send over to the machines
IISReset /STOP or /START or /RESTART
So you'd do something like this
PsExec \\Server2 -u Administrator -p somePassword IISReset /STOP
Just be careful with password management if you go this route or any route that involves some type of admin level account impersonation so that no one can get a plain text copy of the admin password.
|
stackexchange-stackoverflow
|
{
"answer_score": 14,
"question_score": 11,
"tags": "iis, powershell, remote control"
}
|
How to install Jupyter Lab/Notebook on Windows 10?
I have been using R/Python and Jupyter Lab/Notebook on Macbook. In my new job, I need to install and run these applications on Windows 10.
I have Python, pip, Jupyter, R4.1 & RStudio installed manually (not through Anaconda). I try to execute step 2/3: Making the kernel available to Jupyter based on installation guide. I got error message in R Console.
> IRkernel::installspec()
Error in IRkernel::installspec() :
jupyter-client has to be installed but “jupyter kernelspec --version” exited with code 127.
In addition: Warning message:
In system2("jupyter", c("kernelspec", "--version"), FALSE, FALSE) :
'"jupyter"' not found
Appreciate your advice.
|
Please check if jupyter is in your user/system path. A quick way to check is by running jupyter in the command line, you could use powershell commandline:
Get-Command jupyter
CommandType Name Version Source
----------- ---- ------- ------
Application jupyter.exe 0.0.0.0 C:\Users\youruser\AppData\Local\Programs\...
If it's not there, then you can add to your system/user path and check with new instance of commandline again.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "r, windows, jupyter irkernel"
}
|
Golang split strings by char type
I want to be able to split the string into substrings where characters and numbers are separate groups:
re:=regexp.MustCompile("**MAGIC HERE**")
fmt.Println(re.FindAllString("abc123def", -1))
I want to be able to get
[abc 123 def]
Any ideas?
|
Try splitting on this pattern:
\d+|\D+
**Code:**
re:=regexp.MustCompile("\\d+|\\D+")
fmt.Println(re.FindAllString("abc123def", -1))
**Output:**
[abc 123 def]
**Demo here:**
# Rextester
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "regex, go"
}
|
How to detect mod_rewrite without apache_get_modules()?
Is it possible to detect `mod_rewrite` in PHP when function `apache_get_modules()` is not available?
|
You could analyze the output of `phpinfo()`:
ob_start();
phpinfo(INFO_MODULES);
$contents = ob_get_contents();
ob_end_clean();
var_dump(strpos($contents, 'mod_rewrite') !== false);
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 3,
"tags": "php, apache, mod rewrite"
}
|
Down voters should not be punished for filtering trash
I don't propose an exact way to do this. Perhaps, the way would be to simply stop deleting points for down votes. Deleting points for down votes gives an obvious disincentive for down voting, and down voting is what keeps the site spam-free and ensures high quality. Also, consider removing more points from the down voted question / answer. Currently the person down voting loses nearly the same as the person being down voted.
If a news anchor plugs a new product each day during his broadcast, he gives up a little bit of reputation as a trade off for boosting the other party's reputation. In SO a user has unlimited reputation to give away at no expense at no expense.
|
The disincentive I have for downvoting is sympathy upvotes. If somebody posts an inaccurate answer, I downvote, and it gets a sympathy upvote, I'm down 1 rep and the inaccurate guy is up 8.
When will they find a cure for sympathy upvotes?
|
stackexchange-meta
|
{
"answer_score": 8,
"question_score": 1,
"tags": "feature request, voting, down votes"
}
|
Is ColdFusion's isSafeHTML() documentation wrong everywhere?
I have been trying to use `isSafeHTML()` to tell users whether the HTML they have submitted is allowed or not. The documentation at both CFDocs.org and Adobe.com show the function requires three parameters: `inputString, policyFile, throwOnError`. However, when I supply all three parameters, I get an error saying it only accepts 1 or 2 parameters.
After some testing, I have come to the conclusion that `throwOnError` is not a valid parameter for this function. Can anyone else confirm this? If so, is there any way to update the documentation so others do not run into the same issue?
|
You are correct, I just tested it on ColdFusion 2016 update 2 (2016,0,02,299200) and it threw:
> Parameter validation error for the ISSAFEHTML function. The function accepts 1 to 2 parameters.
Using this code:
<cfoutput>
#isSafeHTML("html", server.coldfusion.rootdir & "/lib/antisamy-basic.xml", true)#
</cfoutput>
I have updated the cfdocs.org site to remove the `throwOnError` argument. For future reference you can fix docs on cfdocs.org by clicking on the Edit button, or if you just want to point out an issue you can click on the Issue button.
For Adobe docs, you can file a bug report here: <
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "coldfusion, coldfusion 11, coldfusion 2016"
}
|
Comparing chars in C++ - argument of type "char" is incompatible with parameter of type "const char *
Im trying to compare 2 values in C++ (which im new to so please go easy)
struct styles{
int itemNo;
char desc[26];
char brand[21]; //between 3 - 20
char category;
double cost;
};
struct declared above, then im using this code in another function
char cat[2];
for (x=0;x<size;x++)
{
if (strcmp(cat,styleAr[x].category)==0)
its giving me an error with the 'styleAr[x].category' in the if statement: **argument of type "char" is incompatible with parameter of type "const char ***
any explanations on how I could solve this would be great
|
Assuming that `cat` is a string (that is, one character followed by a `'\0'`), then you should do this:
if (cat[0] == styleAr[x].category)
But of course, if you use `std::string cat` and `std::string category`, you can just write:
if (cat == styleAr[x].category)
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "c++, structured programming"
}
|
как вставить значения получаемые в С++ (qtcharts) в qml в определенной вкладке
Перечитал весь гугл по мвс получаю с помощью методов класса данные, в формате [x,y;x,y;......] не получается отрисовать т.к. не могу понять как правильно их отрисовать на уже созданной форме с кнопками полями (файл main.gml)
В консоли видно что все работает, данные идут, но как их правильно передать в конкретное место qml??
есть методы класса которые возвращают массив и его размер ushort scaner::getNpoints() { if (nRF625!==0) return nPoints; } float scaner::getPointsBuffer() { if (nRF625!==0) return *PointsBuffer; } юай, у меня представлен окном с тремя страницами, которые можно перелистывать(для тач панели) на одной из страниц у меня описаны оси, и свойства графика, как мне туда передать значения для построения. Очень важна скорость отрисовки при этом, всех значений сразу, и последующая их перезапись
|
В примере изначально необходимо было добавить в про файл QT += charts, думал что добавил оказывается нет, по этому постоянно были ошибки. Пример по которому я сейчас пробую закидывать данные в qml слой это osciloscope с помощью qqmlcontext, открываю область видимости. дальше в методах класса реализую функционал добавления на графиках значений. по завершению попробую закинуть результато.
Под вкладкой имел ввиду приложение де окно организовано с помощью перелистывающегося экрана)
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c++, qt, qml"
}
|
Adding Wordpress site to Symfony2 (route)
I have done the following steps:
1.) Extracted the latest version of Wordpress to the src folder of Symfony2
2.) Sort out routing (I currently have an issue with this. See below)
I would like to add Wordpress to my site that is currently built using Symfony2. The problem is that all the routes that symfony uses require a controller to be used. However all I want to do is that whenever a user goes to www.example/newsblog he will see the wordpress site (that means it just loads up the Wordpress/index.php file)
Does anybody have any ideas?
|
So after a bit of searching I've finally got the answer. All that I needed to do was add the following to my Virtual Host:
Alias /blog /home/john/development/phoenix/src/web/Wordpress
<Directory /home/john/development/phoenix/src/web/Wordpress>
Options All
AllowOverride All
order allow,deny
allow from all
</Directory>
That way I could view my main website at www.example.com (which was hosted at /home/john/development/phoenix/src/web) as well as view the Wordpress part of the site at www.example.com/blog (which was hosted at /home/john/development/phoenix/src/web/Wordpress)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "symfony, routes"
}
|
json.Decoding a TCP connection and logging the original data at the same time in Go
I'm using a `json.Decoder` to decode a `net.Conn` into a custom struct. I would like to also log the original JSON string sent on the `net.Conn` without modifying it.
I am looking for an efficient way to achieve this. I currently have the following code:
reader := bufio.NewReader(conn) // conn is a net.Conn
dec := json.NewDecoder(reader)
for {
// How can I also log the original data before decoding it into the struct?
var dst customStruct
if err = dec.Decode(&dst); err == io.EOF {
break
} else if err != nil {
log.Errorf("failed to decode message: %s", err)
break
}
// do something with dst...
}
|
Use iotest.NewReadLogger to log the data as the data is read:
prefix := fmt.Sprintf("%p:", conn)
reader := bufio.NewReader(iotest.NewReadLogger(prefix, conn))
dec := json.NewDecoder(reader)
for {
var dst customStruct
if err = dec.Decode(&dst); err == io.EOF {
break
} else if err != nil {
log.Errorf("failed to decode message: %s", err)
break
}
// do something with dst...
}
If the read logger output does not match your taste, then copy the implementation and adjust as needed. The implementation is very simple.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "json, go, tcp, copy, reader"
}
|
Optimize one shard in large SolrCloud index
I have a large v5.3 SolrCloud index and I want to optimize only one shard. I've read that while the entire index may be optimized, it is not possible to optimize only a single shard. Still, I would like to make sure: < "... with SolrCloud, any optimize command will optimize the entire collection, one shard replica at a time, regardless of any distrib parameter."
|
As far as I can tell from the code, no, you can't call optimize on a single shard.
The quote you've included is however wrong (at least for certain versions of Solr) - any optimize do run in parallell across the collection (included in 4.10 and 6.0 at least, not sure about the 5 branch).
There is usually no need to actually call optimize, since the mergeFactor should handle this transparently for you. The exception is if you have a highly static index that never changes after initial processing and updates.
Also remember that an optimize will require at least 2x the disk space available, and that it will eat a lot of resources on the server where the index is being optimized.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "solr, solrcloud"
}
|
Mocha async tests, calling done() issue
I'm developing postcss plugin and want to test it with mocha. Here is my test:
function exec(cb) {
postcss()
.use(regexp)
.process(source)
.then(cb);
}
it('should add warnings to messages', function(done) {
var expected = 'somemessage';
var message = '';
function getMessage(result) {
message = result.messages;
assert.equal(message, expected);
done();
}
exec(getMessage);
});
But it fails and I get `Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test`.
What am I doing wrong?
|
I've found solution myself! We need to return promises in `exec` and `it`, and so then there is no need in `done()`
function exec(cb) {
return postcss()
.use(regexp)
.process(source)
.then(cb);
}
it('should add warnings to messages', function() {
var expected = 'somemessage';
var message = '';
function getMessage(result) {
message = result.messages;
assert.equal(message, expected);
}
return exec(getMessage);
});
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, testing, asynchronous, mocha.js"
}
|
Listing files in a directory within a Jade template
I am currently using the Jade HMTL templating language (used in conjunction with CodeKit) to generate my site. One of the pages of my site needs to be an index of all the pages within specific directory. Rather than manually keep this updated I would quite like to have the generated automatically.
Is there a way within my Jade template to create a list of the all the files in a geven directory? Is it possible to embed some script that could do this?
|
Not exclusively with Jade, but you can pass Jade that info from Node.js.
This example assumes you are using Jade with ExpressJS, but you can adapt it as necessary:
Node.js:
app.get('/', function(req, res) {
fs.readdir(path, function(err, data){
res.render('index', {"files": data});
});
});
Jade (index.jade):
ul
for file in files
li
p= file
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "html, node.js, directory, pug"
}
|
What is the most efficient method for loading widgets in functions.php
I have seen WordPress developers use two different methods for loading custom widgets from the functions.php file.
The first:
include("functions/my-custom-widget.php");
The second:
require_once(dirname(__FILE__) . "/functions/my-custom-widget.php");
Which one of these methods is more efficient. I'm particularly interested in performance if there is a difference at all. Does the require_once follow better 'best practices' ?
I'm sure there are plenty of other ways of doing this. If anyone has a better recommendation I would love to hear it.
Thanks.
|
Both are acceptable but not recommended. Use `locate_template()` instead because a child theme can overwrite the loaded file then.
Example:
$found = locate_template( 'functions/my-custom-widget.php', TRUE, TRUE );
The first `TRUE` tells WordPress not only to _search_ for the file but to _load_ it actually. The second makes it a `require_once` call.
The function return the path to the located file in case you need it later. If nothing is found it returns an empty string.
|
stackexchange-wordpress
|
{
"answer_score": 5,
"question_score": 2,
"tags": "functions, widgets, include"
}
|
How to download tarball from Github
I have this:
curl -L " | tar x -C "$project_dir/"
I am just trying to download a tarball from github and extract it to an existing directory. The problem is I am getting this error:
Step 10/13 : RUN curl -L " | tar x -C "$project_dir/"
---> Running in a883449de956
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 9 100 9 0 0 35 0 --:--:-- --:--:-- --:--:-- 35
tar: This does not look like a tar archive
tar: Exiting with failure status due to previous errors
The command '/bin/sh -c curl -L " | tar x -C "$project_dir/"' returned a non-zero code: 2
does anyone know why it's not a tar archive? If you go to github.com in the browser and put in this pattern, it will download a tar.gz archive:
so not sure why it's not working.
|
So ultimately it's because Github wants credentials. Without 2-factor auth, you can just do this with curl:
curl -u username:password
but if you have 2-factor auth setup, then you need to use a Github access token, and you should use api.github.com instead of github.com, like so:
curl -L " | tar -xz -C "$extract_dir/"
the access token thing is documented here: <
|
stackexchange-unix
|
{
"answer_score": 6,
"question_score": 4,
"tags": "tar, curl, github"
}
|
What is the source for RL Rivest's "reversal of defaults" quote?
I'm doing some work on computing privacy and I need to track down the source for a quote by Ronald L. Rivest which goes like:
> "reversal of defaults": what was once private is now public; what once was hard to copy is now trivial to duplicate; what was once easily forgotten is now stored forever.
This is pretty useful axiom, but I need to be able to read it in context, does anyone know where this is from, book, paper or speech?? I've searched for every combination of terms I can think of in Google, Scholar and the ACM digital library, but no one who uses this quote cites it..
|
I found a citation in "RFID Security and Privacy" by Dirk Henrici. He quotes it like this:
> Ronal E. Rivest, Whither Information Security?, MIT Laboratory for Computer Science, < 2001.
The references section of Henrici's book can be found at the publisher's website (it's the "Back Matter" PDF). Unfortunately the quoted URL gives me a timeout.
**Edit** :
Here's the link Dana the Sane found: hopefully unmangled by the clever software behind this site: <
|
stackexchange-superuser
|
{
"answer_score": 4,
"question_score": 4,
"tags": "privacy"
}
|
A timer event for dash in Python
I am using Dash to build a GUI for sending data to a remote server. The update process is asynchronic - as the data could take time to load. After the user presses a button on the dash GUI it saves the data on the remote server as a CSV file, and once the file is saved it tells the server (using an API) to start running the upload process. I would like to show the user the progress of the upload using a callback that will fire every 5 seconds. I couldn't find any documentation on Dash's web site regarding this type of callback. Is there any method for firing a callback every X seconds?
|
I found the answer on Dash's forums. The element is called an "interval".
Here is a working example which triggers an event every 5 seconds:
import dash_core_components as dcc
import dash_html_components as html
import dash
app = dash.Dash()
app.layout = html.Div([
dcc.Interval(id='interval1', interval=5 * 1000, n_intervals=0),
html.H1(id='label1', children='')
])
@app.callback(dash.dependencies.Output('label1', 'children'),
[dash.dependencies.Input('interval1', 'n_intervals')])
def update_interval(n):
return 'Intervals Passed: ' + str(n)
app.run_server(debug=False, port=8050)
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 2,
"tags": "python, plotly dash"
}
|
How can i use 2 picker view in my iPhone app?
I want to use two picker view in one xib. How can i do that ?
|
You can use single PickerView for two operations- Pass Array Values with Tag Values
for First Operation :
self.pickerView = [[NSMutableArray alloc]initWithObjects:@"France", @"Italy", @"California", @"", nil];
self.pickerView.tag = 111;
For second operation:
self.pickerView = [[NSMutableArray alloc]initWithObjects:your array values, @"",nil];
self.pickerView.tag = 222;
Then in
-(void)pickerView:(UIPickerView *)pView didSelectRow:(NSInteger)row inComponent: (NSInteger)component
{
if (self.pickerView.tag == 111) {
NSLog(@"First Picker View selected Value")
}
else if(self.pickerView.tag == 222){
NSLog(@"Second Picker View Selected Value")
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "iphone, objective c, cocoa touch, ios4, uipickerview"
}
|
Two Alert Views in One View Controller - buttonIndex Response
I am trying to perform the smile task of having two alerts in a single View Controller. The code below works fine, but how would I make another instance of it elsewhere in the View Controller. I am concerned that if I duplicated the code, my buttonIndex would not know which alert it is responding to. Any ideas? Thanks!
-(void)alertChoice
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title"
message:@"Message" delegate:self
cancelButtonTitle:@"Cancel" otherButtonTitles:@"Confirm", nil];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1)
{
//do something
}
}
|
You can use the `tag` property on `UIAlertView` to decipher which alert is which:
-(void)alertChoice
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Title"
message:@"Message" delegate:self
cancelButtonTitle:@"Cancel" otherButtonTitles:@"Confirm", nil];
alert.tag = 0;
[alert show];
}
-(void)alertChoice1
{
UIAlertView *alert1 = [[UIAlertView alloc] initWithTitle:@"Title"
message:@"Message" delegate:self
cancelButtonTitle:@"Cancel" otherButtonTitles:@"Confirm", nil];
alert1.tag = 1;
[alert1 show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(alertView.tag == 0)
{
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 25,
"question_score": 5,
"tags": "ios, objective c, uialertview"
}
|
How do I get an h1 and h3 to align at the bottom in a flex box?
I would like the H1 and H3 to align at the bottom on the text, I can't get it to happen.
I've made a codepen <
<div class="flex-div">
<h1>Title</h1>
<h3>Description</h3>
</div>
.flex-div{
background: black;
color: dodgerblue;
font-family: monospace;
display: flex;
align-items: center;
justify-content: center;
}
h1 {
margin-right: 1rem;
}
|
change style to this, it should works:
<style>
.flex-div{
background: black;
color: dodgerblue;
font-family: monospace;
display: flex;
align-items: baseline;
justify-content: center;
}
h1 , h3 {
margin-right: 1rem;
margin-bottom:0px;
</style>
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 3,
"tags": "css, flexbox"
}
|
KSH Loop through num_machines In the below script
I have to iterate
MACHINES_NUM=X
if [ "$MACHINES_NUM" = x ]
then
mkdir -p /RDS_RO/HOME/MACHINE1
mkdir -p /RDS_RO/HOME/MACHINE2
fi
for i in $MACHINES_NUM
do
mkdir -p /RDS_RO/HOME/MACHINE1/MACHINE$i
done
|
Try this:
#!/bin/ksh
MACHINES_NUM=3
for i in $(seq $MACHINES_NUM)
do
echo mkdir -p /something/$i
done
Remove the word `echo` if you like what it does and run it again.
**Output**
mkdir -p /something/1
mkdir -p /something/2
mkdir -p /something/3
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "linux, shell, unix, ksh"
}
|
Xcode 4.5 iOS SDK 6.0 Beta 4 compiled app gives me thin white lines in background
you all know the blue background with the thin white lines in the iOS "Settings" app. I set a grey background color for all of the views in my app which works as expected. Now when I build the exactly same code with the Xcode 4.5 (4G144l) "Preview"-Version with the iOS 6 beta 4 SDK an let it run on a device with iOS 6 beta 4 or the iPhone 6.0 Simulator my background grey is replaced by this "blue with thin white lines"-style and I have no clue why. No one seems to have this problem. Anyone?
thanx
|
This problem occurs for all tables that use the `UITableViewStyleGrouped` style and try to set a background color. A change was made in iOS 6 that causes the background view to be set for these tables, which overrides the background color property. The solution is to clear the background view in the UITableView.
`table.backgroundView = nil;`
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 2,
"tags": "ios6, xcode4.5"
}
|
Simplify form of mySql Query
I need to simply following SQL query. Is there any way to get it??
select *
from product a
where a.brand_id
in (select ib.brand_id from
SUBSCRIBED_CHANNEL ia inner join product ib
where ia.product_id=ib.product_id and ia.user_id=3)
and a.product_id not in (select ib.product_id from SUBSCRIBED_CHANNEL ia
inner join product ib where ia.product_id=ib.product_id and ia.user_id=3)
Edited: four table:
product (PRODUCT_NAME, PRODUCT_ID, BRAND_ID)
SUBSCRIBED_CHANNEL (USER_ID, PRODUCT_ID)
brand (BRAND_NAME, BRAND_ID)
user (..., user_id)
product to brand -> many to one
product to user -> many to many
subscribed_channel -> middle table
I need to get products that are not subscribed by user.
for example: if Nike Brand has product xx, yy and zz
and if user is only subscribed to xx then my query has to give only yy, zz as a result.
|
(Amended) Try:
select distinct a.*
from product a
join product b on a.brand_id = b.brand_id
join subscribed_channel i on b.product_id = i.product_id and i.user_id=3
left join subscribed_channel n on a.product_id = n.product_id and n.user_id=3
where n.product_id is null
Alternatively:
select a.*
from product a
join product b on a.brand_id = b.brand_id
join subscribed_channel i on b.product_id = i.product_id and i.user_id=3
group by a.product_id
having sum(case when a.product_id = b.product_id then 1 else 0 end) = 0
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "mysql, sql"
}
|
Are these long 5525 barrel jack proprietary?
I have tried to connect a 12v DC adaptor and also a battery pack to my telescope unsuccessfully. Sadly it seems Celestron DC jack needs to be around 2mm longer than common 5525 DC ports. I was wondering what are **those long ports are called** and if Celestron is using an uncommon port to make customers buy its products or there is a technical reason for that?
Celestron DC5525 connector with ~14mm head.
 {
NSLog(@"It is impossible to convert temperatures less than −273.15 degrees Celsius, because this is absolute zero, the coldest possible temperature.");
}
It's actually only about the first line, but I wanted to give some context.
Any suggestions?
I've looked it up here on SO, but everyone else's error hasn't had such simple code like mine, although it appears they have a common problem of having the wrong encoding for certain punctuation, perhaps?
It's got to be just some syntax this on my if statement..
**UPDATE:**
It looks as though it also displays 2 other stray errors:
Stray '\210' Stray '\222'
|
− != -
Your minus, isn't a minus.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 4,
"tags": "c, objective c, syntax, compiler errors"
}
|
Extract data from url (PHP)
<
I need extract all results from here.
Edit: Extract results by id: example
$result1 = result['1']; $result2 = result['2'];
|
Use curl to fetch data and decode the json to array in php.
<?php
$json=fetchPageFromURL('
$obj=json_decode($json,true);
print_r($obj);
echo "<hr>";
foreach ($obj as $key => $value) {
foreach (array('result','url','v-url','title','content') as $nnn => $keyname) {
if(0===strpos($key, $keyname)){
$id=substr($key, strlen($keyname), strlen($key)-strlen($keyname));
$fin[$id][$keyname]=$value;
}
}
}
print_r($fin);
function fetchPageFromURL($url){
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($curl);
curl_close($curl);
return $data;
}
?>
Updated to fetch details and put them away.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "php, jquery, json"
}
|
Executing command prompt's functionality using Win32
What Windows API functions are available to execute command prompt's functionality? For example, I like to execute dir command and want to show the output in GUI without using cmd.exe in Windows.
|
You can start `cmd /c dir S:\ome\Path` from your process and grab the output. Otherwise it's not possible. But if you're not interested in particular formatting details of `dir` then you're probably better off just enumerating files/directories and display them.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "c++, c, winapi"
}
|
XSteream Java Obj to XML Skipping some of the fields
How to skip certain fields of object in serialization of Obj to XML.
code is here
|
From Xtream
> How do I specify that a field should not be serialized?
>
> Make it transient, specify it with XStream.omitField() or annotate it with @XStreamOmitField
Try www.google.com
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "java, xml, object, xstream"
}
|
JPEG compression and decompression over and over again
I'm fairly new to Matlab and image and signal processing. What I have so far is that I'm able to read in an image and perform a DCT conversion and fill this into a matrix and then reconstruct an image by placing low to higher DCT coefficients (5, 10, 15, 30) and performing an inverse DCT to get this figure ---> !enter image description here
What I am wondering is how can I re-compress the reconstructed images to perform another transform to show further JPEG loss? How would I go about it? Thanks and I hope you will be patient with my explanation of what I'm doing/trying to do as I am quite new to this fantastic world!
|
Ideally, you should make a function to do the compression. If you feed the output in a loop you can continue to compress your image.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "matlab, jpeg, dct"
}
|
Eloquent ORM does not allow ? operator used in JSONB lookup
Is it possible to run this postgres query with Eloquent ORM?
select * from "table" where "column"->'key' ? '1'
It throws error for using `?` in the query. Is there any alternative approach?
|
You can use `jsonb_exists` function. All question marks determines as placeholder for prepared statements.
Or in php 7.4 you can use `??` (answer here: How to use Postgres jsonb '?' operator in Laravel with index support?)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "laravel, postgresql, eloquent, orm"
}
|
Let $G$ be a group with order 12. Which of the following claims are false?
> Let $G$ be a group with order 12. Which of the following claims are false?
Does Lagrange's Theorem imply that there could exist a subgroup with order 6? I'm not sure where to begin. The question was taken from a past test with multiple choice answers, and the question asked which of the following claims were false:
• G must have an element of order 2.
• G must have a subgroup of order 6.
• G must have a subgroup of order 2.
• None of the above, they are all true.
|
The first option is true because of Cauchy's theorem. This will also imply the existence of subgroup of order $2$(consider the subgroup generated by element of order $2$). Second option is false because $A_4$ is a group of order $12$ which has no subgroup of order $6$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "group theory"
}
|
In NetBeans, how do I remove this red underline?
I've added the following comment to the start of a Java program:
/**
*
* George Tomlinson (I'm not the author). I took this from the *internet* and made one correction.
* This program converts the string entered by the user from hexadecimal to ASCII.
*/
The word 'internet' (italicised above but _not_ in the actual program) is being underlined in red by NetBeans. The error it displays is 'misspelled word', but it's not misspelled. In Word I would just add it to the dictionary, but I can't find any such option here. Does anyone know how to sort this out?
You can see a screenshot here:
!Screenshot with red underline
|
1. Put the cursor on the word
2. Press Alt + Enter
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 32,
"tags": "netbeans"
}
|
Why does custom Estimator end up overriding Nothing type?
I am implementing a custom estimator which has troubles accessing a parameter `ava.util.NoSuchElementException: Failed to find a default value for isInList`. It is defined as follows:
trait PreprocessingParams extends Params {
final val isInList = new Param[Array[String]](this, "isInList", "list of isInList items")
}
To better debug the problem I created a minimal example here < the `ExampleTrans` works just fine. However, I would rather like to include the functionality of the transformer into an estimator which performs some data cleaning as well.
But now I face strange compile issues `overriding method has wrong type - expecting Nothing`
What is wrong with the return types of my `ExampleEstimator`?
|
You didn't specify the generic types of `Estimator` type constructor and so `Nothing` has been used instead.
Use:
class ExampleEstimator(override val uid: String)
extends Estimator[ExampleTransModel] with PreprocessingParams {
...
}
The full definition of Estimator is as follows:
abstract class Estimator[M <: Model[M]] extends PipelineStage
Note the generic type `M` that extends Model.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "scala, apache spark, apache spark ml"
}
|
What are the performance difference using Axapta with a terminal server installation vs a client installation?
This seems a 'stupid' question, but let me explain. I'm working for a company that use Axapta exclusively via Terminal server, so: 1 AOS server and 1 terminal server where all employee connect and use Axapta. I would like to know if there are some performance difference using the client installed in each single pc instead using the client in terminal server client. Thanks
|
The installation of client software is the same.
Performance, well as all client instances runs on the same terminal server, one user can affect the performance of the other users.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "axapta, dynamics ax 2009"
}
|
Can I use RxJava2 and RxAndroid in a single java class library?
I'm tasked with creating an SDK that can be consumed from both Android & Java applications using ReactiveX programming. I already have an android project using RxAndroid created, but now I need to extend it with RxJava2.
The question I'm facing is whether I should create 'regular' java class library and use it for both scenarios or create 2 separate packages (which would mean a lot of duplicate code + maintenance).
Is this even possible? And if so, is it a good practice?
|
> whether I should create 'regular' java class library and use it for both scenarios
Yes. What I would do to start is simply change your Android library project to be a standard Java library and replace RxAndroid dependency by RxJava. Most code should still compile. Code which doesn't will mostly use schedulers provided by RxAndroid and can be changed to take `Scheduler` parameters.
Then create an Android Library project which depends on the Java Library and put the RxAndroid-specific code there.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "rx android, rx java2"
}
|
error sending photoMessage in balebot
I've tried to send a photoMessage.Socket disconnect while trying to send photo/file message with empty error in [promise catch callback] I dont know why?How can i fix it?
[2018-05-07 13:31:40.432] [TRACE] [default] - Sending on socket: {"$type":"Request","id":"3","service":"messaging","body":{"$type":"SendMessage","peer":{"$type":"User","id":XXX,"accessHash":"YYY"},"randomId":"796200377717532288","message":{"$type":"Document","fileId":"-5218264593238523391","accessHash":6687875,"fileSize":"157727","name":"871073.jpg","mimeType":"image/jpg","thumb":{},"ext":{"$type":"Photo"},"caption":{"$type":"Text","text":"test"},"checkSum":"checkSum","algorithm":"algorithm","fileStorageVersion":1}}}
[2018-05-07 13:31:40.435] [TRACE] [default] - send callback: err: undefined
[2018-05-07 13:31:43.221] [INFO] [default] - Connecting...
[2018-05-07 13:31:43.913] [INFO] [default] - Socket Connected!
|
It’s necessary to specify the thumbnail,width and height in photoMessage.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "bale messenger"
}
|
Retrieving files from VirtualBox on Mac (scp or...?)
I am able to get files from my local machine to my virtual machine by doing:
scp -P 2222 myfilepath/myfile.csv vmuser@vmhost:/vmfilepath/
I edited this file, and now I would like to do the reverse. I tried:
scp -P 2222 vmfilepath/myfile2.csv myuser@localhost:/myfilepath/
And several variants thereof. It does not accept my password.
Any suggestions to get myfile2.csv from the VM? Either using scp or actually finding the file on my system (I tried searching for it; it does not appear in Finder). I'm currently looking into shared folders, but if that doesn't work I'm still curious why `scp` isn't working.
|
Try this from your host:
scp -P 2222 vmuser@vmhost:/vmfilepath/myfile2.csv myfilepath/
|
stackexchange-superuser
|
{
"answer_score": 2,
"question_score": 0,
"tags": "linux, macos, ssh, virtualbox, scp"
}
|
How to add a location block that applies to all incoming requests?
I would like any incoming HTTP request (regardless of domain name) that begin with a certain path to be sent to a local server. For example:
location /special/path/ {
proxy_pass
}
If there is no matching `server {}` block for a given domain name, Nginx will route the request to the `default_server`. But I need the request to **always** be routed to the local server, _even if a matching`server {}` block is found_.
How would I go about this?
Bonus: if there is a way to do this outside of the `server {}` that currently has `default_server` set, that would be awesome.
|
I think you might have to configure a suitable block in every server. You can do this with an include rather than copy and paste. This should work in the default server.
So in each server block use something like this
include /etc/nginx/fragments/path.conf
And in /etc/nginx/fragments/path.conf
location /special/path/ {
proxy_pass
}
Note that you shouldn't put it in the sites-enabled directory as the nginx.conf includes them, and it's invalid syntax in that context.
Someone else may have a better way than this, but I believe this will work.
|
stackexchange-serverfault
|
{
"answer_score": 3,
"question_score": 1,
"tags": "nginx, http"
}
|
Running a javascript after x number of page views
I want to show a marketing popup after users has been on my site for either a certain amount of time or after a certain number of page views. Eg. i want it to pop after the user has browsed 3 pages.
How do i do this using either JavaScript/jQuery or PHP?
|
Ok, people proposed PHP solution, I will complement javascript one. Here is very simple `localStorage` approach:
if ((localStorage.pageViews = (+localStorage.pageViews || 0) + 1) > 3) {
alert('Marketing');
}
Demo: < (refresh page 3 times).
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 3,
"tags": "javascript, php, jquery"
}
|
Application of Fermat's Little Theorem/Fermat Euler Theorem
Find an integer $x$ with $0\leq x \leq73$ such that $$2^{75}\equiv x \pmod{74}$$
I think I'm supposed to be using either Fermat's Little Theorem or the Fermat-Euler theorem here but I don't think I can do it directly because $74$ is not prime nor do I have $\operatorname{hcf}(2,74)=1.$
What should I be doing?
|
$$2^{75}\equiv x \pmod{74} \Rightarrow \frac{2^{75}}{2} \equiv \frac{x}{2} \left(\text{mod}{\frac{74}{2}}\right) \Rightarrow 2^{2 \cdot 37} \equiv \frac{x}{2} \pmod{37} \\\ 4^{37} \equiv \frac{x}{2} \pmod{37}$$
$37$ is prime, so you can apply Fermat Little Theorem. That is:
$$a^{37} \equiv a \pmod{37} \Rightarrow \frac{x}{2} = 4 \Rightarrow x = 8.$$
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 2,
"tags": "modular arithmetic"
}
|
Define return value in Spark Scala UDF
Imagine the following code:
def myUdf(arg: Int) = udf((vector: MyData) => {
// complex logic that returns a Double
})
How can I define the return type for myUdf so that people looking at the code will know immediately that it returns a Double?
|
Spark functions define several `udf` methods that have the following modifier/type: `static <RT,A1, ..., A10> UserDefinedFunction`
You can specify the input/output data types in square brackets as follows:
def myUdf(arg: Int) = udfDouble, MyData => {
// complex logic that returns a Double
})
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 6,
"tags": "scala, apache spark, user defined functions, udf"
}
|
IIS7 URL Rewrite rule to perform a 301 redirect from *.html files to *.php files
I would like to use the URL Rewrite module of IIS7 to create 301 redirects based on a specific pattern.
I have a web site that consists of only .HTML files. I am converting the site to .PHP files, but keeping all of the same filenames. For example, the following urls...
/index.html
/contact/contact.html
/membership/member.html
will become...
/index.php
/contact/contact.php
/membership/member.php
Can anyone advise on how to create this rule?
Thanks.
|
Here you go:
<system.webServer>
<rewrite>
<rules>
<rule name="html2php" stopProcessing="true">
<match url="^(.+)\.html$" />
<action type="Redirect" url="{R:1}.php" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
</system.webServer>
Tested on IIS 7.5 with URL Rewrite module v2.0 -- works fine.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "iis, iis 7, url rewriting"
}
|
live() and on() method, and FF browser
I have this code that use live method, and it works in Opera and Chrome:
$(".dynamicaly_created_div").live("click",function(){
$(event.target).parent().remove();
});
But not in the FF. So i tried to replace "live" with "on" (i read somwhere that live is deprecated). But then, this does not work in any browser.
Is ther any solution for this?
|
Have you tried passing the event into the function?
$(".dynamicaly_created_div").live("click",function(e){
$(e.target).parent().remove();
});
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 0,
"tags": "jquery selectors, jquery, jquery on"
}
|
Creating an automatic windows task that runs cmd
Hey guys I have no idea how to make windows scripts or what language or anything so I need your help. I am trying to create a scheduled task that will run once a week, open cmd.exe, enter 2 lines of code, then close cmd.exe
if it helps the code i need to run is:
dir d: /b >> c:\some_text_file.txt
dir f: /b >> c:\some_text_file.txt
|
Thanks Ken, I was able to schedule a task to run a batch file.
this link helped me figure out how to start <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "windows, cmd, scheduled tasks"
}
|
Causing right-click to fire left-click
I've found that this code appears to block the right-click pop-up menu:
document.oncontextmenu = function () { return false; };
## However, I need for it to be treated like a left-click. This is used on a form with radio buttons where students are making choices. Thanks for your help.
I think Jeff's solution takes care of the original issue. In conjunction with it, I need an alert-type ok/cancel box to fire when the user clicks a submit button, but I need for it to (1) block the right-click, and (2) ignore keypresses (particularly the Enter key). Is this doable? Thanks.
|
Use `event.target` and `click()`:
document.oncontextmenu = function (event) {
event.target.click();
return false;
}
JSFiddle Demo: <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "javascript events"
}
|
Keyframe all bones in armature at once?
How do I keyframe the location, rotation and scale for all bones in an armature at once?
|
Select all bones in pose mode, Press I and T to insert keyframes for LocRotScale (i.e. location, rotation, scale)
|
stackexchange-blender
|
{
"answer_score": 1,
"question_score": 0,
"tags": "rigging, armature, bones, keyframes, timeline"
}
|
Is Qt Creator source code not included in Qt Src?
Although I chose to install source code when installing Qt, I could not find the source code for Qt Creator in the Src directory. Isn't the source code for Qt Creator included in Qt source? Isn't Qt Creator part of Qt?
|
Qt and Qt Creator are both developed inside the Qt Project, but are still two separate projects. Qt Creator depends on Qt, but not the other way around, one can use Qt perfectly fine without Qt Creator. They are released independently and with different versioning.
The "sources” package in the Qt installer refers to the Qt source code only, not to Qt Creator. In the installer you’re offered different versions of Qt, all with their own “sources” packages, but only one Qt Creator (the latest one).
You can find the Qt Creator source code in the Qt Download section (the source code archives end in .tar.xz/.tar.gz/.zip) or in the Git repository.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "qt, qt creator"
}
|
How to avoid multiple event listeners from being attached?
Is the following code going to attach multiple event listeners or will React Native / expo-linking only allow one event listener be attached at a time?
import * as Linking from 'expo-linking'
import { useIsFocused } from '@react-navigation/native'
const MyComponent = () => {
const isFocused = useIsFocused()
useEffect(() => {
fetchData()
Linking.addEventListener('url', _handleEvent)
}, [isFocused])
const fetchData = () => {
// ...
}
const _handleEvent = () => {
// ...
}
return (
<View><View>
)
}
Is there are a way to check if an event listener already exists so I can do something like:
useEffect(() => {
fetchData()
if(!eventListenerExists){
Linking.addEventListener('url', _handleEvent)
}
}, [isFocused])
|
It'll attach multiple handlers, adding one each time `isFocused` changes. To remove the previous handler when attaching the next, return a function that React will call:
useEffect(() => {
fetchData()
Linking.addEventListener('url', _handleEvent)
return () => Linking.removeEventListener('url', _handleEvent) // <======
}, [isFocused])
You want to do that **anyway** so that the handler is removed when your component is completely unmounted.
This is covered in the React documentation here.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "javascript, react native, expo, react navigation"
}
|
Python sum time from file txt
I'm using a script:
import sys
sys.argv
entry = 2
t = 0
SEC = 0
min = 0
hrs = 0
with open (sys.argv [1]) as fp:
for in line fp:
entry+=1
if entry% 8:
continue
t + = int (line)
sec = t% 60
t // = 60
min = t% 60
hrs = t // 60
print ("Total time:% d hours% 02d minutes% 02d seconds"% (hrs, min, sec)
Entrance:
> 315: 31: 54 0:00:32 1:11:24 8:18:18 111: 35: 56 112: 45: 26 0:21:33
of course much bigger;)
And there is an error:
> invalid literal for int() with base 10: '112:45:26\n'
I checked 10x. There are no white characters in the input txt file. So what is the cause?
|
After giving some tought, the best approach for this situation is a custom converter instead of trying to adapt the ones present at Python std library
# you should change this to an open file - read()
dataset = """315:31:54
00:00:32
01:11:24
08:18:18
111:35:56
112:45:26"""
acc = 0
# unfortunatelly this is a non-standard dataset of timestamps, therefore
# the best approach is to create your own converter
for line in dataset.split():
split_time = line.split(":")
acc += int(split_time [0]) * 60 * 60 + int(split_time [1]) * 60 + int(split_time[2])
print("total in seconds:", acc)
>>> total in seconds: 1977810
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, python 3.x"
}
|
What's the difference between BrowserModule and platformBrowserDynamic?
What are the purposes of these two modules?
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
|
`platformBrowserDynamic` is a function used to bootstrap an Angular application.
`CommonModule` is a module that provides all kinds of services and directives one usually wants to use in an Angular2 application like `ngIf`. `CommonModule` is platform-independent.
`BrowserModule` exports `CommonModule` and provides a few services specific to the browser platform (in contrary to `ServerModule` or `ServiceWorkerModule`).
`BrowserModule` should only be imported in `AppModule`, `CommonModule` can be imported everywhere.
|
stackexchange-stackoverflow
|
{
"answer_score": 27,
"question_score": 8,
"tags": "angular"
}
|
How do I format this table into being better looking?
I have made this table but it's not really good looking. How could I improve it? Thanks!
\documentclass[a4paper, 11pt]{article}
\usepackage{tabularx}
\begin{document}
\begin{center}
\begin{tabular}{ | m{4em} | m{1.3cm}| m{1.3cm} | m{1cm} | }
\hline & Gedopt & Nicht . &\\
\hline
Test zeigt positiv & $\frac{0,999}{600}$ & $\frac{1,2}{600}$ & $\frac{2.199}{600}$ \\
\hline
Test zeigt negativ & $\frac{0,001}{600}$ & $\frac{597,8}{600}$ & $\frac{597,8}{600}$\\
\hline
~~~~~~~~~~~~~~~~~~~~~~~~ & $\frac{1}{600}$ & $\frac{599}{600}$ & \\
\hline
\end{tabular}
\end{center}
\end{document}
|
Use the `booktabs` package, and get rid of the vertical lines:
\documentclass[a4paper, 11pt]{article}
\usepackage{tabularx}
\usepackage{booktabs}
\begin{document}
\begin{center}
\begin{tabular}{m{4em}m{1.3cm}m{1.3cm}m{1cm}}
\toprule & Gedopt & Nicht . &\\
\midrule
Test zeigt positiv & $\frac{0,999}{600}$ & $\frac{1,2}{600}$ & $\frac{2.199}{600}$ \\
\midrule
Test zeigt negativ & $\frac{0,001}{600}$ & $\frac{597,8}{600}$ & $\frac{597,8}{600}$\\
\midrule
~~~~~~~~~~~~~~~~~~~~~~~~ & $\frac{1}{600}$ & $\frac{599}{600}$ & \\
\bottomrule
\end{tabular}
\end{center}
\end{document}
 {
return new Promise((resolve, reject) => {
const stringValue:string = "...explicit string...";
resolve(stringValue);
});
}
async function f() {
let s:string = "";
await P().then((res) => { s = res; });
}
The error is at the statement `s = res`:
> [ts] Type '{}' is not assignable to type 'string'.
Why is this happening?
|
You have to explicitly specify return type.
function P(): Promise<string> {
return new Promise((resolve, reject) => {
const stringValue:string = "...explicit string...";
resolve(stringValue);
});
}
async function f() {
let s:string = "";
await P().then((res) => { s = res; });
}
TypeScript assumes return type of P is `Promise<{}>` when you do not specify return type. You can check it at < , type your code on left side and put mouse on `P().then(` , you will see that typescript assumes return type as `Promise<{}>`.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "typescript"
}
|
convenience initialization
Is there a convenience process to assign the value of Property "Caller" in the constructor below to a single line?
public partial class SecurityPrompt : Form {
Form1 Caller { get; set; }
public SecurityPrompt(Form1 _caller) {
Caller = _caller;
InitializeComponent();
}
}
|
There is object initializer syntax, but that creates the constructor and then assigns public properties. You'd have to refactor your constructor here if you wanted to use that.
Using object initializer:
> The compiler processes object initializers by first accessing the default instance constructor, and then by processing the member initializations.
If you do use this your property won't be set until after the constructor is created. So if you call functions in the constructor expecting your property to be there it won't. Keep that in mind.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "c#, constructor, initialization"
}
|
Create branch at specific change set, move changests after this point to different branch
_Hypothetical scenario:_
By mistake, I've been working away on my 'Main' branch.
What I need to do, is effectively reset my Main branch to a particular changeset - 1001 for example. Changesets after 1001, I want to move to a new branch - 'Dev'
Is this possible?
I come from a git background, so if this were a git repository, I would probably use something like:
git checkout -b Dev 1001 //create branch at 1001
git checkout Main //back on Main
git reset --hard 1000 //reset main to 1000
|
No, this is not possible in the server based source control world.
I would recommend that you take a copy of your code, and roll back the change.
Then create a branch and overwrite the changes that you copied. Dirty, but works...
Solution: Use git
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "tfs, branch, alm"
}
|
Indent text left and right
I am using the `p tag` to align text left and right on the same line using:
.left
{
float: left;
text-indent: 5px;
margin-top: 0px;
}
.right
{
float: right;
text-indent: 5px;
margin-top: 0px;
}
<div id="content">
<p class="left">Left Text </p>
<p class="right">Right Text </p>
</div>
The left text will indent by 5 pixels, the right text will not. I have tried -5px and just 5px, any ideas how I could do this?
Thanks
|
You can use `margin-left` and `margin-right` instead. Or `padding-left` and `padding-right` depending on your desired output/requirement.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 2,
"tags": "html, css"
}
|
glob: Match files with multi-dotted extension but exclude some depending on sub part in extension
I have a folder with tsx files and test tsx files structured as shown
packages
packageName
src
index.tsx
sample.tsx
sample.test.tsx
tests
index.test.tsx
I have been able to so far write a glob pattern that matches the tsx files that looks like this: `packages/**/*.{tsx,ts}` However I would like to exclude the test files in the glob pattern, files that have `.test.tsx`, how would I do that
|
Try
shopt -s globstar extglob
printf '%s\n' packages/**/!(*.test).@(tsx|ts)
See the extglob section in glob - Greg's Wiki.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "bash, grep, glob"
}
|
absolute path for image file not working
echo '<img src="../../images/delete.png" id="aaa" />aaa '; (working fine)
//define( 'ROOT_DIR', dirname(__FILE__) ); is in a file at root folder.
//i able to use this ROOT_DIR to include class files without any problem
//BUT, when I use it with photo image, it just not working!
echo '<img src="'.ROOT_DIR.'/images/delete.png" id="bbb" />bbb';
Guys, any idea what's wrong?
|
You need to work from the web server root, not the file system root.
If your main page is `/var/www/html/index.html` and your image is `/var/www/html/images/delete.png`, then your image href should be `/images/delete.png`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "php, image, file, path, absolute"
}
|
how to handle onLoad Event on img tag and others
how to handle `onLoad` Event on img tag?
example:
$ ('img'). onload (function (e) {
alert ('image loaded' + $ (this), attr ('src'));
})
is like the imageLoader
and others tags like script, link, etc...
|
jQuery callback on image load (even when the image is cached)
$("img").one('load', function() {
// do stuff
}).each(function() {
if(this.complete) $(this).load();
});
Seems to work for me, and should fix the caveat with caching.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "javascript, jquery, dom"
}
|
Non-vanishing vector field on $\mathbb{R}P^{2n+1}$
I'm trying to cook up a non-vanishing vector field on $\mathbb{R}P^{2n+1}$. I know that $S^{2n+1}$ admits one, namely $(x_1,\dots,x_{2n+2})\mapsto (-x_2,x_1,\dots,-x_{2n+2},x_{2n+1})$. Moreover, I know that $S^{2n+1}$ is a smooth double cover of $\mathbb{R}P^{2n+1}$ via the map $x\mapsto \\{x,-x\\}$. Since this vector field is odd, $X(p)=-X(-p)$, I was hoping there might be a way to cook up a vector field on $\mathbb{R}P^{2n+1}$. So, this motivates the two following questions:
1. Specifically, how may one **_explicitly construct_** a non-vanishing vector field on $\mathbb{R}P^{2n+1}$ (using the route above or not).
2. Say $\tilde M$ and $M$ are smooth manifolds, and $p:\tilde{M}\to M$ is a smooth covering map. If $X(p)$ is a smooth vector field on $\tilde{M}$, under what conditions is there a natural way to cook up a vector field on $M$? (I don't mean natural in the rigorous sense).
Thanks!
|
More generally. Suppose that a group $G$ acts properly discontinuously on a manifold $M$ and that you have a vector field $X$ on $M$ which is invariant under $G$, so that for all $g\in G$ and all $p\in M$ we have $$d_pg(X_p)=X_{gp}.$$ Then the quotient $M/G$ is a manifold, the canonical projection $\pi:M\to M/G$ is smooth and locally a diffeo, and there is a vector field $Y$ on $M/G$ such that $d_p\pi(X_p)=Y_{\pi(p)}$ for all $p\in M$.
In particular, if the field $X$ happens to be everywhere non-zero, the field $Y$ has the same property.
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 5,
"tags": "differential geometry, manifolds, differential topology"
}
|
Changing a single table from DirectQuery to Import
I have a table that I pulled for a report using DirectQuery. I find myself needing to change that table (and only that table) to Import mode so I can merge in a table (entered using the "Enter Data" option). Is there a way to change only a single table to Import? I looked online, and all the answers I saw said to right-click on the table, and select the "properties" option to change the storage mode, but the properties option isn't listed. I'm at a bit of a loss.
|
You can alter the storage mode from Direct Query to Import for selected objects. The table properties are in the relationship designer (in the most recent version of Power BI, I think the documents haven't been updated on the MS Docs site), there you can change it to 'Import'. Warning you can't change Import to Direct Query, so always save a version before you do it just in case you need to go back
 into logic groups, maybe some of theme should have different authors
2. Analyze html, find wrappers, etc, where content is stored
3. custom coding part, scrape html with some scripts, maybe a php one into wordpress xml import file(s) i suggest to divide such huge amount into couple xml files.
4. import via wordpress import tool Simple WordPress Import Structure XML Example
Or you can try such plugin: HTML Import 2
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "wordpress, wordpress theming"
}
|
Running on Android Studio on my Mac is becoming impossible
I have a 2019 MacBook Pro 13" with a 10th gen i5 and 8 gb of ram. Whenever I try to run android studio on my Mac. My life becomes a nightmare. If I even try to change some of the preferences, it just stops responding, and the weird part is that everything else keeps running perfectly, there are absolutely no issues with any other app running while android studio is frozen I am learning how to code and use such programs and I have no idea why this is happening when I've seen people use 6-7 year old MacBook Airs to run it and it works. I have no plugins installed, just the basic out-of-the-box settings. Can someone please help me.
|
**Android Studio freezes on macOS Big Sur**
On machines running macOS Big Sur, Android Studio 4.1 might freeze when you open a dialog.
To work around this issue, do one of the following:
* Go to the Apple Menu, select **System Preferences > General**. In the **Prefer tabs when opening documents** option, select "never". Then restart Android Studio.
* Upgrade to Android Studio 4.2, currently available in the Beta channel.
As mentioned by Android Studio Itself
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "macos, android studio"
}
|
form.reset() of jquery-form-validator issue
I have a form as below which I validate using this **validator** plugin:
<div class="col-md-8 col-md-offset-2 form-contact">
<form action="/Home/SendMessage" id="contact-form" method="post" autocomplete="off" class="wow bounceInUp has-validation-callback animated">
//..All other form controls
</form>
</div>
but when I tried to `reset` the `form` as below
$('form#contact-form').reset();
OR
$('#contact-form').reset();
it gave me console.error **`Uncaught TypeError: $(...).reset is not a function`**
but when I try to `reset` the form as below it resets perfectly.
$('.form-contact form').get(0).reset();
Can anyone tell why this is happening or what is the reason behind this?
|
It is because `$('#contact-form')` retuns the form in an **array of the object**. In this case array of form object with length 1. Write that in browser console and see what happens.
the `reset()` is a **native javascript function** which requires specific `form` object which the selector doesn't provide without `$('#contact-form')[0]`
use `$('#contact-form')[0].reset();` which gets `first form` from the array.
!enter image description here
try **console.log($("#contact-form"));** in the console. then you can see the result by expanding the object.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "jquery, forms, validation"
}
|
Unable to watch a high resolution and high frame rate video
I have a video of a tennis match whose
> Resolution = 1280 * 720
> Codec = H264
> Frame rate = 50fps
>
(Copy paste from info given by totem media player)
My laptop is not powerful enough to play this video smoothly. How can I reduce the frame-rate of this video so that my laptop can play it? I have observed that my laptop can play videos with 25fps without an issue.
I use ubuntu. I wouldn't mind using windows to edit/re-encode this video.
|
FFmpeg is multiplatform and will do what you want with a simple command line such as:
ffmpeg -i input.mp4 -r 25 output.mp4
where `-r` option sets the desired frame rate.
* * *
You can install FFmpeg from the Ubuntu repositories:
apt-get install ffmpeg
… or by building it from source, as explained in this tutorial.
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 1,
"tags": "video editing"
}
|
Finding multiple types of tags with lxml findall() with xpath?
I would like to search an XML file for multiple tags.
I can evaluate these command separately:
tree.findall('.//title')
tree.findall('.//p')
but how can I evaluate them together in the same time. I am looking for a syntax like `.// title or .//p`
I tried this command from an SO post
tree.findall('.//(p|title)')
but I get this traceback error `SyntaxError: invalid descendant`
|
Instead of traversing the tree two times and joining the node sets, it would be better to do one pass looking for a `*` wild-card tag name and checking for the tag name via `self::` (reference):
tree.xpath("//*[self::p or self::title]")
Demo:
In [1]: from lxml.html import fromstring
In [2]: html = """
...: <body>
...: <p>Paragraph 1</p>
...: <div>Other info</div>
...: <title>Title 1</title>
...: <span>
...: <p>Paragraph 2</p>
...: </span>
...: <title>Title 2</title>
...: </body>
...: """
In [3]: root = fromstring(html)
In [4]: [elm.text_content() for elm in root.xpath("//*[self::p or self::title]")]
Out[4]: ['Paragraph 1', 'Title 1', 'Paragraph 2', 'Title 2']
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 6,
"tags": "python, xml, lxml"
}
|
"Twelve of a times" table
I found a math problem on Twitter.
However, as it was presented, its solution is trivial. I managed to make it a bit more challenging by muddling up some equations:
.
Thanks for the help in advance .
|
SQL queries return _unordered_ sets unless the query has an `ORDER BY`. This is actually an extension of the fact that SQL tables represent _unordered_ sets. There is simply no ordering.
So, using `LIMIT` with no `ORDER BY` returns _arbitrary_ rows. It may look like the rows are ordered, but they are not -- at least no by SQL standards. You need an `ORDER BY`.
One caveat: I will admit that SQLite is such a simple database that it only allow one thread per query. As such, it might actually "reliably" return results in a particular order. However, I have never found documentation that guarantees this behavior and contradicts the SQL standard. So, relying on the ordering of a result set with no `ORDER BY` is quite risky, even if it seems to work.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "android, sql, database, sqlite"
}
|
How to expand all directories in Projects window in netbeans
I want to expand all directories in Projects window in netbeans.
Why? Because when I click on the project root, and start typing to search the files, it only searches through files of open directories.
If you right click in the projects window, you can see Collapse All, but no Expand All.
Anyone know a shortcut or button somewhere. Or an alternate method of searching all files by filename without expanding all.
|
Still don't know how to expand all, but don't need to.
To search through all files by filename in netbeans, use shortcut:
ALT + SHIFT + O
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "search, user interface, netbeans, shortcut"
}
|
How can I Ignore the first paragraph but affect all the others in CSS?
While using selectors, how can we ignore the first element and then effect all of the remaining elements in that selector?
For example:
<p>Users said:</p>
<p>Hey Ya!</p>
<p>Hey Ya 2!</p>
<p>Hey Ya 3..!</p>
Now I want to ignore the first one that says `Users said:`, and affect all the other `<p>`s. I took a look at `:gt` selector but it doesn't help. Are there any alternatives for `:gt` or any other way to do that?
Thanks in advance.
|
p:not(:first-child) {
background-color: #FF0000;
}
note that this works only on css3
* * *
if you have an older browser you should do something like this
p {
background-color: #FF0000;
}
p:first-child {
background-color: transparent;
}
you basicly need to revert your changes that you made for the first element
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 2,
"tags": "html, css, css selectors"
}
|
How to split a footnote only to odd pages
I have a document which uses the `eledpar` package to edit parallel texts. On the even pages, I have a original text from an author and on the odd pages I have my commentary of the text. All is synchronized by the `eledpar` package.
My problem is concerning footnotes. I have very big footnotes on the original text side (even pages). LaTeX automatically splits these footnote on two (or more) consecutive pages. I would like to split these footnote **only** between _even_ pages. I don't want a footnote about the original text to be split on the commentary side (odd pages).
How can I achieve this?
|
The new version of eledmac-eledpar 1.19.0-1.13.0, now send on CTAN, fixes this issue.
Basically, you must:
* set the vertical size allowed to the notes, with `\maxhXnotes[<series>]`
* set that you want notes only for right pages, with `\onlyside[<series>]{<side}`
for example
\maxhXnotes{0.8\textwidth}
\onlyXside{R}
Read § 4.4 of the new handbook of eledpar for more details.
ps : now, we have an eledmac and an eledpar tag.
|
stackexchange-tex
|
{
"answer_score": 3,
"question_score": 3,
"tags": "footnotes, double sided, eledmac, eledpar"
}
|
constraining object to a triangle plane
I've been looking all over the place and I can't seem to find the right constraint for this. I have a circle that needs to be constrained to a triangles area.
Limit Distance Constraint doesn't seem to work because it limits it to a sphere which can go out of the bounds of the triangle.
Limit Location Constraint doesn't seem to work because if my triangle's vertices are (0,0,0),(2.5,5,0),(5,0,0) and I max out x at 5 and y at 5 the object can go to (4.9,4.9,0) which is not in the triangle.
Any help would be greatly appreciated.
|
Create a new mesh shaped in the way you require the object to be constrained - in your case a single triangular face - and add a Shrinkwrap constraint to your object set to Closest Surface Point with Target set to the mesh. This will constrain the location to the closest point on that mesh. This will work for any shape of constraint.
To demonstrate, here a Copy Location constraint has been added to Suzanne to move her to the location of an empty. In addition, the Shrinkwrap constraint has been added and targetted at the triangular mesh.
 | echo $out
sm@tp1:~/pc$
but in here there is no output
|
In the second line you are assigning the output to the variable `out`. If you later want to see what the variable `out` is, just type `echo $out` afterwards:
sm@tp1:~/pc$ out=$(php get.php | grep "PhP" | cut -c24-33 | sed -n 1p)
sm@tp1:~/pc$ echo $out
In other words, don't use the pipe `|` and just echo on another line, or you can just replace that pipe with a semicolon `;`.
sm@tp1:~/pc$ out=$(php get.php | grep "PhP" | cut -c24-33 | sed -n 1p); echo $out
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "bash"
}
|
Hadoop EMR job runs out of memory before RecordReader initialized
I'm trying to figure out what could be causing my emr job to run out of memory before it has even started processing my file inputs. I'm getting a "java.lang.OutOfMemoryError cannot be cast to java.lang.Exception" error before my RecordReader is even initialized (aka, before it even tried to unzip the files and process them). I am running my job on a directory with a large amount of inputs. I am able to run my job just fine on a smaller input set. Does anyone have any ideas?
|
I realized that the answer is that there was too much metadata overhead on the master node. The master node must store ~150 kb of data for each file that will be processed. With millions of files, this can be gigabytes of data, which was too much and caused the master node to crash.
Here's a good source for more information: <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "hadoop, out of memory, heap memory, emr"
}
|
Creating a thread in another class
I am trying to create a thread in the main function for the function named thefunction() in the ThreadMe class. The tricky part is that I need to start a thread in another class TYIA -Roland
#include <iostream>
#include <process.h>
#include <windows.h>
int main() {
char cincatcher[24];
std::cout << "I want to run a thread using a function on another class\n";
// Here is a good place to start the thread
while( true ) {
std::cin >> cincatcher
}
}
class ThreadMe {
void thefunction();
};
void ThreadMe::thefunction() {
while( true ) {
std::cout << "working!\n"
Sleep(800);
}
}
|
You cannot start thread directly with a class method. You must wrap the class method into a normal function, then start thread with the function. Like the following:
void threadBody(void *p) {
ThreadME tm;
tm.thefunction();
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c++, multithreading, concurrency"
}
|
Are the windows clocks which are low resolution updated at thread context switches
Several years ago I noticed that at the time the .Net DateTime class only changed in increments of about 10 - 15 milliseconds. That happens to coincide with what I understand is the typical duration of a thread context in windows (which is why threads never sleep for less than that). Are the low resolution windows clocks exposed there really updated precisely at thread context switches? Can they be used as a cheap and dirty way to detect context switches?
|
In fact, I'll go with an actual answer:
Are the low resolution windows clocks exposed there really updated precisely at thread context switches?
No - you've got it backwards. The low-resolution Windows clock MAY precipitate a context-change, eg. if an API call with a timeout times out, or a Sleep() call expires.
Can they be used as a cheap and dirty way to detect context switches?
No, because context-switches may not happen on every timer interrupt and happen often upon all the other hardware interrupts and API calls.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "windows, multithreading, timer"
}
|
effect drag and drop file icon on my program effect
How can I achieve the effect of dragging an arbitrary file icon on the icon of my program? That is, I want to make it so that if I drag a file to my program, the program starts and opens this file. In the figure, MyProgram is a program in C # that I write. File is the file I want to open.

{
if (args.Length > 0)
Console.WriteLine(args[0]); // Here's the file path
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, .net, drag and drop"
}
|
Convert horizontal range to array and print
I can't print a horizontal range. This is surprising, because my code works perfectly for a vertical range. What didn’t I understand?
Sub hello()
Dim i As Long
Dim enumTitles As Variant
Dim listTitles() As Variant
' enumTitles = ThisWorkbook.Worksheets("hello").Range("A1:A3")
' Works.
enumTitles = ThisWorkbook.Worksheets("hello").Range("A1:C1")
' Doesn't work.
listTitles = enumTitles
For i = LBound(listTitles, 1) To UBound(listTitles, 1)
Debug.Print (listTitles(i, 1))
'Only one result is displayed. Not three.
Next i
End Sub
The goal is not to print obviously. It is to reuse its values.
Thanks a lot for your help.
|
Excel range() function will return 2D array to the _enumTitles_.
So, when you are running it for rows the code print all values of 1st row. But columns is the second dimension of the 2D array, that's why you are receiving only 1st value (all values of 1st row again).
For Columns Loop you have to use 2nd dimension as below:
' Use len of 2nd dimension
For i = LBound(listTitles, 2) To UBound(listTitles, 2)
' Loop by columnt ID
Debug.Print (listTitles(1, i))
Next i
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "excel, vba"
}
|
Unable to create private queue with MSMQ
I've been dealing with this problem since last week...none info in the internet that actually solve my problem....n I'm very very new to MSMQ
Whenever i try to create a new private queue....i get this error message alt text
and then when i check services ,the Message Queuing Triggers is not started..when i try to start it ...it gives me this error:- alt text
then when i check the event viewer :-
alt text
But still i cant create new queue....please help me...i've been stuck here for a week... :(
|
it's ok guys...i'm able to create the q already :) through Computer Management
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "msmq"
}
|
Detect Office 365 group in Outlook recipient list
Is it possible to detect Office 365 Group as email recipient when iterating over email recipient list? EmailAddressDetails.recipientType does not have a special value for it. I noticed that the group is of " _other_ " `recipientType`, but I wouldn't like to rely just on that.
![Office 365 group in Outllok](
|
As of now there is no way to do that using Office-js api. You can use graph api to do that. With me/memberOf you can find all the groups in which you are a member, and look up in that list for the interested email.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "office365, outlook addin, office js"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.