INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Ruby on Rails User interface Gems
I would like to know list of gems which is helpful for creating a very good looking (user interface) application. | I'd say use the bootstrap-sass and then look over the Twitter Bootstrap documentation. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "ruby on rails, ruby, ruby on rails 3, ruby on rails 3.1, rubygems"
} |
More efficient central widget in a QMainWindow: QGLWidget VS QGraphicsView
I am using a QMainWindow for my app and want to do some openGL rendering. 2 approaches:
1) set as central widget a QGLWidget and do all the rendering there,
OR
2) set as central widget a QGraphicsView, set the viewport to my QGLWidget to create the rendering context and do the rendering in my scene.
Which one would be preferable when it comes to efficiency? (I will be adding some other objects later which in the former case are going to be QGLWidgets (as child widgets) and in the latter QGaphicsItems) | Using a QGLWidget and rendering with OpenGL directly will in most cases be more efficient, but it will require more work to manage a dynamic set of rendered items. Using the QGraphicsView framework will have some overhead, but it provides many features for managing rendered items. The amount of overhead for QGraphicsView will depend upon various details, but in most cases it will not be a bottleneck and it can be adjusted for various usage patterns. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 3,
"tags": "qt, opengl es 2.0, qgraphicsview, qmainwindow"
} |
jQuery Validation adding a new method
what I'm wanting to do is add a new validation method that will validate if 2 fields are not equal DEPENDING if a radio button is ticked (see here - <
The code I have works, but I have had to fudge it a little by adding the field in the actual method where I would rather pass it through.
So at the moment I have ...
jQuery.validator.addMethod("test", function(value, element, param){
// check if dependency is met
if (!this.depend(param, element)) return "dependency-mismatch";
return value != $("#ImEqDepEq").val();
},
jQuery.format("Should not match Equality value.")
);`
I obviously just want ($("#ImEqDepEq").val()) to be another parameter that I pass in.
I hope this makes some kind of sense, I'm rubbish at explaining things :(
cheers
Daz | You can pass additional info to the rule using `param` option.
$("form").validate({
rules: {
ImEqDep: {
test: {
depends: function () {
return $("#ImEqDepRad1Yes").is(':checked');
},
param: '#ImEqDepEq'
}
}
}
});
jQuery.validator.addMethod("test", function (value, element, param) {
// check if dependency is met
if (!this.depend(param, element)) return "dependency-mismatch";
return value != $(param).val();
}, jQuery.format("Should not match Equality value."));
Demo: Fiddle | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "jquery, jquery validate"
} |
Accessing a variable's information
I am creating a tool to find the temperature of two areas in New Mexico. In the data set, there is a temperature variable inside a dictionary (`main`) that I can not seem to get the contents of for my program. The output should be `288.142` and yes I know this is in kelvins.
NMNorthzip=[87401,87301]
for x in NMNorthzip:
r = requests.get("
+str(x) + ",us&appid=id")
data = r.json()
forecast = data['list']
for n in forecast:
main = n['main']
for z in main.items():
print(z)
Output:
('temp_max', 288.142)
('sea_level', 1028.46)
('grnd_level', 797.18)
('temp_min', 288.142)
('temp', 288.142)
('humidity', 26)
('temp_kf', 0)
('pressure', 797.18) | You're converting the dictionary to a list and printing the (key, pair) tuples resulting from the `.items()` function. So remove this:
for z in main.items():
print(z)
Instead access dictionary items:
temperature = main['temp'] | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "python, dictionary, for loop"
} |
Generate random letters in C
here is my code. I am trying generate random alphabet but i see same letters. example: ( **Y** HTGDHFBSHXCHF **Y** FUXZWDYKLXI) How can i fix it? just i need mixed alphabet not same letters. Thank you so much.
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void random_string(char * string, unsigned length)
{
/* Seed number for rand() */
srand((unsigned int) time(0));
int i;
for (i = 0; i < length; ++i)
{
string[i] = rand() % 26 + 'A';
}
string[i] = '\0';
}
int main(void)
{
char s[26];
random_string(s, 26);
printf("%s\n", s);
return 0;
} | The operation you are looking for is called a _shuffle_ or a _permutation_. It is not sufficient to call a random-letter function 26 times, since, as you see, you can generate duplicates.
Instead, start with the string `"ABCDEFGHIJKLMNOPQRSTUVWXYZ"` and perform a shuffle operation. If you want to learn by doing such things from scratch, I recommend reading about the Fisher-Yates Shuffle then crafting an implementation on your own. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 2,
"tags": "c, encryption, random"
} |
returnActivity events when calling startActivity method
I have an `Activity` and I start an appliction chooser with `startActivity`.
**Question** : How can I wait with the finishing the parent activity until the user has selected a preferred mail app?
Uri uri = Uri.parse("mailto:" + "[email protected]")
.buildUpon()
.appendQueryParameter("subject", "subject")
.appendQueryParameter("body", "body")
.build();
Intent emailIntent = new Intent(Intent.ACTION_SENDTO, uri);
startActivity(Intent.createChooser(emailIntent, "chooser Title"));
finish(); | As stated in this post, you could use IntentPicker instead of IntentChooser
Intent intentPick = new Intent();
intentPick.setAction(Intent.ACTION_PICK_ACTIVITY);
intentPick.putExtra(Intent.EXTRA_TITLE, "Launch using");
intentPick.putExtra(Intent.EXTRA_INTENT, emailIntent);
this.startActivityForResult(intentPick, REQUEST_CODE_MY_PICK);
// You have just started a picker activity,
Then you can listen for the result of the intent pick by adding the following callback method in your activity:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == REQUEST_CODE_MY_PICK) {
// start the activity the user picked from the list
startActivity(data);
//you can finish() your activity here
}
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "android, android intent, android activity"
} |
Java using "-cp" and "-jar" together
Earlier, I had just one jar file and the manifest was set up such that I can simply run my program as:
java -jar MyApp.jar
Now, I have separated my functionality into two jar files - MyCore.jar and MyApp.jar.
The following command works:
java -cp "*" com.mycompany.mypackage.App
But I cannot get the following to work
java -cp "*" -jar MyApp.jar
I get a ClassNotFoundException.
I prefer using "-jar" switch. Is there a way to make it work? | I have a Manifest.mf file like this.
Manifest-Version: 1.0
Main-Class: com.mycompany.mypackage.App
Class-Path: MyApp.jar MyCore.jar log4j.jar
You can just add any jar files you need to the Class-Path line. Then as long as the jars are in the class path you can run the java -jar command without -cp. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 9,
"tags": "java"
} |
"is it me, or..." meaning and usage
What does "is it me, or..." mean?
Examples:
* Perhaps it is just me, but I find Intel's ultrabook pitch somewhat confusing.
* Is it me, or is this a bug? | Is it me = is it my mistake/fault.
"Is it me, or is this a bug?" - Is this my fault for not understanding something or is it a bug.
The implication is normally that you don't really think it is your mistake so it's phrased as a faked apology. ie `I might be mistaken but I don't really believe I am`.
It can also be used to make an insult/comment, "Is it me or should she really not be wearing that at her age?", assumes those you are talking to agree with you. | stackexchange-english | {
"answer_score": 5,
"question_score": 4,
"tags": "meaning in context"
} |
Delete all apps that match a filter
Is there a quick way to do something like:
`cf delete *-failed`
To delete all applications ending with `-failed` ? | If you're on Linux/Unix/Cygwin, you can do this:
cf apps | tail +5 | cut -d ' ' -f 1 | grep "my-filter" | xargs -n 1 cf delete -f
The first will get a list of apps, the second will strip off the headers that the cf cli writes, the third cuts out just the app names and the fourth filters and the fifth will run `cf delete -f` for each app it finds.
There are tons of variations on this, to filter and grab only the information you want. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 6,
"tags": "cloud foundry"
} |
How can I get RequestMethod of ServletRequest?
I have ServletRequest, which client machine sent. How to know which one it is: `GET` `POST` `UPDATE` or `DELETE`? | If you are using Spring MVC and your comunication protocol is HTTP, you don't need use ServletRequest, you can use directly HttpServletRequest in your method like this:
public ModelAndView index(HttpServletResponse response, HttpServletRequest request)
But if you need use ServletRequest and you are sure your comunication protocol is HTTP you can cast your ServletRequest to HttlServletRequest and use getMethod() like Shriram said. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 8,
"tags": "java, spring, httprequest"
} |
How to switch a row dimension to a column dimension in R?
I have a df looks like below.
Year Month Cont
1 2011 Apr 1376
2 2012 Apr 1232
3 2013 Apr 1360
4 2014 Apr 1294
5 2015 Apr 1344
6 2011 Aug 1933
7 2012 Aug 1930
8 2013 Aug 1821
9 2014 Aug 1845
10 2015 Aug 1855
So my question is how can I switch the rows in "Month" the column. The result should look like this.
Cont Apr Aug
1 2011 1376 1933
2 2012 1232 1930
3 2013 1360 1821
4 2014 1294 1845
5 2015 1344 1855 | You can use `reshape2`:
library(reshape2)
dcast(df, Year~Month, value.var="Cont")
Or `tidyr`:
library(tidyr)
spread(df, Month, Cont) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "r"
} |
Equivalent for TzSpecificLocalTimeToSystemTime() on win2k?
One of our developers used this call:
TzSpecificLocalTimeToSystemTime() but unfortunately we cannot keep it as the code must work on Win2K as well.
What alternatives are there for similar functionality? | There is no equivalent, not even with WINE. It relies on timezone info stored in the registry, retrieved with GetTimeZoneInformation(). Note how the WINE code ends up in find_reg_tz_info(). That info is just missing in Win2k.
You'd have to create your own timezones table. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c++, datetime, winapi"
} |
How to see if a subspace is contained in another subspace?
So basically I have a problem with 2 subspaces given in the following spans $$U=\mathscr L\\{(1,2,-1,3),(2,4,1,-2),(3,6,3,-7)\\}$$$$V=\mathscr L\\{(1,2,-4,11),(2,4,0,14)\\}$$ And I am asked if it is true if U$\subseteq$V or V$\subseteq$U. I understand the concept of 2 subspace being equal or proving a subset being a subspace of $\mathbb R^n$ by checking the sum of the vectors and the multiplication by a constant but I don't believe to understand the procedure to check if one subspace is contained in another one. | If the generators of $V$ are in $U$, then $V \subseteq U$.
EDIT: in this particular case, you can do it faster. Call $u_1, u_2, u_3$ the generators of $U$. Then $u_2 - 2u_1 = 2(u_3 - 3u_1)$, so both $U$ and $V$ have dimension $2$. You just have to check if they are equal or not. | stackexchange-math | {
"answer_score": 2,
"question_score": 1,
"tags": "linear algebra, vectors, invariant subspace"
} |
VSCode - How to uninstall themes that can't be found by searching '@installed @category:"themes"'
I have some themes that can't be found by searching:
`@installed @category:"themes"`
And I don't think they come built-in.
How to uninstall those themes?
!VS Code theme listing
Actual theme names typed here for easier searching:
PowerShell ISE
Quiet Light
Solarized Light
Abyss
Kimbie Dark
Monokai
Monokai Dimmed
Red
Solarized Dark
Tomorrow Night Blue | First I want to address that these themes you mentioned are all **built-in**.
To remove those themes from coming to the list, go to Extensions and type `@builtin`, then disable the unnecessary themes.
 connected?
