INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Combine two tables and search float +-10
I have two tables in a SQLite database - schools and persons.
Table: schools
+----------+-----+-----+
| name | X | Y |
+----------+-----+-----+
| School 1 | 100 | 40 |
| School 2 | 23 | 2 |
| School 3 | 98 | -50 |
+----------+-----+-----+
...and...
Table: persons
+----------+----------+----------+
| person | person_X | person_Y |
+----------+----------+----------+
| Person 1 | 95 | 42 |
| Person 2 | 24 | 4 |
| Person 3 | 98 | -10 |
| Person 4 | 160 | 111 |
+----------+----------+----------+
I want to list all persons where person_X and person_Y matches the X and Y in the school table +-10. So in this case I would like the result to be: Person 1 and Person 2 (because they are close to School 1 and School 2).
I have tried many ways, but get it only to work. Can someone please help me?
|
This just requires a join with criteria which checks the range overlap:
SELECT
p.person,
s.name
FROM persons p
INNER JOIN schools s
ON p.person_X BETWEEN s.X - 10 AND s.X + 10 AND
p.person_Y BETWEEN s.Y - 10 AND s.Y + 10;
touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.view endEditing:YES];
NSLog(@"touch began");
}
I didn't get any `NSLogs` when I taped elsewhere. What am I doing wrong?`
I then tried `self.view.userInteractionEnabled = YES;`, and `self.tableView`, and they both didn't work.
|
Your touches are probably being swallowed by the table view cells. Try putting your keyboard dismiss code in `tableView:didSelectRowAtIndexPath:` on your table view delegate instead.
EDIT:
Perhaps then you ought to use some combination of that and gesture recognizers:
UITapGestureRecognizer *navBarTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard:)];
[self.navigationController.navigationBar addGestureRecognizer:navBarTap];
UITapGestureRecognizer *tableViewTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard:)];
[self.tableView addGestureRecognizer:tableViewTap];
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ios, objective c, uitableview, uitextfield, touchesbegan"
}
|
Add property to object when it's not null
I'm working on a small API and I want to update the data using `HTTP PATCH REQUEST` without using a bunch of if statements. I'm trying to fill the outgoing data object with the changed data only.
update() {
let prop1 = hasBeenChanged.prop1 ? changedData.prop1 : null;
// ...
let propN = hasBeenChanged.propN ? changedData.propN : null;
let data: ISomething = {
// something like --> property != null ? property: property.value : nothing
}
}
Is there any way to create the data object dynamically?
|
You could use `Object.assign` in combination with the ternary operator:
let data = Object.assign({},
first === null ? null : {first},
...
);
This works because `Object.assign` will skip over `null` parameters.
If you are sure that the property value is not going to be "falsy", then it would be bit shorter to write:
let data = Object.assign({},
first && {first},
...
);
Assuming the object is going to be stringified at some point, since stringification ignores undefined values, you could also try
let data = {
first: first === null ? undefined : first,
...
}
|
stackexchange-stackoverflow
|
{
"answer_score": 61,
"question_score": 48,
"tags": "javascript, typescript, javascript objects"
}
|
Subsetting a vector using multiple conditions
> which(LETTERS=="A")
[1] 1
> which(LETTERS=="B")
[1] 2
Can i use one statement in which to get the value of 1,2?
which(LETTERS=="B" or "A")
Error: unexpected symbol in "which(LETTERS=="B" or"
|
which(LETTERS == "A" | LETTERS == "B")
Or:
which(LETTERS %in% c("A", "B"))
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 1,
"tags": "r"
}
|
What is the proper way to write to the Google App Engine blobstore as a file in Python 2.5
I am currently exceeding the soft memory limit when I try to do simple writes to the Google App Engine blobstore. What is the proper way to write this code so that it does not leak memory?
from __future__ import with_statement
from google.appengine.api import files
from google.appengine.api import blobstore
def files_test(limit):
file_name = files.blobstore.create(mime_type='application/octet-stream')
try:
with files.open(file_name, 'a') as f:
for x in range(limit):
f.write("Testing \n")
finally:
files.finalize(file_name)
return files.blobstore.get_blob_key(file_name)
files_test(4000) produces the error:
Exceeded soft private memory limit with 157.578 MB after servicing 27 requests total
|
Unfortunately python's garbage collector is not perfect. Every write you do creates lots of small objects (via protocol buffer creation) that is not collected by python on the fly for some reason. I found that in mapreduce library I have to do
import gc
gc.collect()
from time to time to keep garbage collector happy.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "python, google app engine"
}
|
Can't read attribute value of xml <media:content> tags
I'm trying to read the _media:content_ **url** , without success. How to do it?
> XML
<rss>
<item>
<media:content url="pizza.jpg">
<media:text>Pizza</media:text>
</media:content>
</item>
<item>
<media:content url="pasta.jpg">
<media:text>Pasta</media:text>
</media:content>
</item>
</rss>
> PHP
$xmlDoc = new DOMDocument();
$xmlDoc->load('file.xml');
$x=$xmlDoc->getElementsByTagName('item');
for ($i=0; $i<=2; $i++) {
$item_img=$x->item($i)->getElementsByTagName('media:content')->item(0)->getAttribute('url');
echo $item_img
}
|
Perhaps the worst of solutions:
> PHP
$xmlText= file_get_contents('file.xml');
$xmlText=str_replace('<media:', '<media', $xmlText);
$xmlText=str_replace('</media:', '</media', $xmlText);
$xmlDoc = new DOMDocument();
$xmlDoc-> loadXML($xmlText);
$x=$xmlDoc->getElementsByTagName('item');
for ($i=0; $i<=2; $i++) {
$item_img=$x->item($i)->getElementsByTagName('mediacontent')->item(0)->getAttribute('url');
echo $item_img
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "php, xml, dom, rss"
}
|
Deep copying a Java Map with values that are Sets
I have a map (`Map<String, Set<String>>`), and want to copy the map to a new map object. However, if I just feed the map to the say `HashMap` constructor (`new HashMap<String, Set<String>>(oldMap)`) it won't do a full copy, and only copies the reference to the set, which can be modified and those changes will be reflected in the new map.
Is there a more simply way of doing a full copy other than iterating over each key/value pair and creating a new `HashSet` for each set then adding that to the map?
|
There was some discussion on this here for deep cloning:
Java HashMap - deep copy
It's hard in this situation though as the new map and set need to rebuild themselves. Do you also need to clone the contents of the Set? If so then you could just serialize then de-serialize the whole collection.
Iterating yourself will almost certainly be faster and will let you control how deep the cloning goes. Serializing will be slower but so long as everything in the object tree is serializable it will copy everything in the object tree and maintain things like circular references etc. (For example if you had 2 keys in the map pointing to the same Set object then iterating will split that into 2 sets, serializing will maintain the link).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 6,
"tags": "java, dictionary, hashmap"
}
|
Spent vs Spending
What is the difference between,
> The three pie charts below show the changes in annual spent by a particular school in 1981, 1991 and 2001.
> The three pie charts below show the changes in annual spending by a particular school in 1981, 1991 and 2001.
1. Is _spent_ from the first one past participle?
2. Is _spending_ from the second one present participle?
Why don't we use _spent_ because "the changes(money) were spent by a particular school"?
|
This is historic data about _money that has been spent_. Money is a noun, so anything that substitutes for this is likely to also be a noun.
In this kind of context, "spending" is a _gerund_ \- a verb used as a noun. It means either the money spent in a specific period, or the process/practice of spending money. "Spent" is not suitable for this context, as it is the wrong verb form to be used as a gerund. You could say "money spent" (eg "changes in money spent annually")
You may sometimes see the word 'spend' used in this context (eg "changes in annual spend") which may seem equally ungrammatical, but is accounting terminology.
|
stackexchange-ell
|
{
"answer_score": 0,
"question_score": 0,
"tags": "grammar, sentence construction, passive voice, past participles, present participles"
}
|
Does adding the suffix "ality" to a noun change its meaning?
I thought that -ality was used to turn an adjective into a noun : bestial to beastiality, final to finality.
But I see that some people add it onto the end of nouns : criminal to criminality, position to positionality.
What do you think?
|
There are three parts to the answer:
PART I
We are not adding '-ality', but '-ity'.
Bestial + -ity = Bestiality
Criminal + -ity = Criminality
Final + -ity = Finality
Positional + -ity = Positionality
Functional + -ity = Functionality
PART II
In each of these examples, we are adding -ity to an adjective and turning it into a noun. Criminal can be noun as well as an adjective. For example, "criminal offence", so can be positional, e.g. 'positional reference'.
So your original hypothesis is correct (with slight adjustment to the suffix). We add -ity to the adjectives ending into -al to form a noun.
PART III
As to your question about the change in meaning. The change is that now you are talking about the phoenomenon of the quality. Finality is a state or phenomenon of the quality 'being final'.
|
stackexchange-english
|
{
"answer_score": 5,
"question_score": 0,
"tags": "nouns, suffixes, morphology"
}
|
ConcurrentModificationException: .add() vs .addAll()
Why does the following occur? Shouldn't both work?
List<String> items = data;
for( String id : items ) {
List<String> otherItems = otherData;
// 1. addAll()
//Causes ConcurrentModificationException
items.addAll(otherItems);
// 2. .add()
//Doesn't cause exceptions
for( String otherId : otherItems ) {
items.add(otherId);
}
}
Is it because `add()` adds to the collection Items, but `addAll()` creates a new collection thus modifying Items to be a different instance of List?
**Edit** `items` and `otherItems` are of concrete type `ArrayList<String>`.
|
Neither operation is proper, since it modifies the collection while iterating it.
Examining the implementation of ArrayList shows that calling either `add` or `addAll` should successfully throw the ConcurrentModificationException on the next loop iteration. The fact that it isn't doing that for `add` means that either there is an obscure bug in the ArrayList class for the particular version of Java you have; or (more likely) `otherItems` is empty, so in the second case, you aren't actually calling `add` at all.
I'm sure `otherItems` must be empty, because if adding to the `Items` list "worked" in the way you want, then it would grow every time around the loop, causing it to loop indefinitely until dying with an OutOfMemoryError.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 3,
"tags": "java, foreach, concurrentmodification"
}
|
Understanding Legendre-fenchel Transform, looking for an easy example and intuition
Looking for help in understanding this transform. I have no background in real analysis but need this stuff for my research.
I hope someone can give me some light on the intuition behind this transform and better if you can provide some example I can work with.
Thanks in advance.
I already found some information related to it here
But, still not able to fully understand.
Thanks.
|
Will answer my own question since I found a very good reading material which helped me to fully understand the topic.
If interested, take a look here.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "real analysis, random variables, large deviation theory"
}
|
vi vsplit, command needed
say I have two files: file1 and file2
is there a single command that I can run on terminal to open ONE vi screen which is vertically splited and show file1 and file2 on either side?
Thanks, Cheng
|
@cheng I asked this on #vim channel briefly some weeks ago. At that time, could come up with this solution: In example below, I opened `file1.txt` first in vi, and felt need of `file2.txt` splitted in vertical frame.
vi file1.txt
Ctrl+W+v
:sp file2.txt
Ctrl+W+w
:q
Initially, it opens the file1.txt in full screen, then 2nd command, splits that file on vertical pane. 3rd command opens file2.txt in horizontal splitted mode. 4th one jumps over to the first vertical splitted module and last one closes that.
Obviously, this approach is just usable when you have to open the file in ongoing vim session. As @ravi mentioned in link, `vim -o file1.txt file2.txt` at start will do the same job.
I will highly appreciate the simpler approach for the desired task. :)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "vi"
}
|
Migrate systemusers to CRM with Scribe
Im trying to migrate the systemuser from CRM OnPremise to CRMOnline using Scribe.
I mapped in my dts all the required fields but the next error happen all the time:
> This is not a valid Microsoft Online Services ID for this organization.
The only guid mapped is the businesunit so I dont see the problem. Any ideas?
|
That would not work. In CRM Onine used other approach. You will have to create users manually.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "dynamics crm, dynamics crm online, scribe workbench"
}
|
How to deal with a database in Android's Tab Activity
So I have an Android app that is running in a TabActivity that separates 3 different activities through this tabs. I've set a DatabaseHandler class with SQLite and all, fine.
The thing is, so far I don't really know how to deal with the database since it will be receiving data from one of the activities and I need to be showing that data in a different one. I don't know if I should declare the db in the main TabActivity or where, I've never worked with SQL in Android before and I'm pretty lost at the moment.
I tried to picture it so it is more understandable: Explanatory Graph (Sorry, I don't have enough reputation yet to post the image into the post directly)
Thanks in advance.
|
You should be okay, as long as you close your connection with the database as soon as you're done reading/writing to the database.
Each activity should be able to have their own DatabaseHandler.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android, sql, database, tabs"
}
|
MS-Access Check box IF statements
How would i add a check("chk3") that will be ticked when ("Customer order Number") field has been inputted. when an order number is entered, then the check box will tick..
i also would like to know if it is possible that When the value field ("Value") is under £10,000 then the check box ("chk2") will tick. if it is over £10,000 then it will not tick

