INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Pin::as_mut(&mut self)
From the source for `Pin::as_mut` \- **pin.rs:**
impl<P: DerefMut> Pin<P> {
...
pub fn as_mut(&mut self) -> Pin<&mut P::Target> {
unsafe { Pin::new_unchecked(&mut *self.pointer) }
}
...
}
I don't understand why `&mut *self.pointer` is used instead of `self.pointer`, What is wrong with the following sentence?
unsafe { Pin::new_unchecked(self.pointer) }
|
`Pin::new_unchecked(self.pointer)` would just return a `Pin<P>` instead of a `Pin<&mut P::Target>`, deref coercions won't be considered. It will also attempt to _move_ `pointer` out of `self` and cause a compiler error.
Using `*` will _dereference_ `self.pointer` into a `P::Target` and `&mut` makes it return a mutable reference.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "rust"
}
|
CallerID in Dialogue
In my Rivr application I was using
> firstTurn.getParameter("nexmo_caller_id");
to get caller ID as I saw that parameter passed by Nexmo, but I've changed to Voxeo and obviously that is not working anymore. Does Rivr has any standard method to get Caller ID (remote caller number) in a Dialogue?
Thanks
|
See < but change `session.connection.uuid` with the session variable that contains the info. In VoiceXML 2.0, it's `session.connection.remote.uri` but Voxeo also offers `session.callerid`.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "voicexml, rivr, voxeo"
}
|
What is the semicolon in C++?
Roughly speaking in C++ there are:
* operators (`+`, `-`, `*`, `[]`, `new`, `...`)
* identifiers (names of classes, variables, functions,...)
* const literals (`10`, `2.5`, `"100"`, ...)
* some keywords (`int`, `class`, `typename`, `mutable`, ...)
* brackets (`{`, `}`, `<`, `>`)
* preprocessor (`#`, `##` ...).
But what is the semicolon?
|
The semicolon is a _punctuator_ , see 2.13 §1
> The lexical representation of C++ programs includes a number of preprocessing tokens which are used in the syntax of the preprocessor or are converted into tokens for operators and **punctuators**
|
stackexchange-stackoverflow
|
{
"answer_score": 21,
"question_score": 23,
"tags": "c++"
}
|
"Spoon feed" vs. "spoonfeed"
Is there a whitespace in _spoonfeed_? I have to choose between writing _Spoon Feed Code_ and _Spoonfeed Code_.
|
> Mightn't you also _spoon-feed_ code? @Brian Hooper
For AE and BE this seems to be the most common usage and the one I would also have suggested.
spoonfeed: 158,000, spoon feed: 696,000, spoon-feed: 699,000.
|
stackexchange-english
|
{
"answer_score": 3,
"question_score": 1,
"tags": "verbs, orthography, spacing"
}
|
extended floating action button for scrren swipe
Hi I want to make an Extended floating action button when I swipe up my screen it will become shrink, and when I swipe down it will be extended. I tried a lot to search this answer but not found that's why I asked this question. thanks in advance
|
if you are making it visible or invisible using recyclerview scroll
then
recyclerView.addOnScrollListener( new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dy < 0)
floatingActionbutton.hide();
else if (dy > 0)
floatingActionbutton.show();
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged( recyclerView, newState );
}
} );
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android, floating action button"
}
|
Multiple SELECT statements from different tables
I have two independent tables: 'Clients' and 'Country'.
**Country Table:**
IdCountry Country
1 SPAIN
2 PORTUGAL
**Clients Table**
IdClient Entity IdCountry
1 Adam Alves 2
2 Peter Smith 2
3 David Ramos 1
4 Rafael Castro 1
I would like to add a new client into 'Clients' table but using the information from 'Country' table like this:
INSERT INTO Clients(IdClient, Entity, Country)
SELECT max(IdClient) + 1, '--New--' FROM Clients,
SELECT IdCountry FROM Country WHERE Country = 'SPAIN'
I would like to have this INPUT:
IdClient Entity IdCountry
5 --New-- 1
But if I run this query, it doesn't work. Could anybody help me, please?
COMMENTS: I prefer don't use autoincrement option.
Thank you very much.
Wardiam
|
You can do it like this:
INSERT INTO Clients(IdClient, Entity, Country)
SELECT
(SELECT MAX(IdClient) + 1 FROM Clients),
'--New--',
(SELECT IdCountry FROM Country WHERE Country = 'SPAIN')
See the demo.
Results:
| IdClient | Entity | Country |
| -------- | ------------- | ------- |
| 1 | Adam Alves | 2 |
| 2 | Peter Smith | 2 |
| 3 | David Ramos | 1 |
| 4 | Rafael Castro | 1 |
| 5 | --New-- | 1 |
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "mysql, sql"
}
|
sorting k sorted lists by their max element
If I had k sorted singly linked lists and sorted them (mergesort) by each list's largest element (last in the list), what would the big O (running time / time complexity) be? Assuming list 1 ~ k has different size: n_1 ~ n_k. I was thinking O(k * log(MAX(n_1 ~ n_k))) but not sure how or why I came to that line of thinking.
|
Assuming that you have O(k) units of memory to store max element of each list, the time to merge sort lists themselves, i.e. without merging their elements, would be O(sum(Ni) + k*log k).
The first term is there because you need to navigate to the end of each list exactly once; after that you can "tag" the list with its max value, and perform merge sort on tagged lists. The second term comes from sorting k items using merge sort. The fact that the original lists are sorted becomes irrelevant, because you need to traverse the entire list anyway.
If the lists are modifiable, the timing complexity would remain the same even without an additional storage, because you could reverse the lists, sort them, and then reverse them again. Reversing a list takes O(sum(Ni)), so the time complexity would remain the same.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "algorithm, sorting, time complexity, big o, mergesort"
}
|
What is a good set of default settings to use for GC logging in Java 9+?
Prior to Java 9 I was familiar with a set of "mandatory" (as recommended in Optimizing Java) flags for GC logging that I would enable for instances of a JVM. These were:
-Xloggc:gc.log -XX:+PrintGCDetails -XX:+PrintTenuringDistribution -XX:+PrintGCTimeStamps -XX:+PrintGCDateStamps
With Java 9 and the introduction of Unified GC Logging is are there any recommendations for an equivalent set of "mandatory" GC logging settings?
|
The corresponding flags to use for GC logging with Java-9 and above would be:
-Xlog:gc* -Xlog:age*=debug
Reference - Enable Logging with the JVM Unified Logging Framework
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "java, garbage collection, java 9"
}
|
Как повернуть только одно изображение в canvas
Всем привет.
Пишу html5 платформер, так вот, встала задача вращать изображение героя, все это в canvas. Но при рендеринге вращаются и фон и и все остальные герои, каша одним словом.
Перерыл весь интернет в поиске решения проблемы, пробовал создавать новый контекст для каждого героя `this.ctx = canvas.getContext("2d");` но не помогло, прошу вашей помощи, заранее спасибо !)
|
// Сохраняем настройки канваса до всяких манипуляций с ним
ctx.save();
// Сдвигаем все адресованные пиксели на указанные значения
ctx.translate(canvas.width/2,canvas.height/2);
// Поворачиваем на `degrees` наш градус
ctx.rotate(degrees*Math.PI/180);
// Рисуем повернутую картинку
ctx.drawImage(image,-image.width/2,-image.width/2);
// Восстанавливаем настройки на момент когда делали `ctx.save`
// то бишь до `ctx.translate` и `ctx.rotate`. Рисунок при этом сохраняется.
ctx.restore();
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "javascript, canvas, разработка игр"
}
|
Add Remote option not shown in PyCharm
I am trying to set up a remote debugger with PyCharm on a Vagrant Machine. I am following this PyCharm tutorial. However, the Add Remote option is not available for me. Just Add local and Create VirtualEnv.
Any idea why is this happening?
|
Just as a guess: are you using the free community edition of PyCharm? Unfortunately remote interpreters and remote debugging are only supported by the professional edition. You might take a look into the editions comparison on their website.
If you are using the pro version, we might have to dig a little deeper.
|
stackexchange-stackoverflow
|
{
"answer_score": 20,
"question_score": 14,
"tags": "python, debugging, pycharm, remote debugging"
}
|
Getting member variables through reflection in Kotlin
If I have a class in Kotlin:
class Foo{
var x= null
var y=null
}
I want to check which of these members have been set at runtime through reflection. I can iterate over them and check for null in Java.
Foo foo= new Foo();
//this gives me the value of foo.x
Foo.class.getDeclaredField("x").get(foo);
How can I do the same in Kotlin/Native? I know I can achieve this in Android by
Foo::class.java.getDeclaredField("x").get(foo)
But this doesn't work in native environment.
|
I'm just going by the documentation, so the below may be a bit wrong, but you could try this:
val prop : KCallable = Foo::class.members.firstOrNull { it.name == "x" }
if (prop != null) {
val xValue : Int? = prop.call(object)
//you have to declare the type of the xValue
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "reflection, kotlin"
}
|
Effect of variability due during motor skill training
When training fine motor skills, are identically setup practice sessions ideal or, like machine learning, does adding noise/variability to the practice session increase skill acquisition?
|
According to "Motor Skills Are Strengthened through Reconsolidation01514-6)" (available through SciHub) adding variability to practice sessions increases learning speed. In the paper, patients were directed to move a cursor on a screen to certain targets via pinch force. Patients who's pinch force mapping was modified during each trial ended up learning faster and performing better on the original pinch task.
|
stackexchange-cogsci
|
{
"answer_score": 4,
"question_score": 3,
"tags": "cognitive psychology, learning, motor"
}
|
Running a process in background process on the server
Hi I have a website that I need to work on. Where once a process is started by the user it needs to run until certain conditions are met from live temperature data. It could take days before the process is completed. So once process is started it needs to run continuously on the server. I have no idea how to go about it. I read about background worker processes but I am not sure if I am on right track. I want to accomplish this using asp.net and C# if possible. Can anyone put me on right track? Thanks
|
ASP.NET is not a good choice for implementing such long running background workers, because the worker process is recycled once in a while to minimize the effect of memory leaks (depends on the configuration, might be very often).
However, you can implement a Windows Service that runs on the server and is independent of the web application. The web application and the Windows Service can communicate through WCF (or the database) for instance.
Of course, installing a service on a web server might be prohibited for security reasons, so you should check this before.
An alternative that is more lightweight in comparison to a Windows Service is to create a Console application and run it periodically through a scheduler, if that also meets your requirements.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, asp.net"
}
|
Enigmail Public Key Reference
I seem to remember in earlier versions of EnigMail, the Thunderbird add-on that it was possible to have it display the location of your public key (name & server). This doesn't seem to be the case any more. This was a useful; feature for me as I tend to use a single public key for several accounts, but would like to indicate the key being used to sign the message. It seems to me that it would be a good practice to advertise where your public key is available as there are many key servers.
* Does anyone know how to activate this functionality again (other than a sig) ?
* Is it a bad security practice to advertise where your key is?
(My current versions are Thunderbird 3.1.6 and EnigMail 1.1.2).
|
Found it: If you look at the individual settings for each account, under "OpenPGP Security", if you select the "Use PGP/MIME by default" option, in the advanced settings you can specify that you want to send your keyID, and also which server to look for it on.
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 0,
"tags": "thunderbird, public key, enigmail"
}
|
Python Regular Expression of long complex string
So I am scraping data from a webpage and the received data usually is as followed:
`233989 001 0 / 49 T R 4:15 PM - 5:30 PM 205 IST Building 01/13/14 - 05/02/14 Controls View (814) 865-8947 266200 002 0 / 43 M W F 10:10 AM - 11:00 AM 110 IST Building 01/13/14 - 05/02/14 Controls View (814) 865-8947`
I am trying to split the data from the pattern ###### (6 numbers, i.e. `233989`) to the phone number which represents the end of the current data line (i.e. `(814) 865-8947`) Because I know it'll always end with 4 numbers I came up with the expression:
`(^[0-9]{1,6}$[^[0-9]{1,4}$]*[0-9]{1,4}$+)+`
This does not seem to work though. Can anyone lend a helping hand?
|
You could use this:
r'(\d{6}.*?\(\d{3}\) \d{3}-\d{4}) ?'
Then rebuild it on `$1\n`
Like so: <
Python:
import re
s = '233989 001 0 / 49 T R 4:15 PM - 5:30 PM 205 IST Building 01/13/14 - 05/02/14 Controls View (814) 865-8947 266200 002 0 / 43 M W F 10:10 AM - 11:00 AM 110 IST Building 01/13/14 - 05/02/14 Controls View (814) 865-8947'
spl = re.split(r'(\d{6}.*?\(\d{3}\) \d{3}-\d{4}) ?', s)
for line in spl:
print line
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "python, regex"
}
|
When table name already exist I want to show a message but also ask again for a new table name
I want to verify if a table exist, if exist I want to show a message "Table already exist" and ask again user to enter a new name for table.
But when user enter a table name that already exist, Im getting only the message "Table already exist" but its not asking again to enter the name for the table.
Do you know why its not working?
def validField(info):
field = ""
while not field:
field = raw_input(info)
if not field:
print "Empty field"
return field
def createTable():
tableName = validField("Please enter the name for table: ")
try:
verifyTable = test.get_table(tableName)
except BotoServerError:
print "Table already exist"
tableName = validField("Please enter the name for table: ")
|
How about:
def createTable():
ok = False
while not ok:
try:
verifyTable = test.get_table(raw_input("Please enter the name for table: "))
ok = True
except BotoServerError:
print "Table already exist"
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python"
}
|
How can I search for a string of JavaScript code in a large project?
I am new to a company and their code is not documented. I'm calling a complex function but cannot get it to work. I'd like to see how this function is called in their production code. The more examples of it's usage I can find, the better. This function is rarely called. All of their code exists in one Visual Studio project. There is about 150 sub-projects. I'd say the chance that a sub-project uses this function is 5%. Each project contains a wide variety of file types. What I'd like to do specifically, if find all JavaScript files with "insert string here" in their code. How can I do this?
This project is also hosted by Team Foundation Server.
|
Notepad++ has a great find-in-file tool. However, it took a long time because it had to search through 2.43GB of data. You can see how to use it here: <
Thank you for the suggestion Simon! It found 66 results.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "javascript, visual studio"
}
|
Divide and Conquer Recurrence Relation
 = 4T(n) + \lfloor\frac{n}{2}\rfloor$
