INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Can a shape be both similar and congruent?
I know that congruent shapes have the same size and the rotations don't matter. I just want to know if congruent shapes can also be similar at the same time. I've seen that similar shapes have one shape that is a different size in comparison to another shape with proportional sides and the same angles. So is it safe to say that congruent shapes can also be similar?
|
Yes; it is safe to say so. In general, if two shapes are congruent, then they must also be similar.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "geometry"
}
|
Are triggers asynchronous (on asp.net command object for SQL Server 2008 R2 )
I have some additional (archival) data processing that needs to happen on a SQL Server Update call from ASP.net web app.
I would like to run that independent from the web thread that calls the sql update Command (using the command Object call (not Async) for SQL Server 2008 R2).
All documentation I have read seems to indicate that a SQL Server trigger will not be running asynchronously, meaning that my web thread will be waiting for the update as well as the trigger to finish executing. Can anyone confirm this? Would like to know before I implement an independent async call for my archival sql command.
|
The trigger is run **in the same context** and the same transaction as the SQL operation that fired the trigger, e.g. in the same context and transaction as your `UPDATE` statement. The transaction (and thus the call from your ASP.NET code) doesn't terminate until the trigger has been executed. That's one of the main reasons why triggers should be used sparingly, and if used, the trigger must be very small, nimble and fast - do **NOT** do any heavy lifting and extensive processing and external calls in a trigger!
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "sql, asp.net, sql server 2008 r2"
}
|
send parameters from anchor tag to struts2 action
I have a list of names of students in a class that being printed on JSP using iterator. I am giving each name a different id. Now I want to get the details of the name when a user clicks on the name. I am using struts2. How can I send this name to action when I click on the hyperlink of that name.
<s:a href="actionName" id="<s:property value='name'>"><s:property value='name'></s:a>
when I click on the name I should be able to send that name to the action. I have to send the name because I am using the same action for getting individual details of the students.
I saw in Internet that we can do this using JS. But I don't how to do it. Can some one help me?
|
You can pass name as parameter to action by
<a href="actionName?param=<s:property value='name'>" id="<s:property value='name'>"><s:property value='name'></a>
Remember to write the getter and setter method for param.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "javascript, jquery, jsp, struts2"
}
|
load locally stored image in UIWebView
My requirement is to load locally stored image in the UIWebView.
My code is as follows:
NSBundle *mainBundle = [NSBundle mainBundle];
NSURL *homeIndexUrl = [mainBundle URLForResource:@"web" withExtension:@"html"];
NSURLRequest *urlReq = [NSURLRequest requestWithURL:homeIndexUrl];
[self.webView loadRequest:urlReq];
My html file is as follows:
<html>
<body>
<img src=“Initial.png”>
</body>
</html>
I have referred following links but I am not getting my ultimate output
link1 link2
|
This thing worked for me:
The image should not be in the xcassettes.
NSString *imagePath = [[NSBundle mainBundle] pathForResource:imageFileName ofType:imageFileExtension];
NSString *imgHTMLTag = [NSString stringWithFormat:@"<img src=\"file://%@\" />", imagePath];
NSURL *Url = [mainBundle URLForResource:@"img_icon" withExtension:@"png"];
[self.webView loadHTMLString:imgHTMLTag baseURL:Url];
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "ios, objective c, iphone, uiwebview"
}
|
Where is `defaults -currentHost write domain key value` written to?
When I use `defaults write domain key value` the information is written to `~/Library/Preferences/domain.plist`.
When I use the `-currentHost` flag, it has a higher priority then when I just use `defaults` without a specified host.
But where is the value actually written to? It is consistent between system startups, so it must be somewhere on the disk...
|
If you use `-currentHost` with `defaults` it acts on `.plist` files in:
$HOME/Library/Preferences/ByHost/
As an example, I did not have a `com.apple.finder` _plist_ file at that location and when I executed the following command, one was created at that location.
defaults -currentHost write com.apple.finder GoToField "/foobar"
* * *
$ defaults -currentHost read com.apple.finder GoToField
/foobar
$
* * *
Note the full file name contains a UUID however you do not need to include it when `-currentHost` is used, the normal naming is all that's needed as shown in the command line above.
Example: `$HOME/Library/Preferences/ByHost/com.apple.finder.6966D045-28DC-544A-97C2-98CDB668DC8B.plist`
|
stackexchange-apple
|
{
"answer_score": 3,
"question_score": 4,
"tags": "system prefs, defaults"
}
|
Java Spring View formatatting currency
I have BigDecimal property in model. Is's storing money value . Now i want to show money in 123 456 789,00 format.
i want to do it in view part of application. I am using Spring framework.
what is a best practise to do it?
|
The best way to format money value in the JSP view is to use JSTLs.
For example:
<fmt:formatNumber currencySymbol="$" type="number" maxIntegerDigits="2" value="${balance}" />
In your case you may have to set a different pattern (to display the space after each 3 numbers)
<
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, spring, spring mvc"
}
|
Best way for verifying server compliance to Apple's ATS / TLS 1.2 requirement
So Apple requires TLS 1.2 with Forward Secrecy for URLs beginning iOS 9. Independent of the app, what's the best way to verify that a server meets all the requirements?
nscurl just outright doesn't work - or I don't know how to use it. My output simply repeatedly says CFNetwork SSLHandshake failed, even though I know the server is compliant.
TLSTool works to some extent but I cannot force the Forward Secrecy (FS) ciphers to be used.
openssl can specify specific cipher for the client mode, but the version I have doesn't have FS ciphers. How do I upgrade openssl?
What's the best way? So far I've had to ssllabs.com's analyze.html. Any suggestions?
|
Basically `nscurl --ats-diagnostics <url>` just tries all possible variants of connection to server and responses with PASS/FAIL results for each test. You should just find which tests pass for your server and set ATS configuration accordingly.
Here's a good article on ATS and checking server compliance, it also contains an nscurl example.
|
stackexchange-stackoverflow
|
{
"answer_score": 55,
"question_score": 18,
"tags": "ios, ssl, tls1.2, app transport security"
}
|
Pseudorandom bit generator: analogue circuit for microcontroller digital input
I want the most cost effective way for a basic pseudorandom number generator in a microcontroller. I will use the PIC16F54 which has extremely limited resources. I am thinking about using noise with simple analogue circuitry to generate random 1's and 0's at one of its digital inputs. The degree of randomness is not critical. However, the level of EMI noise that the circuit will be subjected to is unknown, besides the fact that it will be in a residential setting with little or no shielding.
Are there any particularly simple low-cost circuits that could be used? Or should I simply focus on some basic algorithms? (There will be one random seed generator: a push switch, after which the algorithm could do its thing. I should probably ask on Stack Overflow for some simple algorithms).
|
Given that the degree of randomness is stated as not critical:
One random number generation mode that takes minimal resources is to read an _open_ ADC pin within the code, and use the _difference_ between one reading and its previous as a random number source. Make sure the ADC pin is not pulled high or low.
Using the differences eliminates any specific bias on the ADC pin, and provides a random sequence of zero-biased values. Depending on bit depth required, add up a series of such values if necessary.
The method lends itself to easy experimentation, so you can know pretty quickly whether the approach is providing sufficient entropy to meet requirements. If greater entropy is needed, **connect an open wire to the ADC pin** to provide greater sensitivity to external electric fields.
|
stackexchange-electronics
|
{
"answer_score": 3,
"question_score": 5,
"tags": "noise, random number"
}
|
Output from gcc containing all included source code?
Right now, I'm using a combination of `gcc -g` and the `objdump -S` modes to generate assembly code with debug source code interleaved. However, I'm having trouble correlating some of the functions that were in the executable to their original source because the final executable contains source code from many different files. Is there a way to get a debug pure source representation (with no assembly) of all of the functions in an executable, using the gcc toolchain? That is, I'm looking for the source that was used for all of the functions in my executable, arranged in the order that the functions appear in the executable, so that I can compare that source to the `objdump -S` output (which I'm also comparing to Ghidra and Binary Ninja output).
Thanks for your time in responding!
|
I'm not aware of any way to do what you're asking (INAE), however you could try this to obtain readable source using objdump:
objdump -l --source-comment <file>.o | grep -e '^\/' -e '^#'
This will include the filename and line number for each line of source while excluding the assembly.
|
stackexchange-reverseengineering
|
{
"answer_score": 1,
"question_score": 0,
"tags": "linux, objdump, gcc, debug"
}
|
php 101 DateTime using atom format
I'm trying to use the DateTime class to output the current time in DateTime::ATOM format.
I'm not sure if I'm even using it correctly. Or do I have to import a library or maybe turn on a wamp php module.
I'm getting "syntax error, unexpected T_NEW" error
here is the code:
<?php
function d()
{
$df = new DateTime(DateTime::ATOM);
echo $df;
}
?>
|
You'd use `DateTime` like this:
$time = new DateTime;
echo $time->format(DateTime::ATOM);
The constructor (`new DateTime`) expects the _time_ you want to create the object for, the _format_ doesn't matter at this point. You specify the format when _outputting_ the time.
Having said that, the error you're getting seems pretty unrelated and may not have anything to do with that specific line.
|
stackexchange-stackoverflow
|
{
"answer_score": 15,
"question_score": 9,
"tags": "php"
}
|
Parfor for Python
I am looking for a definitive answer to MATLAB's parfor for Python (Scipy, Numpy).
Is there a solution similar to parfor? If not, what is the complication for creating one?
UPDATE: Here is a typical numerical computation code that I need speeding up
import numpy as np
N = 2000
output = np.zeros([N,N])
for i in range(N):
for j in range(N):
output[i,j] = HeavyComputationThatIsThreadSafe(i,j)
An example of a heavy computation function is:
import scipy.optimize
def HeavyComputationThatIsThreadSafe(i,j):
n = i * j
return scipy.optimize.anneal(lambda x: np.sum((x-np.arange(n)**2)), np.random.random((n,1)))[0][0,0]
|
There are many Python frameworks for parallel computing. The one I happen to like most is IPython, but I don't know too much about any of the others. In IPython, one analogue to parfor would be `client.MultiEngineClient.map()` or some of the other constructs in the documentation on quick and easy parallelism.
|
stackexchange-stackoverflow
|
{
"answer_score": 20,
"question_score": 59,
"tags": "python, matlab, parallel processing"
}
|
Handling multiple Try/Except statements
I am using multiple try/except blocks to assign values of a dataframe (say data) to 3 variables(say b,c,d) I want to handle **IndexErrors** if positional indexer is out-of-bounds. What I am currently doing is shown below:
b,c,d=None,None,None
try:
b=data.iloc[1,1]
except:
pass
try:
c=data.iloc[2,1]
except:
pass
try:
d=data.iloc[0,2]
except:
pass
I want to know if there is a better of doing this like a function try_except() or something so that I can use it as shown below:
try_except(b=data.iloc[1,1])
try_except(c=data.iloc[2,1])
try_except(d=data.iloc[0,2])
|
You could just write a function that performs a lookup and catches the exception, but incidentally, `except: pass` is probably a bad idea. You should be more specific with your error handling.
def safe_get(container, i, j):
try:
return container[i,j]
except IndexError: # or whatever specific error you're dealing with
return None
b = safe_get(data.iloc, 1, 1)
c = safe_get(data.iloc, 2, 1)
d = safe_get(data.iloc, 0, 2)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, error handling, exception"
}
|
gitosis with password authentication (don't want to use ssh-key)
I followed an online tutorial to setup gitosis on my LAN server and it's using ssh-key to authenticate now. All the tutorials I saw were using ssh-key authentication. I was wondering if I can use password to authenticate a remote clone or push?
The reason I want to do this is because there are many machines in my LAN, and I don't want to setup ssh-key from each machine, so it may be easier to just remember one password.
One problem I can see with password authentication. If the gitosis need to authenticate per file, then this will be a pain to implement.
|
Yes it is possible, but it requires for a process :
* listening for your git requests
* making the authentication
* passing that request to the gitolite script.
Since you don't want ssh-based authentication, that means no ssh-daemon.
That leaves you with an Apache httpd process, which you can easily configure (git or not git) to authenticate against:
* a file
* an LDAP
* ...
In the `VirtualDirectory` you will define, you will then call the gitosis script, that you have to modify for it, in turn, calling the **`git http-backend`** (the "smart http" cgi script).
I didn't test it with the quite old and obsolete gitosis.
But it works just fine with **gitolite** : see **how to setup gitolite to use smart http mode**
|
stackexchange-superuser
|
{
"answer_score": 2,
"question_score": 4,
"tags": "passwords, git, authentication"
}
|
Counting with placeholders
How to manage that placeholder will start counting from 1. For example, if the input is 3, how can I display "enter the number 1", "enter the number 2" and "enter the number3"
numbers = int(input("how many numbers do you want? "))
for i in range(numbers):
x = int(input("enter the number " + "%d" % ()))
|
I'm not old enough to comment, so have to put this as an answer..
As per your code, you will be ended with 'x' having only the last number, to avoid this, you can probably define x as a list and keep appending to it so that you also capture the previous entries.
numbers = int(input("how many numbers do you want? "))
x = []
for i in range(numbers):
x.append(int(input("enter the number " + str(i+1))))
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python"
}
|
Is it correct to use a comma in this equation?
Consider:
Then, the sequence $k_i$ given by (3.38) is increasing and converges to
\begin{equation}\label{eq:weired_equation}
k^\xi = k_1\times k_2 \times c \times d,
\end{equation}
where $c$ and $d$ are defined in the Theorem 2.
I have the questions:
1. What are the grammatical errors in the above piece?
2. Should a comma be used after the equation \eqref{eq:weired_eqution}.
|
There should be no difference in punctuation whether you write the equation on display or inside the text.
So since there would be a comma if written inside the text, the comma is correct.
* * *
Considering the 1st question, see my comment. In the end, the piece can look like
Then the sequence $k_i$ given by (3.38) is increasing and converges to
\begin{equation}\label{eq:weired_equation}
k^\xi = k_1\times k_2 \times c \times d,
\end{equation}
where $c$ and $d$ are defined in Theorem 2.
In the label, there's a typo and it should be `weird_equation`, but I did not correct this to avoid you problems with cross-referencing.
|
stackexchange-tex
|
{
"answer_score": 6,
"question_score": 2,
"tags": "equations, punctuation, typography, grammar"
}
|
PHP - Javascript integration?
Suppose you are in a php file and you want to run a javascript function that has both javascript and php inside of it. How would you go about doing this? Ex:
<?php
<script>
function myFunction(){
// php code
document.write("Hello World!");
}
</script>
?>
I know I can easily make a php function for this particular code, but just for future reference, I would like to know how to do this.
I apologize if this has been answered before but it seemed difficult to word in google search.
|
The PHP code has to output text that is valid inside the javascript. Something like this.
<?php
<script>
function myFunction(){
// php code
var message = "<?php echo "My alert message"; ?>";
window.alert(message);
}
</script>
?>
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "javascript, php"
}
|
Tool to reformat VB.Net code - specifically line breaks
Are there any tools available for automatically formatting vb.net code - specifically for adding line breaks at a predefined line length? I'm working with a lot of code with long lines (thousands of lines), and manually reformatting it is quite time consuming. I've seen a number of tools for rearranging code into regions etc., but haven't found any that reformat with line breaks. Free would be great.
|
Try having VS auto-wrap your lines. The option should be in the Tools | Options | Basic | Settings | Word Wrap.
Another thing to do is go to the Edit | Advanced | Format Document menu option, which helps clear the air with not well-formed documents.
A 3rd option is to install DevExpress' Code Rush Xpress add-on, which add's very handy vertical lines for when code blocks begin and end, and also helps in refactoring code. You can get it from here: < It's free, but doesn't support the Express editions of Visual Studio.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "vb.net, reformat"
}
|
How to optimize h.264 to play it on every possible device
I coding videos in MP4 for my windows phone, but now I want to be sure that this videos will be played on every mobile device possible, so question is: What the best unified settings for H.264 codec I need?
|
Not every device supports every resolution or framerate, so those aspects are outside of H.264 encoding parameters. That said, a framerate of 30 fps or under, and a resolution of 480p or smaller should be safe for most devices currently in use.
As for H.264 encoding, Baseline profile, and a level of 3.x is sufficient. You should only need to specify the profile.
|
stackexchange-avp
|
{
"answer_score": 0,
"question_score": -1,
"tags": "encoding, mp4, h.264"
}
|
The requested file (go1.13.7.linux-amd64.tar.gz) is unknown to the buildpack when pushing golang web app to heroku?
I have created a golang REST API and am trying to deploy it to heroku. I've built it on windows 7.
I linked my github account to push my golang web app to heroku, but I am getting the following error:
`The requested file (go1.13.7.linux-amd64.tar.gz) is unknown to the buildpack!`
I am using dep to package my app. Here is the metadata i provide to heroku in my Gopkg.toml:
[metadata.heroku]
root-package = "restapitest"
go-version = "go1.13.7"
install = [ "./..." ]
My file project folder looks like this:
C:\$GOPATH\src\API\RESTAPI\
Vendor\github.com\gorilla
go-sql-driver
Gopkg.lock
Gopkg.toml
main.go
|
It appeared to be an issue with the version. Lowering it to 1.12.0 allowed successful deployment of the app.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "go, heroku"
}
|
Extract comma seperated Value using regex in oracle
I have following as input
Str := "Name1 Surname1 (AB123), Name2 Surname2 (MN456), Name3 Surname3(xy789)"
Required out put
AB123,MN456,xy789
I am using following regex in oracle
SELECT TRIM (
REGEXP_SUBSTR (
'Name1 Surname1 (AB123), Name2 Surname2 (MN456), Name3 Surname3(xy789)',
'[[:alpha:]]{2}[[:digit:]]{3}',
1,
1,
'i'))
FROM DUAL;
Which returns me only value `AB123` I want all with comma separated.
Please help
Thanks in advance.
|
so complicated answers...
There is much more simple one:
select rtrim(regexp_replace('Name1 Surname1 (AB123), Name2 Surname2 (MN456), Name3 Surname3(xy789)',
'([^\(]+?\(([[:alpha:]]{2}[[:digit:]]{3})\))','\2,',1,0,'i'),',')
from dual;
Hope this helps.
**EDIT:** A bit changed version:
select rtrim(regexp_replace('Name1 Surname1 (AB123), Name2 Surname2 (MN456), Name3 Surname3(xy789)',
'[^\(]+?\(([[:alpha:]]{2}[[:digit:]]{3})\)','\1,',1,0,'i'),',')
from dual;
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "regex, oracle"
}
|
jquery Full Calendar: callback 'after' the calendar has loaded completely
Is there a callback in Adam Shaw's jquery full calendar which is called after the calendar has rendered completely?? I want to call the clientEvents function in that call back to get all the events on the client side. I tried doing this in viewDisplay, but it is called before the events are rendered and the clientEvents returns 0 events.
|
Actually you can add it by yourself. Update the function `render` in the `fullcalendar.js` like this
function render(inc) {
if (!content) {
initialRender();
trigger('complete', null, true);
}else{
calcSize();
markSizesDirty();
markEventsDirty();
renderView(inc);
trigger('complete', null, true);
}
}
And add to the initial call callback function:
$('#calendar').fullCalendar({
editable: true,
complete: function() {alert('complete');},
or, as you wanted, you can access all events
complete: function() {
var events = $(this).fullCalendar('clientEvents');
for(var i in events)
{
alert(events[i].title);
}
},
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 11,
"tags": "javascript, jquery, callback, fullcalendar"
}
|
In javascript, use object['property string']. How can I do like that in AngularJS 2?
I have two objects. A object is {'id': 'abc', 'pwd': 'pwd1'} and B object is Array. B is string of A object property. like this. ['id', 'pwd']
I want use at ng2 component template.
*ngFor(#str of B)
{{A[str]}}
But that is not working.. How can i do like javascript? ng2 is using the {{object.property}}.
I don't know how can use like javascript!
++ Edit this vote..
template: '<tr *ngFor="#str of B">
<th>{{str}}</th>
<td>{{A[str]}}</td>
</tr>'
export class @@{
A = [{'id': '1', 'pwd': 'pwd1'}];
b = ['id', 'pwd'];
}
I use like that. but that is don't showing values. How can I do???
|
The following code works for me:
@Component({
selector: 'my-app',
template: `
<div *ngFor="let str of B">
{{A[str]}}
</div>
`
})
export class App {
A = {'id': 'abc', 'pwd': 'pwd1'}
B = ['id', 'pwd'];
}
See this plunkr: <
**Edit**
Be careful to use back ticks if you want to define a string on several lines (and not single quotes). In your case for the template attribute of your component.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "angular"
}
|
Extracting cells from struct in Matlab?
Consider the following code in Matlab
for h=1:2
B=randn(3,2);
C=randn(3,2);
A={B C};
baseA_.A=A;
eval(['baseA.A' num2str(h) '= baseA_;'])
end
clearvars -except baseA
Now in each iteration `h` of a loop I want to extract the `1x2` cell inside the struct `Ah`.
I have tried
for h=1:2
indA=sprintf('A%d', h);
Acell = struct2cell(baseA.(indA));
end
but `Acell` is a `1x1` cell containing a `1x2` cell. I want directly `Acell` equal to the `1x2` cell. Any suggestion?
|
You can modify the second loop as follows:
for h=1:2
indA=sprintf('A%d', h);
Acell = baseA.(indA).A;
end
At each iteration Acell will be overwritten but I'assume you posted only a part of the loop code.
Moreover, by using the same approach you've used in the second loop, you can avoid using `eval` replacing that line of code with:
%eval(['baseA.A' num2str(h) '= baseA_;'])
indA=sprintf('A%d', h)
baseA.(indA)=baseA_;
Hope this helps.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "matlab"
}
|
react-native realm : Initial data upon app installation/update?
My app idea will have many rows of texts to use like a dictionary. Is it possible in Realm to have seed data where the data in the app is static and you can't change it other than myself when I manually edit it?
For example if I download a dictionary app, then that app is going to come with data (words and it's definitions) that I can't change. And the devs of that app can periodically add new definitions of words or fix typos when giving out updates and user would see it.
|
You can do this by creating a Realm file offline and bundling it with your app. You bundle a Realm file by copying to the Resources directory in a `Copy Files Build Phase`, or by putting it in the `assets` directory on android. Once you have bundled a Realm file with your app, you can either open it read-only in place, or made a read-write copy by copying it to your data directory by calling `Realm.copyBundledRealmFiles()` at launch with copies all bundled Realm files for you.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "javascript, database, react native, realm"
}
|
Как сделать ограничение на ввод в input пробелов?
Нужно чтобы при вводе в инпут допускался только один пробел. Предполагаю что для этого надо регулярное выражение. Только найти не могу... Может у кого-то есть другие варианты. ) помогите пожалуйста
|
$("#enter").click(function() {
var text = $('#input').val();//Получаем значения из инпут
var count = text.match(/[ ]/g);//Ищим пробелы
if(count) {//Если есть пробелы
count = count.length;//Считаем кол-во пробелов
if(count >=1) {//Проверяем
alert('Введено максимальное кол-во пробелов');
}
}
});
<script src="
<input type="text" id="input">
<button id="enter">Enter</button>
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "javascript, html, jquery, css"
}
|
How to capture what Alexa console sends to the endpoint?
I am currently learning about the chatbots and developed two different skills. One has an endpoint on Azure and the other's endpoint is on AWS. Everything works fine. I would like to know if there is a way to see what the Alexa console sends to your endpoint (including the header)? The Alexa console only shows the body. I would like to capture header and body so I can test my endpoints with Postman.
:
override var keyCommands: [UIKeyCommand]? {
return [
UIKeyCommand(input: "Q",
modifierFlags: [],
action: #selector(self.close),
discoverabilityTitle: "Close app")
]
}
func close() {
exit(0)
}
Input is the key to use, for example CMD+Q (only put Q). Action is the selector to call and discoverabilityTitle is the title of the shortcut, for example "Close app". It will be displayed in iPad when the user holds the CMD key.
It only works with CMD keys and other specials keys:
UIKeyInputUpArrow
UIKeyInputDownArrow
UIKeyInputLeftArrow
UIKeyInputRightArrow
UIKeyInputEscape
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "ios, swift, keyboard, remote control"
}
|
after_commit and after_destroy callbacks are not called on ActiveRecord::Relation delete_by method
I am using ActiveRecord::Relation `delete_by` method to delete a record but this is not triggering `after_commit` and `after_destroy` callbacks. See below example:
class User < ActiveRecord::Base
after_commit :expire_cache
after_destroy :expire_cache
def expire_cache
puts "expire_cache is called"
end
end
User.delete_by(user_id: 1234) # doesn't trigger expire_cache method
Is my expectation about the callbacks is right? What am I doing wrong?
|
> Is my expectation about the callbacks is right?
No. Your expectation to trigger a callback with `delete_by` is wrong.
> What am I doing wrong?
Your understanding is not matching with doc.
As per the Doc, skipping-callbacks `delete_all` will skip the `callbacks`
> * `delete_all` Just as with validations, it is also possible to skip callbacks.
>
> * These methods should be used with caution, however, because important business rules and application logic may be kept in callbacks. Bypassing them without understanding the potential implications may lead to invalid data.
>
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "ruby on rails, ruby on rails 6"
}
|
Zend Framework internal routing
For example, I have a page in my application called page2 that I want to access like mysite.com/page2
in the application.ini file I would have a section for it
resources.router.routes.index.route = '/page2/'
resources.router.routes.index.defaults.controller = index
resources.router.routes.index.defaults.action = page2
My question is, what if I have several pages that I want to access as children of the index controller. There must be a method that doesn't involve creating a new section in application.ini every time I have a new page...
Any advice?
|
This StaticRoute plugin by Ekerete Akpan uses reflection to inspect your default controller and add static routes of the form `/actionname` for all action methods it finds there.
This means that you don't have to add an explicit route for each of those actions. Just add an action to the default controller and the corresponding view-script in the expected place. No need to change any routing files or `application.ini` just to add a new top-level url.
Note, however, that since the plugin uses Reflection to inspect your default controller, using it has performance implications.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "zend framework, url rewriting"
}
|
Prevent user from accessing admin page
I have a php login page with session control. It routes a normal user to info.php and an admin user to info_admin.php. If I login with a "normal" user it goes to info.php, however, in the address bar, I can go to info_admin.php and it doesn't kick me out, gives me access. How can I control this or prevent the user from doing this manually?
For info, I'm using this script: <
Thanks very much!
|
Just to make Lotus Notes' code a bit more compact:
<?php
if (!isset($_SESSION['user_level']) || ($_SESSION['user_level'] != 2)) {
header('Location: login.php');
exit;
}
?>
<!-- Your page HTML here -->
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 0,
"tags": "php, mysql, session"
}
|
Proof of Dirichlet's theorem
I was reading David M. Burton's _Elementary number theory_ a few months ago. They mentioned Dirichlet's theorem on arithmetic progressions (without proof) which states:
> There are infinitely many primes in any arithmetic progression.
I thought, since they said it, that the proof would be very advanced, so I didn't search for a proof. But now, I have (almost) mastered elementary number theory, and I can understand analysis, analytic number theory and algebraic number theory.
So please give a proof of Dirichlet's theorem. I have given my background, so please give a proof that I can understand. If the proof is too long for this site, please link an article containing the proof.
I read this and this question, but they didn't answer my question, so I wish my answer doesn't get closed.
Note: Here is a proof, but I want more proofs.
|
You can find a nice proof for Dirichlet Theorem in this book
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 1,
"tags": "number theory, reference request"
}
|
Extract information from XCUIElement
If I'm trying to write a generic test that isn't dependent on labels or other value-specific elements, how do I get that information? Like if I were to tap a tableview cell and need some information from there later. Like to identify which cell was tapped. How could I grab a label from it using an XCUIElement?
|
The information you can extract from `XCUIElement` is limited to those in the `XCUIElementAttributes` protocol. The most notable of these are, `identifier`, `value`, and `title`.
You can set the `identifier` via `-accessibilityIdentifier` in your production code. The `value` property can be set from a couple of different paths, but it's usually the the active state of a control. For example, a picker's selected element.
You can try using the Accessibility Inspector to see what's already set on your element and then using a query to find that element.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "xcode7, ui testing, xcode ui testing"
}
|
nodejs expressjs angularjs routing
i want to redirect from an express function to an angularjs partial to load with the controller of that view.
app.js -->nodejs
function(req, res, next) {
console.log(req.session);
if(req.session.user/* && req.session.user.role === role*/)
next();
else
res.redirect("/#/login");
}
app.js -->angularjs
app.config(function($routeProvider){
$routeProvider
.when("/create", {
templateUrl : "/users/usersCreate",
controller : "users"
})
.when("/delete", {
templateUrl : "/users/usersDelete",
controller : "users"
})
.when("/login", {
templateUrl : "/sessions/sessionsCreate",
controller : "sessionsCtr"
})
.otherwise({ reditrectTo : "/" });
})
its not working :( help
|
You cannot redirect Angular.js when requesting a partial. Angular.js is issuing an AJAX call and that won't follow a redirect response in the same way a browser does.
This other answer provides guidance on how to go about it:
<
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "javascript, angularjs, node.js, express, url routing"
}
|
Query performance issue when executing from another database
I try to execute a query from another database, using both synonyms and a direct call like ` select * from [DB].[schema].[view] `.
When I run the query on the original database it executes in 1 second. If I call the view from another database, no matter if I use synonyms or a call like "[DB].[schema].[view]" it take about 1.5 MINUTES to execute. Any idea what the problem might be?
USE DB
GO;
select * from schema.view //working fine : 1 second
GO;
use master
GO;
select * from db.schema.view //taking more than 1.5 minutes
GO;
|
It seems it's a compatibility level problem. Thanks to this post: <
Curios it's that if compatibility level is 140 I have bad performance, but if I change the compatibility level to 100 everything works fine
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "sql, sql server, database, tsql, database performance"
}
|
x86_64-linux-gnu-ld cannot find -lyaml
Having this problem every time i run my crystal application. Search over the internet but unfortunately nothing solves my problem. The screenshot of the actual error is below and need to mapping a class to different datatypes. For example:
COLUMN: DOCUMENTDATA
ORACLE DATATYPE: BLOB
SQLSERVER DATATYPE: VARBINARY(MAX)
INFORMIX DATATYPE: TEXT
How I do it in my `classmap`?
|
You do not need to put it in your mapping, just leave it.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "nhibernate, types, multiple databases"
}
|
JS, jQuery loose-leaf calendar effect plugin
Is there `JS` plugin,e.g. `jQuery` or any other,that imitates effect of loose-leaf calendar?
Here is image of calendar.
It's needed, that top half falls into bottom when changing date in calendar.
!enter image description here
Perhaps, jQuery Accordion is closest,but it imitates a little bit other effect.
|
Take a look at this question: JavaScript Flip Counter
And this is a demo from one of the links: <
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 4,
"tags": "javascript, calendar, effect, folding"
}
|
Declare type of a struct field by type of another struct field
Here is *s3.GetObjectOutput struct:
type GetObjectOutput struct {
...
Metadata map[string]*string
...
}
I want to declare my struct with a struct field has type of Metadata field in GetObjectOutput struct like this
type MyObject struct {
Metadata *s3.GetObjectOutput.Metadata
...
}
But it was not correct. How do I declare a struct with a field has type of another struct's field instead of explicitly write down:
type MyObject struct {
Metadata map[string]*string
...
}
|
@William Poussier In that way I have to use a global variable just for use its type. As @zerkms suggested I copied Metadata type from *s3.GetObjectOutput
type Metadata map[string]*string
and use:
type MyObject struct {
Metadata
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "go, struct, types, field"
}
|
Plot subsets of one variable on x-y axis (avoid spreading/reshaping data frame)
I wonder whether it's possible to plot row subsets of one variable in a x-y axis without having to spread/reshape the data frame?
# Fake data
library(tidyverse)
id <- 1:6
size <- c(5, 2, 3, 4, 2, 8)
colour <- rep(c("red", "blue", "green"), 2)
df <- data.frame(id, size, colour)
# Attempt
x11()
ggplot(data = filter(df, colour %in% c("blue", "red")),
aes(x = size[colour == "blue"],
y = size[colour == "red"])) +
geom_point()
# Desired result
.
# Subset data once so we wouldn't need to subset twice for nrow
id <- 1:6
size <- c(5, 2, 3, 4, 2, 8)
colour <- rep(c("red", "blue", "green"), 2)
df <- data.frame(id, size, colour)
pd <- subset(df, colour %in% c("blue", "red"))
# Use dummy empty data.frame
library(ggplot2)
ggplot(data.frame(),
# Submit x,y values as vectors that go every second entry
aes(pd$size[seq(2, nrow(pd), 2)], pd$size[seq(1, nrow(pd), 2)])) +
geom_point()
 at the beginning of a string.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "regex"
}
|
How to get the unique results from Lucene index?
I am trying to search from lucene index . I want to get the unique results but its returning the duplicate results also. I searched on google and found it can be done with the help of a collector. How can I achieve this?
I am using the following code:
File outputdir= new File("path upto lucene directory");
Directory directory = FSDirectory.open(outputdir);
IndexSearcher= new IndexSearcher(directory,true);
QueryParser queryparser = new QueryParser(Version.LUCENE_36, "keyword", new StandardAnalyzer(Version.LUCENE_36));
Query query = queryparser.parse("central");
topdocs = indexSearcher.search(query, maxhits);
ScoreDoc[] score = topdocs.scoreDocs;
int length = score.length;
|
You should have a field named for example "duplicate" and set the value to "true" on indexing time when it already has a duplicate in the index.
So you can search for
Query query = queryparser.parse("central -duplicate:true");
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 5,
"tags": "duplicates, lucene"
}
|
Adding thousand-separators and apostrophe to a number won't show the separators unless i remove the apostrophe?
I'm working on a macro to add separators and an apostrophe at the beginning of a number:
Sub Apostrofe()
Selection.NumberFormat = "#,##0"
For Each cell In Selection
cell.Value = "'" & cell.Value
Next cell
End Sub
Output for 123456789 is 123.456.789 but when it adds the apostrophe at the beginning, the format is lost. On the formula bar i see '123456789 but the separators won't appear unless i remove the apostrophe from the number.
I tried to concat the number in parts while manually adding the ' and . but the result is the same. Adding the apostrophe in the Format of the code added it on the cell but it wouldn't appear on the formula bar.
If i manually write the apostrophe + number with separators it works but i receive hundreds of numbers which must be formatted this way.
How can i modify the macro to do what i need?
|
If you use an apostrophe the value will be converted to text.
It seems that in your example you do not change the value itself (to the text equivalent containing the formated number), you just apply the format to the cell and then overwrite it with '.
I think you should try following code:
cell.NumberFormat = "@" ' set cell format to text
cell.Value = Format(cell.Value, "#,##0") ' Format() returns formated number as a string
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "excel, vba"
}
|
If two different symmetric positive definite matrices have equal determinants then $A-B$ is neither positive semidefinite nor negative definite
Recently I've asked question about the set given as $\\{x: x^T(A-B)x = 1\\}$. In that question I wanted to prove that such set isn't bounded, and according to the answer I can do it if I can prove the fact from the title of this question i.e.:
> If $A$ and $B$ are different, symmetric, positive definite $n \times n$ $(n > 1)$ matrices such that $\det A = \det B$ then the matrix $A - B$ is neither positive semidefinite nor negative definite
Could you please help me to start the proof? I have no idea how to do it (namely how to use the equality of determinants)
|
Audience request: we can begin with orthogonal $Q$ such that $Q^TB Q = D$ is diagonal with positive diagonal elements. We can then continue with a diagonal matrix $W$ with diagonal elements certain reciprocals of square roots, so that $W Q^T BQW = W^T Q^T B Q W = I,$ and name P = QW.$
there is a matrix $P$ with $\det P \neq 0$ so that $P^T B P = I.$ Then $$ P^T ( A - B) P = C - I, $$ where $$ C = P^T A P $$ is symmetric, positive definite and, since $\det B \cdot \det^2 P = 1,$ so $\det A \cdot \det^2 P = 1,$ we get $$ \det C = 1.$$
Let's see, if all eigenvalues of $C$ are equal to $1$ then it is the identity matrix; that needs a little proof using symmetry and orthogonal matrices. In this case, $A = B$ and $x^T (A-B)x = 1$ is impossible.
Otherwise, $C$ has an eigenvalue larger than $1$ and another eigenvalue smaller than $1,$ which tells us that $C-I$ is indefinite.
You should look up Sylvester's Law of Inertia, which has to do with the "congruence" I am using.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "linear algebra, matrices, quadratic forms"
}
|
App has been unlisted from Google Apps Marketplace
I had my app in the marketplace for around an year and recently found it was unlisted. I think it might be because one of the instances of the app was using the old API. I fixed it but found no way to inform Google so the listing could be activated again.
Today, I found that the listing has completely been deleted from the marketplace.
Can someone help sharing insights on what might have happened or what is the process to bring back the listing? Or perhaps how to reach out to someone at Google to help resolve this?
Many Thanks
|
The Google Apps Marketplace V1 (GAM v1) is being deprecated, during this process the applications that were not migrated to the new version (GAM v2) were unlisted.
Here you can find information about the GAM v2 and how to publish your app in this new platform. <
One difference is that the new listing version runs under Chrome web store <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "google apps marketplace"
}
|
Iphone interface builder
hey all my question about how the developers makes their interface the buttons, slider, segmented control and other is any program can make those thing ? and then import it to interface builder ? my brother is a graphic designer and he work a lot a 3d modeling he can make all those thing in 3ds max, maya or cinema 4D but how to tell the interface builder about each element like this is a slider or this is a button on so on. or their is a specific program ?
cheer
Bob
|
I think you won't find such a utility anywhere. All those UI elements you find in iOS (or any other GUI, for that matter), need to be individually coded, with rasterized images or vector graphics or whatever to make them look nice, but the behaviour needs to be written in code (unless this has already been done, and you only need to tell the UI element which graphics to use, as it is the case with UIButton in iOS, for example).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "iphone, cocoa touch, xcode, interface, interface builder"
}
|
How can I remove a gem from my Rails 3 project without getting this really strange Bundle error?
The error is: You have modified your Gemfile in development but did not check the resulting snapshot (Gemfile.lock) into version control
WHAT VERSION CONTROL? Why/how does Bundle know anything about version control? I just removed a line from my Gemfile. Am I not supposed to do that?
|
Do `rm -rf .bundle && bundle install` from your project root.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 6,
"tags": "ruby on rails 3, bundle, bundler"
}
|
Completion Handler deprecated for UIActivityViewController
I am using a UIActivityViewController to share content from within my app. When the activity is completed, I want to turn off the UITableView editing mode. However looking at the documentation I saw that the completionHandler property of UIActivityViewController has been deprecated as of iOS 8.0. There is no deprecation statement from what I can see, I am wondering what the new sanctioned way of doing this is.
|
Since the property description is the same seems like you should use _completionWithItemsHandler_
The completion handler to execute after the activity view controller is dismissed.
> @property(nonatomic, copy) UIActivityViewControllerCompletionWithItemsHandler completionWithItemsHandler
>
> When the user-selected service finishes operating on the data, or when the user dismisses the view controller, the view controller executes this completion handler to let your app know the final result of the operation.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "ios, uitableview, ios8, uiactivityviewcontroller"
}
|
Story about first Spacecraft
A couple of years ago I've heard about an interesting (based on the hearing) story.
I didn't know what it is: a small tale or a novel.
The storyline is evolved around a first interstellar Spacecraft and life there - it allows for many peoples to live there. In this story (based on the hearing of mine) the evolution of life of people is described. And the most memorable thing was, in my interpretation:
> Children start to asking, why in the old movies and books the sky often described as blue, red with no stars. But they knew that the sky is **always** black, they knew it by looking out of a porthole.
That's all I remember about the story.
|
This wouldn't be, by any chance, Orphans of the Sky, would it?
|
stackexchange-scifi
|
{
"answer_score": 6,
"question_score": 10,
"tags": "story identification"
}
|
Java Stack Comparison
I'm wondering how to accomplish this:
1. Compare two Stack objects
2. Do this recursively
3. After the method that does this is complete, the Stacks remain as they were to begin with (i.e. same order, same items).
Only the `push`, `pop` and `isEmpty` methods for `Stack` is available.
I'm looking more for theoretical help than coding help, but any insight would be appreciated.
|
In pseudo-code, you could do something like this:
boolean compareStacks(a, b) {
if (a.isEmpty() != b.isEmpty()) return false; // check if one is empty
if (a.isEmpty() && b.isEmpty()) return true; // check if both are empty
element_a = a.pop(); // grab elements and compare them
element_b = b.pop();
if (((element_a==null) && (element_b!=null)) || !element_a.equals(element_b)) {
a.push(element_a); // if they are not equal, restore them and return false
b.push(element_b);
return false;
}
result = compareStacks(a, b); // compare shortened stacks recursively
a.push(element_a); // restore elements
b.push(element_b);
return result; // return result from recursive call
}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 7,
"tags": "java, stack"
}
|
TimeZone Id from GMT offset in Java
I want to get the TimeZone Id of area in java,I have the list of GMT offsets say -3 it should give me ADT. I am facing really difficulty can anybody help me.
Regards
|
Your requirements are not well-defined because there are multiple timezones for most offsets. On top of that, three-letter "timezone IDs" should be avoided as well because they're often ambiguous (e.g. IST stands for 4 completely different time zones).
The only completely unambiguous timezone IDs are continent/city combinations as used by the tz database, e.g. "Europe/Berlin" or "America/New_York". There's over 400 of them to cover things like daylight savings time and historical changes.
Timezones are much more complex than most people realize.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "java"
}
|
Slide Unlocker ImageView
> **Possible Duplicate:**
> Slide Unlocker ImageView ViewFlipper
I want to create a Slide Unlocker (just like on the iPhone)
I can´t use gestures for that, right? Because I should can change the position of the ImageView of the Unlocker permanently. The ImageView should "follow" my finger.
Do I have to use a simple onTouchListener on the ImageView?
|
You should work on your accept rate, you're more likely to get better help if you don't have 0%.
You could likely repurpose a SlidingDrawer to do what you want.
The other option is to pull out the SlidingTab java file from the Android source code and include it in your own project, and make use of it how you like. Since this Object was not included in the public APIs you must provide your own copy of it if you wish to use it in your application.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "android, imageview, slide, unlock"
}
|
Unusual mathematical terms
From time to time, I come across some unusual mathematical terms. I know something about strange attractors. I also know what Witch of Agnesi is. However, what prompted me to write this question is that I was really perplexed when I read the other day about monstrous moonshine, and this is so far my favorite, out of similar terms.
Some others:
* Cantor dust
* Gabriel's Horn (also known as Torricelli's trumpet)
* Koch snowflake
* Knaster–Kuratowski fan (also known as Cantor's leaky tent or Cantor's teepee depending on the presence or absence of the apex; there is also Cantor's leaki _er_ tent)
Are there more such unusual terms in mathematics?
* * *
_Jan 17 update:_ for fun, word cloud of all terms mentioned here so far:
!enter image description here
and another, more readable:
!enter image description here
|
Complex theorems often use simple, illustrative names.
Ham Sandwich Theorem
No Free Lunch Theorem
Ugly Duckling Theorem
Some are named by the scenario they are describing
Birthday Attack
Doomsday Argument
Other by the accompanying real-life events
Happy Ending Problem
and finally the top 10 Dirty Mathematics from Spikedmath (slightly edited to take up less space) !enter image description here
A Survey on Cox Rings
Cox-Zucker machine
|
stackexchange-math
|
{
"answer_score": 34,
"question_score": 97,
"tags": "soft question, terminology, big list"
}
|
Error when trying to deploy OSGi bundle containing Servlet on Domino server
I am trying to deploy an OSGi bundle on a Domino server. The bundle contains a servlet and static web resources. The resources and the servlet are registered using the _org.eclipse.equinox.http.registry.resources_ and _org.eclipse.equinox.http.registry.servlets_ extension points. The bundle is copied to the applications/eclipse/... folder below domino/data.
When I enter the alias to the static resources I get the requested page. This page in turn makes a request to the servlet but gets a 500 return code. The server console shows **HTTP Web Server: Command Not Handled Exception**
In the error log there is a message **java.lang.ClassCastException: mypackage.SimpleServlet incompatible with javax.servlet.Servlet**
The SimpleServlet is simply a class which implements javax.servlet.Servlet.
Can anyone say why this might be happening? What can I do to get more information?
|
This looks like you have multiple copies of the Servlet API hanging around. You need to find out if there are multiple bundles exporting the `javax.servlet` package, and make sure that both the HTTP server bundle (which is part of Domino, presumably) and your own bundle import it from the same place.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "servlets, osgi, lotus domino"
}
|
Association between a custom list and an external list
I have a very basic question.
I have a Custom List and I'd like to add a lookup column from an External List based on a WCF Service. Is it possible?
E.g. I have employers in a custom list. I'd like to associate them whit their company, but the company id and name comes from an External List.
Thank you all in advanced!
|
Yes of course you can create custom list with lookup column from external list Regards.
|
stackexchange-sharepoint
|
{
"answer_score": 0,
"question_score": 1,
"tags": "bcs, lookup column, external list"
}
|
Will it reveal a website between a link shortener and a redirect?
so I can easily edit some links, I was thinking about having my website act as the middle part, where I store the links in the database and use PHP to redirect (kind of like a shortener but probably with more basic code)
I did a test with two URL shorteners, and to me it seemed like the middle one wasn't revealed at all, however, I don't know what would happen if one went slow (like the browser could possibly say receiving data from x or actually put the URL in the bar). Also, even if it wasn't anything obvious, would you still be able to see headers received from the site or something?
|
Your browser will know. The first one just returns a response with a redirect header containing the new url. The browser will use this url to make a new request to the second redirect url.
You can ~~probably~~ see this happening when you inspect the Network tab in the developer tools (F12) in your browser.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, redirect"
}
|
What is the best way to build serverless app offline?
I'm trying to create a REST API with aws (Nodejs) and dynamodb. Most of the time I do not have access to AWS and I need to have everything running offline to test and only deploy when I have an amount of work done. Is there any guide or good practices that help me in the development?
Thanks in advance!
|
you can run offline version of dynamodb on your localhost. The easiest is to have it in container in docker. Then you dont have to manage it at all and it will work in every environment that has docker installed.
This is what we have in package.json scripts for serverless application
"start": "sls offline start",
"start-local": "npm run force-dynamo sls offline start --stage=localhost",
"force-dynamo": "npm run stop-dynamo && npm run start-dynamo",
"start-dynamo": "docker run -d -p 8000:8000 dwmkerr/dynamodb -sharedDb",
"stop-dynamo": "docker stop $(docker ps -a -q --filter ancestor=dwmkerr/dynamodb --format=\"{{.ID}}\")",
However if you do not care that much about CI/CD pipeline or reusability on multiple devices -> you can just install dynamoDB, run it and based on configuration just target your offline/online dynamodb.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "node.js, amazon dynamodb, offline, aws serverless, amazon dynamodb local"
}
|
CMake variable expansion using "@" vs. "${}"
Consider the following:
SET(TEST_DIR, "test")
INSTALL(PROGRAMS scripts/foo.py DESTINATION ${TEST_DIR})
INSTALL(PROGRAMS scripts/foo.py DESTINATION @TEST_DIR@)
The first `INSTALL` command does not work. The second does. Why is that? What is the difference between those two? I have not found any reference to `@@` expansion except in the context of creation of configuration files. Everything else only uses `${}` expansion.
UPDATE: OK, obvious bug in the above. My `SET()` command has an extraneous comma. Removing it, such that it looks like:
SET(TEST_DIR "test")
results in both `@@` and `${}` expansions working. Still wondering (a) what is the meaning of `@@` as opposed to `${}`, and why only the former worked with my incorrect `SET()` statement.
|
According to the documentation for the `configure_file()` command when configuring a file both the `${VAR}` form and `@VAR@` form will be replaced VAR's value. Based on your experience above and some testing I did both forms are replaced when CMake evaluates your `CMakeLists.txt`, too. Since this is not documented I would recommend against using the `@VAR@` from in your `CMakeLists.txt`
Note that when using `configure_file()` you can restrict replacement to only the `@VAR@` form by using the `@ONLY` argument.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 6,
"tags": "variables, cmake, expansion"
}
|
Start cmd-scripts sequentually at system startup
I have Windows 2012 system with some servers. Every server starts with batch script, and some servers depends on another.
I need to start these scripts sequentially. I have 4 cmd files: startMasterServer.cmd, startSlaveServer1.cmd, startSlaveServer2, startAnotherUtility.cmd.
Slave servers can start only after master server. But when I execute startMasterServer.cmd, it need 1-2 minutes to start. Another utility don't need anything for it, it can be started at any time.
How to manage autostart of servers in Window 2012? Maybe start scripts with timeouts or something???
And how to start my batch script when OS starts? No any user logged in at this time.
|
Maby you can use `timeout 5` this for example will wait 5 seconds before continue the script.
So in your case you might want to use the following:
> startMasterServer.cmd
> timeout 120
> startSlaveServer1.cmd
> timeout 120
> startSlaveServer2.cmd
> timout 120
> startAnotherUtility.cmd
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "windows, batch file, cmd"
}
|
Blazor + RPC workaround
I believe that Blazor is a very cool thing. But, as I understand, a lot has not been realized yet. I would like to start using it, despite the fact that this is a pilot project. In this regard, I have a question: how can I make any RPC bundle? As I understand it, the .NET implementation of SignalR can not be used, but are there any workarounds? Thank you UPD: <
|
I would wait for the release of 0.4.0: <
In this release support for SignalR is included, which the Blazor team is actively working on right now: <
I think that any workaround would require to create your own Javascript interop, which is much more work than waiting on SignalR support.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, asp.net, .net, signalr, blazor"
}
|
Determine trigonemtric ratios given angle
Determine the primary trigonometric ratios for -pi/2
The answer is -1 and the solution is probably really simple, but I was wondering how do you get it?
|
Well, actually, because circles are weird. I mean, we all know it's because $sin(-\frac{\pi}{2}) =-1$ and we can solve it by looking at the unit circle, because that's how we one day defined, $sin$, $cos$ and by doing so $tan$. If we take an angle of $\frac{\pi}{2}$ **downward** , or anti-clockwise, (because it's negative), and we take the y-coordinate of that point, then what we actually did is simply calculating $sin(-\frac{\pi}{2})$ resulting into -1. That's how you get it.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "trigonometry"
}
|
Can Skeleton Killed Creepers Be Autospawned
As we all know, when a skeleton kills a creeper it drops an music disk, and if you didn't know you can pick up an mob during its dying animation using a safari net and auto spawn exact copies of it which will instantly die. When you make a skeleton kill a creeper, and you can catch it before it dies, can you put it through the autospawner and autospawn creepers that will drop music disks?
|
No the record would not drop. The arrow does not maintain the shooter as a nbt tag and the creeper does not maintain the killer as a NBT tag either.
When capturing a mob in a safari net, it saves all of the NBT information of the creature, and because the creeper does not store the DamageSource in a NBT tag, this information is lost upon capturing a creature.
|
stackexchange-gaming
|
{
"answer_score": 1,
"question_score": 1,
"tags": "minecraft java edition, minecraft feed the beast"
}
|
How to check null response in .pipe(map) Rxjs operators?
getDetailsById(eId: number): Observable<Details> {
return this.api.post('detailsapi', cacheOptions, { Id: eId })
.pipe(
map((eDetails: any) => ({
id: eDetails.eId,
subDetails: this.mapSubDetails(eDetails.eSubDetails || [])
})),
catchError((err) => {
const template: Template = {
id: 0,
subEquipment: []
};
return Observable.throw(err)
})
);
}
I'd like to check in above code if `eDetails` is null or not. If null then I want to stop all the calls in `Observable.forkJoin`.
|
You can add a `filter` in the `pipe`:
.pipe(filter(isNotNull))
And use a typeguard for the same:
export function isNotNull<T>(value: T): value is NonNullable<T> {
return value != null;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 3,
"tags": "javascript, angular, typescript, rxjs, observable"
}
|
How to know the location on slurm script using the squeue command
I am running several experiments on a cluster. I have to use so many scripts from different application folders and its hard to track with slurm scripts are currently running. Is there any way to know the location of the scripts also using squeue command?
I use "squeue - username -all" command to list all the jobs I am running
|
You can request the `command` that is run, this will give you the location of the script that was submitted:
$ squeue --user $USER --Format jobid,command:100
68286079 /home/users/[...]/exp1/submit.sh
[...]
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "slurm"
}
|
Any idea how to create scroll effects on wordpress like apple's ipad presentation?
i'm trying to find a theme or plugin in order to create a site like this one < On every scroll you see elements moving as well as when you reach on ipad the element remains sticky and the scroll is inside the ipad's screen.
Any suggestion on how to do this?
Thanks in advance
|
for animation scrolling effect you can check < , if you want ready made plugin for Wordpress then you can download this WP plugin
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "wordpress, scroll"
}
|
Kubernetes client (certificate) exception is thrown when spring-cloud-starter-kubernetes-config added as a dependency
I encountered the following error when added **spring-cloud-starter-kubernetes-config** dependency to my pom.xml:
io.fabric8.kubernetes.client.KubernetesClientException: An error has occurred. Caused by: java.security.cert.CertificateException: Could not parse certificate: java.io.IOException: Empty input Caused by: java.io.IOException: Empty input
To disable k8s, I added in bootstrap.yml following param:
spring:
cloud:
kubernetes:
enabled: false
But even after that nothing changed and the error remained.
Where else should I look? What parameter should I add so that if I have this dependency in pom.xml, I disable Kubernetes when running tests?
|
That problem could happen due to the installed `kubectl`. The easiest way to avoid this problem - rename `~/.kube` (directory with configs) to some other name like `~/.kube-hide`
mv ~/.kube ~/.kube-hide
And when you will need to use your `kubectl` rename it back
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "java, maven, kubernetes"
}
|
Partially overwrite in a file through script
I see
`<command> >> <filepath>` appends the command line to the file
and
`<command> > <filepath>` replaces the entire contents of the file with the command given passed.
How to pass the command to the file so that only the _last line_ of the file is overwritten?
|
That's not built in to the shell in the same way simple overwrite and append are. You have to do it in two steps, first remove the last line, then append:
X=$(head -n -1 filepath)
echo "$X" > filepath
command >> filepath
Or you can overwrite with the new contents all at once:
X=$(head -n -1 test)
(echo "$X"; command) > test
Note that in both cases, we capture the old lines that we want to keep in a variable first as a separate command. This is because as soon as a command with a ">" directive begins executing, the shell will clear the file, and any attempt to read those lines will be too late.
|
stackexchange-askubuntu
|
{
"answer_score": 1,
"question_score": 0,
"tags": "command line, scripts"
}
|
Negative int to hexadecimal conversion
I am converting some integers to hexadecimals but the problem i have is when i pass a negative value to convert it to hex.
Example:
String satpos = "13.0";
String satposs=satpos.replaceAll("\\.", "");
int satposition = Integer.parseInt(satposs);
String nids = Integer.toHexString(satposition);
String finished = nids+"0000";
Application returns "820000" in this case and that is the correct value i need. But if i pass:
String satpos = "-7.0";
String satposs=satpos.replaceAll("\\.", "");
int satposition = Integer.parseInt(satposs);
String nids = Integer.toHexString(satposition);
String finished = nids+"0000";
Application returns "ffffffba0000" but i should get "DCA0000"
Any help is appreciated.
|
Based on a comment by Andreas, here is a test program that prints the values you want:
public class Test {
public static void main(String[] args) {
convert("13.0");
convert("-7.0");
}
private static void convert(String satpos) {
String satposs = satpos.replaceAll("\\.", "");
int satposition = Integer.parseInt(satposs);
if (satposition < 0) {
satposition += 3600;
}
String nids = Integer.toHexString(satposition);
String finished = nids + "0000";
System.out.println(finished);
}
}
If the angle is negative, add 3600 because the angle is in tenths of a degree.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "java"
}
|
How can IPv6 host know default router's IPv6 address using RA?
I know an IPv6 host will send Router Solicitation (RS) messages, and a router on the link will reply Router Advertisement (RA) messages.
In the RA message, there is the `Source Link-Layer Address` and `Prefix Information` in options. So a host can know the router's MAC address, and it can generate it's IPv6 address.
How can a host know the router's IPv6 address (router's link-local or global address)?
|
The RA IPv6 packet will have the router address as the source IPv6 address.
A host doesn't really need to know the router's IP address to send packets to other hosts. On a LAN, frames are sent to a layer-2 (MAC) address. The layer-3 IPv6 packet will have the destination host IPv6 address, not the router address. If a host is on a different LAN, the packet will still have the destination host IPv6 address, but the frame will have the destination MAC address of the router.
|
stackexchange-networkengineering
|
{
"answer_score": 2,
"question_score": 1,
"tags": "ip, ipv6, ip address, network discovery, icmpv6"
}
|
Is it possible to test the health of a graphic card?
We know that we can test the remaining lifetime in TBW for SSDs, but is there something similar for GPUs? Is there a kind of heuristic in order to see the current state of the GPU? I'm asking this because I'd like to buy a second hand GTX 1080 Ti, so I just want to check its condition once taken.
|
**No, it's not possible.**
Like all other persistent digital storage media, SSDs have limited write cycle count. It's natural and predictable. We know that every SSD will run out of write cycles at some point and it's fairly predictable. That's what TBW estimates.
But like any other device, SSDs can also fail due to random failures and TBW doesn't take that into account (TBW estimates memory lifetime only). GPUs suffer only this kind of failures - there are no components that have predictable wear patterns.
GPUs that were used eg. for mining have high failure rates because they operated for prolonged periods of time in conditions that they weren't designed for, usually 24/7 with sub-optimal cooling.
|
stackexchange-superuser
|
{
"answer_score": 2,
"question_score": 0,
"tags": "gpu, lifespan"
}
|
Kinect 2.0 barcode scanning
I was wondering if there were any third party libraries that provide support for barcode scanning using Kinect 2.0 in C#.
I think the Kinect SDK doesn't provide any support for such a thing.
|
ZXing.Net supports Kinect.
<
You need the zxing.dll and the zxing.kinect.dll from the binaries package. ZXing.Net is available as NuGet package but it doesn't include the zxing.kindect.dll.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "kinect, barcode scanner"
}
|
Stay logged in while RDP session is over
I wasn't able to find answer to my question. Is it possible to use RDP protocol (I am using Windows 8.1) and once I finish with remote control and disconnect from session, last logged user would stay logged in or he would log in automaticly?
I am using teamviewer to remotly controll my PC, even from my bed, but it transfers image data, which makes it slow and in many cases unusable for me (it also has other disadvantages for me but it's not important for my question). I tryed application with RDP protocol on my tablet which works just fine, only bad thing is, that once I disconnect from the session, pc which is beeing controlled is stucked on user login screen, therefore it is unusable for me.
Any ideas?
|
I found a solution and it is really simple as expected. There is a command which disconnects you from remote session and reconnects that session to the remote computer's console. In human language: it closes your RDP session and "route" it to the console of the logged user so the user stays "connected" and there's no need to manually fill the password again. For the info., in RDP settings there is no option for this behaviour. At least not in gpedit.msc.
The "mojo" command:
tscon [SessionID] /dest:console
SessionID can be obtained with this command:
qwinsta
And some links:
* info about tscon
* tscon man page
* info how to get session id
|
stackexchange-superuser
|
{
"answer_score": 9,
"question_score": 5,
"tags": "windows, windows 8, remote desktop, windows 8.1, remote control"
}
|
Getting my first credit card - do UK companies have a fixed charge for owning a credit card?
I am looking to take out my first credit card to assist in the improvement of my credit score. I have been hunting around card offers online, and have found some I am willing to give a try. The top think on my list of questions, is that do UK Companies/banks have a fixed charge for owning the credit card? So, for instance.
I take out the card, decide not to use it for a month of three. Would I be charged at X Amount a month/year for not taking items out on credit? despite any charges like this are either not explained on the website, nor are clearly mentioned?
|
I can't vouch for the UK, but in the US most basic cards have either no fee or a fairly small yearly fee (about US$15, if you don't have a problematic credit record). Shop around.
|
stackexchange-money
|
{
"answer_score": 3,
"question_score": 4,
"tags": "credit card, united kingdom, fees"
}
|
Constructor Chaining vs Similar ones
I have the following constructors:
public Class1()
{
this.Variable = new Variable();
}
public Class1(Variable vari)
{
this.Variable = vari;
}
Which can be rewritten as:
public Class1()
: this(new Variable())
{
}
public Class1(Variable vari)
{
this.Variable = vari;
}
Is there any benefit from writing it the second way or would they be practically the same?
|
The first one duplicates logic. Even if said logic consists of a single assignment statement.
|
stackexchange-softwareengineering
|
{
"answer_score": 5,
"question_score": 0,
"tags": "c#, design"
}
|
returning shared_ptr member of an rvalue
In C++ Concurrency In Action - Practical MultiThreading page 167, there's the code snipet
std::shared_ptr<T> wait_and_pop()
{
std::unique_ptr<node> const old_head=wait_pop_head();
return old_head->data;
}
Why do we have to move assign rvalue `wait_pop_head()` to a const variable first? Is there a reason why we can't shorthand the code to following?
std::shared_ptr<T> wait_and_pop()
{
return wait_pop_head()->data;
}
|
Indeed, there is no reason that your alternative could not be used.
The temporary will live long enough.
But some people just prefer to write it out.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c++, c++11, shared ptr, rvalue"
}
|
I need to remove the backslashes from the following string which is a URL I have in a data frame in R
Can someone help me fix this? I am trying to remove the backslashes and the numbers between them from the following string.
a<-c("/organization/energystone-games-100-a\307\201\265\347\377\263\306\270\270\306\210\217")
I want to remove the backslashes and the numbers so the expected result should look like below:
/organization/energystone-games-100-a
|
There are actually no backslashes in the input. Backslash followed by digits is how R renders certain special characters. To remove them remove each character that is not lower case letter, upper case letter, digit, slash or minus.
gsub("[^a-zA-Z0-9/-]", "", a)
## [1] "/organization/energystone-games-100-a"
Actually no upper case letters appear so if you are only concerned about such strings then the pattern could be reduced to `"[^a-z0-9/-]"` .
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "r"
}
|
How to get a single array return value in mongodb?
I'm using Nodejs, Typescript and Mongodb. I take a nested array in my query but i only want to get a single array from db. My query is :
let sampleQuery:any = await OfferModel.aggregate([
{$match : {CompanyLoginMail : CompanyLoginMail}},
{$lookup: {from: "members",localField: "MiddleManMail",foreignField: "Email",as: "mems"}},
{$project : {
mems : { $filter : {input : "$mems" , as : "mems", cond : { $ne : ['$$mems.Email' , CompanyLoginMail]}} }
}}
])
return sampleQuery;
I get this from mongodb:
[
{
[
{},{},{}
]
}
]
But i want this:
[{},{},{}]
|
Assuming your current output looks like this:
[
{
mems: [
{},{},{}
]
}
]
you need two additional pipeline stages, $unwind and $replaceRoot:
db.collection.aggregate([
{ $unwind: "$mems" },
{ $replaceRoot: { newRoot: "$mems" } }
])
Mongo Playground
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "node.js, mongodb, typescript, aggregate"
}
|
core file deleted in woocommerce / wordpress
I have noticed that the file "wp-admin/includes/ajax-actions.php" is deleted automatically in production. Even if I upload this file via ftp, it gets deleted after some time ( ~5min ).
I cannot reproduce this behaviour in the local environment.Do you know any way to discover who deletes this file?
Wordpress: 5.6 Woocommerce: 4.8 Production environment is hosted in plesk 18.0.30
|
Exact same issue here. Took me a while to figure it out. The file is constantly being deleted. It causes a whole mess on the admin panel (images not loading, themes or plugins cannot be installed, theme settings cannot be modified, etc.). I discovered it's some kind of a scheduled job on the server that deletes all instances of the file (even if you backed it up on another folder) and it is not related with WP Toolkit security optimizations. Ι've already sent a message on my hosting provider and will post an answer once it is resolved.
EDIT: Turns out it was a misconfigured antivirus that was deleting the file from all installations. It was an isolated insident that was solved.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "php, wordpress, woocommerce, plesk"
}
|
Can't use PHP extension Solr in Ubuntu 13.10 (Apache)
After I upgraded to Ubuntu 13.10, the local development version of my website stopped working with a PHP warning:
include(SolrQuery.php): failed to open stream: No such file or directory
I checked the pecl solr extension is installed:
> sudo pecl install solr
pecl/solr is already installed and is the same as the released version 1.0.2
I checked the Solr Apache extension is set up:
> cat /etc/php5/apache2/conf.d/solr.ini
extension=solr.so
Any idea where the problem could be?
* * *
The command `php -m` doesn't seem to show solr.
|
The fix was to uninstall and then reinstall the solr pecl extension:
sudo pecl uninstall solr
sudo pecl install -n solr
sudo service apache2 restart
* * *
Before uninstalling, I noticed the `solr.so` was in the wrong place (`/usr/lib/php5/20100525/solr.so`). After uninstalling and reinstalling, it is in `/usr/lib/php5/20121212/solr.so` which is found by Apache, etc.
|
stackexchange-askubuntu
|
{
"answer_score": 4,
"question_score": 3,
"tags": "apache2, php, 13.10, solr"
}
|
webpack scss background image path error
I have the following rule on line 258 of my style.scss file:
background: url(img/bg-light-grey.gif)
I then run the command `webpack` and it successfully builds. I go to my webpage but I see I don't see the image included on my webpage. I open up chrome debugger and it says that line 258 of my style.scss has:
background: url(build/4932049asdfjaoi3j234.gif)
In my Chrome debugger, I replace that line with absolute url
background: url(
And now the image appears.
How do I get webpack to compile the file paths properly for my images? Alternatively, I don't mind stringify or base64encode these things into my bundle.js file. Whatever it takes to get these images to render properly.
|
I found the answer here:
Webpack - background images not loading
I had to make a change in my webpack.config.js from
{ test: /\.scss$/, loaders: [ 'style', 'css?sourceMap', 'sass?sourceMap' ]},
to
{ test: /\.scss$/, loaders: [ 'style', 'css', 'sass' ]},
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "sass, webpack"
}
|
ArcPy if part of string not in field, then delete row
I am able to use UpdateCursor to find and delete rows if a field contains part of a string (code below works). Now I want to do the opposite--if part of this string is _not in_ my field, I want to delete the row. Is there a "not_in" function/syntax?
with arcpy.da.UpdateCursor(mySHP, ['OID@', 'Comments']) as cursor:
for row in cursor:
if 'this phrase' in row[1]:
cursor.deleteRow()
|
Either add a `not` to the if statement:
with arcpy.da.UpdateCursor(mySHP, ['OID@', 'Comments']) as cursor:
for row in cursor:
if 'this phrase' not in row[1]:
cursor.deleteRow()
or you could add an else block:
with arcpy.da.UpdateCursor(mySHP, ['OID@', 'Comments']) as cursor:
for row in cursor:
if 'this phrase' in row[1]:
pass
else:
cursor.deleteRow()
|
stackexchange-gis
|
{
"answer_score": 5,
"question_score": 0,
"tags": "arcpy, python, cursor"
}
|
Laravel 5 : Parse error: syntax error, unexpected '?', expecting variable (T_VARIABLE)
On my Local server everything was good was using mailtrap mail server as smtp server. but when my website is on live server and when I trying to reset password (forgot password ) getting following error screenshot is attached.I am using hostgators cpanels inbuilt smtp. any more details I will provide if needed. name for taxonomy and content type?
My question: Can I (or rather, should I) create a taxonomy and a custom content type that have the same machine name? I plan to 'link' those two together.
I tried to search around and could not find an answer, I found out that two custom fields cannot have the same name, even if they belong to two different content types for example. So that would lead me to suggest that the answer to my question is probably not (i.e. they would try to use the same table name). But I don't know if that's correct.
Say I create a site for a school, and want to have a custom content type 'staff' that will hold teachers, administrative staff, etc. I will also have a vocabulary that has these different staff categories (teachers, administrative staff etc), which I also thought of giving it the name 'staff'. Is this a bad idea?
PS: I'm using Drupal 8
|
Technically you can have same name for taxonomy and content type as the underlying machine name is not the same and there is no confict.
Practically it might not be a good idea as it might confuse the end users but it depends on the problem you are trying to solve.
So based on your description `staff category` might be a better name for your category.
|
stackexchange-drupal
|
{
"answer_score": 1,
"question_score": 0,
"tags": "nodes, database"
}
|
Duvida onkeyup javascript
Quando digito no `input` alguma palavra, o texto digitado vai pra maiúscula.
No Mozilla Firefox e no Internet Explorer eu posso voltar o indicador que fica piscando pra digitar uma letra e posso editá-lo em qualquer parte.
Já no Google Chrome, toda vez que volto o indicador, ele vai automaticamente pro final do texto digitado. Como faço pra que fique igual aos outros navegadores, onde é possível voltar e não ir pro final do texto?
Nome: <input type="text" id="fnome" onkeyup="javascript:this.value=this.value.toUpperCase();">
|
# Sem Javascript
Experimente usar CSS para isto, ao invés de Javascript, dessa maneira não re-escreve o valor do input:
Nome: <input type="text" id="fnome" style="text-transform: uppercase;">
Veja exemplo aqui.
# Com Javascript (jQuery)
Se fizer questão do Javascript ou, por algum motivo, gostaria de manter o "efeito" de transformação das letras de minuscula para maiúscula e andar com o cursor pelo `input` sem que ele volte para a posição final, é possível fazer assim:
HTML:
Nome: <input type="text" id="fnome">
JS:
$("#fnome").keyup(function(){
var start = this.selectionStart,
end = this.selectionEnd;
$(this).val( $(this).val().toUpperCase() );
this.setSelectionRange(start, end);
});
Veja exemplo aqui.
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 5,
"question_score": 4,
"tags": "javascript, html"
}
|
Sojourn time of a CTMC
Soujourn time of a CTMC at time $t$ is defined as :
$$T(t)= \inf\\{ s > 0 : X(t+s) \neq X(t)\\}$$
My question is why "inf", not min ? Here $T(t)$ belongs to the set $\\{ s > 0 : X(t+s) \neq X(t)\\}$. Then we can write minimum. Is this correct ?
|
If your chain is known to be right continuous, then indeed you can replace the inf with min. Otherwise you cannot. Let $S \sim \mathrm{Exp}(\lambda)$ be an exponential random variable, and consider the chain on the state space $\\{a,b\\}$ defined by $$X(t) = \begin{cases} a, & t \le S \\\ b, & t > S. \end{cases}$$ (This chain starts at $a$, jumps from $a$ to $b$ at rate $\lambda$, and from $b$ to $a$ at rate 0.) We have $T(0) = S$, but the infimum is not achieved since $X(S) = X(0)=a$.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 4,
"tags": "markov chains"
}
|
Proving $\sec^2\theta\left(1 - \frac{\sin^2\theta}{\sin^2A}\right) = 1 - \frac{\tan^2\theta}{\tan^2A}$
> Prove that: $$\sec^2\theta\left(1 - \dfrac{\sin^2\theta}{\sin^2A}\right) = 1 - \dfrac{\tan^2\theta}{\tan^2A}$$
Please help. I tried changing $\tan$ to $\sin$ from RHS, simplifying LHS but didn’t work ! This is what I tried:
$$RHS = 1-\frac{\frac{sin^2\theta}{cos^2\theta}}{\frac{sin^2A}{cos^2A}} = \frac{\frac{sin^2A}{cos^2A}-\frac{sin^2\theta}{cos^2\theta}}{\frac{sin^2A}{cos^2A}} = \frac{sin^2Acos^2\theta-sin^2\theta cos^2A}{cos^2\theta} = sec^2\theta[sin^2A(1-sin^2\theta)-sin^2\theta(1-sin^2A)] = sec^2\theta(sin^2A-sin^2\theta) = ???$$
|
You are missing $\sin^2 A$ from your denominator. Indeed, $$\require{cancel}\dfrac{\frac{\sin^2A}{\cos^2A} - \frac{\sin^2\theta}{\cos^2\theta}}{\frac{\sin^2A}{\cos^2A}} = \dfrac{\frac{\sin^2A\cos^2\theta - \sin^2\theta\cos^2A}{\cancel{\cos^2A}\cos^2\theta}}{\frac{\sin^2A}{\cancel{\cos^2A}}} = \dfrac{\sin^2A\cos^2\theta - \sin^2\theta\cos^2A}{\sin^2A\cos^2\theta}$$
And so, in your last line, you have $$\sec^2\theta\left(\dfrac{\sin^2A - \sin^2\theta}{\sin^2A}\right) = \sec^2\theta\left(1 - \dfrac{\sin^2\theta}{\sin^2A}\right)$$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": -1,
"tags": "trigonometry"
}
|
How to test the CPU with a simple C++ program
In my opinion, I have two ways to do this:
One is to use a loop:
t1 = getTime();
for(int i = 0; i < 9999999; i++)
{}
t2 = getTime();
And now I can check `t2 - t1`.
The other is to create many threads, each thread does the same loop above.
I don't know if the second way is better than the first one.
Or maybe there are better ways to test CPU?
|
This loop does nothing and will be optimized out by every reasonable compiler.
To get reasonable benchmark results, you'll have to solve (somewhat) reasonable problems, like calculating many digits of pi, finding big primes or whatever task(s) you want to base your definition of _fast_ on, with good implementations of efficient algorithms.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "c++, cpu, benchmarking, timing"
}
|
Android Studio - Android Device Monitor - Empty View
I am trying to use the Android Device Monitor within Android Studio, but somehow I managed to remove all views.
I have tried resetting the perspectives, Window->Show View->(Any View), and even re-installing Android Studio but nothing shows up.
!Android Device Monitor
Does anyone know how to reset the Device Monitor back to it's default views? (With the devices on the left, and the heap/threads/allocation views on the right.)
Thanks for your help!
|
I've experienced this same problem by using **Window -> Reset Perspective**. One should expect this to _fix_ this issue, not break it. Go figure.
In any case, the DDMS workspace preferences are stored in `%USERPROFILE%\.android\monitor-workspace` (e.g. `C:\Users\my_user\.android\monitor-workspace`).
Just delete that folder and you're good to go.
|
stackexchange-stackoverflow
|
{
"answer_score": 32,
"question_score": 12,
"tags": "android, android studio, ddms"
}
|
Installing a stud wall without connecting to ceiling?
what is the best approach to installing a stud wall (making walk in wardrobe) without also screwing into the ceiling? I am going to pull back the carpet and nail into the floor but I am wondering if I can secure by another means instead of going into the ceiling as well. Thanks
|
Often walls in office buildings do not extend to the roof or floor above. (Suspended ceilings are installed in the offices.)
If the room is about 12’ or so with a double top plate, it probably doesn’t need to be braced. If it’s over 12’ or so, I’d add a 2x4 brace from the top of the wall up to the floor above.
|
stackexchange-diy
|
{
"answer_score": 1,
"question_score": 1,
"tags": "walls"
}
|
Integral calculus - complex numbers
I need help to integrate this, i tried changing variable and it didn't work, i tried integration by parts, and it failed too.
$\frac{1}{2π}∫e^{jx\omega}\frac{(1/6)}{(1/6-j\omega)}d\omega$
I need to integrate from $-\infty$ to $\infty$
Can someone give me a hint where to start.
Thank you
|
The Fourier transform has the following property:
$$f(-\omega)=2\pi\mathcal{F}(G(t))$$
where $G(\omega)=\mathcal{F}(f(t))$
Let $f(t)=\text{sgn}(t)$ then $$\mathcal{F}(f(t))=\frac 1{2\pi}\int_{-\infty}^{\infty} \text{sgn}(t)e^{-j\omega t}d\omega=\frac 1{2\pi}\left[\int_{0}^{\infty}e^{-j\omega t}d\omega-\int_{-\infty}^{0}e^{-j\omega t}d\omega\right]$$ $$=\frac 1\pi \left[\frac{e^{-j\omega t}}{-j\omega}\right]_0^\infty=\frac j{\pi\omega}$$
In addition, if $\mathcal F(h)=G(\omega-\omega_0)$ then $h(t)=e^{j\omega_0 t}f(t)$
Combining these three hints gives you another way of solving the integral.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "integration, complex integration"
}
|
Why should I use @Url.Content("~/blah-blah-blah")?
I can't understand the benefit(s) that I can get from `Url.Content()` method in ASP.NET MVC. For example, you see `src='@Url.Content("~/Contents/Scripts/jQuery.js")'`. Why should I use it? What reasons might exist for using it? What benefits, advantages, etc. over using plain old simple references like `src='/scripts/jquery.js`?
**Update:** Based on the answers, I'd like to know if there is any other reason for using it, other than handling virtual folders? Because I haven't seen using virtual applications that much (which of course doesn't mean that it hasn't been used that much).
|
Mapping virtual paths is it's only purpose. If you do not ever need to map them and are sure your app or it folders will not sit under other apps then it won't serve you any purpose.
From the docs note if you don't use ~ you get no change in the result anyways: "Remarks If the specified content path does not start with the tilde (~) character, this method returns contentPath unchanged. "
|
stackexchange-stackoverflow
|
{
"answer_score": 26,
"question_score": 39,
"tags": "asp.net mvc"
}
|
what method for nanobot to control human body without affecting the brain?
i mean controling the external body like limb and such without internally going into human brain or mindcontrol using nanobot, or going inside human skin or nerve (contact with skin is fine but not something like going inside muscle or skin etc).
so the person is controlled like puppet but still conscious or aware.
|
Control of the muscles of a human body is limited if one remains outside of the body. We do have some limited ability to do so using electric fields, such as those produced by TENS units. These can cause a muscle to contract.
However, such contractions yield very little control. Our muscles are organized into muscle units, which are small groups of fibers within a muscle that always contract together. Our bicep has about 53 of them, and we recruit them in various orders to have fine control over our motion. If one is using TENS style electrical fields, it's hard to affect them one at a time -- you tend to contract the whole muscle. An individual being controlled in this way would be jerky, like a zombie.
To get a sense of what it would be like, consider playing QWOP, a game which challenges you to run by controlling the leg muscles directly.
|
stackexchange-worldbuilding
|
{
"answer_score": 1,
"question_score": -1,
"tags": "science in society, nanotechnology"
}
|
getDefaultGcsBucketName Response contained no data
I try to call AppIdentityService#getDefaultGcsBucketName but it throws an exception: Response contained no data. According to the docs, the default bucket should be ready to use. Code:
//Field
private AppIdentityService service;
//in ctor
this.service = AppIdentityServiceFactory.getAppIdentityService();
//call inside a method
final String baseUrl = GCS_URL + "/" + service.getDefaultGcsBucketName() + "/" + fileName;
|
If you created your app prior to the 1.9.0 SDK release, you have to manually setup your default GCS bucket. Read this article for more information (I know its for PHP, but its applicable across all languages).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "google app engine"
}
|
Heavy GUI application with Python?
Is it possible to create high GUI apps or graphics intensive games using python? I am a beginner at programming I want to make GUI apps along with web applications and also I'm interested in Machine Learning. Many resources says python is best for ML and Web apps and not for GUI Is there any ways to create it.
|
If you'd like to create 2D games with Python, there are several libraries you can use:
* PyGame or PyGame Zero
* Pyglet
I have also heard good things about Panda3D for 3D games. There is an openGL wrapper as well, but that one sounds like it has quite the learning curve.
Machine Learning is a different ballgame entirely. You would want to look up pandas, matplotlib, dask and several other libraries to get started with that discipline.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "python, wxpython"
}
|
Overriding generic abstract method's return type without type safety warnings
In some `SuperClass` I have an abstract generic method:
protected abstract <T extends Foo> T getFoo();
In my `SubClass` I try to override it with:
@Override
protected SubFoo getFoo() {
return new SubFoo();
}
where `public class SubFoo extends Foo`
in my subclass's `getFoo` I get the following error.
"Type safety: The return type SubFoo for getFoo() from the type SubClass needs unchecked conversion to conform to T from the type SuperClass"
My questions are:
1) Is there any scenario where this is not safe ?
2) If not, shouldn't the compiler be able to figure that out ? what is preventing the compiler from figuring out that SubFoo is a subclass of Foo at compile time ?
3) Is there a way to achieve something like this, but warning free ?
|
Yes, this is unsafe and illegal. The `SuperClass` declaration you've written allows the _caller_ \-- not the `SuperClass` subclass -- to choose which subtype of `Foo` it wants, so your implementation in `SubClass` doesn't implement it properly.
Instead, you must have `T` as a generic parameter for `SuperClass` itself, not just the method: `SuperClass<T extends Foo>`, and then `SubClass extends SuperClass<SubFoo>`.
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 3,
"tags": "java, generics, abstract"
}
|
Delete from table with(snapshot)
I was trying to learn querystore. When going through few queries involved in query store one of the query is below
DELETE TOP (1000000)
FROM [sys].[memory_optimized_history_table_1179151246]
WITH (SNAPSHOT)
**Full query:**
(@rowcount INT OUTPUT) DELETE TOP (1000000) FROM [sys].[memory_optimized_history_table_1179151246] WITH (SNAPSHOT)
OUTPUT
DELETED.[ColdRoomTemperatureID], DELETED.[ColdRoomSensorNumber], DELETED.[RecordedWhen], DELETED.[Temperature], DELETED.[ValidFrom], DELETED.[ValidTo]
INTO [Warehouse].[ColdRoomTemperatures_Archive]
WHERE [ValidTo] < GetHkOldestTxTemporalTs()
I searched a lot to see what the `WITH (SNAPSHOT)` option means, but I was not able to find anything.
Can you please help me in understanding what does `WITH (SNAPSHOT)` mean?
Let me know ,if you need any further info.
|
This is a table hint that can be used in various statements (SELECT, INSERT, DELETE, UPDATE, MERGE). See the related page at msdn: Table hints and the linked Introduction to Memory-Optimized tables.
For further information about isolation levels, see SET TRANSACTION ISOLATION LEVEL (Transact-SQL).
> **Syntax**
>
>
> WITH ( <table_hint> [ [, ]...n ] )
>
> <table_hint> ::=
> [ NOEXPAND ] {
> INDEX ( index_value [ ,...n ] )
> | INDEX = ( index_value )
> | FORCESEEK [( index_value ( index_column_name [ ,... ] ) ) ]
> | FORCESCAN
> ...
> | SNAPSHOT
> ...
>
>
> ...
>
> `SNAPSHOT`
>
> Applies to: SQL Server 2014 through SQL Server 2016.
>
> **The memory-optimized table is accessed under`SNAPSHOT` isolation.**
> **`SNAPSHOT` can only be used with memory-optimized tables** (not with disk-based tables).
> For more information, see Introduction to Memory-Optimized Tables.
|
stackexchange-dba
|
{
"answer_score": 2,
"question_score": 1,
"tags": "sql server, sql server 2016, memory optimized tables, query store"
}
|
Any way to figure out whether a site was created via Self-Service Site Creation or "regularly"?
Is there any way to figure out whether a site was created by a user, using self-service site creation or by an admin by Central Administration or PowerShell?
I tried looking through the `SPWeb.AllProperties` for some identifier or `SPSite.GetSelfServiceSiteCreationSettings`, but that only contained whether self-service was enabled for the site, not whether the site was created using it. The only workaround I found so far: `SPSite.RootWeb.Author` which hopefully is different for self-service created site.
Besides using a custom provisioning provider which would write a custom property into the root web - any standard way to figure out how the site was created?
|
SharePoint doesn't store the method used to create a site anywhere. Your only indicator would be to identify sites whose author doesn't actually have the appropriate permissions to create sites. As far as a custom provisioning provider, the SPWebProvisioningProperties object passed to the provider doesn't offer any information as to the method either.
|
stackexchange-sharepoint
|
{
"answer_score": 1,
"question_score": 4,
"tags": "powershell, provisioning providers, self service"
}
|
Is it safe to chown on /usr/lib?
Can I do this?
sudo chown -R myUsernName /usr/lib
I mean can I do this without worrying that my OS will be broken? Or permissions will be screwed up?
Here is the reason why I would like to do it
* <
and here is why I don't and I came here to ask you guys:
* How to get back sudo on Ubuntu?
|
Two things:
(1) There is absolutely no advantages for this. The files in `/usr/lib` are supposed to be owned by root/system, as MANY things on the system which are owned by root are dependent on them.
(2) This is also a very good way to break your system.-
Just to make a point, follow this general rule of thumb:
**If in doubt, don't do it.**
|
stackexchange-unix
|
{
"answer_score": 12,
"question_score": 4,
"tags": "ubuntu, permissions"
}
|
Koa-swagger: access-control-origin error after cors being set
I am playing around with koa and swagger. It gives me the error of "may not have the appropriate access-control-origin settings" even after I set the cors.
App.js
var cors = require('koa-cors');
var swaggerApp = koa(),
port = 8080;
var options = {
origin: '*',
headers: ['Content-Type', 'Authorization','Origin', 'X-Requested-With']
}
curl i
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,HEAD,PUT,POST,DELETE
Access-Control-Allow-Headers: Content-Type,Authorization,Origin,X-Requested-With
Content-Type: application/json; charset=utf-8
Content-Length: 203
Date: Mon, 31 Aug 2015 17:13:55 GMT
Connection: keep-alive
{"basePath":" about API"}]}
|
Unfortunately the swagger ui cannot give complete warnings when there's a CORS error. In your case, please look to see that < exists. If not, you might get the same error message.
It also looks like the swagger definition is quite old (1.0). Can you look at using a newer library, such as <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "cors, swagger, koa"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.