Consider the set $Map(T^4,S^2)$ of continuous maps from the 4 dimensonal torus $T^4$ to the 2 dimensional sphere $S^2$, endowed with compact-open topology, can we show it is not connected? How can we calculate its singular homology and $\pi_1$? | The accepted answer is incorrect. The problem is in Hint 2, which conflates based maps with unbased maps, and in particular which conflates the based loop space $\Omega X$ of a pointed space $(X, x)$ (the space of maps $S^1 \to X$ sending a fixed basepoint in $S^1$ to $x$) with the unbased or free loop space $LX$ of a space $X$ (the space of maps $S^1 \to X$, with no further hypotheses). Hint 1 and Hint 2 together were supposed to convince you that the space you're looknig at is the 4-fold based loop space of $S^2$, which satisfies
$$\pi_0(\Omega^4 S^2) \cong \pi_4(S^2) \cong \mathbb{Z}_2$$
but that's not true; the 4-fold based loop space of $S^2$ is the space of maps $S^4 \to S^2$ sending a fixed basepoint of $S^4$ to a fixed basepoint of $S^2$, and has nothing to do with $T^4$. The space you're looking at is in fact the 4-fold _free_ loop space $L^4 S^2$. | stackexchange-math | {
"answer_score": 3,
"question_score": 5,
"tags": "algebraic topology"
} |
WAMP 64x with apps doesn't work
I got a project running for a client with PHP 5.3.13 and when I moved the whole site including the databases from their servers to my WAMP server some PHP functions don't work. So at first I write some new PHP functions, but now it seems like it will be like write a whole new page. So what I want is to use PHP version 5.3.13 on my WAMP server.
I read on WAMP's page that you could use apps or addons so I downloaded both Apache 2.2.2 and PHP 5.3.1 but now it is a red icon on both. When I try to switch PHP to a different it says that my Apache is not compatible with my PHP, or when I try to switch my Apache it says the same.
So I search the web, and it seems to be that my WAMP install is 64x version with PHP 5.4.12 and Apache 2.4.4. So I am thinking if I can install a new WAMP server on the same HDD or will it destroy something?
Otherwise is there some other way around this? | If you want to use the ADONS you have to install WAMPServer 32bit, as all the adons are compiled 32bit.
32bit is a better idea anywhay currently as not all extension have a 64bit equivalent.
So install WAMPServer 2.2e and that will make it easier to install PHP ADDON versions. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, mysql, apache, 64 bit, wamp"
} |
is there an event that fires at a specific time?
Is there a .NET event that fires at a specific time (eg. at 19:00) as opposed to timer which fires when the countdown finishes? It can be used as a scheduler to call certain method. | Take a look at Quartz.net.
It's a great scheduling library for .net. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": ".net, events, timer, scheduler"
} |
Show components in Altium schematic, but exclude from design
I am designing an I2C multiplexer circuit in Altium 17.0 which includes a reset input through a transistor.
In this particular PCB, the reset function will not be needed, and the reset pin of the mux will just be tied to ground. But, I have a small sub-circuit (input port, transistor, three resistors, output port) that generally would be included with this multiplexer.
, I have to the push home putton on the devices'. It is very frustrating. Does anybody know how to switch applications by keyboard like "Windows key + tab" on Windows? | If you are using a MacOS/iOS BT keyboard with the Option and Command (aka clover leaf or open Apple) keys, then this should help you out…
iPad Navigation Keyboard Commands Basic keyboard navigation shortcuts on iPad are as follows:
Control+Option+H – Home button Control+Option+H+H – Show multitask bar Control+Option+i – Item chooser Escape – Back button Right Arrow – next item Left Arrow – previous item Up + Down Arrows simultaneously – tap selected item Option + Down Arrow – scroll down Option + Up Arrow – scroll up Option + Left or Right Arrow – scroll left or right Control+Option+S – turn VoiceOver speech on or off iPad App Switcher Keyboard Commands Arguably the most useful set of commands are related to app switching:
Command+Shift+Tab – switch to the previous app Command+Tab – switch back to the original app Left+Right Arrow, then Option + Left or Option+Right – navigate through Dock
Source: <
More shortcuts: < | stackexchange-apple | {
"answer_score": 4,
"question_score": 9,
"tags": "iphone, ipad, keyboard, switching"
} |
How can I differentiate anonymous in Push
I would like to differentiate the anonymous users from the non-anonymous in Push. Is there a way to access that data? I see there is no Data Views but three reports in which I don't see how I can retrieve this information.
* Push Account Summary
* Push Message Detail
* Push Message Summary | Audience segmentation can be easily done with the use of `Tags`, `Attributes` and/or `ContactKey`.
Personalization can also be completed using AmpScript. You could, for instance, say, "Welcome!" (for a contact without a "firstName" attribute set) or "Welcome, Bill!" (if the "firstName" is known.)
You have access to these, and other fields in Audience Builder's MobilePush Demographics. | stackexchange-salesforce | {
"answer_score": 2,
"question_score": 2,
"tags": "marketing cloud, reporting, mobilepush, push"
} |
ShareActionProvider - send string with link
Couldn't find the answer to my problem, so here is my question: I have an app storing debts and where i can send the debt info to anyone using ShareActionProvider in the actionbar. It all works fine, i can send a string via, let's say, whatsapp. So far, so good. I wanted to include a link to the app in the play store at the end of the message but couldn't find out how to do it.
Here the intent I'm sending via the ShareActionProvider
Intent i = new Intent();
i.setAction(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_TEXT, share_message);
i.setType("text/plain");
How can i achieve to add something like this: Don't forget to check out this | just append the link to the end.
Intent i = new Intent();
i.setAction(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_TEXT, share_message + " + getPackageName());
i.setType("text/plain"); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "android, android intent, shareactionprovider"
} |
C# Dynamically Generate Queues
I have a class called "BatteryPack:"
public class BatteryPack
{
public string BatteryType;
public int BatteryCount
}
I want to organize the packs into queues based on `BatteryType`, so that I can take batteries from one pack in a type, and then move to a different pack and take some from that.
The problem is, I don't know how many different battery types I have until runtime, so I can't make the queues beforehand. Is there a way for me to generate queues at runtime, or is there another way to solve this problem while allowing me to maintain a distinct place in the list? | something like this?
Dictionary<string, Queue<BatteryPack>> TypeToPack = new Dictionary<string, Queue<BatteryPack>>();
foreach(BatteryPack pack in BatteryPacks)
{
if(!TypeToPack.ContainsKey(pack.BatteryType))
TypeToPack.Add(pack.BatteryType, new Queue<BatteryPack>());
TypeToPack[pack.BatteryType].Enqueue(pack);
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": -2,
"tags": "c#"
} |
Adding Author Metadata to a TXT or CFG file
Basically I am looking for a way of "branding" a cfg file. Specifically a CSGO-config, so yes, nothing too important. I'm just surprised, that after quite a bit of google search, I still havent found anything. | In general, plain text files (and probably .cfg files) do not contain any metadata by default. The file system should keep track of some properties for these file types, but they won't otherwise transfer across filesystems.
If you would like to "brand" your file, perhaps you could add a comment to the top with your name. It would be about as permanent and immutable as any metadata anyways. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "metadata, config, author"
} |
Execute search/replace in PhpStorm as action
I'm looking for a solution to:
1. store favorite "Find Occurrences of ..." and
2. execute them without any more questions by the UI in one stroke
I know the option `ALT + 3` -> `STRG + E` to open the last Find Usages, but that are only "Find" and not "Replace in Path" actions
Maybe I need to develop a plugin - that could look like this:
DO REPLACEMENTS:
----------------------------------
[X] foo -> bar
[ ] bar -> foo
[X] ): boolean -> ): bool
----------------------------------
[add] [execute] [execute & review]
----------------------------------
but any other ideas are welcome!
Important is to use PhpStorm`s file scopes! Because I would like to use my own custom scope. | You can use "Structural Search Inspection". It's base on the "Structural Search and Replace" engine which is pretty powerful. Once configured you can run the inspection using the "Run Inspection by Name..." action with a custom scope. It has a quick fix which can be used to replace occurrences. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "phpstorm"
} |
Trouble editing local.xml
I'm quite puzzled by this one. I'm fairly new to the Magento architecture, so forgive me if this is a simple issue. I've got my caches disabled.
I'm on Magento 1.7.0.2, and I've created a vertical category navigation to sit in my left sidebar on all pages. I then tried to add a layout update to local.xml. Nothing happened. I checked the valudation on the xml - no errors.
Here's the update I'm trying:
<reference name="left">
<block type="catalog/navigation" name="catalog.leftnav" template="catalog/navigation/vert_nav.phtml" />
</reference>
Next, I tried placed it in catalog.xml, and sure enough, it appeared in the right spot on the home page. When I click through to the category pages, however, it disappears. I assume this means that catalog.xml is not in play on category pages? Is there another xml for this? | To make it appear in category pages you should place it under `catalog_category_default` for both (Anchor) and (Non Anchor) categories it should look like
<catalog_category_default translate="label">
<label>Catalog Category (Non-Anchor)</label>
<reference name="left">
<block type="catalog/navigation" name="catalog.leftnav" template="catalog/navigation/vert_nav.phtml" />
</reference>
Same is to be done with Anchor Category | stackexchange-magento | {
"answer_score": 1,
"question_score": 1,
"tags": "magento 1.7"
} |
How to find if color exists in an image
I am new to open cv and trying to find detect if green color exists in my image or not.
I have the upper color bound and lower color bound in my cv2.range. When I just open with cv2.bitwise_and see the color it shows that there is green color but I don't know how to print if green exist or not
hsv_image= cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
lg = np.array([56,255,251])
ug = np.array([60,255,255])
gmask = cv2.inRange(hsv_image,lg ,ug)
color = cv2.bitwise_and(img,img,mask=gmask)
if gmask.equals(img):
print("green exist")
else:
print("not found")
I expect to see as the output green exist in a given image | You can use `cv2.countNonZero()` on the masked image. Since `cv2.inRange()` returns a binary mask of all pixels within your minimum/maximum color threshold, the idea is that if there is at least one white pixel on the mask then the color exists
pixels = cv2.countNonZero(gmask)
if pixels > 0:
print("green exist")
else:
print("not found") | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 3,
"tags": "python, image, opencv, image processing, computer vision"
} |
Evaluating expressions contained as strings
I've a database which returns vaild CL expressions within double quotes.
Is it possible to convert these strings to expressions.
For example, I make a query from this DB via CLSQL and as a result it returns me:
`"(foo a b)"`
How should I convert this expression to:
`(foo a b)`
and further evaluate it? | > (read-from-string "(foo a b)")
(FOO A B) ;
9
The `9` is the second of multiple values produced by `read-from-string`; you can ignore it:
(eval (read-from-string "(foo a b)"))
will do what you want given the proper definitions. | stackexchange-stackoverflow | {
"answer_score": 15,
"question_score": 10,
"tags": "common lisp"
} |
PHP regex remove space in specific string
Im trying to remove the " " (space) in the following string. Be aware that this is only part of a string (there are valid spaces in it just not this one). So the code should identify this string then remove the space.
**Example:**
18-Sep 00:20
**Test:**
/\d{1,2}-[a-z]{3}\s*( )\d{2}:\d{2}/ | Or try
/(\d{1,2}-[A-Z][a-z]{2}) +(\d{2}:\d{2})/ // REGEXP
with
"$1$2" // as the replacement string
This way the replacement will only affect string fragments with three digit month names, starting with a capital letter. It will also remove more than one blanks if necessary. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "php, regex"
} |
É possível realizar uma adição com campo varchar?
tenho o seguinte update:
update ex
set ex.seq_docum_ref = '00001',
ex.nr_chv_nfe_ref = ref.ChaveNfTerceiro,
ex.cd_docum_ref = case when ChaveNfTerceiro is not null then coalesce(ref.DocSispro,'') else case when ref.SerieNotaProd is not null then 'NFP'+cast(ref.SerieNotaProd as varchar) else '' end end,
ex.cd_docum_nr_ref = ref.NrNfTerceiro,
ex.cd_pessoa_ref = ex.cd_pessoa_emi,
ex.dt_nota_ref = replace(convert(varchar, ref.DtNfTerceiro,103),'/',''),
ex.in_ent_sai = 'S'
no campo
ex.seq_docum_ref
quero que ele some mais um a cada update realizado, no entanto o campo é varchar, como posso fazer essa adição e manter o tipo do campo? Preciso disso para entregar uma tarefa no trabalho. Desde já obrigado! | Se não errei na sintaxe, experimente algo como
UPDATE ex
set seq_docum_ref= right (('0000' + cast ((cast (seq_docum_ref as int) +1) as varchar(5))), 5),
...
Mas o melhor mesmo é utilizar uma tabela auxiliar para armazenar o contador como valor numérico e, sempre que for necessário obter a próxima sequência, solicitá-la e então armazenar na tabela convertendo para string com zeros à esquerda. No artigo Geração de sequências numéricas você encontra formas de gerar uma sequência confiável. | stackexchange-pt_stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "sql server"
} |
TenantNotAvailableException, when trying to call business partner from s4 CF SDK
I am trying with deploying the basic business partner app on my local tomee, and i am getting the below error "TenantNotAvailableException: Failed to get current tenant: tenant not available" while calling <
 you can set the `ALLOW_MOCKED_AUTH_HEADER` environment variable to `true`. This will provide a mocked tenant in case to tenant could be identified by the SDK. In step 7 of our blog series you will learn how to setup an approuter to provide you such a tenant so that you can remove the variable. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "s4sdk"
} |
Why can't the two plates of a capacitor have unequal charge?
This is what was given in my textbook:
"The net charge on every component in the system is always zero. Thus no component can collect a net excess of charge, although some components can hold equal but opposite separated charges."
I can't quite understand why this is so. For example, what would happen if the two plates of a capacitor had unequal opposite charges? | The assumption of charge neutrality is based on our notion of common electric circuits, where charge is free to move under the influence of electric fields.
If the amount of positive charge on one capacitor plate **did not** equal the amount of negative charge on the other plate then the **electric field** between the plates would attract and draw charge as needed to establish neutrality. | stackexchange-electronics | {
"answer_score": 2,
"question_score": 0,
"tags": "capacitor, circuit analysis"
} |
Auto-resize iPhone xib app to ipad
I built an iPhone app "using xib" with 5-6 screens. Now I want to auto-resize the display for iPad. I am using xcode 4.6.
Do I have to rebuild the entire code using storyboards? It will be a very tedious work. Is there any solution for this? | You'll need to create only new xib files for iPad and name them as `ViewController_iPhone.xib` and `ViewController_iPad.xib` and when switching your views, just put a simple condition
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
ViewController *viewController = [[ViewController alloc] initWithNibName:
@"ViewController_iPad" bundle:nil];
} else {
ViewController *viewController = [[ViewController alloc] initWithNibName:
@"ViewController_iPhone" bundle:nil];
} | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 3,
"tags": "iphone, ios, ipad, xib"
} |
Keep running total of file opens/reads?
Is there a linux kernel module or perhaps a different filesystem to keep a running total of the number of times a file has been opened?
I realize this bit would be asking a lot, but if you could also tune it so it doesn't increment the count unless x% of the file was read while it was open, that would be fantastic.
Thanks. | Yes! This would be the `inotify` system. It's built into the kernel, you just have to hook it. One of the events you can monitor are file-open (IN_OPEN) and file-close (IN_CLOSE). Once you've built a tool to monitor things you can get these counts pretty simply. Unfortunately, it doesn't event on percent-read, just `read`. | stackexchange-serverfault | {
"answer_score": 3,
"question_score": 1,
"tags": "linux, files, filesystems"
} |
Connect .content:hover and img:hover, so they activate at the same time
I am trying to connect these 2 hover classes, so they activate at the same time:
#recent-posts .content:hover {
-webkit-box-shadow: 0px 0px 10px 3px rgba(0,0,0,0.04);
-moz-box-shadow: 0px 0px 10px 3px rgba(0,0,0,0.04);
box-shadow: 0px 0px 10px 3px rgba(0,0,0,0.04);
}
#recent-posts img:hover {
outline: 11px solid #ff7454;
margin-bottom: 15px;
}
So whenever you hover over content OR an image both hover classes will activate. I have tried a bunch of different ways to do this and read all over but this seems a little more complicated than it should be.
Can anyone point me in the right direction?
Here is a jsfiddle with what I have so far: < | I would use the parent selector to style the child-elements:
#recent-posts .thumbnail:hover {
...
}
#recent-posts .thumbnail:hover img {
box-shadow:....
}
If the elements would not have one common parent, you have to use JavaScript. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "css, hover"
} |
Importing email data into list stops at 100
I am following the example given in <
My question is that the threads list stops at 100. There are definitely more than 100 threads in my inbox. I am using Spyder (Python 3.7). Is that a Spyder limitation? Because Python can clearly handle larger lists. Thank you. | Take a look at "nextPageToken" in the thread.list
< | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 1,
"tags": "python, list, limit, gmail api, spyder"
} |
Beth one equal to beth two not known?
Wolfram Alpha seems to say that ($\beth_1=\beth_2$) is unknown, but i'm pretty sure that $\beth_2$ is greater than $\beth_1$ ? is this just a bug in WA or is there a way in set theory that you can make them equal ? | $\beth_1$ is the cardinality of the reals; $\beth_2$ is the cardinality of the power set of the reals, and is strictly bigger. I think this "unknown" is "WolframAlpha doesn't know", rather than that humanity does not know. | stackexchange-math | {
"answer_score": 10,
"question_score": 4,
"tags": "set theory, infinity, wolfram alpha"
} |
Which of ppp, tcp, rtp and tls are connection-oriented protocols?
There is not much to say here - I'd like to ask which of these for protocols:
* Point to Point Protocol
* TCP
* Real Time Protocol
* TLS
...are connection-oriented and which of them are reliable? | The protocols you list are at different communication layers, so a direct comparison doesn't necessarily make much sense. TLS and RTP are above the transmission layer, while PPP is a link layer protocol, and these usually (not always) don't care about connections in the sense e.g. TCP does (though link layer protocols might provide services to make sure frames are not lost and arrive in order). To make a long story short, only TCP from your list is a connection-oriented protocol. TLS and RTP work both on top of TCP and UDP. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "networking, tcp, ssl, rtp, ppp"
} |
Regex substitution with Notepad++
I have a text file with several lines like these ones:
cd_cod_bus
nm_number_ex
cd_goal
And I want to get rid of the `-` and uppercase the following character using Notepad++ (I can also use other tool but if it doesn't get the problem more troublesome).
So I tried to get the characters with the following regex `(?<=_)\w` and replace it using `\U\1\E\2` for the uppercasing trick but here is where my problems came. I think the regex is OK but once I click replace all I get this result:
cd_od_us
nm_umber_x
cd_oal
as you can see it is only deleting the match.
Do you know where the problem is?
Thanks. | The search regex has no capture groups, i.e. the \1 and \2 references in the replacement do not refer to anything.
Try this instead:
Search: _(\w)
Replace \U\1\E
There you have a capture group in the search part (the parenthesis around the \w) and the \1 in the replacement refers back to what was captured. | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 5,
"tags": "regex, notepad++"
} |
How to convert a REAL32 to a Vector
so I want to read a STL-File for a project and ran into the problem of not knowing how to read a REAL32 number and convert it to a useable Float Value.
TLDR how to read 12 byte REAL32 and convert it to 3 coordinates
(from Wikipedia)
foreach triangle - 50 bytes:
REAL32[3] – Normal vector - 12 bytes
REAL32[3] – Vertex 1 - 12 bytes
REAL32[3] – Vertex 2 - 12 bytes
REAL32[3] – Vertex 3 - 12 bytes
UINT16 – Attribute byte count - 2 bytes
end | Real32 is not 12 byte long. Each vertex has 3 real32 number, each one is for x, y and z coordinate respectively. Each coordinate is represented by 4 bytes that means 32 bit in little endian format, and that format is called real32. You can write a function that converts 4 bytes real32 number to double. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, stl"
} |
Migrate HTML Site to ASP.NET MVC 3
I have just ported an HTML site over to ASP.NET MVC 3.
Google appears to have a lot of the old pages indexed, e.g.
and now this will be
I'd like a way to force users and Google to be permanently redirected to the new URL structure. Some of the redirects aren't as simple as dropping the .html, so the ability to fine-tune the redirect paths would be great.
I'm hosting on Windows Server 2008 R2, so if I can do this through IIS then great, else I don't mind implementing something in code.
Any ideas please?
I've had a hunt round Google, but not found anything that seems to fit the bill.
Thanks. | I'd set up a catch-all route and a `Redirects` table in your DB. In a catch-all handle I'd check if there's an entry for a requested URL in the `Redirects` and redirect to a new URL. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "asp.net mvc 3, asp.net mvc routing, iis 7.5, windows server 2008 r2"
} |
Parsing a Auto-Generated .NET Date Object with Javascript/JQuery
There are some posts on this, but not an answer to this specific question.
The server is returning this: `"/Date(1304146800000)/"`
I would like to not change the server-side code at all and instead parse the date that is included in the .Net generated JSON object. This doesn't seem that hard because it looks like it is almost there. Yet there doesn't seem to be a quick fix, at least in these forums.
From previous posts it sounds like this can be done using REGEX but REGEX and I are old enemies that coldly stare at each other across the bar.
Is this the only way? If so, can someone point me to a REGEX reference that is appropriate to this task?
Regards,
Guido | The link from Robert is good, but we should strive to answer the question here, not to just post links.
Here's a quick function that does what you need. <
function deserializeDotNetDate(dateStr) {
var matches = /\/Date\((\d*)\)\//.exec(dateStr);
if(!matches) {
return null;
}
return new Date( parseInt( matches[1] ) );
}
deserializeDotNetDate("/Date(1304146800000)/"); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 4,
"tags": "c#, javascript, jquery, .net, date"
} |
Found an error in a paper I presented at a student engineering conference. Should/can I talk about it in my MS applications?
Some background information: Found an error in a paper that I already presented at a student engineering conference; what should I do now?
I am inclined to talk about the paper because I was awarded the 2nd best paper. And although it isn't published (only printed in conference proceedings) and it was a student conference, I still made a big error. | Reading your background, it seems that everything about the work was correct except for a mistake in translating the algorithm from code to pseudocode. Moreover, you've done your best at correcting the mistake. Mistakes happen in science, and especially when it comes to the dread pseudocode (personally, that's why I always include actual executable code whenever I can).
From what you've presented, I think you have every reason to be proud of this work and none to be ashamed. Talk about the work in your applications. Talk about the paper. Talk about the experience in getting it corrected. Anybody who you'd actually want to work for will see all of these as strengths and not weaknesses. | stackexchange-academia | {
"answer_score": 4,
"question_score": 4,
"tags": "graduate admissions, masters, errors erratum"
} |
WPF: Display empty Rows even if listbox/Listview is empty
Is it possible to have empty rows displayed inside of a listbox/listview in wpf? I've been trying to replicate a repeating pattern of rows after my data so the listbox looks "full" but I haven't managed to figure out how to do this as of yet. The problem is the listbox will only show if there is any data in the observablecollection its bound to, so if there is no data the listbox wont render anything, and even if there is data, it'll only show the amount of rows the observablecollection is holding and nothing below the rows. I want to be able to have empty rows appearing in the listbox after the data, or a repeating pattern of empty rows if at all possible. Any help or tips would be appreciated. | There are several ways to achieve this result: 1) Add more (empty) rows to your collection 2) Use a separate collection that wraps your collection, and contains the empty rows (this is useful if you don't want to pollute your source with extra data) 3) Create a custom panel to use (instead of StackPanel, WrapPanel, etc) that your ItemsControl can use to display the items - then the panel itself handles displaying the empty rows. This a more robust and less hacky solution than 1 and 2, but requires more effort and WPF knowledge.
4) Create a subclass of ItemsControl (or ListBox/ListView) that automatically adds extra Items to fill the remaining space (similar to (3), but instead of a custom panel plugged into the ListBox, you are customizing the ListBox to create extra items for any panel to display. This is useful if you want to reuse the logic in different contexts where the consumer might want to vary the Panel type used. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "c#, wpf"
} |
Mysql query throwing error
I am getting a :
You have an error in your sql syntax; check the manual that correspondes to....
here is my query. I do MSSQL, I am new to mysql .. Please help
IF EXISTS (SELECT * FROM TIMESHEET WHERE EMPLOYEEID = '1' AND PERIODENDINGDATE = '2011-01-30')
UPDATE TIMESHEET SET STATUSCODE = 'P', PERIODENDINGDATE = '2011-01-30', DEPARTMENTCODE = 'IT'
MINUTESMON = '200', MINUTESTUE= '200', MINUTESWED='200', MINUTESTHU='200'
MINUTESFRI='200', MINUTESSAT='200', MINUTESSUN='200'
ELSE
INSERT INTO TIMESHEET (EMPLOYEEID, STATUSCODE, PERIODENDINGDATE, DEPARTMENTCODE, MINUTESMON, MINUTESTUE,
MINUTESWED, MINUTEDTHU, MINUTESFRI, MINUTESSAT, MINUTESSUN)
VALUES ('1','P','2011-01-30','IT','200','200','200','200','200','200','200') | Unless this is part of a stored procedure or function or trigger, this simply isn't a valid form for a MySQL query. You can't just write freeform logic into a single query with MySQL.
You probably want to write an `INSERT INTO...ON DUPLICATE KEY UPDATE` query. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "mysql"
} |
How to accept user input from within a function?
I am new to Python. This code snippet is supposed to define a function getinput(), which is supposed to accept user input and put that value into variable stuff. Then I call the function, and print the value of the variable stuff.
def getinput():
stuff = input("Please enter something.")
getinput()
print(stuff)
The problem is that the program is not working as expected and I get the error:
NameError: name 'stuff' is not defined
In contrast, without defining and calling a function, this code works just fine:
stuff = input("Please enter something.")
print(stuff)
And I can't figure out why that should be so.
Please help. I am learning Python to coach my kid through his school course, and I am using Google Colab with Python 3.7.11, I believe. | There is a lot of possibilities of printing `stuff` that you could do -
def getinput():
stuff = input("Please enter something.")
print(stuff)
getinput()
You can print it inside function and call it
* * *
def getinput():
stuff = input("Please enter something.")
return stuff
print(getinput())
You can return the `stuff` and print it ( **BEST Solution** )
* * *
def getinput():
global stuff
stuff = input("Please enter something.")
getinput()
print(stuff)
Or you could use global keyword | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -1,
"tags": "python, google colaboratory"
} |
Flex dynamic form height
I'm not sure if this is possible, is there a way to get the `<mx:Form>` to set its own height based on the position of an element within it?
For example something like this:
<mx:Form height="{submitBtn.y + submitBtn.height}">
<mx:FormItem>... </mx:FormItem>
<mx:FormItem>... </mx:FormItem>
<mx:FormItem>... </mx:FormItem>
<mx:FormItem>
<s:Button id="submitBtn" label="Submit" />
</mx:FormItem>
</mx:Form>
where the form `height` is dynamically set based on submitBtn's y position and its height.
I tried using Alert.show to show these values and turned out `submitBtn.y = 0` and `submitBtn.height` = 21. height sounds reasonable, but I know the `submitBtn.y` can't be 0 since it's below several other
Is it possible to set the form height dynamically? | Yes. Do it in the measure method:
private var n:Number = 0;
override protected function measure() : void {
super.measure();
if (submitBtn) {
var fi:FormItem = FormItem(submitBtn.parent);
n = fi.y + fi.height;
}
}
Then just set the height to **n**.
Edit: I changed this to specify the containing FormItem, not the button, which is what I tested in my own sample code first. You can either get the button's parent or give that FormItem an ID. But this way does work. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "apache flex, actionscript, adobe, mxml"
} |
Scrollmagic setPin Method Causes Link issues in Create-react-app
I'm using Scrollmagic and GSAP in my create-react-app and pinning a section while child elements are animated on scroll. I've achieved this HOWEVER anytime I click on my nav links (using Reach Router) it goes to an empty/white page.
When inspecting elements in Chrome, the `<div id="root"></div>` is not fed any data which explains the empty/white page. If I refresh that page, it renders all content as expected. Additionally, it will also render if I comment out `.setPin('#scrollStarts')` line.
The empty/white page also throws the following errors:
Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.
Has anyone experiencing similar behavior and able to find solution? | I added a parent/wrapping `<div>` and it solved the issue. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "reactjs, animation, gsap, scrollmagic"
} |
How to set python generated table for each value in separate cells *.CSV
I am trying to generate _.CSV file (or_.txt). The script is simple. However, the generated *.CSV file is putting all values in one cell in each row. I want each value to be in separate cell. Kindly advise.
from tabulate import tabulate
nestedlist = [["Point 1",0,5,0],
["Point 2",0,0,0],
["Point 3",5,0,0],
["Point 4",5,5,0],]
with open('GCP.csv', 'w') as f:
f.write(tabulate(nestedlist, headers=['n','x','y','z'],tablefmt="plain")) | I suggest using `pandas`:
import pandas as pd
nestedlist = [["Point 1",0,5,0],
["Point 2",0,0,0],
["Point 3",5,0,0],
["Point 4",5,5,0],]
df = pd.DataFrame(nestedlist, columns=['n','x','y','z'])
df.to_csv('GCP.csv', index=False) | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "python, csv"
} |
get string between characters sed
I have a string
> abc\xyz\file.txt#4 - blah blah blah
I want the file number so I did the following -
> abc\xyz\file.txt#4 - blah blah blah | sed -e "s/[A-Z,a-z,\,/,.#:,-/s]//g"
It gives the expected output - 4
But when the string is -
> abc\xyz1\file.txt#4 - blah blah blah | sed -e "s/[A-Z,a-z,\,/,.#:,-/s]//g"
It gives the output as - 14.
So I was trying to get string between '#' and '-' I tried -
> abc\xyz1\file.txt#4 - blah blah blah |sed 's/^. _# //; s/-._ $//'
but it only works when there is space before #, which is not true in this case.
What am I doing wrong? | Try using
sed 's/.*#\([0-9]*\).*/\1/'
This searches for everything up to and including the `#, followed by zero or more numbers, followed by the remainder of the line. So the search string matches the entire line.
It then replaces the matching pattern (that is, the entire line) with the part that matches the sub-pattern between the escaped parens, which is the ~~droid~~ number you're looking for.
To print only the matching lines, use
sed -n 's/.*#\([0-9]*\).*/\1/p'
where the `-n` flag suppresses the default behavior of printing every line, and the `p` suffix prints the matching lines. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "sed"
} |
What is a Rack - "no acceptor" error?
While trying to run my config.ru, I'm getting an odd error I can't seem to debug called a 'No acceptor' error.
Full error message:
eventmachine.rb:572:in `start_tcp_server': no acceptor (RuntimeError)
Does anyone know what this error means? Thanks. | As @Fivell says, I think the problem is that you have a previous instance of `thin` still running. Rather than start on another port though, I would recommend killing the previous instance. Something like this should do the job (I recreated the problem here, so this is real output on my end):
telemachus caps $ ps ax | grep ruby
153 ?? S 7:52.18 ruby /usr/local/bin/djsd
15801 ?? S 0:00.40 ruby caps.rb # this is our problem, get it's PID
15973 s000 S+ 0:00.00 grep ruby
telemachus caps $ kill -9 15801 # thin needs -9 - hard to kill
telemachus caps $ ps ax | grep ruby
153 ?? R 7:52.86 ruby /usr/local/bin/djsd
16057 s000 S+ 0:00.00 grep ruby
Depending on how you started your app, you may need to `grep` for something different (say if you used `shotgun` or `rackup`). | stackexchange-stackoverflow | {
"answer_score": 12,
"question_score": 8,
"tags": "ruby, rack, thin"
} |
Using Template For Returned JSON Data From Server
I was looking at the Window component documentation. There is a request option called "template". I am assuming this template can be used to format JSON data returned from the server. So, the template I used was the following:
"#= html #"
The data returned from the server is something like:
"html": "<span>Hello world!</span>",
"instanceId": "10A",
"data": null
However, I always get a Javascript error that says "ReferenceError: html is not defined".
Any ideas why html is not defined though it comes in the response body?
Regards. | You should specify that the return data type is json.
Example:
$("#win").kendoWindow({
content: {
url : "/getData",
template: "#= html #",
dataType: "json"
}
}); | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "kendo ui"
} |
How do I access other users' AWS Lambda Test Events as root user?
So I'm logging into AWS using my main account as the root user (which may or may not be a bad idea ultimately, but for now it's fine). When I head over to the Lambda and look at Test Events, I cannot see the test events that other IAM users have created. It would make sense that an IAM user couldn't see the root user's assets, but I'm confused as to why I as root user don't have access to their assets.
In short, I want to be able to run tests using the events someone else created (and vice versa), but I can't see them. I don't want myself (and anyone else) to have to replicate all tests that others create since they are useful for all of us in collaboration and testing.
It seems weird that I can access/edit/run the Lambda functions etc, but not the test events. I also tried creating a new IAM user and copying the permissions of another user and I still don't have access to their test events.
Thanks! | The Lambda test events are specific to a logged-in console user and cannot be shared across users.
If I recall, these events were originally stored in browser local storage which meant that a given user couldn't go to another browser or another machine and retrieve the events. That changed with this Improved Testing on the AWS Lambda Console announcement and now they are persistent for the logged-in user so you can go to another browser or machine. But they're not sharable and, afaik, there is no API that will retrieve them for you.
A better solution, in my opinion, would be to revision-control a small number of scripts that invoke Lambda functions with known payloads. This could be part of your repo's test suite and shared across a team. | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 3,
"tags": "amazon web services, aws lambda"
} |
Javascript - canvas - drawImage does not work
I have read all the other similar posts but I don't understand why it I have this problem.
I have a canvas (#canvas) and an image (hero.png) on the page, and a JS file loaded at the end of the body. In the JS code...
This works:
var game = {};
game.canvas = document.getElementById('canvas');
game.ctx = game.canvas.getContext("2d");
game.draw = function(){
game.ctx.drawImage(game.hero, 200, 200);
}
game.hero = new Image();
game.hero.src = "hero.png";
game.hero.onload = game.draw;
And this doesn't work:
var game = {};
game.canvas = document.getElementById('canvas');
game.ctx = game.canvas.getContext("2d");
game.hero = new Image();
game.hero.src = "hero.png";
game.hero.onload = game.draw;
game.draw = function(){
game.ctx.drawImage(game.hero, 200, 200);
}
Nothing appears. No error in the console. Why???
Thanks! | You can call functions before define them only with this syntax:
function draw()
{
//COde here
}
By writting
game.draw = function(){};
You define a method to your object, you don't define a JavaScript function: that's why you can't call it before define it :) | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "javascript, html, canvas, drawimage"
} |
Play framework Application installation
I need to host and run my play application in a normal pc not in a server. what are the things(software/applications) I need to install in that pc and Is it possible to to? and I know Play has in-build Netty Server. Please help me to do this | If you only have the application to run on a PC I assume somebody has compiled and packaged the application for you. There are several ways how a Play app can be packaged.
For example if it has been packaged as a ZIP file, unzip it on the PC to an empty directory. It should then contain directories like `bin`, `conf`, `lib` and maybe more. The `bin` directory contains a file with the ending `.bat`. Run this file, e.g. `C:\appdirectory\bin\appname.bat`.
Make sure that the PC has the required Java Runtime Environment installed (e.g. Java 8).
You can find further instructions in the Play documentation. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "scala, playframework"
} |
Execute event on first click only
I’m trying to execute the below click(function) only on first click, but it always executes whenever I click on the map. Is it possible to use One-Click with the below code ? Thanks in advance
var placedMarkers = 0;
var availableMarkersToPlace = 1;
setTimeout( function(){
if(placedMarkers >= availableMarkersToPlace)
return;
placedMarkers++;
var map = Appery("google_map").gmap;
google.maps.event.addListener(map, 'click', function(event) {
localStorage.setItem('selectedLat', event.latLng.lat());
localStorage.setItem('selectedLng', event.latLng.lng());
placeMarker(event.latLng,map);
alert(event.latLng);
});
}, 1000); | Just create flag-value, which will decide, run your function or skip:
var placedMarkers = 0;
var availableMarkersToPlace = 1;
var clicked = false;
setTimeout( function(){
if(placedMarkers >= availableMarkersToPlace)
return;
placedMarkers++;
var map = Appery("google_map").gmap;
google.maps.event.addListener(map, 'click', function(event) {
if(!clicked) {
clicked = true;
localStorage.setItem('selectedLat', event.latLng.lat());
localStorage.setItem('selectedLng', event.latLng.lng());
placeMarker(event.latLng,map);
alert(event.latLng);
}
});
}, 1000); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -2,
"tags": "jquery, google maps"
} |
Deletions don't show up in the profile's activity tab
I just deleted an answer of my own that should have been a comment. I would have expected a deletion action to show up in the activity tab of my profile, but there isn't.
What's the rationale to ignore deletions in the activity?
PS: I know now that I also could have flagged the answer for conversion into a comment, but it was an old and inactive question, so no need. | No deleted content appears in user profiles, not even for 10k users. Only diamond mods can see those posts right in the profile. (Not saying this is necessarily the behaviour we'd like, but that's what happens.)
The reason why it's done this way is because deleted content is considered as "never having been created in the first place." This is also why a reputation recalc does not count reputation earned or lost on deleted content. | stackexchange-meta | {
"answer_score": 2,
"question_score": 3,
"tags": "support, deleted answers, self delete, activity"
} |
How to use string.Endswith to test for multiple endings?
I need to check in `string.Endswith("")` from any of the following operators: `+,-,*,/`
If I have 20 operators I don't want to use `||` operator 19 times. | If you are using .NET 3.5 (and above) then it is quite easy with LINQ:
string test = "foo+";
string[] operators = { "+", "-", "*", "/" };
bool result = operators.Any(x => test.EndsWith(x)); | stackexchange-stackoverflow | {
"answer_score": 57,
"question_score": 31,
"tags": "c#, string"
} |
GBM in R giving negative numbers?
I was under the impression that simulations involving geometric brownian motion are not supposed to yield negative numbers. However, I was trying the following Monte Carlo simulation in R for a GBM, where my initial asset price is: $98.78$, $\mu = 0.208$, $\sigma = 0.824$. I initialized my dataframe as such: (I am just doing 1000 simulations over 5 years, simulating the price each year)
V = matrix(0, nrow = 1000, ncol = 6)
V_df = data.frame(V)
Then:
V[, 1] <- 98.78
I then perform the simulations (with $dt = 1$):
for (i in 1:1000) {
for (j in 1:5) {
V_df[i,j+1] <- V_df[i,j]*(mu*dt + sigma*sqrt(dt)*rnorm(1)) + V_df[i,j]
}
}
When I then check $V_{df}$ there are many negative entries. Would anyone have an idea as to why this is so?
Thanks. | With such a large time step (annual), you would be far better off using the exact GBM solution rather than discretizing what is technically only valid in an infinitesimal sense.
So you'd use $V_{t_2} = V_{t_1} . e^{(\mu-\frac{\sigma^2}{2})(t_2-t_1)+\sigma(W_{t_2}-W_{t_1})}$
Where $W_{t_2}-W_{t_1} \sim N(mean=0,var=t_2-t_1)$
You would then have positive values only.
The downside is the exponential takes a little more time to calculate, but I assume that is a secondary concern here. | stackexchange-quant | {
"answer_score": 3,
"question_score": 1,
"tags": "programming, monte carlo, brownian motion"
} |
Coinbase API call to get crypto spot prices
Just started exploring CoinBase APIs.
I found that
* there is a new set of APIs under the umbrella of Coinbase Cloud: <
* there is an older(legacy?) set of APIs known as Coinbase Digital API: <
I need to programmatically fetch current spot price for certain cryptocurrencies, I found an endpoint for this in the old API: <
Is this the correct API call to get the prices? Is there an equivalent endpoint in one of the new Coinbase Cloud APIs? | you can use the spot price api
<
example: <
or you can use the ticker api (I think this is the better option)
<
example: < | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "coinbase api"
} |
Get all ModelState Errors on view
At my Controller I add some ModelState Errors. So, when I render my View, I want to get all these Errors and change the color of the labels of the fields that contain a error.
So, I think I need to get all the ModelState Errors, get the field names and then change the color. This is the a good way?
How can I get the ModelState Errors in my view? | You can access it through `ViewData.ModelState`. If you need more control with errors on your view you can use
`ViewData.ModelState.IsValidField("name_of_input")`
or get a list of inputs with errors like this:
var errors = ViewData.ModelState.Where(n => n.Value.Errors.Count > 0).ToList(); | stackexchange-stackoverflow | {
"answer_score": 31,
"question_score": 19,
"tags": "c#, html, asp.net mvc 3"
} |
Sum exponentials
$$-\sqrt{\lambda}t-\lambda(1-e^{\frac{t}{\sqrt{\lambda}}})=-\sqrt{\lambda}t+\lambda(\frac{t}{\sqrt{\lambda}}+\frac{t^2}{2\lambda}+...)=\frac{t^2}{2}\text{ as lambda aprroaches infinity}$$
How did we get to $\frac{t^2}{2}$ | I got it now. Thanks Yves. Multiplying lambda into the brackets and subtracting the term outside we are left with $(\frac{t}{2}+....) $ all the other terms have lambda as the denominator. | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "sequences and series"
} |
Detecting a circle of a specific color (or gray level) with openCV
Is there a way to detect a circle with a specific grey level using openCV? I want to detect a circle that marks out from the others.
Currently, I'm using cvHoughCircles to detect my circles. I know the method returns an array of cvSeq containing the info on each circle (point and radius), but it does not provide any color information.
Thank you | You should first isolate the colour you want, and then do a houghcircles on that image.
Say you want to find green circles from a bunch of green, red and blue circles. Its simple in this case, just threshold the green channel. You'll get only the green circle in the thresholded image. Do a sobel/canny on it and execute houghcircles. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 3,
"tags": "image, opencv, detection, geometry"
} |
What's the easiest way to duplicate a column?
Currently, I'm getting the ID of the column via a select statement and insert all the returned values (except the ID).
Is there an easier way to do it? | I don't know Oracle one bit, but there should be an equivalent to
INSERT INTO TABLENAME select * FROM tablename WHERE id = x | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "php, oracle, duplicates"
} |
is there any way to show all info windows on Maps API v2?
So, as in title: is there any way to show all info windows on Maps API v2?
I've read that it cannot show only one at the same time.
Thanks! | Nope.
According to the docs, only 1 info window is shown at a time.
But you can have a custom marker which looks like an info window.
> An info window allows you to display information to the user when they tap on a marker on a map. By default, an info window is displayed when a user taps on a marker if the marker has a title set. **Only one info window is displayed at a time.** If a user clicks on another marker, the current window will be hidden and the new info window will be displayed. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 2,
"tags": "android, google maps"
} |
Can I apply the brutal property to Power Strike / Furious Assault?
Both Power Strike and Furious Assault add extra [W]'s of damage to an attack.
If the weapon being used is Brutal, does the brutal property extend to the additional [W]'s added from these powers? | Yes. Anytime you roll dice from a [W] you get to apply brutal. You even get to apply it when you roll high crit [W] dice. | stackexchange-rpg | {
"answer_score": 4,
"question_score": 2,
"tags": "dnd 4e"
} |
Unknown meaning of colon ( : ) in assembly instruction
I'm using a disassembler (SmartDec: < and the many of the instructions in the generated disassembly look similar to this:
mov rax, [rip + 0x32b5]:64
I'm unfamiliar with the `:64` part of this instruction. What does it mean?
Other examples:
cmp [rcx + r8 * 0x8]:64, 0x0
mov eax, [rip + 0x592a]:32
jmp [rip + 0x6bad]:64
This disassembler doesn't show the corresponding machine code, so I used a hex editor and looked up the address that it said this instruction was at:
1665: mov rax, [rip + 0x19a4]:64
This is what was there, 16 bytes worth, in Little Endian:
54 00 00 49 89 E8 FF 15 DC 5F 00 00 E9 57 FF FF | It's the size of the memory operand, printed for whatever reason. I have deduced it from an example on the SmartDec home page which reads as `movzx edx, [ecx]:16` As such this is just the equivalent to what would be `movzx edx, word [ecx]` in other assemblers (or `word ptr`). It is only useful if the size can not be deduced from the other operand, as in this `movzx` case. `SmartDec` seems to be showing it every time though, e.g. for your example in the question, `mov rax, [rip + 0x32b5]:64` it's clear that the size is 64 bits so it's not helping much. | stackexchange-stackoverflow | {
"answer_score": 9,
"question_score": 4,
"tags": "assembly, x86, x86 64, disassembly"
} |
IIS does not list a website that matches the launch url
I need to debug the website i 'm developing (ASP.NET MVC3, Razor, .NET 4, VS2010 SP1 (as administrator)) in IIS7 (Vista Home) and getting the error:
IIS does not list a website that matches the launch url.
To test if it has to do something with the settings of the app, i did create from scratch an empty new ASP.NET MVC3 website, set for IIS, created virtual directory, launched with F5 and i worked fine!
I again did create a second website project with the exact same settings (just to be sure) and this also launched as expected.
This leads my to think that i have some configuration problem!? But what? In the past i used IIS very rare, so my knowledge is somehow limited in this direction.
Any hints? | I hate answering my questions: in my question i stated that i was running VS under the administrator account. **This was not true**!!!
So the solution (for me) was to run VS2010 as administrator (Start->In Vista menu right click-> Run as administrator)...so simple.
As a side effect: VS2010 let me also create Virtual Directories without any problems (prior to that i got error messages stating that i have to manually adjust these) | stackexchange-stackoverflow | {
"answer_score": 355,
"question_score": 181,
"tags": "visual studio 2010, debugging, iis 7, windows vista"
} |
A weird symbol related to Sobolev spaces on manifolds
Can someone tell me what the following mathematical symbol is?
: (followed by p over k, but that's not the issue, I understand.)
Quick MWE, showing two ways:
\documentclass{article}
\usepackage{amsfonts}
\usepackage{fontspec}
\newfontfamily{\mathfont}{NotoSansMath}
\begin{document}
$\mathfrak{E}$ vs. {\mathfont\symbol{"1D508}}
\end{document}
? | Yes, there is a single boot.ini file, usually located in C:\Windows.
You can check it from System configuration Utility: Start menu -> Run and type `msconfig.exe`
!alt text | stackexchange-superuser | {
"answer_score": 2,
"question_score": 2,
"tags": "windows, hard drive, multi boot, boot.ini"
} |
Google News RSS Feed -
Trying to get just a text description out of this good news feed, i dont' want the html but i can't find a common way to split it out..
| If you know how to get the HTML data from the right XML-element (`<description>` in this case) you can just strip all HTML with PHP's strip_tags
This seems to work like you want it:
$news = simplexml_load_file('
foreach($news->channel->item as $item) {
echo $item->title . "\n";
echo strip_tags($item->description) ."\n";
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, xml, rss, google news"
} |
Functions completion handler Swift 4
How i can return error and completion result and call my function like that? What should i write in my function, to return completion result and error if there are any?
example:
signIn(withEmail: emailTextField.text!, password: passwordTextField.text!) { (user, error) in
if error == nil {
self.performSegue(withIdentifier: "loginToHome", sender: nil)
} else {
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
}
}
my function to edit:
static func signIn(email: String, enablefor: String,
func: String, completion: @escaping ((User) -> Void)) | Declare it like this:
`completion: @escaping ((User?, Error?) -> Void)`
Inside your function:
`completion(user, nil) // when you have user`
`completion(nil, error) // when you have error`
On the completion block call:
completion: { user, error in
if let error = error {
// handle error
}
if let user = user {
// handle user
}
} | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "swift, function"
} |
iPad - Popover with table view - show details on tap of cell
In my iPad application, on click of a button "Show" it will show 7 cells which has "Favorites". On taping that, I want to push a new table view controller which shows the list of favorite items. But I want the new table view pushed in the same pop over without closing it. Also it will have "back" button on the top left to go back if needed.
It is something like "book marks" button click in "Amazon Kindle". Is this possible? | Sure you got a few options
1- Use a UINavigationController as the root of the view hiarchy in the popover, then just use that to push and pop view controllers as needed
2- Just use a UIViewController and add or remove the subviews as need (use a toolbar for your back button)
I would probably go for option 1...
Daniel | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "ipad, uipopovercontroller"
} |
Determine if $\lvert\sin(x)\rvert$ is differentiable
**Question**
Part (a)
Given the function $$f:\Bbb R\to \Bbb R$$ defined by $$f(x)=\lvert\sin(x)\rvert$$ determine where $f$ is differentiable and find its derivative
My initial idea was to substitute $f(x)$ into the $$\lim_{x\to c}\frac{f(x)-f(c)}{x-c}$$ but I don't know where to go from after substituting this in, I know the answer is $$\frac{\sin(x)\cos(x)}{\lvert\sin(x)\rvert}$$ and it's differentiable for all $x\ne n\pi$ where $n\in \Bbb Z$.
Part (b)
Let $m,n\in \Bbb N$. Given the function $$g:\Bbb R\to \Bbb R$$ defined by $$g(x)= \bigl(\sin(x^m)\bigr)^n$$ show that $g$ is differentiable and find its derivative.
My thought process was to show that the limit exists again which in turn show that $g$ is differentiable and would also give me the derivative, however would I need to check both the right and left hand side limits as $x$ approaches $c$ and if there both the same then the derivative exists right? | The simple answer is to use the chain rule:
$$\frac{d}{dx}\Big[|x|\Big]=\frac{x}{|x|}$$
With $u=|\sin(x)|$
$$\frac{d}{dx}\Big[|\sin(x)|\Big]=\frac{d}{du}\Big[|u|\Big] \cdot \frac{d}{dx}\Big[\sin(x)\Big]=\frac{u}{|u|} \cdot \cos(x)=\frac{\sin(x)\cos(x)}{|sin(x)|}$$
Now, if you want an explanation of why $\frac{d}{dx}\Big[|x|\Big]=\frac{x}{|x|}$, keep reading.
$|x|$ can be defined in two ways.
The usual way is to use a piecewise function, but there is a much more intuitive way.
$$|x|=\sqrt{x^2}$$
Boom. We can now use a super simple application of the chain rule which you could do yourself.
$$\frac{d}{dx}\left[\sqrt{x^2}\right]=\frac{2x}{2\sqrt{x^2}}=\frac{x}{\sqrt{x^2}}=\frac{x}{|x|}$$
Edit: If you want a proof of $|x|=\sqrt{x^2}$, just use that as your definition of $|x|$, that's what I do. | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "real analysis, derivatives"
} |
How can i print json file that is produced from ParseHub on screen?
I use ParseHub to get data from an Ajax-based website. The data is returned in json file format. I have been struggling to print returned json file for hours, but could not be successful. Here is my php code:
<?php
header('Content-Type: application/json;charset=utf-8');
$params = http_build_query(array(
"api_key" => "xxxxx",
"format" => "json"
));
$result = file_get_contents(
'
false,
stream_context_create(array(
'http' => array(
'method' => 'GET'
)
))
);
echo $result;
?>
By the way, json_decode() function didn't work. Can anyone help me?
UPDATE: I uploaded code and output of the code. You can check to give some ideas.
Code -> this link Output -> this link | From the ParseHub API documentation:
> The Content-Encoding of this response is always gzip.
Try to use gzdecode function for your $result variable. And then decode it with json_decode().
Note that it requires PHP 5 >= 5.4.0 or PHP 7 version. Also you can try to use Parsehub REST api wrapper class. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "php, json, parsehub"
} |
How does @MTOM ensures file integrity when uploading/downloading file?
When using JAX-WS @MTOM to transfer a file, does it have a build-in file integrity check? Or you have to do it on your own after the download/upload is completed? | it relies on the "implicit" integrity of TCP. There isn't a layer above that within the actual protocol. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "web services, jax ws, mtom"
} |
Efficient Downloading methods
Requirement : In an app, During the first launch it is required to download all the images and data from the remote server and store them into sdcard and local sqlite database respectively. And, in the later times, the app works locally without network connection.
So, the `HTTP` response comes in `JSON` format and it needs to be parsed and stored into the database and the after parsing `JSON` I will get the image paths which needs to be downloaded and stored into the sdcard.
Currently, I am thinking to implement this using an `AsyncTask` for respective API calls. Please let me know if there any other efficient alternatives OR if there are any sample source codes doing similar task. TIA... | If it really needs to be separate files you can use the Download Manager.
But I would recommend packing and compressing everything into one archive file and download that.
Maybe you can use an Expansion File?
If you decide to use an AsyncTask be aware that depending on your targetSdkVersion (>11) and Android Version (>4.0) it might not run multithreaded without setting a thread pool executor. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "android, download, android asynctask"
} |
Should I use ipairs or a for loop
I have read that the use of ipairs is slow compared to a for loop, should I change my programming habit? I'll be using lua 5.2 one day, currently 5.1.
My arrays are approximately 1000 items at most.
local mytbl = { 'a','b','c','e'}
for i,v in ipairs(mytbl) do
print(i,v)
end
for i=1,#mytbl do
print(i,mytbl[i])
end | <
pairs: 3.078 (217%)
ipairs: 3.344 (236%)
for i=1,x do: 1.422 (100%)
for i=1,#atable do 1.422 (100%)
for i=1,atable_length do: 1.562 (110%)
Note, however, that using a numerical `for` loop only works if you're iterating over tables with sequential numeric indices - if you're using hash keys for your tables, or sparse tables, then you'll need to use some form of `pairs()`. | stackexchange-stackoverflow | {
"answer_score": 31,
"question_score": 20,
"tags": "lua"
} |
Reduce Map values concurrently
I have Map of String keys and Seq[Int] values. How can I reduce the Seq[Int] to single Int value concurrently for each key.
for example:
Map("xxx" -> (1 to 10), "yyy" -> (100 to 200))
should be reduced to
Map("xxx" -> 55, "yyy" -> 15150)
concurrently for each key in the Map. | You can use parallel collections both for the Map and the Range e.g.
val x= Map("xxx" -> (1 to 10), "yyy" -> (100 to 200))
x.par.map{case (a,b)=>(a,b.par.sum)} | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "scala, concurrency"
} |
How to call another classes super class?
Lets say I have three classes, A,B,C. B inherits A, is there a way to access the getVal method of Class A, in C?
class A {
getVal method
}
class B extends A {
}
Class C {
main() {
B x = new B
x.getVal?
} | Yes. Assuming the classes remain in the same package - x.getVal will work.
class A {
String getVal(){
return "from a";
}
}
class B extends A {
}
public class C {
public static void main(String [] args) {
B x = new B();
x.getVal();
}
}
It works - because of the default access modifier. Use the `protected` access modifier for inheritance. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -4,
"tags": "java, oop, inheritance"
} |
Difference between Memory and Storage?
What is the difference between Memory and Storage ?
From both the EVM point of view and the contract design one.
Thanks! | They are analogous to memory and hard drive storage in a computer. The contract can use any amount of memory (as long as it can pay for it of course) during executing its code, but when execution stops, the entire content of the memory is wiped, and the next execution will start fresh. The storage on the other hand is persisted into the blockchain itself, so the next time the contract executes some code, it has access to all the data it previously stored into its storage area. | stackexchange-ethereum | {
"answer_score": 34,
"question_score": 39,
"tags": "contract design, evm, storage, memory"
} |
How should breadcrumbs be marked up? Are lists appropriate?
Trying to work out how best to mark up a breadcrumb area on my page and I'm not sure how I should contain it. In my mind there are three options:
### Option 1 - Just Links
<nav>
<a ...>Link 1</a>
/
<a ...>Link 2</a>
/ ...
</nav>
### Option 2 - An Ordered List
<nav>
<ol>
<li>
<a ...>Link 1</a>
</li>
<li>
...
</li>
...
</ol>
</nav>
### Option 3 - An Unordered List
<nav>
<ul>
<li>
<a ...>Link 1</a>
</li>
<li>
...
</li>
...
</ul>
</nav>
Which would be the best to use? | As this source suggests, this is the recommended markup:
<map title="Breadcrumbs">
<a href="/">Home</a>
> <a href="/foo">Foo</a>
> <a href="/bar">Bar</a>
</map>
The links are part of the G65, which states:
> Breadcrumb trails are implemented using links to the Web pages...
The `<map>` tag is from H50.
Yet, you may wish to consider what seems to be a more popular markup, using `<nav>` instead of `<map>`:
<nav title="Breadcrumbs">
<a href="/">Home</a>
> <a href="/foo">Foo</a>
> <a href="/bar">Bar</a>
</nav>
Breadcrumbs are definitely not lists (ordered or not) since they are just a path within an hierarchy. A list involves siblings, which are not part of breadcrumbs. | stackexchange-ux | {
"answer_score": 0,
"question_score": 0,
"tags": "website design, html, semantics"
} |
Numerical computation of Skorokhod integral
How can I numerically compute the Skorokhod integral of a non-adapted process? If it is adapted, that is easy since the integral is just an Ito integral.
I have found that computing the Malliavin derivative is also easy using finite differences, by bumping the Brownian path at a time t. But I can't figure out how to achieve the inverse operation.
Thank you | If you are looking for approximations of the Skorohod integral we can use Wick Riemann sums.
Define for $F \in \mathbb{D}^{1,2}$ and $W$ a Wiener process the Wick product $F \star W_t$ by
$F \star W_t=FW_t -\int_0^t D_s F ds$
then the Skorohod integral $\delta (u)$ of a possibly non-adapted process $u$ is the limit in $L^2$ of the forward Wick Riemann sums
$ \sum u_{t_i} \star (W_{t_{i+1}} -W_{t_i}) $ | stackexchange-mathoverflow_net_7z | {
"answer_score": 4,
"question_score": 3,
"tags": "stochastic processes, stochastic calculus"
} |
Is there a notion of "base" $\mathcal{B}$ for a site, and "$\mathcal{B}$-sheaf", such that a presheaf is a sheaf iff it is a "$\mathcal{B}$-sheaf"?
For a base $\mathcal{B}$ for the topology on a topological space $X$, there is the notion of a presheaf on $X$ being a "$\mathcal{B}$-sheaf", and a presheaf on $X$ is a sheaf iff it is a $\mathcal{B}$-sheaf.
I was wondering, is there a similar notion for sites? I.e., is there such a thing as a "base" $\mathcal{B}$ for a site or a Grothendieck topology, and a notion of a presheaf being a $\mathcal{B}$-sheaf which depends only on the values of the presheaf on $\mathcal{B}$, such that a presheaf is a sheaf iff it is a $\mathcal{B}$-sheaf.
* * *
Large sites provide some motivating examples; e.g., is it possible to say (perhaps with some conditions) that a sheaf on the site of smooth manifolds is determined by e.g. its values on just the Euclidean/Cartesian spaces? | As user Zhen Lin explains in the comments, the notion I was looking for is a dense sub-site. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "category theory, sheaf theory, grothendieck topologies"
} |
Passing ng-change to directive
We have a directive which consists of the select element as shown below
<select class="form-control" ng-if="type === 'select'" name="{{ bsName }}" id="{{ bsName }}"
ng-model="$parent.ngModel" ng-change="$parent.ngChange" ng-options="(item.label || item) for item in items" ng-selected="(item.value && $parent.ngModel == item.value) || $parent.ngModel == item">
and in our view we use it as below
<bs-input type="select" items="cars" bs-name="car" bs-label="Car" ng-model="criteria.car" bs-errors="errors" ng-change="onChange()"/>
But the onChange() doesn't get triggered when I am select a different value from the list. Is passing it as
ng-change="$parent.ngChange"
correct? Am I missign something?
Note: When I don't use a directive and have the select directly in my view everything works fine. | Calling `$parent.ngChange` will try to access the property ngChange on the parent scope. The `ng-change` _attribute_ on the bs-input is something completely different.
What would probably work is calling `$parent.onChange()`, as you're now calling the function directly. However, I hope you see the drawback here, as we're then hardcoding the function which you want to call, which is not your intention.
Also, I'm assuming that you're using an isolate scope in the directive, in which case calling $parent makes no sense (it works, but you want the directive to be independant of parent scopes).
You can look into using $parse to get the function passed through from the outside scope. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "angularjs, angularjs directive"
} |
reject to add arguments in the color type
I am working on painting line, I faced a basic problem with changing the color :S:S
I have the following code, I got an error in the last line of code I cant add argument to new Color(???) >> I cant add the R, G, B color numbers
Paint paint = new Paint();
Random random = new Random();
int R = (int)(Math.random()*256);
int G = (int)(Math.random()*256);
int B= (int)(Math.random()*256);
paint.setColor(new Color(R , G , B)); | You can't create a `Color` object like that. `Color` is just a static Android helper class that handles color-based operations.
Try this:
paint.setColor(Color.rgb(R , G , B));
For reference, see the `Color.rgb(...)` method. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "java, android, animation, colors, paint"
} |
What is difference in -5 and numbers smaller than -5 in python
I've just started to learn so i was just messing in interpreter and found some weird outputs that I couldn't understand. This is what I did and what i got:
c = -5
c is -5
True
c = -6
c is -6
False
This happened for all values smaller(more negative) than -5. What am I missing?
Here's a screenshot of interpreter | You should check out the differences between "is" and "=="
You can see this addressed here Is there a difference between "==" and "is"? | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "python, python 3.x"
} |
Why can questions be closed for being "too localized"?
> **Possible Duplicate:**
> What questions should be closed with reason “too localized”?
I realize that the point of that criteria is that questions should be helpful for other users, as well as answering the question. But isn't the primary purpose of stackoverflow to be a question and answer site? Why is a question considered unacceptable simply because it is only relevant to the asker? For example, this post: < I fail to see why that post should be closed, simply becaus it's unlikely that anyone else will need to know that information. | Closing isn't the same as not-allowed or not-answered. The asker still gets to see the solution, even if the question's deleted for everyone else in the end.
Often this happens to avoid cluttering up the site with questions that are too niche - often the question is closed after it's answered. For example, if you ask me the bug in your code, but your code is convoluted and your program does something unusual, that's worth closing because no-one else needs that solution.
Sometimes it's human error - someone reads the question and thinks "Who would want to know that?" and votes to close when maybe a lot of people who think rather differently do want to know that. Sorry about when this happens.
(If the bigwigs at Meta agree it shouldn't have been closed, it might be re-opened.)
See this answer for good reasons for "too localised". | stackexchange-meta | {
"answer_score": 2,
"question_score": 2,
"tags": "discussion"
} |
sorted array, how many comparisions to find if element in
I have a sorted array, and a number, how many maximum comparisons should I do to find if the number is contained in the array ?
Suppose we have a million of numbers in the array. | To complete the answer from @aponeme, the maximum number of comparisons is equal to
2*upper(log2(n))
The reason is that the size of the array you examine is equal to
n, n/2, n/4, ...n/(2^steps).
Then the maximum number of steps is such that
n/(2^nsteps) = 1, i.e. nsteps = log2(n) | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": -1,
"tags": "algorithm, sorting"
} |
I have tried the general methods of ODE solving and Laplace transform and yet can't seem to get an answer!
This is the question
So, I tried solving this question (in the above link) and I ended up with a differential equation which i could not solve with laplace tranforms or by any other means known to me, I need help to solve the differential equation which now looks like this:
mx"= eE + (e/c)Hy'
my"= -(e/c)Hx'
where e=electric charge c=speed of light E=electric field H=magnetic field
and they are basically constants .
As I have said, I went through the general methods of ODE solving as well as Laplace transforms but none were able to give me the correct answer. | Integrate $\quad my''=-\frac{e}{c}Hx'$ $$my'=-\frac{e}{c}Hx +0$$ The integration constant is $0$ because zero initial velocity and displacement. $$mx''=eE+\frac{e}{c}Hy'=eE+\frac{e}{c}H(-\frac{e}{m\:c}Hx)$$ $$x''+\left(\frac{e}{m\:c}H\right)^2 x=\frac{eE}{m}$$ Let $\omega=\frac{e}{m\:c}H$ $$x''+\omega^2x=\frac{e}{m\:c}H$$ I suppose that you can solve it for $x(t)$ and then compute $y(t)$. This will give you the expected result. | stackexchange-math | {
"answer_score": 0,
"question_score": 0,
"tags": "ordinary differential equations"
} |
Activity destroyed after 1 hour
I'm new to Android development. I'v developed an android application which needs to store the connection/data even after 1 hour. Currently I have all the data and the connections(chromecast mediaplayer) in a singleton class. But, when the user puts the app into the background for about an hour, the activity is destroyed so the connections,data etc are lost causing my app to crash when re-launched.
I've read up on the android services, Can I use these services to hold the singletons so even when the activities are destroyed I can have data binded back to the views when re-launched?
Or is there a way to make sure that the activities are not destroyed when android decides to do a cleanup? Please advise
Thanks. | Android O.S can destroy any activity , when it is low at resources it destroys any activities to make more space for other apps. But you can use background service to hold your singleton
You can use this link to create your background service | stackexchange-stackoverflow | {
"answer_score": -1,
"question_score": 0,
"tags": "android, android activity, android service"
} |
Method over Boolean array should return true if any value in the array is true
This code works very well:
def is_rel_prime?(*args) #1
test = args.combination(2).to_a #2
test.map! { |a,b| a == Rational(a,b).numerator } #3
test.reduce (:&) #4
end
> is_rel_prime?(3,4,5) #=> true
> is_rel_prime?(7,12,14) #=> false
> is_rel_prime?(7,12,15) #=> false
What do I replace the (:&) with so that it will return 'true' if ANY ONE (or more) of the array elements is 'true'? | Your code there is testing `bool & bool & bool`. `Boolean#&` is equivalent to `&&` in general usage. As you might suspect, the corollary here is `Boolean#|`, which is equivalent to `||` in general usage. So, in your code, you would use `test.reduce(:|)` to decide if any boolean in the list is true.
That said, Cary is correct in that Ruby already has facilities for checking the truthiness of any value in an enumerable, via `Enumerable#any?` (and can check the truthiness of all values via `Enumerable#all?`), so you should just use those rather than rolling your own checker. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 3,
"tags": "ruby, boolean operations"
} |
Editing Loop So It Targets Specific Tags?
Confused on how to achieve this, but what I'm trying to do is load posts with the tag "reviews" in the loop on the homepage.
Index.php:
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
get_template_part( 'content-reviews', get_post_format() );
?>
<?php endwhile; ?>
<?php else : ?>
<?php get_template_part( 'no-results', 'index' ); ?>
<?php endif; ?> | Use the `pre_get_posts` action to modify the main query. Place this in your `functions.php` file:
function wpa71787_home_tag_query( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'tag', 'reviews' );
}
}
add_action( 'pre_get_posts', 'wpa71787_home_tag_query' );
You can set any valid parameters of `WP_Query` with this method.
Edit, secondary query excluding tagged posts, use tag ID:
$query = new WP_Query( array( 'tag__not_in' => array( 42 ) ) );
while( $query->have_posts() ):
$query->the_post();
// loop stuff
endwhile; | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, loop, tags"
} |
Reactjs function not being called
I'm implementing the Facebook SDK on my react project, however, I am new to React and I still don't grasp some concepts. I'm calling `handleFBLogin` when a user clicks on a button. This function then calls `checkLoginState` to continue my code's logic. I've already bound `checkLoginState` in the constructor using:
`this.CheckLoginState = this.checkLoginState.bind(this);`
I call this function on `handleFBLogin`, but checkLoginState doesn't seem to be called. I can see the `yes` on my console:
handleFBLogin() {
console.log("yes")
this.checkLoginState;
}
Here's the `checkLoginState` function:
checkLoginState(){
console.log("checloginstate")
window.FB.getLoginStatus(function(response) {
console.log(response);
this.statusChangeCallback(response);
}.bind(this));
}
Why isn't it being called? | It's possible you think to call the function without using parentheses as you do in the event like `onClick={this.yourMethod}`. It works because the react will handle it internally.
But calling a function from a method to another, you need to call the function using parentheses:
this.checkLoginState()
But wait! `this` will be undefined here if have not bind `this`. So, bind this inside your constructor:
this.handleFBLogin = this.handleFBLogin.bind(this)
* * *
Alternatively, you may use public class method:
handleFBLogin = () => {
this.checkLoginState() | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "reactjs"
} |
date-fns format(fromUnixTime(1584161862798), 'yyyyMMdd') invalid time value
I am using date-funs library to manage dates. ( version 2.12.0 ) I need to format unix datetime to 'yyyyMMdd'. And I am getting 'invalid time value' error.
fromUnixTime(1584161862798)
// Sat Feb 03 52170 22:13:34 GMT+0900 ( )
format(startDate, 'yyyyMMdd');
// invalid time value
I am nor sure why this is not working, when
format(new Date(), 'yyyyMMdd')
// 20200413
this works.
I tried to parse the date. It still returns the same error.
format(parseISO(startDate), 'yyyyMMdd');
// invalid time value
Thanks in advance. | format(new Date('yourUnixDateTime'), 'yyyyMMdd') | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 5,
"tags": "date fns"
} |
A probability to 6 in a dice
I have a question about probability of a dice:
I'm reading know about the history of probability and I'm reading about the chance to get $6$ at dice of $\\{1,2,3,4,5,6\\}$.
If you get $6$ you win, otherwise - you lose....
The question is, how many times you need to roll the dice to get a chance for a win that is greater then $\frac{1}{2}$.
The solution I read is: $$1-\left(\frac{5}{6}\right)^n$$ (and the answer is $n=4$...)
My question is:
Why the solution is not $$\frac{n}{6}$$ Because here also $n=4$ will give chance of getting win with more then $\frac{1}{2}$.
If you can explain me where is my mistake it will be great.
**::EDIT::**
I see what I missed! I need to use the Inclusion–exclusion principle
Now I'm understand where I wrong... :)
Thank you! | An easy way to see your solution is wrong is to evaluate it for $n = 6$ or $n = 7$.
Your answer gives a 100% chance of throwing a 6 after 6 throws - which is incorrect.
Your answer gives a _116%_ chance of throwing a 6 after 7 throws - which is even more obviously incorrect.
The deviation between your answer and the correct answer has to do with the fact that you can throw a 6 more than once. If we want to check the chance for $n = 2$, we can count the amount of cases where we threw a 6 on the first throw - $\frac{1}{6}$-th of them. Similarly, in one sixth of the cases we will throw a 6 on the second throw. However, the amount of cases where we threw a 6 on the first _or_ second throw is not $\frac{1}{6} + \frac{1}{6}$, because we counted the case where we threw a six on both the first throw and second throw twice. So
$$ P = \frac{1}{6} + \frac{1}{6} - \frac{1}{36} = \frac{11}{36} = 1 - (\frac{5}{6})^2.$$ | stackexchange-math | {
"answer_score": 4,
"question_score": -1,
"tags": "probability, probability theory"
} |
ask for app rating or review in Google Play, when uninstalling app
I vaguely fondly remember a time when Google Play (Google Store back then?) was pesturing me to leave a review every time I was uninstalling an app.
How can I enable this feature in Android 6? | This is a Google Play Store feature and is not dependent on the Android Version
Features of Play store which frequently change or sunset and there is no way to revert to earlier behaviour. For instance, Play Store asks for a review as mentioned here, a feature earlier not present Why has Google started asking questions when reviewing apps in Play Store? | stackexchange-android | {
"answer_score": 1,
"question_score": 1,
"tags": "google play store, google play services"
} |
Redirect this url permanently with .htaccess
I am trying to permanently redirect a url but it doesn't seem to work, this is what I have in the .htaccess file
RewriteEngine on
rewriteRule ^modules\.php?name=My_Page$ [R=permanent,L]
As you can see I want to redirect modules.php?name=My_Page to < I appreciate any help. Thanks | The path used in RewriteRule doesn't contain the querystring. Use
RewriteEngine on
RewriteBase /
RewriteCond %{QUERY_STRING} ^name=My_Page$
rewriteRule ^modules\.php$ /mypage? [R=permanent,L] | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": ".htaccess, redirect"
} |
Check whether Tensorflow is running on GPU
:
print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))
else:
print("Please install GPU version of TF")
the output should be
Default GPU Device: /device:GPU:0
GPU 0 is your GTX 860m | stackexchange-stackoverflow | {
"answer_score": 14,
"question_score": 6,
"tags": "tensorflow"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.