but still confused whether this is right or wrong.
I got $4T(n)$ because the for-loop loops 4 times with no other extra lines.
However I am not quite sure about the
$+ \lfloor\frac{n}{2}\rfloor$ part.
Since the "printer($\lfloor\frac{n}{2}\rfloor$)" recursively calls the algorithm with $\frac{n}{2}$, I just added it at the end of the relation to show that it is being processed once every time the algorithm is called.
Is this right way to provide the recurrance relation?
Any help will be much appreciated.
Thank you.
|
Close, but $T$ should be "called" when the `printer` function calls itself recursively. Presumably, $T(n)$ counts the number of calls to `printline`. The recurrence [note": _recurrEnce_ ] relation ought to be: $$ \begin{align} T(1) &= 0 \\\ T(n) &= 4 + T(\lfloor n/2 \rfloor) \quad \text{(n > 1).} \\\ \end{align} $$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "algorithms, recurrence relations"
}
|
A filter for two conditions at the same time on album tracks
I have this dataset:
dataset_ex <- data.frame(album = c("Brim","Brim","Brum","Brum"),
track = c("Tad","Toe","Toe","Ram"),
stringsAsFactors = FALSE)
album track
1 Brim Tad
2 Brim Toe
3 Brum Toe
4 Brum Ram
And one song track is redundant (since it appeared in two albums). In this case, the song `Toe`. And I want to eliminate one observation with that song, so I tried:
dataset_ex %>% filter(track != "Toe" && album != "Brum")
But it returns all the observations. My expected result is:
album track
1 Brim Tad
2 Brim Toe
3 Brum Ram
Any help will be greatly appreciated.
|
When comparing vectors you should use single `&` or `|` and I think the condition that you are looking for is `|` here -
library(dplyr)
dataset_ex %>% filter(track != "Toe" | album != "Brum")
# album track
#1 Brim Tad
#2 Brim Toe
#3 Brum Ram
Keep the rows where `track` is not `'Toe'` or `album` is not `'Brum'`.
* * *
Another way -
This gives the row that you want to remove
dataset_ex %>% filter(track == "Toe" & album == "Brum")
# album track
#1 Brum Toe
Now negate the above condition to get the rows that you want to keep -
dataset_ex %>% filter(!(track == "Toe" & album == "Brum"))
# album track
#1 Brim Tad
#2 Brim Toe
#3 Brum Ram
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "r, dplyr"
}
|
Listing results from two connected tables
I have two tables as following:
**files**
id | path | filename
**changes**
id | file_id | change
**file_id** field is connected to the id which is in files table.
What I do with these tables is storing which files are changed and what changes are done in a file.
What I want to do is listing the files and listing the changes which were made in that table under file.
What is the best and most optimized way to do that in PHP?
Thank you for your help.
Regards.
|
Use a JOIN query:
SELECT files.*,changes.change FROM files
LEFT JOIN changes ON change.file_id = files.id
ORDER BY files.id;
This will get you a result set with each row containing:
* id
* filename
* path
* change
With the use of the `ORDER BY` query, you can store the last :
$fileId = null;
foreach ($results as $result) {
if ($fileId != $result['id']) {
echo "{$result['filename']}\n";
$fileId = $result['id'];
}
echo " {$result['change']}\n";
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "php, mysql, list"
}
|
Mac Mini won't start
I got a 2007 Mac Mini off eBay a year ago. Now it won't start. It will show the Apple logo and then when it gets to the blue screen where it would normally show the desktop, the DVI cuts out.
I have taken it apart before, I upgraded the RAM. The back ribbon cable is unplugged which may be the sound. It does start occasionally and when it does I have no sound. The front black plug is also unplugged, which seems to be fan control as it's loud when it's unplugged. (The front black plug wire is broken.)
Any ideas on what to do?
Note: it gets to the blue screen and then the dvi connection drops.
|
This turned out to be the DVI-cable. For some reason, the DVI-cable works better with my PC than the Mac. I plugged it in via VGA and it works.
|
stackexchange-apple
|
{
"answer_score": 1,
"question_score": 1,
"tags": "hardware, mac mini"
}
|
gdb addresses too short
I'm trying to play around with ROP programming and therefore I am using gdb. So I am trying to follow this step:
(gdb) print not_called
$1 = {<text variable, no debug info>} 0x8048444 <not_called>
but when I am running this command I get something like this:
(gdb) print not_called
$1 = {void ()} 0x40062d <not_called>
I am running this on a 64Bit machine:
dirk@discordia:~/devel$ uname -p
x86_64
Am I doing something wrong or is this correct that the addresses on my machine are two bytes less than in the tutorial? And if it's just a gdb switch or something that the addresses on my machine are displayed shorter. How can I switch the way the addresses are displayed?
|
You're running on a **64bit** system, which defaults programs to the **0x400000 page** , and the tutorial was built on a **32bit** system, which defaults to the **0x8048000 page**.
There is no issue.
(And if `gdb` didn't turn off **ASLR** , neither of those numbers would match, as the base page address would have been randomized ' _for your protection_ '.)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "linux, assembly, gdb"
}
|
What did Mako say?
Right before the detonation of the large nuke, Mako said something to Stacker. It wasn't subtitled and I don't speak Japanese. What did she say?
|
She said (sensei aishitemasu), which means "I love you teacher/elder." This was confirmed on Twitter by Travis Beacham, _Pacific Rim's_ screenwriter.
Mako Mori is a Japanese name, which was my first clue that she's Japanese. The others were that the language she and the Marshall spoke early on was Japanese, and the city in her flashback was adorned with signs that had Japanese, not Chinese, on them.
|
stackexchange-movies
|
{
"answer_score": 23,
"question_score": 19,
"tags": "pacific rim"
}
|
Как удалить символы из строковой переменной?
Приветствую всех. Получаю адрес текущей страницы
var A = window.location.pathname;
в которой, к примеру, **/razdel/razdel/page/12345/**
Подскажите, пожайлуста, каким образом откинуть все, что следует за предпоследним слэшом. В PHP прошелся бы прег_сплитом и было бы мне счастье в массиве, а тут прям проблема. Получается только все слеши откидывать.
|
A.replace(/(.*)\/.*\//, '$1');
Дополнение к другому ответу
var text = '/razdel/razdel/page/12345/'.split('/').slice(0,-2).join('/');
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "jquery, javascript"
}
|
String manuplation and SQL search
I have image table which contain resolution column, I like to search by width or height of images.
My actual column value is e.g. 1920x1280.
I want to search something like 1920 > 2048 or 1280 > 1800
so I can list if image is hd, 4k, or 8k.
I guess I need to manipulate resolution column first though I have no idea how achieve it.
|
Your table design violates the rules of First Normal Form and you're run into it's effect. The best way is to split this column by two, width and height, and make simple filter condition as you wish.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "php, mysql, sql, laravel"
}
|
Mock hover state in Storybook?
I have a hover style in my component:
const style = css`
color: blue;
&:hover {
color: red;
}
`;
Can you mock this in Storybook so that it can be shown without having to manually hover over the component?
|
Since in Storybook you need to show the component hover appearance, rather than correctly simulate the hover related stuff,
**the first** option is to add a css class with the same style as _:hover_ :
// scss
.component {
&:hover, &.__hover {
color: red;
}
}
// JSX (story)
const ComponentWithHover = () => <Component className="component __hover">Component with hover</Component>
**the second** one is to use this addon.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 5,
"tags": "storybook"
}
|
remove all consecutive pattern in a string
I have a problem which needs to remove consecutive pattern in a string.
For example,
input: abcbcbcbcd
output: abcd
input: abcbcebcbcd
output: abcebcd
We may only consider the repeating pattern contains only 2 characters.
What is the best way to solve it?
Thanks
|
You may try this regex:
(..)\1+
* Substitution
$1
syntax | note
---|---
`(..)` | any two characters, capture them in group 1
`\1+ ` | repeat group 1 at least 1 time
Check the test cases
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "regex, algorithm"
}
|
Any element of a field may be expressed as the sum of non-zero two elements of the field.
Am I correct in this conclusion?
Any element of a field may be expressed as the sum of some two **non-zero** elements of the field.
I.e. For any $z \in F$ there is $x, y \neq 0 \in F$ such that $z = x + y$
Proof:
$z + (-y) = x$
Certainly. (Any $z$ added to the additive inverse of some $y$ is certainly equal to some $x$ in $F$)
Hence
$z + (-y) + y = x + y$
$z = x + y$
|
First off, we may assume without loss of generality that $z\ne 0$, as $0 = 1 + (-1)$ in every field.
The proof fails because you do not know that $y \ne z$, and thus it could be the case that $x = 0$, meaning you have not found your desired pair of nonzero elements. Your proof thus makes the implicit assumption that there are two distinct nonzero elements $y$ and $z$, a statement true in every field except $\mathbb F_2$. And sure enough, the statement is false in $\mathbb F_2$: $1 = 0 + 1$ and $1 = 1+0$ are the only ways to express $1$ as the sum of two elements of that field.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "abstract algebra"
}
|
Are the authenticated security rules applicable for Firebase Anonymous sign-in?
I am trying to develop an app where I do not want my users to sign-in by their avatar names and not any account such as Google or Facebook with proper security. Is it really possible? I mean, are all the security rules applicable for those who have signed in anonymously?
|
> Are the authenticated security rules applicable for Firebase Anonymous sign-in?
Of course, they are. According to the official documentation regarding Firebase Anonymous Authentication:
> You can use Firebase Authentication to create and use temporary anonymous accounts to authenticate with Firebase. These temporary anonymous accounts can be used to allow users who haven't yet signed up to your app to work with **data protected by security rules**.
And to answer your last question:
> I mean, are all the security rules apply for those who have signed in anonymously?
Yes, the security rules are applicable for an anonymous account, in the same manner, are applicable for an account that is created with a provider such as Google, Facebook, and so on.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "android, firebase, firebase authentication"
}
|
Elementary method to solve this equation
I have to describe ''the sign of the root(s)''$$\sqrt[3]{3+\sqrt{x}}+\sqrt[3]{3-x}-\sqrt[3]{6}=0$$ for k-11 students , who did not learned derivation. I can solve the equation by taking $f(x)=\sqrt[3]{3+\sqrt{x}}+\sqrt[3]{3-x}-\sqrt[3]{6}$ also by graphing <
but , is there a simple trick to show the sign of roots(s) .
Remark:by derivation or graphing we can see 1 positive root exists .
thanks in advance.
|
Since $$a^3+b^3+c^3-3abc=(a+b+c)(a^2+b^2+c^2-ab-ac-bc)$$ and since $$3+\sqrt{x}=3-x=-6$$ is impossible, our equation is equivalent to $$3+\sqrt{x}+3-x-6+3\sqrt[3]{6(3+\sqrt{x})(3-x)}=0$$ or $$(\sqrt{x}-x)^3+162(3+\sqrt{x})(3-x)=0,$$ which after substitution $\sqrt{x}=t$ gives $$t^6-3t^5+3t^4+161t^3+486t^2-486t-1458=0$$ and the last equation has unique non-negative root $t_1=1.731...$
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 2,
"tags": "calculus, algebra precalculus, polynomials, radicals, radical equations"
}
|
Do new versions of OWA have an equivalent to the About page of OWA in Exchange 2010
Using the Exchange 2010 version of Outlook Web App (OWA) you could click the (?) button and then click About to get a really useful page containing information about the Mailbox server, Proxy server, Client Access server, etc.
Is there an equivalent with the 2016/2019 version of Outlook on the web?
The page is really helpful when doing migrations from Exchange 2010 to a newer version since you can see if the OWA is being proxied as well as where the mailbox resides.
|
> Is there an equivalent with the 2016/2019 version of Outlook on the web?
Yep. Normally, we couldn't see the feature `About` from OWA 2016/2019. To realize it, you could switch your OWA version to the light one:
 >= 0 && document.cookie.search('myCookie') < 0){
var productvalue = document.querySelector('input[name=product]:checked').value;
var amount = document.getElementById("frm-amount");
var amountValue = amount.options[amount.selectedIndex].value;
var term = document.getElementById("frm-term");
var termValue = term.options[term.selectedIndex].value;
|
You need to add the **event listeners**.
For the _select box_ , you need to add the `change` event listeners and for the input fields, you could go with `keyup` (or again, `change`).
Also, you need to provide a bit more of your HTML code for a more refined solution.
But, I hope that gives a brief idea.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "javascript, forms, if statement"
}
|
Team System 2008 comnnand unable to find workspace
I am trying to rename a folder in Team System 2008 Source Control to remove a space character:
tf rename "$/Common Controls" $/CommonControls
but I get the error 'unable to determine the workspace'. There doesn't seem to be a way of specifying the workspace. I get the same error if I try to move a folder using the same approach.
What am I doing wrong (or not doing)?
|
You need to get the files locally to do the move or rename. It is not possible to do this server side only.
Create a local workspace, get all the files, then perform the rename within the context of the workspace.
NOTE: You cant rename a root folder. This is linked to the Team Project and neither can be renamed.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "tfs"
}
|
Can I lay stepping stones over a french drain?
I am planning to install a french drain around my garage and make a walkway on top of it. I know the overall procedure for the french drain installation but am not sure how to make a walkway over it. I am thinking of putting stepping stones (e.g., flagstones) over the gravels which would surround the drainage pipes. But, I am concerned as to whether the stepping stones could be firmly stabilized on the gravels. I could not find any article over the web on this issue.
|
Admittedly guesswork, but...
I would expect that, over time, the flagstones would settle into the gravel and mostly stabilize themselves (outside of frost heave and similar issues). There still could be tripping hazards, though, just as there can be with bricks after frost heave and tree roots lift them...
Note that the french drain doesn't have to be exposed through the full 360-degree circuit of the house. If there's a short section where you have a walkway, that probably won't make much practical difference, as long as the whole thing is able to drain properly.
|
stackexchange-diy
|
{
"answer_score": 1,
"question_score": 2,
"tags": "french drain"
}
|
Can two html elements have the same id but in different classes?
I was writing a javascript for an existing application in which there are two forms with separate **id** s, and in each form there is a `div` which has the id `"validationSummary"`. But these `div`s belong to different classes. So my question is can this be possible? Please anyone can explain me is this correct ?
These are the `div`s:
<form id="foo" .....>
<div class="notice_bar validation-summary-errors error_message" id="validationSummary"></div>
</form>
<form id="bar" .....>
<div class="validation-summary-valid notice_bar affirmative_message" id="validationSummary"></div>
</form>
and also the class `notice_bar` is common leading to other confusion!
|
Possible? Yes. Good coding? No.
From w3.org:
> ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 4,
"tags": "html, dom, web frontend"
}
|
Python: How to differentiate categorical values while plotting a scatter plot?
I have a `dataframe` that looks like this:
ContextID EscAct_Curr_A Outlier?
7289972 0.5622317497295798 True
7289973 0.5622317497295798 True
7289998 0.5793991301212501 False
7289999 0.5793991301212501 False
7290024 0.5665235864470339 False
7290025 0.5665235864470339 False
What I would like to do is to plot a `scatter plot` wherein the `ContextID` is in the x-axis and the `EscAct_Curr_A` is on the y-axis and based on the `Outlier?` column. All those True must be of one colour and all those False must be of some other different colour.
|
import pandas as pd
import matplotlib.pyplot as plt
d = {'ContextID': [7289972, 7289973, 7289998], 'EscAct_Curr_A': [0.5622317497295798, 0.5622317497295798, 0.5793991301212501], 'Outlier': [True, True, False]}
df = pd.DataFrame(d)
plt.scatter(df.ContextID, df.EscAct_Curr_A, c=df.Outlier)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, matplotlib"
}
|
Do all representations of finite groups have one-dimensional subrepresentations?
Let V be a representation of a finite group G, and $v\in V$ - a nonzero vector. Put $$u = \sum_{g\in G} gv.$$ Then for any $g\in G$ we have $gu = u$ and therefore $<u>$ is a subrepresentation of V.
I know there is an error here since there are irreducible representations of finite groups which are not one dimensional, but I can't see it. Could someone point it out?
Thank you.
|
It is possible that $u$ is zero.
|
stackexchange-math
|
{
"answer_score": 13,
"question_score": 12,
"tags": "representation theory, finite groups"
}
|
Modify a shortcut like CTRL+F in react
How do I recreate **ctrl + f** shortcut key in my website using react? I want to use any shortcut to trigger a filter function?
|
This code may help you.
window.addEventListener("keydown",function (e) {
if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
e.preventDefault();
// trigger your filters here
}
})
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "javascript, reactjs"
}
|
How is it possible to keep Rust module documentation in separate Markdown files?
This section of the Rust book seems to imply that it is possible to keep Rust documentation in separate .md files, but it does not say how these .md files can then be included back. How does this work?
|
It doesn't. That section on describing the functionality of `rustdoc` is saying that it can process individual `.md` files. The third paragraph touches on this:
> Documentation can be generated in two ways: from source code, and from standalone Markdown files.
Insofar as I am aware, there is no extant way to put code documentation in external files. It would be theoretically possible to do so using a procedural derive macro, but I'm not aware of any crate that actually does this.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 4,
"tags": "rust, documentation, rustdoc"
}
|
Pentaho User Console(PUC) parameter error
When I publish the prpt file in Pentaho User Console(PUC), I am getting error in parameter field when I select parameter values. after select the value from drop down the value is disappear.
(I have attached image)
!Check the red color box error.
I have selected those values in prpt(Check the image)!Selected values in PRD
but its working fine in Pentaho Report designer(PRD). What is the solution?
|
Try unchecking the " **validate values** ". It will work :)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "pentaho"
}
|
Capture High Resolution Screen Shot for Unity Game
I'm working on a mobile game. We need some HD screen shot to use in our **press kit**. I'd like to know, how do we capture HD screen shot of games inside **unity's editor**. Resolution **must support printing quality of banners** that we would use to showcase our game in local game expo.
|
According to this post on Unity Answers there are/were some issues with huge screenshots.
But they suggest using this (FREE) asset (Instant Screenshot) from the asset store. Give it a try and let us know if that works for you (and which resolution you created with).
|
stackexchange-gamedev
|
{
"answer_score": 1,
"question_score": 1,
"tags": "unity, marketing, screenshot"
}
|
iPhone/Objective C: How can I get the UIButton instance from NIB
I placed 1 UIButton on nib, and when user click this button,an IBAction method connect to it with a _Status_ param.
What I want is, user click button and pass the Status to the IBAction method, and in that method, I need access the instance of the button.
How can I get the button's instance without an (id) sender here?
|
You can wire up the UIButton with an outlet like you did with your IBAction to connect it.
In your header add:
UIButton *myButton;
...
@property (nonatomic, retain) IBOutlet UIButton *myButton;
And then link the new outlet with your button in IB.
Then you can access the button with myButton in your instance.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "iphone, objective c, uibutton"
}
|
No internet on multiple computers
At the time, I am working as a sysadmin in a local school. In a specific classroom I have 28 Windows 10 workstations. All of them are connected to the internet via wireless through a single router. 4 out of all the computers refuse to connect to the internet. What could be the issue ?
|
I would check if they 1.) are connected via the right SSID, 2.) Are they getting IP addresses via DHCP. (Windows command prompt, the command ipconfig) If they do have IP's, can they ping the other computers, can they ping the router. After all that are they using the right DNS.
|
stackexchange-serverfault
|
{
"answer_score": 3,
"question_score": -3,
"tags": "networking, wifi, windows 10"
}
|
String macro with trailing backslash \
Is it possible to pass a single trailing `\` character to a string macro?
macro test_str(s)
s
end
test"\\" # results in \\, that is two backslashes
test"\" # does not parse ... the " is treated as escaped
|
It is a work around, but you could invoke the macro directly -- as a macro rather than as a string macro
`@test_str("\\")` works fine.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "macros, julia"
}
|
Threadlock Permatex 24200 vs 24209
I am preparing myself to safety my car. And one of the important components when dealing with wheels and brakes is thread-locks. I decided to go the Permatex brand, thought anyone should just work fine.
I am wondering on what would be the difference between these two products:
* Permatex 24200 Medium Strength Threadlocker Blue, 6 ml
* Permatex 24209 Blue Medium Strength 242 Threadlocker, 6ml
From the image the `Permatex 24209` also says `24200` on the corner. So, for me it is really confusing about the differences.
* * *
I already did some research on this topic. Here are some useful links I found.
* The Ultimate Threadlocker Competition--Which is the Best? from which I got the following comparison results.
 [NC]
RewriteRule ^/?$ "https\:\/\/example\.com\/home" [R=302,L]
# REDIRECT MOBILE
RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{HTTP_HOST} ^example\.com\/home$ [OR]
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC,OR]
RewriteCond %{HTTP:Profile} !^$
RewriteRule ^/?$ "https\:\/\/example\.com\/mobile" [R=302,L]
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": ".htaccess"
}
|
What is a word for difficult to shelf?
I'm trying to express that a certain item's geometric design makes it difficult to shelf, which is why it is often hanged instead. But it is not however "unshelfable".
How can I say "difficult to" in this context? E.g.
> As seen in this copy, the cover was usually perforated to be nailed or hanged to a wall due to its unique design, which made it difficult to shelf.
* * *
EDIT
_**Shelve**_
: to place on a shelf; shelve books
Merriam Webster
|
How about recasting the sentence thus instead?
> As seen..., the unique design of the cover renders it **unconducive** to shelving.
Lexico defines **unconducive** as:
_(usually unconducive to)_
> Making a certain situation or outcome unlikely or impossible.
|
stackexchange-english
|
{
"answer_score": -1,
"question_score": 0,
"tags": "single word requests"
}
|
Python pandas dataframe ValueError: Trying to store a string with len
I have a dict of objects.
data = [{'a': 'qwerty', 'b': 123}]
I create a dataframe:
df = pd.DataFrame(data)
now I want to persist it:
df.to_hdf(filename, 'book', table=True, mode='a', append=True)
now I want to persist another batch of data that slightly longer in size:
data = [{'a': 'qwerty2', 'b': 123}]
df = pd.DataFrame(data)
df.to_hdf(filename, 'book', table=True, mode='a', append=True)
it fails with error:
ValueError: Trying to store a string with len [7] in [values_block_2] column but
this column has a limit of [6]!
Consider using min_itemsize to preset the sizes on these columns
It basically works when only when I keep the size of column the same size but if it is different I am getting the error above. How do I make pandas to work with any size of the string?
|
Finally I found an answer to my own question. Problem is that when I was doing my first `to_hdf` batch it automatically creates a schema based on data provided in array, however if next batch of rows contains data that exceed limit for this column size what has been created in the first batch then it will crash with error: `ValueError: Trying to store a string with len`
So solution is to add `min_itemsize` argument to `to_hdf`:
df.to_hdf(filename, 'book', table=True, mode='a', append=True, min_itemsize={'a': 7})
In other words you can treat hdf as simple SQL table where you need to predefine size for each String column.
Alternatively, you need to write data into a new file.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 3,
"tags": "python, pandas, dataframe"
}
|
Printing jenkins credentials Id
Does anyone know how I can print credentials stored in jenkins? Below script throws:
Unexpected exception caught! groovy.lang.MissingPropertyException: No such property: crd for class: com.test.File
Here is my code:
service.groovy
withCredentials([usernamePassword(
credentialsId: vaultCredentialId, usernameVariable: 'ID', passwordVariable: 'CRED')]){
sh """
crd=${CRED}
for chars in `echo $crd | fold -w1`; do echo "value: $chars" ; done
"""
|
'withCredentials' step will mask any output matching it secrets so If you want to display them you have to do it outside the step.
pipeline {
agent {
label "master"
}
stages {
stage("run") {
steps {
script {
userVar = null
passVar = null
withCredentials([usernamePassword(credentialsId: 'administrator-jenkins', passwordVariable: 'password', usernameVariable: 'username')]) {
userVar = username
passVar = password
}
echo "Username: ${userVar}"
echo "Password: ${passVar}"
}
}
}
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "jenkins pipeline, sh"
}
|
Matching a border of a russian word with \b
Is this a bug or am I doing something wrong (when trying to match Russian swear words in a multiplayer game chat log) on CentOS 6.5 with the stock perl 5.10.1?
# echo блядь | perl -ne 'print if /\bбля/'
# echo блядь | perl -ne 'print if /бля/'
блядь
# echo $LANG
en_US.UTF-8
Why doesn't the first command print anything?
|
You have to tell Perl that the source code contains UTF-8 (`use utf8`), and that the input (`-CI`) and output (`-CO`) are UTF-8 encoded:
echo 'помёт' | perl -CIO -ne 'use utf8; print if /\bпомё/'
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "regex, perl, centos6.5, perl5.10"
}
|
Firebase Cloud Messaging Unsubscribe from all topics
I have a simple news app for my college. To send notifications, I use firebase cloud messaging
My problem: I want to send notifications based on the version of my app from the API. when my app version is 2. I will send a notification to the topic v2. but when users update the app to v3 and I need to maintain v2 of my app then how can I target v3 only
|
You can use a `condition` to send to folks who have only subscribed to v2 and not v3.
condition: "'v2' in topics && !'v3' in topics"
Note that this allows up to 5 clauses only, so I'd recommend also updating the logic in your app to remove subscriptions to older versions. You don't even need to do this conditionally, so it can be as simple as:
Firebase.messaging.subscribeToTopic("v3");
Firebase.messaging.unsubscribeFromTopic("v2");
Firebase.messaging.unsubscribeFromTopic("v1");
If the user is not/no longer subscribed to a topic, calling `unsubscribeFromTopic` doesn't do anything (but doesn't fail).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, firebase, firebase cloud messaging"
}
|
Convert format full name pattern String
I have a String "adam levine". How to convert first letter of every word to uppercase like this "Adam Levine"?
String line = "adam levine";
line = line.substring(0, 1).toUpperCase() + line.substring(1);
System.out.println(line); // Adam levine
|
private static final Pattern bound = Pattern.compile("\\b(\\w)");
public static String titleize(final String input) {
StringBuffer sb = new StringBuffer(input.length());
Matcher mat = bound.matcher(input);
while (mat.find()) {
mat.appendReplacement(sb, mat.group().toUpperCase());
}
mat.appendTail(sb);
return sb.toString();
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "java, string, pattern matching"
}
|
Converting TFS source code to GIT. Is .tpattributes syntax equal to .gitattributes syntax?
I am converting my source code from TFS to Git and I want to convert any `.tpattributes` files into `.gitattributes` files.
It appears the pattern syntax is the same for both files, so I am wondering if it as simple as renaming my `.tpattributes` files to `.gitattributes` files?
Or will more need to be done to ensure the syntax is compatible with Git?
|
You can _start_ by renamming the `.tpattributes` files, but, do check (with a git status before and after) that it does not ignore too much.
As mentioned in this answer
> `.tpattributes` are not recursive. (In fact, they cannot be, since you can have advanced workspace mappings.)
> You will need a `.tpattributes` in each folder.
However, a `.gitignore` applies to the current folder, and all folders below.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "git, tfs, gitattributes"
}
|
How to uninstall iOS 5.0 Simulator from Xcode 4.5
I've installed Xcode 4.5, and since I write apps for fun, I don't intend to support older iOS versions, and to save space on a 500 GB iMac, is there anyway to delete it?
|
Тry to delete iPhone/iPhoneSimulators from supported platforms in Xcode package: /Applications/Xcode.app/Contents/Developer/Platforms
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "ios, xcode, simulator"
}
|
Proxy To Backend Service
I need to proxy an api request of the form `api.myserver.com/service/v1/pricing` to the right backend service.
I configured nginx in this way:
location /service/v1 {
proxy_pass
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_ssl_protocols TLSv1.2 TLSv1.1 TLSv1;
proxy_ssl_server_name on;
proxy_http_version 1.1;
proxy_set_header Connection "";
}
upstream service-v1-pool {
least_conn;
keepalive 32;
server 192.168.1.10:8000;
}
And I setup a basic server at that private address.
The problem is that if I make a request to `api.myserver.com/service/v1/pricing`, the server sees a request `GET //pricing` which fires a `404 Not Found`. The right request should be `GET /pricing`. Thre is something I'm missing in NGINX? Regards
|
You've missed the part about URI transformation
<
> A request URI is passed to the server as follows:
>
> * If the proxy_pass directive is specified with a URI, then when a request is passed to the server, **the part** of a normalized request URI **matching the location is replaced** by a URI specified in the directive
>
In you case URI is `/service/v1/pricing`, matching part is `/service/v1` and it's replaced with `/` thus you've got `//pricing`.
Just add a trailing slash to `location` and you'll get it right.
location /service/v1/ {
proxy_pass
...
}
|
stackexchange-serverfault
|
{
"answer_score": 0,
"question_score": 0,
"tags": "nginx, reverse proxy"
}
|
Orbitals and electron jumping
Bohr model (tries to) explain how electron goes to higher state(orbit) from lower state(orbit) on photon absorption.But in quantum mechanics, we have orbitals which can at most accommodate 2electrons.
Let's consider an electron that has absorbed a photon sufficient to make it jump from Orbital 1 to Orbital 2.If the Orbital 2 is already filled with 2 electrons where will the excited electron go?
|
If the excited electrons can't be stimulated, then the photon simply won't interact with the lower-level electron as the electron's transition is forbidden.
|
stackexchange-physics
|
{
"answer_score": 2,
"question_score": 2,
"tags": "quantum mechanics, electrons, atomic physics, orbitals"
}
|
downloading mulitple images from a website and saving them in sqlite
I am working on a app where I would like to download images from a website and then save those images into a sqlite database. I tried already to find some good tutorials and the only thing that came close to what I would like to do, is a article by Tim Bray.
<
The code is really nice however it does not account for saving each single image. Bitmap unfortunatley (as far as I understand) does not distinguish between each image.
I would like to ask if anybody could give me some pointers or even better has source code for such a problem.
|
If you want to store images into a database you can store them as a BLOB-value. Take a look here for that part: <
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "java, android, sqlite, bitmap, inputstream"
}
|
Detect tap in page?
I have a `PhoneApplicationPage` with some grids, images and a few buttons. If I tap outside my buttons, anywhere in the page (on an image, grid or whatever), I want to open a new page.
How can I detect a tap/click anywhere on the page?
|
I see at least two ways to do that:
1. Listen to the `MouseLeftButtonUp` event on your `PhoneApplicationPage`. It should be triggered by images and labels but not by buttons
2. Listen to the `Tap` event on your `PhoneApplicationPage`. However, this event will be triggered even when the user tap on a button. To prevent this, you can retrieve the list of controls at the tap coordinates in the event handler, and open the new page only if there's no button:
private void PhoneApplicationPage_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
var element = (UIElement)sender;
var controls = VisualTreeHelper.FindElementsInHostCoordinates(e.GetPosition(element), element);
if(controls.OfType<Button>().Any())
{
return;
}
// Open the new page
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "windows phone 8"
}
|
Copying a specific file from one path to another
hello everyone im trying to create this tweak that copies a file from one spot to another everytime a specific app opens. Would this be correct to use. im still really new to this, but trying, what command should be placed to have this run everytime the app opens.
- (BOOL)fileManager:(NSFileManager *)fileManager
shouldCopyItemAtPath:(NSString *)srcPath *path/to/where/file/is
toPath:(NSString *)dstPath *where/i/want/it/copied/to
|
If you want this to run every time the app opens then you can call it from application:didFinishLaunchingWithOptions: in your app delegate.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "objective c, ios, copy, cydia, tweak"
}
|
Bootstrap 3 container change in IE9?
i have created an template for joomla with the bootstrap 3. my website is only local at the moment. it works all perfect in ff and chrome. but when i have a look at my website in IE (9) it seems like the container changed to fluid. the full website looks horrible. Have anybody the same problem?
Dont know what i have to copy from my code, that help to find a solution?
|
Your browser is likely rendering the page using ie7 standards, to change this you can goto settings > F12 developer options and change the document mode to ie9.
You can stop IE from doing this by going to Tools > Compatibility View Settings and disable the checkbox 'Display intranet sites in compatability view'
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "html, css, internet explorer, twitter bootstrap"
}
|
iBook Image Curl Animation on iOS
I am working on `iPhone` app where i have 5-6 set of images. I want to change the image using page curl animation like `iBook` where user can swipe the page as per the finger move with page curl animation. I want to implement same animation on iPhone.. Is there any way to do without using the private libraries or `UIPageViewController` or if there is any sample available to achieve this?
Apart from google search I am getting some kind of libaries such as:
Leaves
paperstack
XBPagecurl
pagecurling
Did not get much help.
|
Please, do not go for exact solution, above solution will give you some idea and you can work on that and extent it. This way you learn more, the more you play. I have suggesting the blog please, go through it explore it.
Turn a page like a Book with UIView?
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ios, iphone, xcode, animation, page curl"
}
|
Why would one need to use lodash/fp/constant?
Why would one need to use `.constant(value)` from `lodash/fp/constant`? I saw some other guys use `_.constant(true)` or `_.constant(1)` but don't really know what is the benefit of it.
From what I know `.constant(value)` return a function that returns the given `value`. I know it has something to do with functional programming, but why don't just use `const VALUE = 1;` instead?
|
From <
// api: object.position = function(time) { return coords }
circle.position = _.constant( [10, 10] )
// api: image.fill( function(x, y) { return color })
image.fill( _.constant( black ) );
> So, mainly for passing constants to APIs that expect functions. Nice.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 4,
"tags": "javascript, functional programming, lodash"
}
|
Find duplicate object by property and Merge using Javascript or UnderscoreJS
I have an array as mentioned below:
var somevalue = [{
code: 1,
name: 'a1'
}, {
code: 2,
name: 'b1'
}, {
code: 1,
name: 'a2'
},
{
code: 1,
name: 'a3'
},
{
code: 2,
name: 'b2'
}
]
From this array, I want to find duplicate element by `code` and merge all elements of the same code into one. So the final output would be:
var somevalue = [{
code: 1,
name: 'a1, a2'
}, {
code: 2,
name: 'b1, b2, b3'
}
]
is there any way to achieve this using `underscoreJS` ?
I can do this by `for-loop`. But In real scenario, its very large array containing JSON object of having 10 properties. So I need some performance oriented solution.
|
You can use array.reduce:
var datas = [{
code: 1,
name: 'a1'
}, {
code: 2,
name: 'b1'
}, {
code: 1,
name: 'a2'
},
{
code: 1,
name: 'a3'
},
{
code: 2,
name: 'b2'
}
];
datas = datas.reduce((m, o) => {
const found = m.find(e => e.code === o.code);
found ? found.name += `, ${o.name}` : m.push(o);
return m;
}, []);
console.log(datas);
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "javascript, arrays, underscore.js"
}
|
how to get the bluetooth address of my own device in Flutter?
There are many packages in Flutter dealing with things related to Bluetooth but none of them enables me to see the Bluetooth address of my own device, does anyone know to do that? thank you in advance?
|
Most mobile operating systems rate the use of BD_ADDR, from the application level, as bad behavior (many applications used this ID to track the user). That is why modern mobile operating systems prevent you from doing this.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "android, flutter, bluetooth, android bluetooth, mobile development"
}
|
Can't boot into ubuntu server 16.04 after successful installation
I've installed 16.04 on Dell R710 server on RAID6. Boot mode is set to UEFI in BIOS.
After successful installation it stays in `grub>` console.
Output to `ls` command is
(hd0) (hd1) (hd1,apple2) (hd1,apple1) (hd1,msdos2) (cd0)
* `hd0` is my RAID6 disk
* `hd1` is the USB stick which I install Ubuntu 16.04 from
Using the rescure option in USB stick I've accessed a `/bin/sh` terminal and checked with `fdisk -l` to make sure it contains `grub.cfg` and its content is as expected
search.fs_uuid b53fe0e6-485e-4278-a604-d309960bc542 root hd0,gpt2
set prefix=($root)'/boot/grub'
configfile $prefix/grub.cfg
In `grub>` console I tried typing first line of above and it says
error: failure reading sector 0x0 from 'cd0'
error: failure reading sector 0x0 from 'cd0'.
error: no such device: b53fe0e6-485e-4278-a604-d309960bc542
|
My RAID6 ends up 3.6TB. I've made a RAID1 drive with 600GB. Then it installs fine. Not sure its the BIOS or GRUB issue. Hope it helps someone with same issue.
|
stackexchange-serverfault
|
{
"answer_score": 0,
"question_score": 1,
"tags": "ubuntu 16.04, grub"
}
|
How to avoid sign extension with AutoIT BitShift()?
While trying to port an algorithm from C, I have determined that the AutoIT BitShift( ) function does sign extension if the high bit of a 32-bit field is set.
ConsoleWrite("Bit shift test: (0x80112233 >> 4)=" & hex(BitShift(0x80112233,4)) & @CRLF) ;### Debug Console
ConsoleWrite("Bit shift test: (0x60112233 >> 4)=" & hex(BitShift(0x60112233,4)) & @CRLF) ;### Debug Console
Bit shift test: (0x80112233 >> 4)=F8011223
Bit shift test: (0x60112233 >> 4)=06011223
See how the first test adds an 'F' to the front.
I think I'm straying outside the normal operations of AutoIT (not a lot of documentation on BitShift and BitRotate, and I don't see anybody else that ran into this problem), but I'm hoping somebody has an easy fix for this.
I'm using 3.6.6 of SciTe, if that matters.
|
I don't consider current BitShift() working wrong. Official documentation says this:
> Bit operations are performed as 32-bit integers.
Since it doesn't say "as **unsigned** 32-bit integers", sign extension seems quite OK.
However, I don't see you point. If you know desired behavior, why not implementing custom function to fit your needs? Here is my variant:
Func BitShiftUnsigned($value, $shift)
If $shift > 0 Then
Return BitAnd(BitShift($value,$shift), BitShift(0x7fffffff, $shift-1))
Else
Return BitShift($value,$shift)
EndIf
EndFunc
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "autoit"
}
|
Django - serving and managing permissions for static content
I have certain documents that I want to limit access to through Django to authorized users with permissions only.
If I'm going to use Django as a _proxy_ to serve static files in a view, what are the implications? I'm used to serving static files in Apache and configuring that my media is served without any handlers, but what happens if someone starts downloading 500mb through my Django proxy? Will my Django thread be locked for that user until he recieves the 500mb response?
|
See the answers to this question to learn how to tell the web server to handle serving the file.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 8,
"tags": "django, static, media"
}
|
In Silverlight, is it possible to honor the ToString() method of a domain object returned from a service call?
In our domain, we override the ToString method on all our domain types.
However, when returning those domain objects in response to a Silverlight service request, the functionality of ToString is lost. ToString() just returns the namespace description of the object as it is imported from the service. My guess is that the domain proxy created by the service reference doesn't include the ToString logic.
Is it possible to get this to work without having to re-implement ToString on the Silverlight client?
**Update:** BTW, this is so I can bind to the whole object and have the string description honored. I have a collection of domain objects coming back from a service. I would like to set the ItemsSource of a UI collection to a list of these domain objects and not have to re-create the ToString logic locally.
|
The proxy doesn't generate a member part for the contract for the ToString() method, because ToString() isn't part of the ServiceContract. Not just that though, I'm not confident that the proxy classes that are generated, intelligently override Object.ToString() when they are created. Could you not add a descriptive method, something like GetDescription() which will be created in the proxy?
If not, could you not just override the method in the proxy (it should be generated as a partial) and provide a client-specific implementation?
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, web services, data binding, silverlight 4.0, tostring"
}
|
Have this code so when a user presses the up or down key the balloon grows or shrinks. Need balloon to burst to "" when it reaches font size over 70
So far the balloon should only be able to reach max 70 font before it bursts. I need to turn the balloon into "". The event listener needs to be removed when the balloon bursts.
let para = document.querySelector('p');
para.style.fontSize = '24px';
window.addEventListener("keydown", e => {
var sizeAsInteger = parseInt(para.style.fontSize, 10);
if (e.key == "ArrowUp") {
sizeAsInteger += 10;
} else {
sizeAsInteger -= 10;
}
para.style.fontSize = sizeAsInteger + 'px';
});
p {
font-size: 50px;
}
<body>
<p></p>
</body>
|
Is this what you want?
let para = document.querySelector("p");
para.style.fontSize = "24px";
const increaseSize = e => {
var sizeAsInteger = parseInt(para.style.fontSize, 10);
if (sizeAsInteger >= 70) {
window.removeEventListener("keydown", increaseSize);
return (para.innerHTML = "");
}
if (e.key == "ArrowUp") {
sizeAsInteger += 10;
} else {
sizeAsInteger -= 10;
}
para.style.fontSize = sizeAsInteger + "px";
};
window.addEventListener("keydown", increaseSize);
p {
font-size: 50px;
}
<p></p>
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -1,
"tags": "javascript, html"
}
|
how to form select query by range
hello i have a search engine for my site. i have two selection fields. i would like to give an example:
input_a: 3 input_b: 5
so the queries should look like:
if ( ($input_a == true) && ($input_b == false) ){
$filter_orders[] = " `col` LIKE '%$input_a%' ";
}
if ( ($input_a == false) && ($input_b == true) ){
$filter_orders[] = " `col` LIKE '%$input_b%' ";
}
if ( ($input_a == true) && ($input_b == true) ){
$filter_orders[] = " `col`= `col`>='%$input_a%' AND `col` = `col`<='%$input_b%' ";
now the problem is, that i dont know, if the last query is incorrect or not. the logic behind that will be that in case of my example the range between 3 and 5 should be found.
so 1,2 `[3,4,5]` 6,7,8...
if there is someone who could help me out i really would appreciate.
thanks a lot.
|
**NO,** sadly that is everything but correct. It should be something like this.
$filter_orders[] = " `col`>='%$input_a%' AND `col`<='%$input_b%' ";
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, mysql, variables, range"
}
|
How to let ogr/gdal CreateLayer() create a `geom` field instead of `wkb_geometry`?
When creating a new table (PostGIS) using OGR/GDAL (2.1+), is there a way to select a specific name for the geometry field (such as `geom`), rather than using the default name?
I created a new table via python3 ogr/grdal liek this:
ds = gdal.OpenEx(connection_string, gdal.OF_VECTOR | gdal.OF_UPDATE)
lyr = ds.CreateLayer( "mylayer", XXX, ogr.wkbLineString)
The problem is that I can't find a parameter to specify the name of the geometry field, only its type. In the table created, the geometry field seems to be called `wkb_geometry` by default:
wkb_geometry geometry(LineString,26945)
Is there a parameter or option to let `CreateLayer()` use a different name such as `geom`?
Related question: Use Postgis to convert wkb_geometry data type to geom datatype
|
As you can see from < CreateLayer support also "options" which are "None" by default.
> The papszOptions argument can be used to control driver specific creation options. These options are normally documented in the format specific documentation.
Usage example for PostgeSQL and Python can be found from the GDAL autotest script <
See for example row 5191:
lyr = gdaltest.pg_ds.CreateLayer('ogr_pg_82', geom_type = ogr.wkbNone, options = ['GEOMETRY_NAME=another_name'])
|
stackexchange-gis
|
{
"answer_score": 5,
"question_score": 6,
"tags": "ogr, python 3, gdal python binding"
}
|
How many subsets of $\{1,2...,n\}$ there are such that if $2$ exists in the set then $1$ isn't
> How many subsets of $\\{1,2...,n\\}$ there are such that if $2$ exists in the set then $1$ isn't?
I think the approach is a recursive formula:
Let $b_n$ be the sequence:
If $2$ is in the set then there are $n-1$ options so $b_{n-1}$
If $2$ isn't in the set then either $1$ is in the set, then there are $n-1$ options so $b_{n-1}$ or, $1$ isn't in the set as well so there are $n-2$ options so $b_{n-2}$.
So the formula is: $b_n=2b_{n-1}+b_{n-2}$ and that I already know how to solve.
Is this right? Is there another way?
|
A set of size $n$ has $2^n$ subsets. If $2$ is in the set then $1$ is not in the set means. $2$ is not in the set or $1$ is not in the set (using $A\rightarrow B$ means $\neg A\vee B$.) To turn this into exclusive cases:
1) $2$ is not in the set or (exclusively) 2) $2$ is in the set, but $1$ is not in the set.
Since these two options are exclusive, we can count he number of sets that satisfy either property
1) If $2$ is not in the set, you're talking about subsets of $\\{1,3,4,\cdots,n\\}$. Since this set has $n-1$ elements, there are $2^{n-1}$ such subsets.
2) If $2$ is in the set, but $1$ is not, you're talking about subsets of $\\{3,\cdots,n\\}$ union with $\\{2\\}$. This results in $2^{n-2}$ sets that have $2$, but not $1$.
Therefore, in total, there are $3\cdot 2^{n-2}$ sets that satisfy the conditions.
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 1,
"tags": "combinatorics, discrete mathematics"
}
|
Turning on verbose logging
Is the "Verbose logging" in Drupal actually the PHP errors that can be activated in various ways (.htaccess, php.ini, settings.php) to be seen on screen?
Is it `drush ws --full` ?
From the material I've seen I can't say for sure if there is a unique definition for this concept in Drupal.
I would thank an experienced Drupal programmer to give the final word on this.
|
Navigate to admin/config/development/logging and set "All messages, with backtrace information".
|
stackexchange-drupal
|
{
"answer_score": 4,
"question_score": 3,
"tags": "8, debugging"
}
|
What is a concise synonym for "height above the ground"?
I am writing a paper and need to mention the height that a person lifted their foot above the ground multiple times. I feel like writing "height above the ground" every time is a bit "wasteful" and am looking for a more concise alternative.
A sample sentence:
> The participants foot ___ was 10 cm higher than in the control group.
Right now I abbreviate to just "height", but I feel like this loses a bit of clarity ... especially if I talk about "foot height" which sounds more like the "size of the foot" to me.
Others use "elevation", but to my supervisor this sounds more like "elevation of land".
Are there any other alternatives (that I, as a non-native speaker am not aware of)?
|
_Height_ would be the best choice from an aviation context. In that domain, _altitude_ refers to your distance above sea level, while _elevation_ refers to the terrain's distance above sea level. _Height_ refers to exactly what you want, which is the distance from you to the ground. This should be sufficiently clear so long as you're not also trying to describe height/thickness of the foot itself in the same text.
|
stackexchange-english
|
{
"answer_score": 2,
"question_score": 1,
"tags": "single word requests, word usage"
}
|
Не получается добавить библиотеку с GitHub в android-проект

// ...
}
Выполнить Build > Make Project"
Вылезает такая ошибка: "could not get unknown property GROUP for object for type org.gradle.api.publication.maven.internal.deployer.DefaultGroovyMavenDeployer"
|
Вы тащите за собой оригинальный `build.gradle`, который пытается опубликовать артефакт на maven репозитории...
Надо просто написать:
dependencies {
...
implementation 'de.hdodenhof:circleimageview:2.2.0'
}
Тогда либа подтянется из репозитория maven
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "android, android studio, библиотеки"
}
|
How does Linux determine filename case on ISO 9660?
Here is a quote from this article:
> ISO 9660 is not a complex file system, but has a few quirks that are worth remembering. It seems that some operating systems also create non-compliant CDs, so beware! The main example of this is the character set that is available for file names. Strictly,filenames may only consist of uppercase letters A-Z, digits, dots, and underscores. Further there is a semicolon which separates the visible file name from its version number suffix. Many operating systems also allow lower case letters and other characters. Linux's VFS displays lower case filenames to the user despite the CD contents actually containing upper case characters.
So my question is, how does Linux know which letters are supposed to be uppercase and which letters are supposed to be lowercase, when on the CD they are all uppercase?
|
The ISO9660 filesystem has only supported filenames in the 8.3 uppercase format.
Some technologies have been designed over the years to extend the ISO9660 filesystem with features like long filenames, lowercase letters, and file permissions. The Joliet) filesystem is the Windows solution, while Rock Ridge is one that works with Linux. In essence they store the original filename, with proper case, in a lookup table that is recorded in the removable media. More information in the Wikipedia article for ISO9660.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "linux, vfs, iso9660"
}
|
how to iterate through an array of strings so that each value is matched with every other 1 once and only once
Say I have an string array with 5 elements, I want to loop through the array so that I have element [0] and element [1] through element [0] and element [4].
I then want to start at element[1] and do the same and again for every element but discarding any matching groupings.
e.g `arr[] {a,b,c,d,e}`
`(a-b),(a-c),(a-d),(a-e)`
then
`(b-c),(b,d),(b,e)`
then
`(c-d),),(c-e)`
then
`(d-e)`
Thanks
|
Something like this may work for you:
List<String[]> result = new ArrayList<>();
String[] arr = {"a", "b", "c", "d", "e"};
for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
result.add(new String[]{arr[i], arr[j]});
}
}
The "collect" part where you add a string array to the list (i.e. `result.add(...)`) can obviously be replaced with whatever you need for your code. The main thing here is that you find your "pair" using `arr[i]` and `arr[j]`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "java, loops"
}
|
Stuck on matrix exponential problem
I want to show that the property $e^{tA}e^{tB}=e^{t(A+B)}$ implies that $AB=BA$. Here $A,B$ denotes matrices and $t\in \mathbb{R}$.
Im stuck, have tried to expand both sides with their taylor series but not sure if this is the way to go.
Could anyone give me a hint?
|
Differentiate 2 times with respect to time $t$ the identity $$e^{tA}e^{tB}=e^{t(A+B)}$$ and then set $t=0$.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 1,
"tags": "matrices, ordinary differential equations, exponential function"
}
|
Why is this statement regarding red-black binary search trees true?
The Statement: _Suppose that some unsuccessful search in a red-black binary serach tree terminates after k key compares. Then, any unsuccessful search performs at least`ceiling(k/2)` key compares._
The explanation of why it is correct: _In the extreme case, the links alternate between red and black (starting with red) and the black height is`ceiling(k/2) - 1`. Any unsuccessful search traces a path from the root to a null link; there are exactly `ceiling(k/2) - 1` black links (not including the null link) along such a path. If the path contains no red links, then it contains `ceiling(k/2)` nodes (and makes `ceiling(k/2)` key compares)._
My opinion: unless k = 0 or 1, it is not possible that `k == ceiling(k/2)`. I begin to think maybe the issue is how I interpret the statement.
|
If _some_ unsuccessful search takes k compares, then _every_ unsuccessful search must take _at least_ ceil(k/2) compares.
That includes the one that takes k compares, since k is _at least_ ceil(k/2).
Note that "at least" means >=
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "algorithm, red black tree"
}
|
Installing libpuzzle windows wampserver
How do i install libpuzzle on a windows wampserver? The readme says this:
Here are the basic steps in order to install the extension:
(on OpenBSD: export AUTOMAKE_VERSION=1.9 ; export AUTOCONF_VERSION=2.61)
cd php/libpuzzle
phpize
./configure --with-libpuzzle
make clean
make
make install
If libpuzzle is installed in a non-standard location, use:
./configure --with-libpuzzle=/base/directory/for/libpuzzle
Then edit your php.ini file and add:
extension=libpuzzle.so
How do i do this on windows with wamp?
|
For windows i.e. wamp, you will have to find a download site that has compiled it for windows PHP.
Make sure its been compile with VC9/10/11 if you are using a recent version of WAMP or VC6 if you are using an old version of wamp.
Most likely you will have to download the source code and compile it yourself, a much more complicated process, as I cannot find anywhere to download a pre-built windows version of this library.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, windows, wamp, wampserver"
}
|
How to underline every line of text, to the end of a block
So, here's my question, I'm doing a newsletter for a customer, which will look like a postalcard.
I want my layout to look like writing on lines
Can anyone help me achieve what I'm trying to do? Putting my text in TD tags doesn't work since I don't know the length of each sentences.
Let me know if you need more info!
Thanks :)
|
in your lines that you need to underline add a style="border-bottom: 1px solid #000"(probably on your containing td)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "css, block, newsletter, underline"
}
|
Android Google Maps snippet auto update in InfoWindow
I'm using Google Maps in my app with few markers. Every few seconds I'm loading from API markers positions. Each marker has set title and snippet. In snippet I would like to display time when data was loaded.
Problem is that when user clicked on one of the markers and `InfoWindow` with title and snippet is visible then after that I change the snippet & the content but the content on visible `InfoWindow` is not changed - user has to click on the map to hide `InfoWindow` and click again on marker - then the content is correct.
Is it possible to refresh `InfoWindow` content after title or snippet has changed?
|
I found solution using Android Maps Extensions <
Call this after update markers data:
Marker m = map.getMarkerShowingInfoWindow();
if (m != null && !m.isCluster()) {
m.showInfoWindow();
}
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 5,
"tags": "android, google maps"
}
|
What's another way of writing this block without using do-end?
How would you write this on the same line or on consecutive lines without do-end?
map.resources :magazines do |magazine| magazine.resources :ads end
|
wouldn't using curly braces work?
map.resources :magazines {|magazine| magazine.resources :ads}
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "ruby"
}
|
Defining keyboard shortcuts from an argument in a function
I would like to write a command that defines key bindings for me, so that I can feed in key `y` (for example) and have it define key bindings for `M-y`, `C-y` etc.
I'm trying to `concat` the command argument into a string, but it gives me the error `Invalid modifier in string`.
(defun my/keypress-definer (keypress)
(interactive)
(concat "\C-" keypress))
(my/keypress-definer "a")
Is there any way to achieve this?
|
The `concat` function takes a list of SEQs and returns a string.
To get the string that describes your key sequence, you would simply write
(concat "C-" keypress)
Use the `kbd` function to return the actual key representation. I think you may end up with something like the following
(defun my/keypress-definer (keypress)
(define-key my-key-map
(kbd (concat "C-" keypress)) 'my/ctl-function)
(define-key my-key-map
(kbd (concat "M-" keypress)) 'my/meta-function))
Documentation:
- [Creating Strings][1]
- [Key Sequences][2]
[1]:
[2]:
|
stackexchange-emacs
|
{
"answer_score": 2,
"question_score": 1,
"tags": "key bindings, string"
}
|
Writing answers to trigonometric equation
I wonder how to write answers to trigonometric equations in more elegant form. For instance if we have $ \displaystyle \sin x = \frac{\sqrt{2}}{2} \vee \sin x=-\frac{\sqrt{2}}{2}$ then I write four cases instead of just one where $\displaystyle x=\frac{\pi}{4}+\frac{k\pi}{2}$
Can anyone explain how to obtain such forms ?
|
$$\sin x=-\frac{\sqrt2}2=-\frac1{\sqrt2}=\sin\left(-\frac\pi4\right)$$
$$\implies x=n\pi+(-1)^n\left(-\frac\pi4\right)$$ where $n$ is any integer
for $\displaystyle n=2m\implies x=2m\pi-\frac\pi4$
for $\displaystyle n=2m+1\implies x=(2m+1)\pi+\frac\pi4=2m\pi+\frac{5\pi}4$
Similarly, $\displaystyle\sin x=\frac{\sqrt2}2\implies $
for $\displaystyle n=2m\implies x=2m\pi+\frac\pi4$
for $\displaystyle n=2m+1\implies x=(2m+1)\pi-\frac\pi4=2m\pi+\frac{3\pi}4$
Observe that the values can be merged into $$n\cdot\frac\pi2+\frac\pi4$$ i.e., each of the four Quadrant has the offset $\dfrac\pi4$
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 2,
"tags": "trigonometry"
}
|
Using Perl Selenium::Remote::Driver for Javascript that loads page later
I'm trying to automate login into <
my $driver = Selenium::Remote::Driver->new;
$driver->get("
I'm able to successfully open the firefox browser and fetch the page. But the input elements aren't visible.
my $page_source = $driver->get_page_source();
$driver->find_element('emailLoginId')->send_keys("abcdefg");
The login section seems to be inside a separate class item,whose html source appears in the browser debugger,but when trying via selenium,the class item is empty. I only know basic Javascript/jQuery... kindly help me out,what is it that I'm missing
my $login_element = $driver->find_element_by_class('loginresponsive');
|
I tested this with Selenium::Chrome and it seems to work fine:
use strict;
use warnings;
use Selenium::Chrome;
# Enter your driver path here. See
# for download instructions
my $driver_path = '/home/hakon/chromedriver/chromedriver';
my $driver = Selenium::Chrome->new( binary => $driver_path );
$driver->get("
$driver->find_element_by_name('emailLoginId')->send_keys("abcdefg");
sleep 45;
Screen shot taken while sleeping (see last line in code above):
 which is then run as CGI by a web app. It runs fine from the Windows command line but as soon as I drop it into the app it throws an `Error 500: Internal Server Error`. I checked the Apache logs and sure enough there's a `ImportError: No module named arcgisscripting`. All of my other modules are working fine (sys, os, etc.) Does anybody know what could be the issue here?
**Update** : I think it might have something to do with this: Why can't python find some modules when I'm running CGI scripts from the web?
|
The link in the question had the answer... The location of `arcgisscripting` is defined in the Windows environment variable `PYTHONPATH`. By printing `sys.path` from a CGI script I could tell this was missing from the variables Apache was using. Easy fix: add this to `httpd.conf`:
`SetEnv PYTHONPATH "c:/path/to/pythonpath"`
And no more `ImportError`!
|
stackexchange-gis
|
{
"answer_score": 3,
"question_score": 2,
"tags": "python, apache, arcpy"
}
|
Excel formula to count non empty cells in a column for distinct values in an other column
I have a list of members in Excel with their date of deaths (date of death not populated, if member is still alive). For one member there can be more lines because there can be more benefit lines associated. I would like to count the number of distinct members who are dead. An example of my list
As a result, I would like to get 2, the count of distinct dead members in my list.
|
You can benefit from SUMPRODUCT:
/COUNTIFS(A2:A9;A2:A9&"";B2:B9;B2:B9&"");--(B2:B9<>""))
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "excel, count"
}
|
Remove consecutive duplicates in Julia
I am quite new in Julia and I don't know how to remove consecutive duplicates in an array. For example if you take this array :
`v=[8,8,8,9,5,5,8,8,1];`
I would like to obtain the vector v1 such that:
`v1 = [8,9,5,8,1];`
Could anyone help me? Many thanks.
|
One method could be to define:
function fastuniq(v)
v1 = Vector{eltype(v)}()
if length(v)>0
laste = v[1]
push!(v1,laste)
for e in v
if e != laste
laste = e
push!(v1,laste)
end
end
end
return v1
end
And with this function, you have:
julia> println(fastuniq(v))
[8,9,5,8,1]
But, when dealing with arrays, one need to decide if elements are to be deep or shallow copied. In case of integers, it doesn't matter.
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 8,
"tags": "arrays, duplicates, julia"
}
|
Google Cloud VM Instance with Wordpress Repeatedly Crashes
I've got a newly deployed Google Cloud f1-micro VM Instance using the Google Click to Deploy Wordpress solution. I've done some basic configurations such as a static IP, DNS config, persistent disk, etc. I also imported data from a previous Wordpress install.
The issue is that about every 10-15 minutes the server crashes and becomes unresponsive. Error 500 when trying to view any page, and SSH becomes unreachable. The console shows the VM Instance is still running though. I have to Reset the VM Instance, and then everything is restored within a few seconds. CPU usage is almost always below 50%. The site currently has almost zero traffic, just me testing it.
Any idea what may be causing it to freeze/crash so often? I know the f1-micro is not a powerful server, but I've read a lot about running Wordpress on it and it seems like it should be able to handle a low traffic website.
|
You can see system log from console in Web UI
. I suggestion you upgrade to bigger vm.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "wordpress, google cloud platform, google compute engine, stackdriver"
}
|
How it is working gc_maxlifetime
Have this session settings:
@ini_set('session.gc_probability', 1);
@ini_set('session.gc_divisor', 1);
@ini_set('session.gc_maxlifetime', 60);
session_set_save_handler('_sess_open', '_sess_close', '_sess_read', '_sess_write', '_sess_destroy', '_sess_gc');
function _sess_gc($maxlifetime) {
echo "GC started";
}
As far as I understand with this settings a garbage collector should run every 60 seconds (because probability and divisor are the same). Im testing this now and strange thing is that GC runs everytime im refreshing the website, it is not waiting until 60 seconds has passed from previous call. It is a bit confusing for me, do I understand something wrong here?
|
session.gc_probability / session.gc_divisor = x
In your case x = 1. (= 100% chance)
This means that the garbage collector will run on EVERY request. That is every request anybody makes.
The garbage collector will ONLY delete sessionfiles that are stale and eligible for deletion, NOT files that were recently modified. What is considered stale is defined by session.gc_maxlifetime
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php"
}
|
K&R Exercise 1-9 solution C programming
The task is to make a C program that replaces multiple blanks with a single blank and I found this solution on another StackOverflow question:
int c;
while ((c = getchar()) != EOF) {
if (c == ' ') {
while ((c = getchar()) == ' ')
;
putchar(' ');
if (c == EOF) break;
}
putchar(c);
}
It works but I am puzzled by the second while loop:
while ((c = getchar()) == ' ')
;
How does line this even remove any white spaces? I thought it just does nothing until it comes across another non-blank character. So then if a sentence had 4 blanks then I would expect it to turn into 5 blanks because your just adding another blank with `putchar(' ')` ? Does it remove the excess blank spaces in a way I'm not aware of?
|
The program reads (using `getchar`) a string from standard input and the outputs (using `putchar`) the same string to standard output **but leaving out the excess spaces**. So effectively it "removes" the extra spaces.
The `while` loop skips over a consecutive block of whitespace in the input while outputting nothing, and then after the loop is done, outputs a single space. That's how it "removes" the spaces.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "c, getchar"
}
|
Google Sheets formulas based on two cells dependent of each other - Appscript maybe?
I have the following issue:
I have Column A and Column B, the user can input data on either A or B and the sheet should do the calculation regardless of what column the data is entered on:
Example: User can enter 1200 in **column A** and **Column B** will display the data /2 (600), but the user can also enter 600 in **column B** and **column A** should display the data * 2 (1200), using formulas will not be an option because if there are formulas in both columns and the user enters the information will delete the formula in either or, is there any alternative on Appscript for this?
|
### Flow:
* Create a `cfg` object to do what's to be done on each column edit
* On a simple edit trigger , check which column and sheet is edited and
* Do calculations as specified by the `cfg` object
### Sample script:
/**
* @param {GoogleAppsScript.Events.SheetsOnEdit} param1
*/
const onEdit = ({ range: rg, value: val }, { columnStart: cs } = rg) => {
const cfg = {
1: { offset: 1, calc: num => num / 2 },
2: { offset: -1, calc: num => num * 2 },
}[cs];
/*Only include Sheet1 Column A and B*/
if (typeof cfg === 'undefined' || rg.getSheet().getName() !== 'Sheet1')
return;
rg.offset(0, cfg.offset).setValue(cfg.calc(val));
};
### References:
* Event objects
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "google apps script, google sheets"
}
|
Editing already defined routes
I'm working on a dynamic project which is adding or changing the route urls. For example: I want to add sub application route like AppName/{controller}/{action}/{id} or maybe a language information like {controller}/{action}/{id}/{language} in this scenario, I can't touch to other routes and I have to override them.
I tried to foreach RouteTable.Routes and there is no editable values for added routes.
Thanks for any help.
|
I found the solution. I cast the items in the RouteTable.Routes to Route object :)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "asp.net, asp.net mvc, asp.net routing"
}
|
How to solve differential equation $y'+\frac xy=x^2y^3$
I've tried to let $u=y^2$, and got $$u'+2x=2x^2u^2,$$ but I still can't solve it.
|
This is a ODE of the Riccati kind which solution involves Bessel functions :