If Nz(Me.txtCustomerOrderNo, "") <> "" Then
Me.chk3 = True
Else
Me.chk3 = False
End If
End Sub
**For Project value is less than 10K:**
Private Sub txtProjEstimate_AfterUpdate(Cancel As Integer)
If Nz(Me.txtProjEstimate, 0) < 10000 Then
Me.chk2 = True
Else
Me.chk2 = False
End If
End Sub
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "ms access, checkbox"
}
|
I'd like to sell my interest in a money judgment/garnishment - not sure of market for that
I am a landlord and just filed with the county sheriff for garnishment of a bad debt - a prior tenant. The tenant has a job and is being garnished - I just don't want to wait fo so long to get the full amount (Around $6000)
Is there a market for these things? I know people do discount these revenue streams -just not sure how I can find a buyer.
I'd probably discount it significantly as I need the money to pay real estate taxes by the end of the year.
|
As others have suggested, if you're considering taking a 50% discount on a revenue stream you feel is low risk because you're having cash flow issues paying those property taxes - I'd recommend you seriously separating these two unrelated concerns and deal with each in most financially astute manner individually.
1. You'll keep more of your hard earned cash
2. You don't have the hassle factor and uncertainty of trying to become proficient in an esoteric field of financial knowledge by Christmas!
|
stackexchange-money
|
{
"answer_score": 3,
"question_score": 5,
"tags": "wage garnishing, cash flow"
}
|
import local drupal site with database already exist
i create a local website in my laptop and now i want to work on the project from an other laptop, after installing the module backup and migrate and active it , i download the public files settings and default database, after that in aquia dev desktop i choose import local drupal site then i choose the folder (public files downloaded) as my local code base folder and for database i choose start with Mysqldatabase dump file, at the end, after i click on the link: my local site, it shows me this :
Not Found
The requested URL / was not found on this server.
|
You can use Backup & Migrate Module for importing and exporting DB's.
> Backup/Restore multiple MySQL databases and code
> Backup of files directory is built into this version
> Add a note to backup files Smart delete options make it easier to manage backup files Backup to FTP/S3/Email or NodeSquirrel.com Drush integration Multiple backup schedules AES encryption for backups
|
stackexchange-drupal
|
{
"answer_score": 0,
"question_score": 0,
"tags": "7, migrations, configuration"
}
|
Spring obfuscation
I've been looking for any solutions to obfuscate a project which uses Spring MVC framework, but I didn't find anything.
When I obfuscate a project with ProGuard, for example, I have something like this:
Before the obfuscation:
Class A:
class A {
MyObject obj1;
//Constructors
//getters & setters
}
ApplicationContext.xml
<bean id="objectOne" class="com.myproject.MyClass" />
<!-- Injection -->
<bean id="A" class="com.myproject.controller.A">
<property name="obj1" ref="objectOne" />
</bean>
After the Obfuscation:
class A {
Z a = new Z();
//Constructors
//Getters & Setters
}
But the ApplicationContext remains the same...
Is there any way to obfuscate the classes and the applicationContext?
|
Obfuscation doesn't work when reflection is involved since it won't know which files contain references to the original class name.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 4,
"tags": "java, spring"
}
|
Forwarding a ssh connection from one port to another
I have a box `B` (say on `1.2.3.4`) which I can only ssh to from another box `A`. But a certain development tool on `192.168.0.1` only allows me to specify the host and port of a ssh server and not anything more complicated than this, so I plan to have a port on `A` to automatically forward ssh traffic to `B`.
I've tried the following but it always gives me `Connection timed out`. How should I be doing this?
sudo iptables -t nat -A PREROUTING -p tcp --dport 2222 -j DNAT --to-destination 1.2.3.4:22
sudo iptables -t nat -A POSTROUTING -p tcp -d 1.2.3.4 --dport 22 -j SNAT --to-source 192.168.0.1
|
Your `SNAT` rule is wrong. Assuming that:
1. You're running these `iptables` commands on machine `A`, and
2. That machine `A` is not, in fact, `192.168.0.1`
Then the value of the `--to-source` argument should be the IP address of `A`, not the address of the machine you want to allow the connection from.
You may also need to add some other firewall rules to allow the port 2222 traffic to flow; NAT rules don't get around filter rules.
If things still aren't working after those changes, packet captures via `tcpdump` from machine `A` will likely reveal what's going wrong.
|
stackexchange-serverfault
|
{
"answer_score": 2,
"question_score": 1,
"tags": "ssh, iptables"
}
|
What does a brown squiggle from Words spelling/grammar checker signify?
This is something I've never seen before, so I'm not sure what Word thinks is wrong. Its suggestions look like the randomish stuff I'd expect from a word not in the dictionary, but that would be a red underline. The standard complaint about contractions would be green, so that's not it either.
The sentence in question is:
> My calendar is more or less free all day, so feel free to call whenever’s good for you.
The underline is on whenever's
|
Apparently, it means there is both a spelling and grammar error
It might have something to do with the word `whenever's` since Firefox is picking that up as misspelled.
|
stackexchange-superuser
|
{
"answer_score": 3,
"question_score": 1,
"tags": "microsoft word 2010"
}
|
How to deploy a Windows forms project with a database connection to some other machine?
I have a small demo windows forms application, which has 2 forms.
1. enter a name in the first form, which will add the name to a table in the database. The back-end used is SQL Server 2008.
2. After successful entry in the database, the user is prompted to the second form, which is basically a demo calculator.
My question is how can I deploy this project to some other machine. Wana create a normal executable file, in the other machine.
I was able to deploy one another windows forms app, which was without a SQL database connection, by using the Setup and Deployment wizard of the VS 2008.
Also, does the other machine would have to have certain prerequisites, like presence of SQL server in it?
I googled... found some MSDN links but could not find meaningful results.
Any assistance or an external pointer to this scenario would be highly appreciated.
|
You can get connections string using `ConfigurationManager` and set connection string in app.config. Getting connection string from app.config example:
string connStr = ConfigurationManager.ConnectionStrings["myConnStr"].ConnectionString;
After deploy you application you can change app.config manually or make in your app simple form for set connection string.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, winforms, sql server 2008, ado.net"
}
|
Can't make vertical fly out sub-menu go full screen
I am using a standard css vertical navigation menu that uses ":hover" to show the sub menu. The menu is done using standard "ul" and "li" elements. The menu is on the left hand side of the page, and when you hover over a menu, it pops out the sub menu to the right of it.
My question is, the sub menu that pops out, is there a way to make it full screen height?
## UPDATE
here is a very easy sample: <
All the surrounding html/css has been removed so that all you can see is the menu.
## UPDATE
I have now managed to do this by using jQuery. The jQuery is:
`$('ul > li > ul').css('height', $(window).height() + 'px');`
<
|
This gave the intended result.
$('ul > li > ul').css('height', $(window).height() + 'px');
However, also see Roddy's additional answer if you wish to align the child elements with the parent element.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "css"
}
|
Making a symbol appear in Flash using AS 3
I would like to create a button in Flash CS6 that makes another symbol appear when clicked. Nothing fancy, just this. How would I do that? This is the code I've got so far:
stop();
button1.addEventListener(MouseEvent.MOUSE_UP revThing);
function revThing(evt:MouseEvent):void{
>what goes here..?<
}
|
One way of doing it is create a movieclip, leave the first frame empty, add a stop() action to it. Put your symbol on frame two, put a stop() action on it. Name the movieclip, for instance symbol_mc. Your command in the button should be
`symbol_mc.gotoAndPlay(2)`
Another way would be to hide the symbol off stage, and position it on stage on button click. Or have the symbol on stage already, but invisible, set visibility on button click.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "flash, events, click, mouse"
}
|
How to make my WP8 app compatible for WP7.8
I am asking here because I'm a little bit confused. I have a working WP8 apps, with WP8 specific features such as speech recognition and custom tiles. I would like to make my app compatible for WP7.x
I know I have to remove speech recognition from my app to support WP7
1 - Where should I start ? Could I use the same project on Visual Studio 2013 or should I create another project on Visual Studio 2012 ?
2- Is it simpler to target only WP7.8 or can I do WP7.5 and WP7.8 in a same project ?
3 - I want to keep the use of async/await method, can I do that in WP7.8 or WP7.5?
Thanks a lot for your answer
|
1. You have to create a new project targeting 7.1. WP7.x apps can run in WP8 devices, but not in the other way.
2. When createing the project, you target 7.1. If you have the latest SDK installed WP7.8 features will be available.
3. You can by adding Microsoft.Bcl.Async package from NuGet
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "visual studio, windows phone 7, windows phone 8, windows phone"
}
|
How do I specify a dependency that end with '<version>-bin.exe' in gradle?
How do I get **winsw-1.19-bin.exe** from the repo below:
repositories {
maven {
url '
}
}
dependencies {
compile('com.sun.winsw:winsw:1.19@exe')
}
The above returns:
* What went wrong:
Could not resolve all dependencies for configuration ':compileClasspath'.
> Could not find winsw.exe (com.sun.winsw:winsw:1.19).
Searched in the following locations:
|
Seems that I was missing the classifier
compile('com.sun.winsw:winsw:1.19:bin@exe')
or
compile(group: 'com.sun.winsw', name: 'winsw', version: '1.19', classifier: 'bin', ext: 'exe')
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "gradle, build.gradle"
}
|
rabbitmq drop message if certain field value is not unique?
I am using an ampq queue with my webcrawler - each crawler instance will get an url to crawl from a message in the queue then add the urls it has found to the queue.
As there will be multiple crawler instances each may find a the same url and add it to the queue.
Is there a built in way to tell rabbitmq to drop the message if the url is know, or to check the queue if a message with the url exists already?
|
**No.** There are no way to check message uniqueness with RabbitMQ mechanism.
AMQP queues and especially RabbitMQ queues are pure FIFO queues.
Probably, you have to implement uniqueness check on application side.
_P.S.:_
_There are nifty workaround to declare queues with the same name as unique field (or it hash) with`x-max-length` set to 1 so duplicates will be lost if there are unprocessed message in queue. But this requires a lot of queues with urls (unique field - url hash) and thus is not the best solution , especially when it comes to consume all that messages from thousands of queues with non-obvious names._
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 2,
"tags": "rabbitmq, amqp"
}
|
How to merge more than two select queries to single result set in oracle
I need to merge the result set of four queries into single result output.
Example:
Select sum(marks) total from table1 Where id > 1000 and id < 2000
Select sum(marks) total1 from table1 where id =>2000
Select sum(tables) totaltbl from table2 where id > 1000 and id < 2000
Select sum(tables) totaltbl1 from table2 where id => 2000
I need the output in the below format
Total total1 totaltbl totaltbl1
100. 2000. 10. 30
|
One option would be applying Conditional Aggregation during joining of the tables :
SELECT SUM(CASE WHEN t1.id > 1000 AND t1.id < 2000 THEN t1.marks END ) "Total",
SUM(CASE WHEN t1.id >= 2000 THEN t1.marks END ) "Total1",
SUM(CASE WHEN t2.id > 1000 AND t2.id < 2000 THEN t2.tables END ) "Totaltbl",
SUM(CASE WHEN t2.id >= 2000 THEN t2.tables END ) "Totaltbl1"
FROM table1 t1
CROSS JOIN table2 t2
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql, oracle, join, aggregation"
}
|
Erro executar UPDATE SQL Server
Ao executar a instrução update abaixo está ocorrendo o seguinte erro. O que pode ser?
> Msg 116, Level 16, State 1, Line 3 Somente uma expressão pode ser especificada na lista de seleção quando a subconsulta não é introduzida com EXISTS
UPDATE EstoqueTarefa
SET EstTarTitulo = (SELECT CONCAT(EstTarTitulo, '-' ,DATENAME(MONTH,getdate())),'-',DATEPART(YEAR,getdate()))
where EstTarID = 246
|
O problema está na SubQuery, apenas realiza select campo1, campo2, etc. Você não precisa de usar o Select porque a função GETDATE() pode ser invocada sem problema.
SET EstTarTitulo = CONCAT(EstTarTitulo, '-' ,DATENAME(MONTH,getdate()),'-',DATEPART(YEAR,getdate()))
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "query, sql update, sql server 2012"
}
|
WP7 background tasks
When reading about background agent, I am confused
1. Windows Phone 7 allow using Scheduled Task to register a background agent. So what is the difference between Scheduled Task and background agent ?
2. There are 2 types of Schduled Task and I use both of them
>
> ScheduledActionService.Add(periodicTask);
>
> ScheduledActionService.Add(resourceIntensiveTask);
>
In MSDN noted that
> Description field is required and is used to describe the agent to the user in the background tasks Settings page on the device
But in the Background tasks settings, I see **only periodic task**
Why is that ?
|
A task is the container that is managet by the operating system and runs at the appoined time. It runs the agent witch is the actual code payload.
take a look of this
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "windows phone 7, background, settings, task, agent"
}
|
What is the difference between collection.find with a callback and without?
What is the difference between:
var cursor = collection.find();
//do something
and
collection.find(null, function(err, cursor) {
//do something
}
Does the first one "block?" If so, does "block" mean that it will lock up node until mongo returns the cursor?
(The first example is from the documentation for node-mongodb-native. If their example is blocking, then why would they put in the documentation?)
|
The first one is synchronous, and will block. If mongo times out, your node server will not be able to do anything else, so essentially "locked up", yes.
This should be avoided unless perhaps during server initialization, or to write command line tools.
The second one will let other events be processed before the callback gets called when the result from mongo is returned.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "node.js, mongodb"
}
|
Default value on generic predicate as argument
First time question for me :)
I need some way to define a default predicate using a generic on the format
Func<T, bool>
and then use this as a default argument. Something like this:
public bool Broadcast(byte command, MemoryStream data, bool async, Func<T, bool> predicate = (T t) => true)
When i do this i get the compile error:
Default parameter value for 'predicate' must be a compile-time constant
Is there a smooth way of doing this that I am missing or should a make the predicate function nullable and change my function logic accordingly?
Thanks,
|
Default values for method parameters have to be compile-time constants, as the default values are actually copied to all the call sites of the method by the compiler.
You have to use an overload to do this:
public bool Broadcast(byte command, MemoryStream data, bool async) {
return Broadcast(command, data, async, t => true);
}
public bool Broadcast(byte command, MemoryStream data, bool async, Func<T, bool> predicate) {
// ...
}
Also, there is a specific `Predicate<T>` delegate in mscorlib which you can use instead. It's the same signature as `Func<T, bool>`, but it explicitly marks it as a delegate which decides whether an action is performed on instances of `T`
|
stackexchange-stackoverflow
|
{
"answer_score": 35,
"question_score": 25,
"tags": "c#, arguments, default value, predicate"
}
|
Disable Frequency Scaling “ondemand” daemon on Ubuntu 10.04
I noticed today that a process "ondemand" was running on my Ubuntu Server that I recently upgraded (following the recommended process) from 9.10 to 10.04. Why on earth would they install this by default on a server, and how do I turn it off?
|
sudo apt-get install cpufrequtils sysfsutils
then
echo performance | sudo tee /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
and repeat for every core/CPU you have.
You can verify the result with `cpufreq-info`.
To make the change permanent: add the following line (or lines - for several cores/CPUs)
devices/system/cpu/cpu0/cpufreq/scaling_governor = performance
to /etc/sysfs.conf (or edit an already existing line).
You may also have a look at this post.
|
stackexchange-superuser
|
{
"answer_score": 7,
"question_score": 4,
"tags": "ubuntu 10.04, cpu, debian, ubuntu server"
}
|
Solve $3x^3=({x^2+\sqrt{18}x+\sqrt{32}})(x^2-\sqrt{18}x-\sqrt{32})-4x^2$
Solve for $x$ in
$$3x^3=({x^2+\sqrt{18}x+\sqrt{32}})(x^2-\sqrt{18}x-\sqrt{32})-4x^2$$
I'm really not good with 4th degree equations but since the 1st term in the RHS looked a simple (a+b)(a-b) application, I tried solving that but I'm really not able to reach to the final answer as it only gets more complicated... can anyone please help me out?
The equation I got was:
$$x^4-3x^3-22x^2-48x-32=0$$
|
Expand $$x^4-3 x^3-22 x^2-48 x-32=0$$ Try to factorize $$x^4-3 x^3-22 x^2-48 x-32=\left(a x+b+x^2\right) \left(c x+d+x^2\right)$$ RHS gives $$x^4+x^3 (a+c)+x^2 (a c+b+d)+x (a d+b c)+b d$$ thus we must have
$$ \begin{cases} a+c=-3\\\ ac+b+d=-22\\\ ad+bc=-48\\\ bd=-32\\\ \end{cases} $$
Final factorization should be $$\left(x^2-6 x-8\right) \left(x^2+3 x+4\right)=0$$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "polynomials, quadratics"
}
|
how to start and Stop GPS by using code in Android
i want enable GPS for 30sec when my application start (when oncreate() method calls ). and after 30 sec it turn to disable mode.
|
Try this code,
LocationManager locationManager =(LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, WLConstants.DELAY_HOUR, gpsl
.getMinDistance(), gpsl);
and to stop the GPS try
locationManager.removeUpdates(gpsl);
Give this after u complete ur time period.
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 2,
"tags": "android, android service, android location"
}
|
apply powershell script to multiple xml files
I have a Powershell script that queries an xml document and outputs the results to a csv file. The script works but I need to apply it to multiple xml files in a folder and output the combined results to a csv. How can this script be modified to do this? Thanks
$xml = XML #load xml document
#this finds file names of yearbook picks
$picks = $xml.Client.Order.Ordered_Items.Ordered_Item |
Where-Object { $_.Description -eq 'yearbook Luster Print' } |
ForEach-Object { $_.Images.Image_Name }
# this finds the Album
$album = $xml.SelectSingleNode("//Album_ID").InnerText -split '_'
$results = New-Object PSObject -Property @{
Last= $album[0]
First= $album[1]
Code= $album[2]
Pick1= $picks[0]
Pick2= $picks[1]
}
#output CSV File
$results | Export-Csv -path D:\demo\myoutput.csv -NoTypeInformation
|
Loop over the XML files and append them to your output file:
# Get all XML files
$items = Get-ChildItem *.xml
# Loop over them and append them to the document
foreach ($item in $items) {
$xml = XML #load xml document
#this finds file names of yearbook picks
$picks = $xml.Client.Order.Ordered_Items.Ordered_Item |
Where-Object { $_.Description -eq 'yearbook Luster Print' } |
ForEach-Object { $_.Images.Image_Name }
# this finds the Album
$album = $xml.SelectSingleNode("//Album_ID").InnerText -split '_'
$results = New-Object PSObject -Property @{
Last= $album[0]
First= $album[1]
Code= $album[2]
Pick1= $picks[0]
Pick2= $picks[1]
}
# Append to CSV File
$results | Export-Csv -path D:\demo\myoutput.csv -NoTypeInformation -Append
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "xml, csv, powershell"
}
|
Have all spacecraft on record been launched from land?
Water is a little buoyant which may be part of the reason a lot of commerce happens on the waves.
* How much of a difference in terms of fuel would it make if the craft were launched from a water-body?
* Have all spacecraft to-date launched from land?
|
Spacecraft have been launched on Air, Land, and Sea.
**Air Launch**
The most popular of these is the Pegasus Rocket from Orbital. The airplane carrying the rocket goes up to ~40,000 ft, and fires off the rocket from below. These have carried a number of missions, including NASA, commercial, and other sources.
**Sea Launch**
The name of a company which launches such rockets. They utilized the Zenit-3SL rockets for all of their launches, and primarily launched GEO satellites from the equator, which reduces considerably the cost to launch a GEO sat, due to the fact that the inclination doesn't have to be removed.
|
stackexchange-space
|
{
"answer_score": 14,
"question_score": 11,
"tags": "launch"
}
|
Using Mozilla Rhino with SBT - Unknown artifact
I am trying to add Mozilla Rhino to my SBT project but it fails to fetch. More specifically I get an error:
> Unknown artifact. Not resolved or indexed
name := "JsCFA-prototype"
version := "1.0"
scalaVersion := "2.11.7"
resolvers += "jabylon Repository" at "
libraryDependencies += "org.mozilla" %% "javascript" % "1.7.2"
Maven Central link:
<
. If you are using single `%` it is being fetched as it is.
So basically what you are asking for is equivalent to:
libraryDependencies += "org.mozilla" % "javascript_2.11" % "1.7.2"
Which does not exist, as sbt reflected.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "scala, sbt, rhino"
}
|
Ruby string operation doesn't work on captured group
This string substitution works:
"reverse, each word".gsub(/(\w+)/, "\\1a")
=> "reversea, eacha worda"
and like this, which is basically the same thing with single quotes:
"reverse, each word".gsub(/(\w+)/, '\1a')
=> "reversea, eacha worda"
but if I try to reverse the string, it fails:
"reverse, each word".gsub(/(\w+)/, "\\1a".reverse)
=> "a1\\, a1\\ a1\\"
I've played with it, but can't seem to get the reverse operation to work.
|
I bump into this all the time. The capture groups are available in the block scope, so rewrite like this:
"reverse, each word".gsub(/(\w+)/) { |match| $1.reverse + "a" }
or since your match is the group, you could omit the group entirely
"reverse, each word".gsub(/\w+/) { |match| match.reverse + "a" }
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 3,
"tags": "ruby, regex, string"
}
|
How can I use pagination in this case?
I'm using the gem called **'acts_as_follower'** and **'kaminari'**.
If I put `.page(params[:page]).per(10)` in the end of the line that fetches records with `acts_as_follower`, it gives back error. So I removed it.
How can I use pagination with this gem **'acts_as_follower'**?
**Error**
NoMethodError in UsersController#following
undefined method `page' for #<Array:0x00000018593928>
Extracted source (around line #53):
50: <% end %>
51:
52: <div class='pagination'>
53: <%= page_entries_info(@users).html_safe %>
54: <%= paginate @users, :window => 4, :outer_window => 5, :left => 2, :right => 2 %>
55: </div>
56:
current **users_controller.rb** Fetching part
@users = User.find_by_username(params[:id]).all_following(order: 'updated_at DESC')
|
Since the `all_following(order: 'updated_at DESC')` method returns an array object, you'd need to use Kaminari's `PaginatableArray`.
Add the code below to your controller:
@users = Kaminari.paginate_array(@users).page(params[:page]).per(10)
Then the pagination should work as you'd expect.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "ruby on rails, ruby on rails 3, kaminari"
}
|
How to transition to skin tone for lips inside blender
I am trying to create lips and hope the top part selected could transition to skin tone. I'm wondering if there's a way to do it without going to an external program to create the UV map. I've checked out these two answers and it works but I feel like there must be a way to do it inside blender? How do you know when to use UV maps as opposed to texturing?
, and in that material, we use a black and white texture to mix between the two materials. Then, we paint a black and white texture. I used basic Blender texture painting. Here, white indicates that we should be using the parameters for the lips, and black indicates we should be using the parameters for face. Of course, you can reverse that if you want.
If you have more complicated materials than the simple diffuse shaders I'm showing, you might consider node grouping everything in those materials instead, for ease of setup.
|
stackexchange-blender
|
{
"answer_score": 1,
"question_score": 0,
"tags": "texturing, materials, color"
}
|
Add client-side answer length validation
Here is a problem I faced with:
1. Try to submit an answer with less characters (29), than minimum required (30)
2. Error shown `Oops! Your answer couldn't be submitted because: body must be at least 30 characters; you entered 29`
3. Quickly add one more character. Click `Post Your Answer`.
4. Captcha is shown (possibly because you did two edits in less than 30 seconds). Forget about being the first one to answer.
The only way to avoid capture is to wait 30 seconds after adding that one character. Odd?
So, why not to check answer length on client side? E.g.
* Disable post button until required characters count entered (see Twitter)
* Show message before posting to server
|
I think this would be a useful feature that should be relatively easily to implement.
I think it's useful to note that Stack Overflow already has this for comments: client code prevents comments from attempting to be submitted unless they meet the minimum length requirement.
Why not add this for answers, too.
!enter image description here
|
stackexchange-meta
|
{
"answer_score": 3,
"question_score": 3,
"tags": "feature request, user interface"
}
|
Release build not working when run without debugging in VS2010
I encountered following problem:
I write program in c++ using VS2010. Debug build works properly when run with/without debugging in VS. When I launch built executable directly it also works.
Release build works when run with debugging in VS and alsp when I launch build executable directly.
Unfortunately, program does not work when I run release build in VS -without debugging-. Window is created and then program crashes quickly (without any error message). Since it crashes when run without debugging I don't know how to identify what causes the problem.
Any ideas what might be causing this? Thanks :)
|
It seems most likely you have some sort of memory error/corruption that just happens to work ok in the debugger.
You can try using couts to isolate how far/where it dies, or try a tool like Purify (or valgrind for free if you can port to Linux).
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "c++, visual studio 2010, debugging, build, release"
}
|
What is the most efficient way to get the remaining array after deleting an item from Array?
`Array.delete` method returns the deleted item.
But, what if I need the remaining array (without changing the original one) ?
Well, this is one option:
%w(hello stack overflow !).delete_if{|x| x == 'overflow'}
# => ["hello", "stack", "!"]
I wonder if there is a nicer way, something like:
%w(hello stack overflow !).<something>('overflow')
Any ideas ?
|
%w(hello stack overflow !) - %w(overflow)
=> ["hello", "stack", "!"]
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "arrays, ruby"
}
|
Including literal JSON content in Velocity (avoiding HTML escapes)
I'm trying to use the Velocity engine embedded in Atlassian's products (and exposed through com.atlassian.templaterenderer) to substitute a JSON value into a template.
In the template, this looks a bit like the following:
<script>
foo = $foo
</script>
However, when I render the template with "foo" mapped to a string `["bar", "baz"]`, the output is the following:
<script>
foo = ["bar", "baz"]
</script>
How can this be avoided?
|
Atlassian has an event handler which performs escaping on any variable with a name not ending with `WithHtml`.
Thus:
<script>
foo = $fooWithHtml
</script>
expands as desired.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 4,
"tags": "velocity, vtl"
}
|
What is the file extension for SQLite code?
In my JS+SQLite project, I'm putting database and table creation SQL code in a separate file, to make the structure clear. What is the recommended file extension? `.sql`?
|
I feel a litte stupid for saying "yes, you got it!", but that is what it is.
The `.sql`-extension is used by some bigger Apps that process Databases, like SQirL and Eclipse IDE.
Keep in mind, that File extensions are purely meant to make it easier for the user to identify its content. So basically, any extension that you deem readable is just as fine as the any other.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "sql, sqlite, file extension"
}
|
MSSQLSERVER agent from Services.msc
Quick question from a conversation with a colleague, I would always restart things like MSSQLSERVER agent from SSCM, however a colleague asking what the difference would be starting restarting the service from services.msc.
It never occured to me if there would be any impact restarting the service from here as opposed to Sql Server Configuration Manager, is it just a best practise thing? Also it is SQL Server 2008 R2 on Windows Server 2008 R2. Any thoughts on if there any any adverse effects starting/restarting from services.msc?
Thanks in advance
Andy
|
It is definitely a best practice. Restarting through Windows services will work but may lead to a slippery slope. Using SSCM out of habit helps avoid the temptation to make changes to the services through Windows Services where registry settings may get out of sync.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "sql server 2008 r2, sql agent"
}
|
Rotate feature shapefile with certain pivot point and angle?
I want to rotate a line feature using certain pivot point and angle, but I can not find what tool to use. If rotating a raster, I can simply use Rotate tool, and there I can easily specify the pivot point and rotation angle. But what should I do if I want to rotate a feature? I know I can simply use "Edit Feature" and "Rotate" toolbar, but it does not provide me the way to specify the pivot point and angle.
|
If you select a feature, select the rotate tool, and then press the "A" key, you can enter a rotation angle. As for the pivot point, you can drag the "x" that marks the rotation spot with the rotate tool and snap it to any spot along the feature.
|
stackexchange-gis
|
{
"answer_score": 6,
"question_score": 1,
"tags": "arcgis desktop"
}
|
Using R to download *.xls files generates error
I'm trying to download a large number of xls files from the BLS servers. When I manually download any of the files, they open perfectly.
But when I try to download the file from inside R:
library(readxl)
tp <- "
temp <- paste0(tempfile(), ".xls")
download.file(tp, destfile = temp, mode = "wb")
this downloads a file of the right size, but attempting to read the file:
data <- read_excel(path = temp, sheet = 1)
returns the error
seek: wanted to seek to sector 5374034 (0x520052) loc=2751505920
|
Set `mode="wb"` to do a binary transfer:
download.file(tp, destfile=temp, mode="wb")
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "r, web scraping, rvest"
}
|
How to use HSQLDB to dynamically generate tables for JDBC application
I want to use HyperSQL as an in-memory database for integration tests of a Java - JDBC application.
If I try the following:
Properties props = new Properties();
props.put("user", "sa");
props.put("password", "");
Class.forName("org.hsqldb.jdbcDriver");
Connection cn = DriverManager.getConnection("jdbc:hsqldb:mem://localhost", props);
Statement st = cn.createStatement();
st.executeUpdate("Insert into foo (bar) values (10);");
I get:
java.sql.SQLException: Table not found: foo in statement [Insert into bar]
I thought there was a way for HSQL to dynamically generate the tables when used as an in-memory database, but I can't seem to find it in the documentation.
|
Why are you executing a query for an INSERT? That won't return a `ResultSet`.
You ought to `executeUpdate()`
There's nothing "automatic" in HSQL. You might be thinking of Hibernate and its hbm2ddl.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "java, jdbc, integration testing, hsqldb, in memory database"
}
|
How to change wx.Listbox strings in python
self.list_box_1 = wx.ListBox(self, -1, choices = self.generateList("imagelist.txt"), style=wx.LB_SINGLE)
newlist=['6','7','8','9','10']
I have a listbox with filenames in it e.g. 1,2,3,4,5 and when a button is clicked I want the listbox to be cleared and the values of newlist overwrite the current values in the listbox
I can change each string in self.list_box_1 using self.list_box_1.SetString(5,1) but how do I overwrite the values in the listbox with the values in newlist
|
Also look for methods for the ListBox in the derivation hierarchy, like `wx.ItemContainer`. `wx.ItemContainer.SetItems` might be helpful:
> Clear and set the strings in the control from a list
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "wxpython"
}
|
catch all types of errors from whole application Android
I have a big Android application and I have a requirement to log all types of errors that could happen in my Application including `"Out of memory"` etc. Is it possible to accomplish?
I can use
try {
} catch(throwable t) {
}
but adding a whole code to `try/catch` sounds bad. And how can I catch an errors like "out of memory"?
|
To tracking crash reports best way is using 3rd party libraries like Fabric or firebase(google). If you cannot use like this libraries, you can try this.
public class MyActivity extends Activity implements Thread.UncaughtExceptionHandler{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if(ex.getClass().equals(OutOfMemoryError.class))
{
try {
android.os.Debug.dumpHprofData(fileName);
}
catch (IOException e) {
e.printStackTrace();
}
}
ex.printStackTrace();
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "android"
}
|
Google Web search API (not custom search)
So google pulled the SOAP API back in 2006, and depreciated the REST API last year. Even though the REST api still works fine, I was wondering if anyone here knows an alternative for the web search. I am not talking about Custom search API (that thing is horrible with a 100 queries/day limit).
Also, I am currently using the REST api for a custom application. I have noticed mixed (and very unreliable) results if I pass search operators such as inurl: or site: with my queries. Does anyone know if these even work with the REST Api?
|
The search parameters do work for Googles deprecated REST API. But search results often do not equal the ones from a regular Google search. Most likely because the two do not (and never will) use the same data index.
* _YAHOOs BOSS_ could be a (non-free) alternative
* _Microsoft_ does offer a simple and free restful API for BING
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "google api, google search, google search api"
}
|
How to Supply Default Value back to DataGridViewCell After Error Message
My current code will show a messagebox that tells the user that only numeric input will be accepted if they input any non-integer into the field. However I can't seem to find out how I might supply a default value back to the datagridviewcell.
Private Sub DataGridViewCOTS_DataError(ByVal sender As Object, ByVal e As DataGridViewDataErrorEventArgs) Handles DataGridViewCOTS.DataError
If StrComp(e.Exception.Message, "Input string was not in a correct format.") = 0 Then
'If e.ColumnIndex = 2 Then
MessageBox.Show("Please Enter a numeric Value")
'DataGridViewCOTS.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = 3
End If
End Sub
|
From this thread <
> The DataError event occurs when an external data-parsing or validation operation throws an exception, or when an attempt to commit data to a data source fails.
>
> Based on it, you can't fix the value here since the value will not be committed. After you changed the correct/default value to the DataGridView Cell, you must commit it. **So, set the e.Cancel = false would be OK**.
So, just set `e.Cancel = false` after you change value and it should work.
Hope this helps
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "vb.net, datagridview, error checking"
}
|
Any way to see which downvote was reversed?
Occasionally I notice I gained 2 reputation for no obvious reason. Presumably someone has just changed their mind about a previous downvote and reversed it, but they didn't leave a comment about it. Is there any way to see where this happened?
|
Reputation can also be "gained" if you downvoted some answer that later got deleted: you get the reputation point back. Two of these, and you get 2 reputation.
Another option is that answer of yours that had a downvote got deleted.. again the reputation is given back.
Downvote can be undone only 5 minutes after being cast, so it's unlikely that you spotted it on time.
|
stackexchange-meta
|
{
"answer_score": 4,
"question_score": -1,
"tags": "support, reputation, down votes, change vote"
}
|
Change default remote git branch in IntelliJ
For some reason, my local `dev` branch is by default a release branch. Is there any way in the IntelliJ UI to change this?
.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "git, intellij idea"
}
|
Multiple networks connected.Which is considered?
Suppose i am connected to two networks-
1. DSL connection.
2.Mobile broadband.
Which one will be considered as the base one and will be used??
Because both do get connected at the same time..!!
|
The one with a 'better' gateway metric will be chosen. To find out which one it is, open terminal and type this:
route -n
I see that I have a gateway with metric 0.0.0.0:
0.0.0.0 192.168.0.1 0.0.0.0 UG 0 0 0 eth0
So eth0 is my preferred adapter.
Another (probably easier) way to find out is to look at the route to Google's DNS server (8.8.8.8)
ip route get 8.8.8.8
This is my output:
8.8.8.8 via 192.168.0.1 dev eth0 src 192.168.0.2
cache
You can see that it is going via eth0. Try this on your machine and have a look at the results.
|
stackexchange-askubuntu
|
{
"answer_score": 3,
"question_score": 1,
"tags": "networking, internet"
}
|
Blogger comments have disappeared
I use standart template "Awesome incorporation" on my blog: (gek0n.blogspot.com) I changed this template to make my blog more readable and comments are gone. Then i create new blog (Testing), install same template and examine the code: i didn't delete any code related to comments.
After this i recognized that "post.allowComments" variable and other bool-variable, related to comments, are set to 'False'. I tried to switch every combination in options, but nothing happened. Not a one option doesn't change values of variables.
How i can fix this? Maybe there is some way to change variables values? Or any type of option that i don't know?
|
I just found a solution! Comments options are in every post and exactly this options turn "allowComments" variable in 'True'.
But not a one forums or users or sites couldn't help me!
P.S. I'm not native English speaker and make questions is hard to me. Sorry for mistakes.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "blogger"
}
|
Voice to text translator raspberry pi
Hi Im new to programming for Raspberry pi, but i have decided to make a "Voice to text translator" using the Raspberry pi.
So here is what it should do step by step:
1. press a button to start.
2. speak to the device via a plugged in microphone.
3. The device will now take the voice and convert it to a text document.
4. Save it to the SD card.
5. Then press a button to stop.
So what i would like to know is, if this has already been made (I could not find any, for Raspberry pi) and if this is even possible?
And thanks for the help by the way! :)
|
Check out jasper I was very impressed that a Raspberry Pi could do such a good job. It only messed up once for me (I said 'mayonnaise' and it put 'many') It is based on CMU Sphinx.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "text, raspberry pi, voice recording"
}
|
Eigen MatrixXf subtract a VectorXf
I have a `Eigen::MatrixXf mat` that has size of 113(rows) X 2009(cols); I am trying to subtract the max of each of its column from each of its column. Here is my code:
VectorXf minVal = mat.colwise().minCoeff(); // mat is MatrixXf
mat.colwise() -= minVal;
Here is the error message:
> Assertion failed: dst.rows() == src.rows() && dst.cols() == src.cols(), file C:\cui\Projects\eigen-3.4.0\Eigen\src\Core\AssignEvaluator.h, line 754
Can anyone give a pointer? Thanks a lot.
|
`mat.colwise().minCoeff()` returns a row vector (you can assign this to a column vector, because in most cases Eigen implicitly transposes row vectors to column vectors and vice versa). You should store the result as a `Eigen::RowVectorXf` and then subtract that from each row, i.e., `mat.rowwise() -= minVal;`
This should work:
Eigen::RowVectorXf minVal = mat.colwise().minCoeff();
std::cout << mat << "\n\n" << minVal << "\n\n";
mat.rowwise() -= minVal;
std::cout << mat << "\n\n";
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "matrix, eigen3"
}
|
Discrete math probability function rolling 12 sided die
Given a 12 sided fair die write down a probability function that gives the probability of rolling x '7's from 20 rolls.
I'm not really sure where to start on this. But I know there are 12^20 total possibilities and that each time you roll the die there is a one in 12 chance of getting a 7. If I did (1/12)^20 that would give me the probability of rolling 20 7s in a row. But how do I include 7s that aren't rolled in a row?
Any ideas would be appreciated very much!
|
The answer is $\binom{20}{x}12^{-20}$ since any dice pattern is equally likely and all you need is to count the number of possible patterns of x 7's out of 20 and divide by the total number of possibilities.
|
stackexchange-math
|
{
"answer_score": -1,
"question_score": 0,
"tags": "probability, probability distributions"
}
|
Greece, ferry from Skiathos to Alonissos
What are the options for getting to Alonissos island from Skiathos in mid June? It seems there are ferries, but they only depart in the morning, however I will be arriving to the airport in the early afternoon.
|
<
> In the summer there are up to 3 ferries per day on the Skiathos - Alonissos route, while in the winter there are at least 6 weekly crossings. The earliest ferry departure is around 10:30 from the port of Skiathos and the latest can be from 16:00 to 21.00 depending on the season and the day of the week.
Further, < lists the Aegean Flying Dolphins leaving Skiathos on 15:40 arriving Alonissos a bit more than an hour later. It seems it is the opposite direction which leaves in the early morning but according to the above during the summer more sailing are expected. It is probably way too early to know the exact June schedule.
|
stackexchange-travel
|
{
"answer_score": 5,
"question_score": 1,
"tags": "ferries, greece"
}
|
Distance between 2 System.Drawing.Point
How can I find the distance between 2 System.Drawing.Point?
I googled and didn't find it...
Dim p1 As New Point(0, 10)
Dim p2 As New Point(10, 10)
Dim distance = ??
In this case, it should be 10, but what about here?
Dim p1 As New Point(124, 942)
Dim p2 As New Point(34, 772)
Dim distance = ??
Thanks!
|
Distance formula: sqrt( (x2 - x1)^2 + (y2 - y1)^2 )
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "math, distance"
}
|
textbox text remove last character
If the string is > 8, I need to remove the last character
How is this possible?
private void textBoxNewPassword_TextChanged(object sender, EventArgs e)
{
if (textBoxNewPassword.TextLength == 9)
textBoxNewPassword.Text = textBoxNewPassword.Text.Remove((textBoxNewPassword.Text.Length - 1), 1);
}
The code appears to do nothing.
|
Use String.Substring Method (Int32, Int32), where the first parameter is the starting index and 2nd parameter is the number of characters. Also if you need to check if the length is greater than 8 the do:
if (textBoxNewPassword.Text.Length > 8)
textBoxNewPassword.Text = textBoxNewPassword.Text.SubString(0,8);
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c#, .net"
}
|
Flex 4 <mx:Component> could not resolve
I am using flash builder 4 to run sample application from "Getting Started with FLEX 3", but the code can't run because there is one place that FB4 can't resolve, I guess this is because the library has been obsolete but after a tons of search I can't find the solution.
Thanks. Bin
|
With Flex4 you'll want fx:Component instead
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 2,
"tags": "flash, apache flex, flex3"
}
|
UIViewAnimation with constraint not working in Swift
I am trying to create an animation where I want to slide a uiview from right to left once parent UIViewController has loaded although I am able to display the view but the animation is not working. My code for animation:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
view.isOpaque = false
UIView.animate(withDuration: 1.0, delay: 1.0, options: .curveEaseOut, animations: {
self.contentXConstraint.constant = 500
self.contentXConstraint.constant = 80
}) { (status) in
}
}
I have displayed the parent view controller as presented viewcontroller:
present(navController, animated: false, completion: nil)
|
You forgot `self.view.layoutIfNeeded()`
self.contentXConstraint.constant = 500
self.contentXConstraint.constant = 80
UIView.animate(withDuration: 1.0, delay: 1.0, options: .curveEaseOut, animations: {
self.view.layoutIfNeeded()
}) { (status) in
}
from <
> Use this method to force the view to update its layout immediately. When using Auto Layout, the layout engine updates the position of views as needed to satisfy changes in constraints
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "swift, uiview, uiviewanimation"
}
|
Poker hand suited connector
6 handed 1/2 cash
All around 100 bb but bb at 30
**Pre**
Hero in CO with T 8
UTG open for 4 bb with one caller, I call, btn fold, sb fold, bb calls.
I am lovin it.
**Flop**
Pot is 17 bb
A J⋄ 7⋄ which is semi good for me
check, 9 bb, call, fold (me)
If I give myself 1 out for runner runner spade and 1/2 for runner nut straight I have 6 outs. I am 1/7.5 but I am not likely to pick up 70 bb if I hit. Felt like I need at least 8 outs to make the call.
Should I have called?
|
I think that calling here would be the worst play and I agree with your reasoning. Additionally, one of your outs (9 of diamonds) either helps another player out even more or else kills your potential action.
I would say however that although folding is fine here, raising would be better than calling if you were to play on (although I'd like it much more with slightly deeper stacks). In fact, when you mix in some speculative hands like suited one-gappers, your bluffing frequency with them should go up to make them profitable and this is a prime spot: you have some outs, the pot already has at least some value, you show a lot of strength with a legitimate range of strong hand possibilities, and you're in position. If re-raised, you could safely fold, and if just called, you have a couple options on the turn depending on what falls.
|
stackexchange-poker
|
{
"answer_score": 3,
"question_score": 1,
"tags": "betting strategy, probability"
}
|
How to add the Geometry type LineString/ MultiLineString within the function QgsGeometryGeneratorSymbolLayer using PYQGIS
Within a function of pyqgis I am trying to create a layer according to multiple steps. I want to change the Geometry type option to LineString / MultiLineString in the function so that this will be done automatically. Is there a variable I can add to the function? , centroid(offset_curve($geometry, length($geometry)/-10.0)), end_point($geometry)), buffer(start_point($geometry), 10000)), buffer(end_point( $geometry), 10000))', 'outline_color': 'black'})
|
Never mind, found the solution: added the line `shape_sym.setSymbolType(QgsSymbol.Line)` afterwords.
|
stackexchange-gis
|
{
"answer_score": 0,
"question_score": 0,
"tags": "qgis, pyqgis"
}
|
How to query for city name as well as length of the smallest city name from the same table
My code is this but gives error, don't know why. Please help!
select city,
min(length(city))
from station
group by length(city)=min(length(city))
order by city asc;
|
If you just want the city with the shortest name, you can simply `order by` and `limit`:
select city, char_length(city) city_length
from station
order by city_length
limit 1
This returns just one row. On the other hand, if you want to allow bottom ties, then you can filter with a subquery, like so:
select city, char_length(city) city_length
from station
where char_length(city) = (select min(char_length(city)) from station)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "mysql, sql, select, sql order by, greatest n per group"
}
|
Is it possible to color the prompt in Bash?
Is it possible to color the prompt ("user@host:~/dir/$") in Bash? Some commands generate a lot of output and it's sometimes hard to find where it started. Coloring would help a lot.
|
Found an easy way to do it:
Uncomment `force_color_prompt=yes` in `~/.bashrc`.
|
stackexchange-askubuntu
|
{
"answer_score": 29,
"question_score": 14,
"tags": "bash, customization"
}
|
truncate integer
I got a task to chop an integer by 1 digit. For example, If the new limit is 3 digits then 1234 will become 999 after the change. if the before change value is 12345 then it should becomes 999 after changes. if the pre-change value is 564 then it will remain unchanged.
This has to be done on Oracle as well as SQL server. the truc function only truncates decimal but not integer.
What is the best way to do this in SQL, PL/SQL or T-SQL?
Thanks in advance.
|
This works for T-SQL. Converting it to other sql dialects should just be as simple as finding the similar methods
declare @numDigits INT = 3;
declare @maxNumber INT = POWER(10,@numDigits)-1 -- gets "999" when using 3 digits, 9999 when using 4 etc
DECLARE @input INT = 1234
DECLARE @output INT = IIF(@input>@maxNumber,@maxNumber,@input)
SELECT @output -- selects 999
Oracle does have the `POWER` function, but does not have the ternary/IIF function
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "sql, sql server, oracle"
}
|
MsgBox vbOKCancel leaves 1 or 2 in cell
I am using an inputbox with type 8 (cell reference / range). Part of the validation of the selected range is with the MsgBox below.
The problem is that when you select a wrong range and the MsgBox prompts you, if you click `Ok` it leaves the number 2 in the cell, and if you click `Cancel` it leaves the number 1 in the cell.
ElseIf myRange.Value = "" Or myRange.Value = 0 Then
'...
myRange = MsgBox("Please Select a Valid Code. Try again?", vbOKCancel + vbQuestion)
If myRange = vbCancel Then 'No retry
Exit Sub
Else 'retry
Run "MyCellToCorrect"
End If
Else
|
You're assigning the return value of `MsgBox`, which will be either `vbOK` (1) or `vbCancel` (2), to the range. You should be assigning it to a numeric variable instead, and then testing that variable:
Dim Res As Integer
....
Res = MsgBox("Please Select a Valid Code. Try again?", vbOKCancel + vbQuestion)
If Res = vbCancel Then 'No retry
Exit Sub
Else 'retry
Run "MyCellToCorrect"
End If
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "excel, vba"
}
|
Regex formatting
I have this regex format for a phone number sample 012-3456789.
malaysianPhoneRegex = "^[0]{1}[0-9]{2}[\\-]{1}[0-9]{7,8}$";
Now I want it to be able to accept 012-3456789 or 0123456789 or 012 345 6789 or 012 3456789
How do I do it, I am still learning on regex.
|
Put the space, hyphen inside the character class and then make it as optional.
malaysianPhoneRegex = "^0[0-9]{2}[- ]?[0-9]{3} ?[0-9]{4,5}$";
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, regex"
}
|
could a robot fly with powerful enough electromagnets?
The robot in question is a large, worm-like mining robot built for digging tunnels. It has electromagnets positioned throughout the segments of its body, for the purpose of pulling metals out of the surrounding earth as it digs. My question is, could this robot use its electromagnets to "push off" of the earth's natural magnetic field (or even just metals in the earth's crust), and fly through the air?
It doesn't have to be prolonged flight, only for a few seconds at a time, since doing this would obviously consume a lot of power.
I would just like to know if the feat is at all possible in the first place.
|
Suppose the electromagnet is strong enough to interact with earth's magnetic field: it will align itself like a compass needle. It will not hover or get attracted all the way to the north or south pole. Earth's magnetic field is uniform around the magnet. Magnet's N will attract Earth's S, while magnet's S will attract Earth's N. The two forces are opposite and will not pull the magnet one way or another, just make it align like a compass.
The electromagnet can be used to repel metals only if a high-frequency alternating current is applied. Here is a demonstration.
In this example, the eddy current generated in the plate is supposed to attract the metal, but the electromagnet flips polarity too fast. The repulsive force between the coil and the plate causes the coil to hover above the plate. That would the closest thing to "fly", in my opinion.
|
stackexchange-worldbuilding
|
{
"answer_score": 5,
"question_score": 2,
"tags": "earth, flight, robots, electromagnetism"
}
|
Having problems profiling memory in Python program using Valgrind
I've looked at some questions about profiling memory usage in Python programs, but so far haven't been able to get anything to work. My program must run as root (it opens a TUN/TAP device).
First, I tried `heapy`; unfortunately this didn't work for me. Every time my code tried to execute `hpy().heap()` the program froze. Not wanting to waste too much timed I decided to try valgrind.
I tried valgrind with massif:
# valgrind --tool=massif ./my_prog.py --some-options value
I think the issue is related to profiling Python programs. I tried my program (which runs as root) and no massif output file was generated. I also wasn't able to generate an output file with another Python program (which doesn't run as root). However, a simple C test program worked fine and produced the massif file.
What are the issues preventing Valgrind and massif from working correctly with Python programs?
|
Instead of having the script launch the interpreter, directly calling it as a parameter to Valgrind solves the problem.
valgrind --tool=massif python my_script.py
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 4,
"tags": "python, profiling, valgrind"
}
|
Number of preimages of hash function from bounded domain
Suppose we have an "ideal" cryptographic hash function
$H: \\{0,1\\}^{n+k}\to \\{0,1\\}^{n}$
and a given bitstring $b\in \\{0,1\\}^{n}$, Can we estimate how many preimages $H^{-1}(b)$ there are?
With ideal I mean that it behaves like a random oracle.
|
I assume you mean behaves like a uniformly chosen function from the set of functions mapping $\\{0,1\\}^{n+k}$ to $\\{0,1\\}^n.$
Let $p_z$ be the probability that the random variable $Z=|H^{-1}(b)|=z,$ for $0\leq z\leq 2^{n+k}.$ Then $$p_0=(1-2^{-n})^{2^{n+k}}\approx \exp[-2^k]$$ which is the probability that a fixed $b$ is missed $2^{n+k}$ times. Of course $\mathbb{P}(|H^{-1}(b)|=z)$ is independent of $z$ and distributed binomially, i.e., $$\mathbb{P}(|H^{-1}(b)|=z)=\binom{2^{n+k}}{z}(1-2^{-n})^{2^{n+k}-z} (2^{-n})^{z}$$
With high probability, the distribution $p_z$ is concentrated around its expectation $Z=2^{k},$ for example via the Chernoff bound.
|
stackexchange-crypto
|
{
"answer_score": 2,
"question_score": 2,
"tags": "hash, collision resistance, preimage resistance"
}
|
Regular Expression in JavaScript giving an uncaught type error
I am developing an application and want to be able to grab only the resource from the URL so I have written a regular expression, but it doesn't seem to be working and I get an uncaught type error. Can anyone help with this?
var link = document.location;
var res = link.match(/\/.*php/g);
|
`document.location` is not a string, but a `Location` object with properties describing the individual components of the URL. It therefore has no `match` method.
Try using `document.location.pathname` instead.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "javascript, regex"
}
|
Log4Net configuration in a plugin dll?
We have a plugin that gets distributed with third party software (also with our own software) Our plugin is written in C# and contains some log4net logging. In our own software, we have a .exe.config that contains our log4net section and allows for configuration. However on the third-party side we are unable to do this.
Any suggestions on how I can configure it from within the code? (Assuming it has not already been configured, in the case of our own software)?
|
The log4net environment is fully configurable programmatically.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 6,
"tags": "c#, .net, log4net"
}
|
Dyno pricing confusion
The following statements seem contradictory to me
Dynos cost $0.05 per hour, prorated to the second. For example, an app with four dynos is charged $0.20 per hour **for each hour that the four dynos are running.**
Pricing is based on calendar time. If you set your app to four dynos, you will be charged $0.20 per hour **regardless of the traffic your site serves during that time.**
(as seen here)
I'm reading it as "you will be charged for a running dyno" then "you will be charged whether or not the dyno is being used"
Please clarify my understanding, because it seems most people don't have this same confusion.
|
A Heroku dyno is considered running when it is ready to receive requests, not necessarily when it is actually serving requests. To rephrase:
> For example, an app with four dynos is charged $0.20 per hour for each hour that the four dynos are **provisioned**
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "heroku"
}
|
Is a prime number $P$ always co-prime with $n$ if $1 < n < P$?
Is a prime number $P$ always co-prime with n such that $$1 < n < P?$$ This would also make sense to me because, just to establish firm definitions, two numbers are co-prime if they share no factors apart from $1$. Hence, if a prime number $P$ is not co-prime with an $n$ such that $$1 < n < P$$ then that means that one of the factors of $n$ is a factor of $P$, which cannot be the case because $P$ is prime. This seemed to make sense to me but I wanted to double-check. I ask this because I was looking at alternate ways to fix the modulo bias in the Fisher-Yates shuffle and I think that if this is the case then I can do it.
|
Yes, that's true. Your proof is also correct.
(Making a community wiki post to get this question out of the unanswered queue without "taking credit" for the answer.)
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 2,
"tags": "prime numbers, coprime"
}
|
Django regex field - unique and without blank spaces
I have a ModelForm, in which I'm having a CharField, which is declared as unique in the Model. But I have 2 problems:
1. If I fill in the form with a field having the same name I don't get an error message.
2. I'd like this field not to contain white spaces.
Is it possible to do that using a ModelForm?
|
You can do something close to this:
class MyModelForm(forms.ModelForm):
# your field definitions go here
def clean_myuniquefield(self):
# strip all spaces
data = str(self.cleaned_data['myuniquefield']).replace(' ', '')
model = self._meta.model
# check if entry already exists
try:
obj = model.objects.get(myuniquefield=data)
except model.DoesNotExist:
return data
raise forms.ValidationError("Value already exists!")
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "django, forms, model"
}
|
Where is the Belt(?) of Shared Space?
I would swear that I've seen an item which allows anyone who has a linked copy to access the same extradimensional space; I'm 99% sure it was published by WotC or Paizo, and I'm 90% sure it was a belt. Similar to a Belt of Pockets or a Handy Haversack, the item connects to an extradimensional space and has the whole "items don't weigh anything or take up space" thing, but all of the attuned copies were connected to the _same_ extradimensional space.
Basically, it lets the players hand-wave who happens to be carrying the healing potions we found back in the previous dungeon.
I want to peg the price at 10-15k per user: high for the amount of space, but with the added convenience of "yes, I _do_ have that potion of Cure Serious".
I've looked in the Magic Item Compendium and the PFSRD, but have come up empty. I'm also striking out on Google.
Assuming I'm not crazy, where does this item live?
|
More broadly than Pathfinder; there is the Pouches of Shared Acquisition in 4ed and Leomund's Secret Chest Ritual has a similar effect.
I'm failing at finding a link for the Pouches; < is the best I've managed so far.
Specifically to Pathfinder, while it's not exactly what you are after, putting Ring Gates inside a pair of bags could work. Although sadly putting them inside bags of holding may not work as they are in different non-dimensional spaces and a GM could justifiably rule that the rings aren't within 100 miles of each other.
|
stackexchange-rpg
|
{
"answer_score": 7,
"question_score": 16,
"tags": "pathfinder 1e, dnd 3.5e, magic items, product identification"
}
|
How can I prevent photos losing vibrancy when printed?
I take a number of landscape photos which I then do quite a bit of post production work with in photoshop elements 9. When I take them to my local photographic shop (I am not talking Boots etc) and get them back they have lost much of their vibrancy and mood. I spoke to the owner and he said that is because they can never recreate the colour on modern laptops/desktops? Is this right? Do I need to go and buy an old screen to mimic what is happening at the developers? He did mention that I could download an application that could imitate various printers. What is this? Anyone else with this issue? Would welcome any advice
|
You can ask the shop for its printer color profile or try to find it online. Then you can see how your printed pictures will look on your screen. E.g this links gives printer profile for costco printers.
|
stackexchange-photo
|
{
"answer_score": 3,
"question_score": 3,
"tags": "printing, color management"
}
|
Check if a file exists in jenkins pipeline
I am trying to run a block if a directory exists in my jenkins workspace and the pipeline step **_"fileExists: Verify file exists"_** in workspace doesn't seem to work correctly.
I'm using Jenkins v 1.642 and Pipeline v 2.1. and trying to have a condition like
if ( fileExists 'test1' ) {
//Some block
}
What are the other alternatives I have within the pipeline?
|
You need to use brackets when using the `fileExists` step in an `if` condition or assign the returned value to a variable
Using variable:
def exists = fileExists 'file'
if (exists) {
echo 'Yes'
} else {
echo 'No'
}
Using brackets:
if (fileExists('file')) {
echo 'Yes'
} else {
echo 'No'
}
|
stackexchange-stackoverflow
|
{
"answer_score": 242,
"question_score": 115,
"tags": "jenkins, jenkins pipeline"
}
|
@property is not set to new value
I have one class as Model - Filter. I need to access this model from my controller. Filter.h
@interface Filter : NSObject
@property (nonatomic, assign) BOOL name;
@end
In my controller:
@implementation NavigationController
@synthesize filter = _filter;
- (IBAction)setVirtualShowProperty:(UISwitch*)sender {
self.filter.virtualRoomSet = YES;
_filter.virtualRoomSet = YES; // I dont know which syntax is better
}
@end
But it doesnt update virtualRoomSet it is still 'NO'. Where is bug? Thanks
|
It looks like you're calling setVirtualShowProperty: before calling navigationController.filter = someFilter;.
The fact that you're setting your boolean value to YES and still seeing it be NO is misleading - it's not really NO, it's just that the object you're setting it on is probably nil.
You should ensure that your navigationController.filter object is indeed not nil when you get to setVirtualShowProperty:.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "objective c, ios, cocoa touch"
}
|
Copy text file into another new text file as a sequential way
Assume I have three text files, data_1, data_2, and data_3. Firstly, I need to copy data_1 inside to another new text file (new_data). Then I need to add data_2 to new_data (includes data_1). Finally I need to add data_3 to new_data (includes data_1 and data_2).
For example,
data_1= 10 10 10
15 15 15
data_2=5 5 5
data_3= 11 11 11
12 12 12
new_data= 10 10 10
15 15 15
5 5 5
11 11 11
12 12 12
How can I perform this task as a sequential way for multiple text files?
|
As you are just appending the file contents one after another, use `cat` maintaining the sequence you want, currently this should do:
cat data_{1..3} >new_data
The shell will expand `data_{1..3}` into `data_1 data_2 data_3`, so the operation would eventually be:
cat data_1 data_2 data_3 >new_data
|
stackexchange-askubuntu
|
{
"answer_score": 12,
"question_score": 4,
"tags": "scripts, text processing"
}
|
How to pad an integer number with leading zeros?
I have strings that are being converted that need to be four characters long. The values are coming in as anywhere between 0 and 4 characters long. I need to pad the strings with zeros to make all IDs 4 characters long:
Example
Input number Need
1 => 0001
121 => 0121
0567 => 0567
So far I have tried:
int temCode = 0;
DataTable dt = objSites.Get_Max_SiteCode();
if (dt.Rows.Count > 0)
{
string siteCode = dt.Rows[0]["SiteCode"].ToString();
string code = siteCode.Substring(siteCode.Length - 4);
temCode = Convert.ToInt32(code) + 1;
temCode.ToString().PadLeft(4, '0'); // same number is coming here without any pad left.
}
|
The problem is that the following:
* `.ToString()`
* `.PadLeft(...)`
all _return_ a _new_ string, they don't in any way modify the object you call the method on.
Please note that you _have_ to place the result into a string. An integer value does not have any concept of padding, so the integer value 0010 is identical to the integer value 10.
So try this:
string value = temCode.ToString().PadLeft(4, '0');
or you can use this:
string value = temCode.ToString("d4");
or this:
string value = string.Format("{0:0000}", temCode);
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c#"
}
|
jqgrid change primary key name from id for inline edit
I have a field called date in the jqgrid and its colModel is like this :
{name:'date',index:'date', width:40, sorttype:"date",key:true,label:"date"},
So this is the primary key which is passed for inline editing. But the issue is, the value is
posted with key name as id. How can I change it to date ? My POST is like :
revenue1 0
id 2013-12-12
revenue2 1
oper edit
I would like to change it to :
revenue1 0
date 2013-12-12
revenue2 1
oper edit
|
You can use the following option of jqGrid:
prmNames: { id: "date" }
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "jquery, jqgrid"
}
|
Refer to an enum inside a struct
I have an struct defined like this in a header file:
struct MessageA {
enum Status {
eReady, eNotReady
};
};
Later, when I try to use this enum:
#include <MessageA.hh>
...
if( status != MessageA.Status.eReady ) continue;
I get the error:
expected primary-expression before '.' token
'Status' has not been declared
I tried the following and it worked:
if( status != MessageA::eReady ) continue;
However, if use:
if( status != MessageA::Status::eReady ) continue;
Then I get the error:
Status is not a class or a namespace
If I needed to specify the name of the enum fully qualified (such as if there were multiple enums with the same values inside) how should I do it?
|
Use the scope operator:
MessageA::Status::eReady;
Also note that prior to C++11 labels of enums were not scoped in which case you would be using the following code:
MessageA::eReady;
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "c++, enums"
}
|
Why models often benefit from reducing the learning rate during training
In Keras official documentation for ReduceLROnPlateau class they mention that
> Models often benefit from reducing the learning rate
Why is that so? It's counter-intuitive for me at least, since from what I know- a higher learning rate allows taking further steps from my current position, and if I'll reduce the LR I might never "escape" a certain minimum.
|
A more complete quote is:
> Models often benefit from reducing the learning rate by a factor of 2-10 **once learning stagnates.**
(my emphasis).
There are two main reasons why your learning might seem to be stuck:
1. You are around a local minimum and in every direction you might go you'd increase your error. In that case, as you correctly state, _increasing_ the learning rate might allow you to "jump out" of the local minimum.
2. You are in a steep valley and are oscillating between the walls. At one point the gradient points steep left; you make a large step in that direction and find yourself on the other side with the gradient pointing steep right. You are basically jumping back and forth far above the minimum. Here, _decreasing_ the learning rate might allow you to descend into the minimum.
The above quote refers to this second case.
|
stackexchange-stats
|
{
"answer_score": 0,
"question_score": 1,
"tags": "conv neural network, keras"
}
|
Turning Off Z3py Print Truncation
I need to print an entire Z3 problem to debug it, but when I print it the output is truncated.
from z3 import *
s = Solver()
... Add many assertions to s ...
print(s)
How do I display everything?
|
Try:
set_option(max_args=10000000, max_lines=1000000, max_depth=10000000, max_visited=1000000)
You might want to play with actual values to come up with something that suits your needs.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, printing, z3, z3py"
}
|
Examples of short maps (Lipschitz functions with $k=1$) with exactly 2 fixed points.
I was just reading about the Banach fixed point theorem, which states that a contraction (a function $f$ satisfying $|f(x)-f(y)|\leq k|x-y|$ for $0<k<1$) has a unique fixed point.
If we have $k=1$ then $f$ is called a short map or a non-expansive map. I'm wondering how many fixed points such functions can have. Clearly if $f$ is the identity function then every point is a fixed point. If $f$ just translates points then there are no fixed points.
Does there exist a function $f\colon\mathbb{R}\to\mathbb{R}$ satisfying $|f(x)-f(y)|\leq|x-y|$, which has exactly two fixed points? If not are there examples of short maps involving different metric spaces with exactly two fixed points?
|
No such $f:\mathbb{R}\to\mathbb{R}$ exists. Indeed, suppose $f:\mathbb{R}\to\mathbb{R}$ is short and $f(a)=a$ and $f(b)=b$ with $a<b$. Then for any $c\in (a,b)$, $f(c)=c$, since if $d<c$ then $|d-b|>|c-b|$ and if $d>c$ then $|d-a|>|c-a|$. So if $f$ fixes two points, it must also fix the entire interval between them.
However, there are many examples in other metric spaces. For instance, taking $S^1\subset\mathbb{C}$ with the induced metric from $\mathbb{C}$ (or the arc length metric), $f(z)=\bar{z}$ is an isometry $S^1\to S^1$ which fixes only $1$ and $-1$. Or more trivially, if $X$ is a metric space with two points, then the identity map works.
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 4,
"tags": "real analysis, analysis, metric spaces"
}
|
Exponential growth of cow populations in Minecraft
Minecraft is a computer game where you can do many things, including farming cows.
When fed wheat, cows in Minecraft breed with each other in pairs and produce one baby per pair. After about $20$ minutes, the baby/babies grow and can breed with each other and their parents. There are no genders in Minecraft, nor any issues with cows breeding with their offspring: all fully grown cows are identical.
**So what is the total number of cows after n 'breedings'?**
Starting with $2$ cows, the total number of cows goes like this:
$$2, 3, 4, 6, 9, 13, 19, 28, 42, 63, 94,$$ and so on.
Let $n$ be the number of times the cows have bred. The number of new cows (difference between two consecutive of the above numbers) equals $$\frac{n - n\%2}2,$$ where $\%$ means modulus.
So what is the total number of cows for any given $n$? I know it is a sum of some sort, but what is it?
|
This is OEISA061418, interestingly the "example" is about Minecraft. The given solution for the $n$th term is
$$ a(n) = \lceil K*(3/2)^n \rceil $$
where $K=1.0815136685\dots$ and $K=(2/3) K(3)$ where the decimal expansion of $K(3)$ is here.
For clarification as to how this formula is used, suppose you want to know how many cows you have after the $10$th breeding cycle. First,
$$ K*(3/2)^n = (1.0815136685)*(3/2)^{10} \approx 62.3655 $$
Now we have to take the ceiling of this number, which just means rounding it up to the nearest integer. Therefore,
$$ a(10) = \lceil K*(3/2)^n \rceil = \lceil 62.3655 \rceil = 63 $$
which agrees with the sequence. Note that for very large $n$, you may need to use a more exact value of $K$ (which is why I posted that second link.)
|
stackexchange-math
|
{
"answer_score": 21,
"question_score": 15,
"tags": "recurrence relations, exponential function"
}
|
Include all rows in table when value in column changes
I have an employee change table which tracks every change made to an employee work history with no clear flag for what that change is. I am trying to track the different departments that an employee has worked for including the first department he/she worked for. So all changes plus the first department he/she worked at. An employee may come back to the department he/she once worked for and we need to be bring those rows too. I have highlighted rows that I would like to bring back
Emp Change History Table
|
You seem to just want `lag()`:
select t.*
from (select t.*, lag(dept_no) over (partition by emp_no order by effective_date) as prev_dept_no
from t
) t
where prev_dept_no is null or prev_dept_no <> dept_no
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql"
}
|
SQL View to find missing values, should be simple
I have two tables with a common id, table1 has a task numbers column and table2 has documents column each task can have multiple documents. I'm trying to find all task numbers that don't have a specific document
Fake data:
SELECT * FROM table1
id tasknumber
1 3210-012
2 3210-022
3 3210-032
SELECT * FROM table2
id document
1 revision1
1 SB
1 Ref
2 revision1
2 Ref
3 revision1
3 SB
But how would I find tasknumbers which don't have a document named SB?
|
SELECT t1.tasknumber
FROM table1 t1
LEFT JOIN table2 t2 ON t2.id = t1.id AND t2.document = 'SB'
WHERE t2.id IS NULL;
There are basically four techniques:
* Select rows which are not present in other table
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "sql, sql server, sql server 2000"
}
|
What to put in "type" when adding new content to node via $node->content
I'm adding new content to a node, but I'm stuck on what to put in `#type`. I know that when you're dealing with a profile page for example, you would put
`'#type' => 'user_profile_item'`
but what to put for new content on a node?
$node->content['newc'] = array(
'#type' => , //what to put here for type
'#title' => t('New'),
'#value' => $newc,
}
|
If you want something displayed on the node page with a title, you'll likely want to use '#type' => 'item'. Otherwise just to display some kind of output/markup the only thing you need is '#value' => 'the html or theme output here'.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "php, drupal, module, drupal modules"
}
|
Regex split on words unless in quotes or brackets
How do I split the following using Regex
words and [other word] combined with "words in quotes"
The output should be split as:
words
and
other word
combined
with
words in quotes
Thanks!
(Answers do not have to be in perl but in general regex format is fine.)
|
You can do it like this:
$string = 'words and [other word] combined with "words in quotes"';
while($string =~ /(?|\[([^]]*)]|"([^"]*)"|(\w+))/g) {
print $1 . "\n";
}
I use the branch reset feature `(?|...|...|...)` to give the three capturing groups the same number.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "regex, perl"
}
|
Java - Using a Conditional To Specify a Parameter in a Super Method
I have a parameterized method that is extended from another class. The abstract class Account is the parent, and SavingsAccount inherits the constructor from it. This constructor is a parameterized constructor. I would like to use a conditional to allow (or disallow) certain values into the double init_balance field which would then invoke the super() for the parent constructor.
if(init_balance < minimumBalance){
//Print message to user asking for larger deposit. (is this enough to do?)
}
But the java language asks me to place the invocation to the parent constructor first-thing in the child constructor. So I can't filter through the child constructor what goes into the parent constructor.
Here is my code on gist
|
If you want to keep a constructor based object creation you can come up with this:
public class SavingsAccount extends Account {
private SavingsAccount(String init_id, double init_balance)
{
super(init_id, validate(init_balance));
}
public static double validate(double init_balance) {
if (init_balance < minimumSavings) {
System.out.println("Message");
throw new RuntimeException("Message"); // or handle this error
}
return init_balance;
}
}
Yet - looking at your example I would probably choose to do the validating outside the constructor.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "java, class, inheritance, constructor, super"
}
|
How can you block the image to appear on WebBrowser Control?
I have created a simple web browser using c# and I want to block the images to appear on WebBrowser control. Can you please show me a sample code for this? Thanks in advance.
|
You can remove image-tags from the source htm like this:
string content = new WebClient().DownloadString(@"
string contentWithoutImages = Regex.Replace(content, @"<img(.|\n)*?>", string.Empty);
webBrowser1.DocumentText = contentWithoutImages;
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "c#, .net"
}
|
Does `QLPreviewItem` works with local files only?
I'm uploading images to `firebase` and in return I'm getting uploaded image URL as `
Now, I have to display this image in `QLPreviewController`. I'm giving the above firebase URL of my uploaded image as `QLPreviewItem`, but `QLPreviewController` displaying filename text instead of image, you can see in the below screenshot. I confirm that the URL has image.
![enter image description here](
Can you please help me to show the images in `QLPreviewController`
|
`QLPreviewItem` works with local file URLs only, it won't download your file for you if you provide it a remote file url.
You need to download your file to your app's local file system before presenting `QLPreviewController` and provide it that local file url.
For advanced usage - multiple urls, dataSource, delegate handling - you should watch Quick Look Previews from the Ground Up from **WWDC 2018**.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ios, swift, qlpreviewcontroller"
}
|
Round table arrrangement for 13 people using graph theory
> 13 Members of a new club ,meet each day for lunch at a round table. They decide to sit such that every memher has different neighbours at each lunch.How many days can this arrangement last?
By using normal combinatorics we can find that number of days is six. But I have no idea how to do it using graph theory.
|
Draw the thirteen vertices in a circle. You can draw six different graphs on these vertices by connecting each vertex to the on next to it, skip one, skip two, etc. Each graph is a cycle graph and indicates the order around the table for one day if you follow the cycle.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 2,
"tags": "combinatorics, graph theory, algebraic graph theory"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.