{
_sessionFactory = Fluently.Configure().Database(OracleClientConfiguration.Oracle10.ShowSql().ConnectionString("Data Source="")
).Mappings(m =>
m.FluentMappings.AddFromAssemblyOf<Status>())
.BuildSessionFactory();
}
The variable that I used is a DateTime object and the column is date type.
Thanks you for your help
|
There was a problem with the table structure
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "oracle, nhibernate, fluent nhibernate"
}
|
return nothing from non-void function in C
what is considered best practice in the following snippet:
int foo(struct data *bar, struct info bla) {
if (!bar) {
bla->status = 0;
return;
}
...
}
in fact, it works fine. but i'm feeling uncomfortable with `gcc` giving me a warning.
* * *
here is the actual code:
static int pop(struct stack **stack, struct info *info) {
int ret;
struct stack *tmp;
if (!*stack) {
info->error = 0;
return;
}
ret = (*stack)->data;
tmp = *stack;
*stack = (*stack)->next;
free(tmp);
return ret;
}
|
Best practice is not to write code like that. If you can't return an integer of some sort at that point, you need to redesign your code. Note that the function as written **will** return a value of some sort to the calling code - you just don't know what that value will be.
The classic way round this is to return the value via a pointer parameter, with the actual function returning a status:
int f( int * p ) {
if ( bad ) {
return 0; // fail indicator
}
else {
* p = 42; // integer return value
return 1; // success indicator
}
}
**Edit:** In the code you posted you are manipulating a stack. Popping an empty stack is undefined behaviour for all stacks I know, so you can just return any integer that takes your fancy (I would return 0) and document the behaviour.
|
stackexchange-stackoverflow
|
{
"answer_score": 15,
"question_score": 6,
"tags": "c, gcc, return, warnings"
}
|
Is it safe to have the AWSAccessKeyId in url
I'm using aws-sdk to create a download link for a file from my s3 bucket
**controller**
s3 = AWS::S3.new(
access_key_id: ENV["AWS_ACCESS_KEY_ID"],
secret_access_key: ENV["AWS_SECRET_KEY"]
)
bucket = s3.buckets['my_bucket']
object = bucket.objects["path/to/file.zip"]
@link_url = object.url_for(:get, { :expires => 20.minutes.from_now, :secure => true })
**view**
<%= link_to "Download", @link_url %>
When I mouse over the link I can see my access_key_id in the url. Is this safe?
|
Yes, AWS_ACCESS_KEY_ID is public and required for matching the URL signature. But AWS_SECRET_KEY is private.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "ruby on rails 3, amazon web services"
}
|
UIImageView pixel-perfect `touches began` for non-transparent parts of UIImage
developing iphone app, I have used a UIImageview and i have set an image of irregular shape
// uiimageview type shutter
shutter = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,320,32.5)];
//setting image on shutter
UIImage* shutterimg = [UIImage imageNamed:@"trayshutter.png"];
[shutter setImage:shutterimg];
// User interaction
shutter.userInteractionEnabled=YES;
and i get touches using touchesbegan
everything is fine, but issue is I also get events in all the rectangle area occupied by the CGRectMake (i.e. 0,0,320,32.5) of imageview, whereas i require events only on the image (which is of shape of -----|||||-----).
How can i make sure that i get events only on the image and not on the rest of area covered by cgrectmake ?
|
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [touches anyObject];
if ([touch view] == yourDesiredImage) {
// Do something here
}
}
EDIT: maybe you can try `UITapGestureRecognizer` instead:
UITapGestureRecognizer * tapGestureRecognizer = [[UITapGestureRecognizer alloc] init];
[tapGestureRecognizer addTarget:self action:@selector(yourTouchMethod:)];
[tapGestureRecognizer setNumberOfTapsRequired:1];
[shutter addGestureRecognizer:tapGestureRecognizer];
[tapGestureRecognizer release];
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "iphone, uiimageview, uiimage, touchesbegan, user interaction"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.