INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How to keep string with quotes?
If user insert this data **16" HOUSEHOLD STAND FAN AA070021A** the output should be same like this **16" HOUSEHOLD STAND FAN AA070021A** but i only get this output 16\ HOUSEHOLD STAND FAN AA070021A, the quotes become "\" .
Before :
16\ HOUSEHOLD STAND FAN AA070021A
After :
16" HOUSEHOLD STAND FAN AA070021A
add_to_quote.php?product_name=16" HOUSEHOLD STAND FAN AA070021A
<?php
$product_name_1 = $_GET['product_name'];
$product_name_2 = str_replace('"', "", $product_name_1);
$product_name = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $product_name_2);
echo $product_name;
?> | Add `urlencode()` to your link:
<a href="add_to_quote.php?product_name=<?php echo urlencode($product_name) ?>">Add To Quote</a> | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "php"
} |
Is there a way to write custom fractions in this format: ½, ⅘, ⅞, etc.?
As the title says,
> Is there a way to write custom fractions in this format: ½, ⅘, ⅞, etc.?
by adding some packages or so? | \documentclass{article}
\usepackage{xfrac}
\begin{document}
\sfrac{1}{2}, \sfrac{4}{5},
\end{document}
 gem install houston`
* Send VoIP notification: `$ apn push "<token>" -c /path/to/apple_push_notification.pem -m "Hello from the command line! "`
Hope this will help someone else!!
Happy coding :) | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 0,
"tags": "swift, xcode, voip, pushkit"
} |
JS get the clicked element with event.target
I am trying to use JavaScript to get a clicked element's information.
Here is the jsFiddle.
And below is my code.
let div = document.querySelector('div')
div.addEventListener('click', function(event) {
// how to get the clicked p tag here?
// this?
// event.target.currentTarget?
})
<div>
<p>text 1</p>
<p>text 2</p>
</div>
How can I use `this` to get the element's information?
Answer: `event.target` Thanks Juan Mendes | Welcome to StackOverflow!
`e.target` should give you the exact element that was clicked to generate the event.
`e.currentTarget` will give you the element that the event is at when the function was called (after bubbling up from the `e.target`)
div.addEventListener('click', (e) => {
console.log(e.target) // the p that was clicked
console.log(e.currentTarget) // this div
}) | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 3,
"tags": "javascript"
} |
Changing a variable inside a function?
I'm trying to get the visitor's OS, but it looks like I'm doing something wrong.
var OS = "N/A";
["windows", "linux", "mac"].forEach(function(item) {
if(new RegExp(item).test(navigator.userAgent.toLowerCase())) {
var OS = item;
}
});
console.log(OS);
Any help, please? | You need to remove the `var` inside the if condition, as you are redeclaring the variable. Only then, you can assign a new value to the variable on the outside.
var OS = "N/A";
["windows", "linux", "mac"].forEach(function Detect(item) {
if(new RegExp(item).test(navigator.userAgent.toLowerCase())) {
OS = item;
}
});
console.log(OS); | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": -1,
"tags": "javascript"
} |
How to slice a list from an element n to the end in python?
I'm having some trouble figuring out how to slice python lists, it is illustrated as follows:
>>> test = range(10)
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> test[3:-1]
[3, 4, 5, 6, 7, 8]
>>> test[3:0]
[]
>>> test[3:1]
[]
>>> test
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
To my understanding, python slice means lst[start:end], and including start, excluding end. So how would i go about finding the "rest" of a list starting from an element n?
Thanks a lot for all your help! | You can leave one end of the slice open by not specifying the value.
test[3:] = [3, 4, 5, 6, 7, 8, 9]
test[:3] = [0, 1, 2] | stackexchange-stackoverflow | {
"answer_score": 119,
"question_score": 80,
"tags": "python, list, sequence, slice"
} |
Bad operand types
public double getRandKg(double[] value)
{
double min = 0.0;
double max = 0.0;
value * 0.90 = min; <------ this is where it says bad operand
value * 1.10 = max; types for binary operator '*'
Random r = new Random(); first type double[] second type double
double randomValue = min + (((max-min)+1) * r.nextDouble());
return randomValue; //
}
It's late and maybe I just can't think straight. It's just saying I can't multiply a `double[]` by a `double`? | `double[]` is an array. How can you multiply an array of `double` values with a single double value?
use `double[someIndex] * doubleVar` to multiply with a single value, and put the expression on the right side, not the left. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -4,
"tags": "java, operand"
} |
IText 7 - Adding border for the page
I am looking for adding page border without hardcoding width and height in IText 7.
Tried with Rectangle, but no setBorder method in Itext 7. Also, this is for the entire page.
Rectangle rect= new Rectangle(100, 100);
rect.setBorder(2);
rect.setBorderColor(BaseColor.BLACK);
document.add(rect);
**Pdf creation**
final PdfDocument pdfDoc = new PdfDocument(new PdfWriter(pdfFileName));
final Document doc = new Document(pdfDoc);
PdfPage page = pdfDoc.getPage(1);
Rectangle pageRect = new Rectangle(page.getTrimBox());
;
Rectangle pageRect = new Rectangle(page.getTrimBox());
new PdfCanvas(page).setStrokeColor(ColorConstants.RED).setLineWidth(5).rectangle(pageRect).stroke(); | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": -2,
"tags": "itext7"
} |
Would the moon be brighter if it were completely spherical?
I remember reading Galileo's 'Dialogue Concerning the Two Chief World Systems' where Salviati and Sagredo explain how the moon would be almost entirely dark if it were a perfect sphere but after discussing this with a friend recently I wonder whether Galileo's argument might actually be wrong.
If you follow the following link on page 69, Sagredo gives the following argument:
'If the moon were smooth as a mirror, only a very small part would show itself to the eyes of a peson as illuminated by the sun, although an entire hemisphere would be exposed to the sun's rays. The rest would remain, to this observer's eyes, unilluminated and therefore invisible' | That depends on how literal you want to be. If the moon were perfectly spherical, but the dust on top were the same, it would be just as bright as it is now.
However take that to a literal extreme replacing the moon with a perfect sphere, most of the light hitting the moon would not bounce to your eye but would reflect based on the angle in which it hits. It would turn the moon into a gigantic spherical mirror. And as such, the sun's light would be represented by a tiny bright dot representing the small point where the sun's light would have to hit in order to reach your eye.
It would certainly be bright but not much brighter than the brightest star in the sky, while most of the rest of the moon would reflect the blackness of space. | stackexchange-physics | {
"answer_score": 5,
"question_score": 3,
"tags": "optics, geometric optics"
} |
Image Thumbnail Display in Drupal with Colorbox
I'm not very familiar with Drupal and I was hoping for some guidance. I believe a module called "Colorbox" is what I'm working with here, but I'm not sure. I have views of different content types, basically they're all different kinds of pictures. (Portrait, Landscape, etc.) Each view/content-type has it's own page. In the Content Type>Manage Display section, I can set the format of the image to be "Colorbox" but instead of getting pages that look like this:
<
I get pages that look like this:
<
Any help would be appreciated. | The Content Type >> Manage Display setting is for "Node" settings. If what you have shown us is in fact a View (Embedded in a Node perhaps?) and not just Node output, then you need to adjust the settings in your View.
If it's a View, it looks like it's set to show a title instead of the actual image field but I can't be sure. You would also need to specify Colorbox settings and image settings as well in the specific View.
Can you confirm the screen capture you provided is of a View or simply Node output? | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "drupal, colorbox"
} |
Calculate the area of the region in the first quadrant...
Calculate the area of the region in the first quadrant bounded by the curves $4y = x, x^2y = 16, $ and $xy = 16.$
!My solution
Was I right in adding the area under $y = 16/x^2$ from 8 to 4 back in? | You are making this more complicated than it needs to be. Why not just split the shaded region up into two regions, one from $x=1$ to $x=4$ and the other from $x=4$ to $x=8$. Then the area is \begin{equation*} \int_1^4 \left(\frac{16}{x} - \frac{16}{x^2}\right)\,dx \+ \int_4^8 \left(\frac{16}{x} - \frac{x}{4}\right)\,dx. \end{equation*} | stackexchange-math | {
"answer_score": 3,
"question_score": 2,
"tags": "integration, area"
} |
Checking for exact matches in two dictionaries
I have multiple dictionaries, some consisting of data, and one having values I want to check match in the data dictionaries.
data = {a: '1', b: '2', c: '3', d: '4', e: '5', f: '6', g: '7'}
desiredValues = {b: '2', e: '1', g: '7'}
For the matching keys in each dictionary, I want to compare the values and see if they match or not. If 1 or more of the values doesn't match, I want to know which ones. Ultimately, I'd like to be able to have some sort of setup where I could compare multiple dictionaries of data to the single desired values dictionary and get an output for each one along the lines of:
b = True
e = False
g = True
Thank you for taking the time to read my question! Sorry if it's rather simple, I just haven't been able to find a clear way to do this yet. | Iterate through `desiredValues`, then check if the key is in `data` using `data[key]` where `key` is the current key from `desiredValues`:
data = {'a': '1', 'b': '2', 'c': '3', 'd': '4', 'e': '5', 'f': '6', 'g': '7'}
desiredValues = {'b': '2', 'e': '1', 'g': '7', 'z':'shouldn\'t be in data'}
for key, value in sorted(desiredValues.items(), key=lambda i: i[0]):
if key in data:
print('{}:'.format(key), value == data[key])
else:
print('{}:'.format(key), 'not in data')
Output:
b: True
e: False
g: True
z: not in data | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "python, dictionary"
} |
Links not working from subdirectories
I want to make multiple pages on my website, but to keep everything clean I want to make different directoriess with the different pages. However, I use php to make a different file with my header that is included in all my pages, so I only have to change the code of my header once and it will be the same on all pages.
The problem is that the links I use in my menu items (like home, contact, about, etc.) will not work anymore when you're on a page inside a directory (I'll make an example below).
So my question: Is there a home folder on a website (like ~/ on unix) or is there another way to make it work?
Example of my directory structure:
htdocs
index.php
header.php
menus
contact.php
about.php
(a link to index.php won't work anymore if you're on the contact.php page) | Sounds like you're using relative paths in your menu links. Use an absolute path instead by starting with a "/":
<a href="/index.php">Home</a>
<a href="/menus/about.php">About</a>
or a complete URL:
<a href="
<a href=" | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "php, html, home directory"
} |
How to prove that if a line is perpendicular to the radius of a circle at its endpoint of the circle, it must be tangent to the circle.
I have seen proofs for proving if a line is tangent to the circle, then it has to be perpendicular to the radius of the circle. But I want to know how you can prove the other direction of this statement since this is biconditional statement. Start with the hypothesis that some line is perpendicular to the radius of the circle, then prove it must be a tangent line to the circle.
If I were to use the proof by contradiction, do I have to consider the case where the line intersects the circle at two points as well as the case when the line is not meeting the circle at all? | The hypothesis should be that line $t$ is perpendicular to the radius $OT$ at point $T$ on the circle of center $O$. In that case, if $P$ is another point on $t$, different from $T$, then we have $OP>OT$ (hypotenuse is greater then leg). It follows that all points of $t$, except $T$, are external to the circle, and $t$ is thus a tangent. | stackexchange-math | {
"answer_score": 5,
"question_score": 1,
"tags": "geometry"
} |
How to build CPython for Android?
I want to port some algorithms written on Python to Android. The algorithms don't use any OS specific staff, only several CPython modules for data processing. And I don't want to use some heavy frameworks like kivy. Are there any easy way to build cpython for Android? | I didn't find how to build it. But I downloaded Crystax NDK and found out python libraries already compiled and just copied them to my project. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "android, python, cpython"
} |
UIWebView Error in iPhone
I am getting this error in webview while loading this url : <
"Error Domain=WebKitErrorDomain Code=102 UserInfo=0xde6ce0 "Frame load interrupted""
[webView loadRequest:[NSURLRequest requestWithURL:
[NSURL URLWithString:@"thumbzine.com/rssfeed.php?vol=104"]]];
What is this error due to ?
Thanks | Try this
NSString *urlText = [NSString stringWithString:@"
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlText]]]; | stackexchange-stackoverflow | {
"answer_score": -1,
"question_score": 2,
"tags": "objective c, uiwebview"
} |
Persisting data for amazon ec2 instance running postgres
I am provisioning a cheap postgres instance for myself by installing directly on amazon ec2. Everything will be deployed using terraform. I would like the database data to persist between restarts / teardown / redeploy of infra.
What is the conventional way to achieve this?
* **(a) define an amazon EBS resource separately** , so that terraform teardown does not destroy it, and always provide its arn as a mounted storage attachment to the ec2 instance?
* **(b) define amazon EBS resource with terraform** , but set a `final_snapshot = true` and also set a `snapshot_id` so that on _terraform destroy_ , the data will be backed up somewhere. If so, how do I reincorporate this data in the next ec2 instance?
* **(c) something else** I don't know about / haven't thought of?
Any tips appreciated. | You can provision the EBS resource out of band, fetch (or store) the volume id and associate with it. Or you can also use EFS the same way, using user-data to mount EFS on boot | stackexchange-superuser | {
"answer_score": 0,
"question_score": 1,
"tags": "amazon ec2, postgresql, terraform"
} |
Azure data disk - Getting files from exported disk file
I have recently done an azure disk export. This disk was attached as a data disk to one of my Linux VM. I had mounted one of my pods volume to this disk. Unfortunately, due to some problem with the environment, I am unable to re-mount my disk. Now, I want to take the backup of those files which are on the disk. I ran a disk export which downloaded a file with the name abcd without any extension. File with given properties: -
` and `GetDirectLinkToPublished` methods of the provider.
I would really like to inserts custom HTML code (instead of the standard linked image) in this window, so I can embed functionality for previewing images and galleries. Is this possible through the ECL provider, or do I need to make a GUI extension to add something like a new preview to implement such functionality? | ECL does currently not support this, so you would have to make your own UI extension. | stackexchange-tridion | {
"answer_score": 3,
"question_score": 7,
"tags": "2013, ecl"
} |
$x$ is a non-negative integer and $\sqrt{x^2 + \sqrt{x + 1}}$ is a positive integer.
> Find non-negative integer $x$ such that $\sqrt{x^2 + \sqrt{x + 1}}$ is a positive integer.
Because $\sqrt{x^2 + \sqrt{x + 1}} > x$, we let $x^2 + \sqrt{x + 1} = (x + y)^2, (y > 0)$
That means $$\begin{aligned} &x^2 + \sqrt{x + 1} = x^2 + y^2 + 2xy\\\ &\implies \sqrt{x + 1} = y^2 + 2xy\\\ &\implies x + 1 = y^4 + 4x^2y^2 + 4xy^3 \end{aligned}$$
And this is where I was stuck. | **Hint:**
For $x>0,$
$$x^2 < x^2+\sqrt{x+1} < (x+1)^2,$$
so there's no solution besides $x=0$. | stackexchange-math | {
"answer_score": 6,
"question_score": 0,
"tags": "algebra precalculus"
} |
Ant -f<buildfile> not working but -file<buildfile> works
Has anyone else seen ANT refuse to honour the -f option but happily work with the -file option.
ant -f cms.xml etc etc - gives the response: build.xml does not exist!
ant -file cms.xml etc etc - : works
This is ANT 1.8.1 with IBM JRE 1.6. Certainly the first time I've ever seen such behaviour. The -f option was working with one target but not with another. Each target was calling a different custom task.
Can the setting of properties in each custom task upset the -f option?
I would appreciate any thoughts, Stuart. | Looking at the source code, I can't see how this is possible as `-f` and `-file` are treated in exactly the same way.
else if (arg.equals("-buildfile") || arg.equals("-file")
|| arg.equals("-f")) {
i = handleArgBuildFile(args, i);
}
I'd encourage you to look at the source too. | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 1,
"tags": "java, ant"
} |
Codeigniter - hand over variabel / title tag from controller to the view
i`ve a simple controller. Now i want to change the title for each site. I want to hand over a < title > variabel like $title to my header.php ?
<title><?php echo $title; ?></title>
This is my really simple Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Site extends CI_Controller {
public function index() {
$this->home();
}
public function home() {
$this->load->view("site_header");
$this->load->view("site_nav");
$this->load->view("content_home");
$this->load->view("site_footer");
}
public function about() {
$this->load->view("site_header");
$this->load->view("site_nav");
$this->load->view("content_about");
$this->load->view("site_footer");
}
} | Adding Dynamic Data to the View
Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading function. Here is an example using an array:
$data = array(
'title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message'
);
$this->load->view('blogview', $data);
when you want to dislay that variable data within view etc... | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "php, codeigniter"
} |
Module to edit field data on multiple instances/nodes (in bulk)
I've a need to allow my client to easily edit the price field for the projects (content type). In total there're about 1.5k nodes and he wants to change the price once and that it would be applied to all the 1.5k projects/nodes.
Is there a way to do it using some of the existing modules in an easy way, so that an amateur could make the change? Or can it be achieved by custom module, if so could you give some instructions in terms of how should it be done programatically?
I'm not a developer, but will pass it to my colleague, who's a developer. He tried to code a custom module, but it takes about 18min to update the field data for 1.5k nodes... So apparently something is not right.
Thanks. | For Drupal 7 you will need views bulk operations which packages this and other bulk operations. For Drupal 8 you need Bulk Update Fields
Below the procedure is for Drupal 8 but very similar for Drupal 7
Install the module and modify the **Admin content** view found by going to `admin/structure/views/view/content` or perhaps you can use any view that you want.
`add field` and search for `Node operations bulk form` to add and make sure you enable
**Selected actions: Bulk Update Fields to Another Value**
With this when on the view page you can select 1 or more nodes and modify fields in bulk | stackexchange-drupal | {
"answer_score": 1,
"question_score": 0,
"tags": "7, nodes, entities"
} |
Skin Editing/Overlaying bullet holes
You see, especially in FPS games, when a bullet hits a wall or a character, etc. You end up with the bullet hole.
Is this usually done with the actual skin temporarily changing, or just an overlay of another image (or something totally different)?
Could anyone give me pointers on how to go about this? I'm using XNA (C#) | A naive solution would be to use a small quad positioned and rotated to match the surface where the bullet hit with a transparent texture of a bullet hole.
There are some more advanced techniques involved if you want the hole to clip properly if you shoot near an edge of a wall, or if you shoot something rounded.
These are called "decals" if you want to look into more details. Here's a blog post that goes into some of those techniques. < | stackexchange-gamedev | {
"answer_score": 5,
"question_score": 3,
"tags": "xna, c#, xna 4.0"
} |
Как прокинуть IP-адрес через роутер?
У меня есть статический IP в сети. Дома стоит роутер. Как мне прокинуть IP к определенному ПК, чтоб можно было зайти на него из вне по IP? | На роутере - раздел Port forward, а дальше - интуитивно, ибо не знаю, какой роутер. | stackexchange-ru_stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "windows, ip, роутер, static ip"
} |
sshguard - must a user declare behavior rules?
From this answer I understand that `sshguard` does include a default behavior that should suit most users, at least those with minimal webserver environments, yet it wasn't clear to me from the documentation and from this article if one **must** change the defaults or add directives upon them.
Must a user declare behavior rules for `sshguard`? Isn't it shipped with a default set of rules (similar to CSF-LFD)? | All what you will need to do is:
* Setup your iptables for ports managed by sshguard as writen in article.
* Review defaults for sshguard in config. You will need to check if default values fits your server needs. Ex. number of failed auths on ssh before adding ip drop to iptables. Or time for which the rule should be there.
Most of those should be fine but when you are running service where auth failures are quite common like webmail where user is trying to remember his password by trying it 10times or 20 times you should consider checking the config. | stackexchange-askubuntu | {
"answer_score": 2,
"question_score": 2,
"tags": "ssh, security, iptables"
} |
Why isn't there Math.Pow that takes an int as the exponent?
I read that the `Math.Pow` implementation is pretty complicated to be able to handle fractional powers. Why isn't there a version that takes an int for the exponent to make a faster version when you don't need fractional powers? | Because you'd just need to convert it back into a float to multiply it against the logarithm of the base.
# nm = em × ln n | stackexchange-stackoverflow | {
"answer_score": 6,
"question_score": 11,
"tags": "c#, .net, performance, math"
} |
Filter categories/tags to display in multiple metaboxes for selection in back-end
My site uses a lot of categories and tags for author selection in the back-end. To make it more user friendly for authors I need to arrange the categories and post tags in numerous metaboxes for selection on the post edit screen. I would like to display some selected categories and their children in one metabox for author selection while other categories will go into a second and third metabox and so on. The same should apply to the tags. Can anyone point me in the right direction how to accomplish such a customization? Can I register new taxonomies which will include categories/tags based on their ID's and create new metaboxes displaying only those ID's?
The Wordpress default metaboxes for categories and tags display all categories in one box.
Thanks! | Yup! Just register a new taxonomy in your functions.php and it'll show up in your post editor.
function my_custom_taxonomy(){
$args = array(
'settings' => 'here'
);
register_taxonomy('Authors', 'post', $args);
}
add_action('init', 'my_custom_taxonomy');
< | stackexchange-wordpress | {
"answer_score": 1,
"question_score": 0,
"tags": "categories, metabox, tags"
} |
Which class to define as positive in unbalanced classification
In a classification task, why do we usually choose the minority class as "positive" case for response variable? For example, if there are 1000, 9000 for class A and B respectively, we usually define class A as 1 and class B as 0, thus the response variable can have average as 0.1 instead of 0.9. If the response variable has average like 0.6 or 0.7, will there be any issues for the classification algorithm? Do we need to choose the class with average 0.4 or 0.3 as positive class? Thanks in advance! | It does not matter. It is done that way because it would be something like disease detection where most people don’t have the disease, but that’s what you want to catch. However, all of the math works out fine either way. If you made the heathy class the $1$s, your model would be outputting the probability of being healthy instead of the probability of having the disease. The English phrasing of those two might carry different connotations, but the mathematical logic is the same. | stackexchange-stats | {
"answer_score": 8,
"question_score": 5,
"tags": "classification, unbalanced classes"
} |
What is different between itms vs itms-apps when opening url from device
I've an app in appstore and when it has an update the link was given in the format `itms://itunes.com/apps/[AppName]` Now I've recently uploaded a new version of my app and from the older app when I click the update link it takes us to store but doesnt give option to update. It gives a button saying open, I have to then take the store option again for download then it comes with the update option. So, I changed the link format to `itms-apps://itunes.com/apps/[AppName]/[AppId]` and this time when I clicked on the link it opened up correctly giving me option to update. Was this a new update in the format? What was the difference between opening link between these two formats? | Using `itms-apps:` will leads you to **App Store** directly.
Using `itms:` will leads you to App Store page in **iTunes Store**. You'll see "App Store" as navigation title and a button links you to App Store on the upper right corner.
I used to use `itms:` in my app. But I found that app status on iTunes Store was sometimes not up-to-date as App Store was. I haven't confirmed what caused this but now I use `items-apps:` instead. | stackexchange-apple | {
"answer_score": 2,
"question_score": 2,
"tags": "ios, itunes, applications, ios appstore, url"
} |
Is it true that a ring has no zero divisors iff the right and left cancellation laws hold?
This is the definition of zero divisor in Hungerford's _Algebra_ :
> A zero divisor is an element of $R$ which is **BOTH** a left and a right zero divisor.
It follows a statement: It is easy to verify that a ring $R$ has no zero divisors if and only if the right and left cancellation laws hold in $R$; that is, for all $a,b,c\in R$ with $a\neq 0$, $$ab=ac~~~\text{ or }~~~ba=ca~~~\Rightarrow~~~ b=c.$$
I think it is not true. But I can't find a counterexample. | **Lemma** : A ring has a left (or right) zero-divisor if and only if it has a zero divisor.
**Proof** : Assume $ab=0$ for $a,b\neq 0$.
If $ba=0$, you are done - $a$ is both a left and right zero divisor.
If $ba\neq 0$, then $a(ba)=(ab)a=0$ and $(ba)b=b(ab)=0$, so $ba$ is a left and right zero divisor.
* * *
Now it is much easier to prove your theorem.
If $ax=ay$ and $R$ has no zero-divisors, then $a(x-y)=0$. But, by the lemma, $R$ also has no left-zero divisors, so either $a=0$ or $x-y=0$.
Similarly for $xa=ya$.
On the other hand, if cancellation is true, then $a\cdot b=0=a\cdot 0$ means that either $a=0$ or $b=0$. So there can't be any left zero divisors, and thus no zero divisors. | stackexchange-math | {
"answer_score": 7,
"question_score": 9,
"tags": "abstract algebra, ring theory"
} |
Is every sigma algebra generated by some subclass.
Let $\Omega$ a non empty set and consider and $\cal{A}$ a sigma algebra in $\Omega$. Is there always a set $\cal{C}\subset\mathscr{P}(\Omega)$, $\cal{C}$ strictly contained in $\cal{A}$ such that $\cal{A}$ is generated by $\cal{C}?$
For example, is the Lebesgue measure generated by some $\cal{C}?$
**Obs.** <
I have already seen the discussion in the above link, but I'm not asking noting special about the class $\cal{C}$.
Also in the above case the answer is quite sophisticated. I'm wondering if in the question I ask the answer is more simple. | If you take $\mathcal{C}=\mathcal A$, then you'll have a set that generates $\mathcal A$. If you want a smaller set, take $\mathcal{C}=\mathcal{A}\setminus\\{\emptyset\\}$. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "measure theory"
} |
copy treeview to list<treenode> by value
I'm trying to copy a list to a list, but it keeps copying it by reference, so a change in one changes the other. I tried cloning but it didn't copy the parent- child relationship.
foreach (TreeNode item in listNodesdestination)
testNode1.Add((TreeNode)item.Clone());
thanks. | Since it is serializable, you could perform a deep copy using a memory stream. deep copy via memory stream - stack overflow | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": ".net, winforms, treeview"
} |
Natural log summation representation
In working through a problem, I've encountered the need to express
$\log n = \sum \limits_{k = 1}^{n - 1} \log(1 + \frac{1}{k})$
where $\log k $ is the natural logarithm of k. I'm fairly certain the above equality holds (please let me know if otherwise), but I'm not quite sure how to derive it. Any help would be greatly appreciated.
So far, I've tried expressing $\log n = \log(n!) - \log((n-1)!)$ to no avail.
Many thanks! | It telescopes after you do a little algebra:
$$\begin{align*} \sum_{k=1}^{n-1}\log\left(1+\frac1k\right)&=\sum_{k=1}^{n-1}\log\frac{k+1}k\\\\\\\ &=\sum_{k=1}^{n-1}\big(\log(k+1)-\log k\big)\\\ &=\log n-\log 1\\\ &=\log n\;. \end{align*}$$ | stackexchange-math | {
"answer_score": 6,
"question_score": 2,
"tags": "logarithms, summation"
} |
Can't download DOC or PDF from iCloud web app
> **Possible Duplicate:**
> Why won’t iCloud let me download Pages documents uploaded from a computer?
I recently updated Pages, Numbers and Keynote to the latest versions, and my OS to Mountan Lion. I went ahead and tried the "documents in the cloud" feature by saving a Pages document on iCloud.
As a long time user of the now shut-down iWork.com beta, I was surprised and pleased to find the following menu on the iCloud.com iWork web app:
!Download Pages document in multiple fornats
**iCloud appears to allow download in other formats but the options are disabled for some reason. How can I enable this document to be downloaded in PDF and WORD formats?** | It seems to be enabled after having opened on iOS, my thinking is that it's something to do with the message you get when opening an iOS version of something created on OS X, which lets you open copy or open, saying that it may look different. Anyway, after opening on iOS, you can download from iCloud.com in all three formats, however, after saving or editing on OS X the PDF and DOC options are blanked again. | stackexchange-apple | {
"answer_score": 2,
"question_score": 1,
"tags": "pages, iwork, icloud"
} |
Хочу вывести дату создания и дату редактирования таска, но выдает белеберду. Laravel+Vue
 in tasksProp" :key="task.id" >
<td scope="row">{{ task.id }}</td>
<td>{{ task.title }}</td>
<td>{{ task.description }}</td>
<td>{{ task.created_at }}</td>
<td>{{ task.updated_at }}</td> | Такой ответ обычно возвращается с БД (универсальный формат даты). Вы можете форматировать его в необходимый при выводе из API в Laravel (используется Carbon):
'created_at' => $user->created_at->format('Y-m-d H:i:s')
Вы также можете форматировать дату на фронтэнде, например, через Moment:
this.$moment(date).format('YYYY-MM-DD HH:mm:ss'); | stackexchange-ru_stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "laravel, vue.js, api"
} |
How to change UITextField keyboard type to email in Swift
In objective-c I can just say the following.
[self.promoTextField setKeyboardType:UIKeyboardTypeEmailAddress];
I tried googling it but just get ways to do it in objective-c. | Try this :
# Swift 3
self.promoTextField.keyboardType = UIKeyboardType.emailAddress
// Or Shorter version
self.promoTextField.keyboardType = .emailAddress
# Swift < 3
self.promoTextField.keyboardType = UIKeyboardType.EmailAddress | stackexchange-stackoverflow | {
"answer_score": 152,
"question_score": 60,
"tags": "swift, uitextfield"
} |
timely in-app purchases on ios
Are we able to open any timely in-app (as consumable) for any time period like 1 day or even 1 hour? What is apple's reaction to such in-app?
If I am able to do it, and I don't want it to be a subscription type of in-app (not recurring) what is my in-app's type? Should it be consumable or subscription?
Any articles and tips on timely in-app purchases on iOS, consisting Apple's behaviour would be appriciated.
possible examples:
* 1 Hour Super Strength
* 1 Day Invisibility | That's a typical use of a consumable item. You might want to start the applicable time frame on first use instead of when bought.
Keep in mind that you will need to track the purchase and usage yourself, and it might involve your own server if it's tied to an application that the user can play on several devices or platforms. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "iphone, objective c, ios, in app purchase"
} |
Can we find exotic energy from outer space which is several times powerful than nuclear energy?If antimatter how?
Some thing Like we see in sci fi films | Currently we do not have enough knowledge/understanding on the workings of Dark Energy or Dark Matter to come to a satisfying conclusion that answers your question but for now, the substance that can create the biggest boom with the least amount of it is AntiMatter. An Antimatter - Matter annihilation bomb would create a very big explosion of pure energy, way bigger than what Nuclear Fusion or Fission can ever achieve. Maybe next time we might find more exotic forms of Matter and manipulate it enough to create a bomb that you proposed. | stackexchange-physics | {
"answer_score": 0,
"question_score": -4,
"tags": "energy, cosmology, exotic matter"
} |
Win IoT: Ethernet Config
Is there any way to reconfigure default Ethernet settings on Raspberry Pi 3 with Win 10 IoT? I managed to get it working with WiFi and it does connect with my PC over Ethernet cable, but still I would like static address possibly etc. | You can do this using PowerShell if you setup a remote management session to your device.
For example:
$adapter = Get-NetAdapter `
-Name Ethernet
New-NetIPAddress `
-InterfaceAlias $adapter.Name `
-AddressFamily IPv4 `
-IPAddress 192.168.1.55 `
-PrefixLength 24 `
-DefaultGateway 192.168.1.1;
Set-DnsClientServerAddress `
-InterfaceAlias $adapter.Name `
-ServerAddresses ("192.168.1.2","192.168.1.3") | stackexchange-raspberrypi | {
"answer_score": 2,
"question_score": 1,
"tags": "pi 3, windows iot"
} |
nginx, x-accel-redirect and mime types
In my nginx 0.8.34 setup I'm using the X-Accel-Redirect feature to control file downloads in the application code while not having the application handle the download itself.
After much pain this now basically works except nginx always returns the file with `text/html` content type.
The default content type is application/octet-stream, specified in the `http` block.
The server block contains, among other things, the definition of the directory where the files are stored:
location /files {
default_type application/octet-stream;
alias /srv/www/uploads;
internal;
}
So I specified the content type even here but nothing has changed.
I don't want to set the Content-Type by the application because then I would slow me down (I'd first have to determine it). So ideally nginx would return the correct mimetype based on the file extension (I do include mime.types in the `http` block). | If you want to let nginx guess the right mime type, you juste have to make sure no content-type is returned from your backend server.
With django:
response = HttpResponse()
response['Content-Type'] = ''
response['X-Accel-Redirect'] ='/my/file.jpg'
return response | stackexchange-serverfault | {
"answer_score": 17,
"question_score": 10,
"tags": "nginx, mime, mime type"
} |
Is a Multiple Domain SSL Cert necessary for Exchange?
We have a client with an external domain of abc.com and an internal domain of xyz.local. I see a lot of articles stating that for Exchange you should have a multi-domain cert that has Subject Alternate Names for both the external and internal domains. However, we have a couple clients that have only the external name covered in the certificate and it seems to be working fine. They aren't receiving SSL error messages in Outlook or when accessing OWA. Can anyone explain why a cert that covers both the external and internal domain name would be necessary? Are there circumstances where someone could skip the internal domain without consequence?
As pointed out in the comments I could have phrased my question better. Can someone give any good reasons to have a cert that covers both internal and external domain names? This is suggested by this DigiCert article: < I've also seen Microsoft TechNet articles say something similar. | Really this should be Joe's, as his comment is basically the answer...but to bring it home I guess:
> **Can someone give any good reasons to have a cert that covers both internal and external domain names?**
Most shops that run Exchange do so for their own employees. As such employees often work on their computers on the internal LAN that the Exchange server(s) are on, and resolve these server's to internal DNS names.
At the same time, such employees use smart phones, work from home, work during traveling, etc. and need accessibility via ActiveSync, Outlook Anywhere, OWA to use the Exchange servers "services". Thus requiring resolution to EXTERNAL DNS names.
Typically internal and external domain names aren't the same (both in regards to hostname and domain name). | stackexchange-serverfault | {
"answer_score": 0,
"question_score": 0,
"tags": "ssl, exchange, domain, certificate"
} |
Pass hidden value in webpage using jqGrid javascript to server code on record insert
I want to insert a new record in the jqGrid with a default field (hidden) as a parameter to the controller. I was able to pass the parameter for the grid get query request by using
datatype: 'json',
postData: {
parameter_to_pass: function () { return document.getElementById('the_hidden_field').value; }
},
but I can't get the create new record to work.
Thanks in advance! | If you use form editing the you can extend the data, which will be send during Add operation, by usage of `onclickSubmit` callback:
$("#grid").jqGrid("navGrid", "#pager", {},
{}, // edit options
{ // add options
onclickSubmit: function () {
return {
parameter_to_pass: $("#the_hidden_field").val()
};
}
}
); | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, jquery, jqgrid"
} |
Sort complexity expressed via distinct number of elements
I am reading Probabilistic counting algorithms for database applications. In the introduction an algorithm for finding an intersection is specified:
Sort A, search each element of B in A and retain it if it appears in A.
It is claimed that if a, b are number of elements in A and B, and $\alpha, \beta$ are the number of distinct elements in A, B then the complexity of this algorithm is $O(a\log\alpha + b\log\alpha)$. My question is, why the sorting of A is only dependent on the number of distinct elements? Is there some kind of algorithm I am not aware of? If so, why the same algorithm could not be used for the second strategy? The second strategy is:
Sort A and B, use merge-like operation to discard duplicates.
For this algorithm the complexity is $O(a\log a + b\log b + a + b)$ which makes sense to me. | You can use a balanced binary search tree to sort $A$ in time $O(a\log\alpha)$ by going over the elements of $A$, for each element searching whether it already appears in the tree, inserting it if it isn't already there. You can then perform the second stage in $O(\log \alpha)$ per element of $B$, for a total of $O(b\log\alpha)$.
If you are allowed to use hashing on the elements of $A$ and $B$, then you can use a dynamic hash table to compute the intersection in expected $O(a+b)$ time by using a similar strategy. | stackexchange-cs | {
"answer_score": 3,
"question_score": 2,
"tags": "algorithms, complexity theory, sets"
} |
Compute cohomology ring of $S^1 \times \mathbb{C} P^{\infty}/(S^1 \times \{x_0\})$
I want to compute the cohomology ring of the space $S^1 \times \mathbb{C} P^{\infty}/(S^1 \times\\{x_0\\})$.
By Künneth formula, the cohomology ring of $S^1 \times \mathbb{C}P^{\infty}$ is $\mathbb{Z}[\alpha, \beta]/(\beta^2,\alpha \beta)$,where $\alpha$ is the generator of $H^2(\mathbb{C}P^{\infty})$ and $\beta$ is a generator of circle. But how to compute the quotient space really puzzles me. I also know that there is a formula $H_i(S^1 \times X)=H_i(X)\oplus H_{i-1}(X)$. However I don’t know whether this formula helps? Maybe we can use the long exact sequence for pairs, but it’s still complicated to compute. Hope someone could help. Thanks! | Your space is the reduced suspension of $\mathbb{C}P^{\infty} \sqcup * $. This implies the multiplication is trivial, and Mayer-Vietoris says the additive structure of a suspension is just the cohomology shifted up.
The key geometric picture to have is that your space is the union of two cones on projective space, joined at the base and tip. | stackexchange-math | {
"answer_score": 1,
"question_score": 2,
"tags": "algebraic topology, homology cohomology"
} |
How can I apply log laws here?
Solve for $x$: $$ 2^{2x+1} - (17)2^x + 8 = 0 $$
I have the answers: -1, 3
I tried a few different transformations, but couldn't get a clear answer. I suspect that I am overlooking a property of log that would be useful.
Edit: using a u substitution for $2^x$, I was able to factor the quadratic into:
$(2u-1)(u-8)$
$2^x = 1/2$
$2^x = 8$
$x = -1, 3$ | Don't bother with log at first. The real question is, what is $2^{2x+1}$ in terms of $2^x$? I.e. if you have the latter, what do you do to it to get the former? That way you can say $u=2^x$ is its own variable, rewrite the equation entirely with $u$, solve for $u$, and _then_ take the base-2 logarithm to find $x$. | stackexchange-math | {
"answer_score": 2,
"question_score": 2,
"tags": "logarithms"
} |
What does presale mean in Ethereum?
I have seen a lot of discussions about presale wallets, but have no idea what it means.
What do the terms "presale" and "presale wallet" mean in Ethereum? | The presale ran from 22nd of July 2014 to 2nd September 2014. This was before the general public launch of the network.
For the first couple of weeks, 2000 ETH cost 1 BTC. Thereafter, your 1 BTC gradually got you fewer ETH. See:
What was the approximate cost of 1 ETH during pre-launch (Aug 2014)
The "presale wallet" was the keystore file loaded with the ETH each participant purchased, which could then be downloaded.
See Launching the Ether Sale blog post for more information. | stackexchange-ethereum | {
"answer_score": 6,
"question_score": 7,
"tags": "presale, terminology"
} |
Graph of composition of absolute function
Let $f$ be defined as $$f(x)=\begin{cases}x-1&-1\le x \le0\\\x^2&0 \le x \le 1\end{cases}$$ and $$g(x)=sin x$$ Then find $$h(x) = f(|g(x)|) + |f(g(x))|$$
I have drawn $f(x)$:
$ from here? | I assume that $g(x)$ is also defined in the interval $[-1,1]$.
Take at first the interval $[-1,0]$. Then $g(x)= \sin(x) \le 0$ but $|\sin(x)| \ge 0$. Therefore
$$x\in [-1,0] \quad \to \quad h(x) = f(|\sin(x)|) + |f(\sin(x))| = \sin^2(x) + |\sin(x) - 1| \\\ = \sin^2(x) + |1-\sin(x) | = \sin^2(x) + 1-\sin(x), $$ In the last line I used the fact that $(1-\sin(x)) \ge 0\to |1-\sin(x)|=1-\sin(x))$.
Now for the second part of interval, $[0,1]$,
$$x\in [0,1] \quad \to \quad h(x) = f(|\sin(x)|) + |f(\sin(x))| = \sin^2(x) + \sin^2(x) = 2\sin^2(x).$$ | stackexchange-math | {
"answer_score": 1,
"question_score": 0,
"tags": "functions, graphing functions, absolute value, function and relation composition"
} |
Android releasing and app into the market
I am nearly done with my first android app and there's still a bit more work to do but I want to get feedback from users about what they like/hate/bugs to fix, etc. I plan on making the app free with ads. Now I have been testing my app on my phone (HTC Magic) and plan on doing some simple testing on the emulator using different configurations. Would it be a good idea to release the app as being beta as it is now? And then fix up any issues and implement the full features I want in it later on and re-release it? I don't want the beta ratings to hurt the final version so would I'm guessing I simply release it as a new app instead of an update to the beta?
Also If I was to release the beta should I be releasing it with or without ads?
I would love to hear your experience with your apps!
Thanks | In this kind of situations, that's exactly what you can try to do: release a beta version of your app so that the bugs don't hurt your rating on the Market. What I prefer to do in this kind of cases:
* Don't add Ads. After all, it's just to be a testing experiment. Not too many people is going to download your app.
* Offer a bounty for people who discover bugs. For example, you can give a free fully functional copy of your app to the people who helped you find bugs.
* Use a Log system for Android that automatically send you reports of your app.
* Try to make sure your app will be tested on different devices with different screen sizes, configurations, etc.
Once you have fixed bugs and done the appropriate modifications you can go ahead and share your app with the whole world. | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 2,
"tags": "android, release, beta, google play"
} |
Find the leftmost (most significant digits) of a large exponent calculation, say $99^{99}$
I want to find the initial 10 digits of an exponent calculation whose result is a very large number - Say, $99^{99} = 3.697296 \times 10^{197}$
I only need to know the digits $3697296$
Is there any way of finding this without doing the full calculation? | Use common logarithms and a decent calculator. Using a fairly mediocre one on your example, I get $99\log_{10}99\approx197.5678842652$; subtracting $197$ and raising $10$ to the resulting power, I get $3.697296376497$, so the number must be about $3.697296376497\times10^{197}$.
**Added:** More generally, for $a^b$ calculate $b\log_{10}a$, subtract the integer part, and raise $10$ to the resulting power. If $n=\lfloor b\log_{10}a\rfloor$, the integer part of $b\log_{10}a$, your number is
$$10^{b\log_{10}a-n}\times 10^n\;,$$
and you’ll be able to read of the most significant digits from the lefthand end of $10^{b\log_{10}a-n}$. | stackexchange-math | {
"answer_score": 5,
"question_score": 4,
"tags": "logarithms, power series, exponentiation"
} |
How to exchange content depending on a boolean?
I want to exchanges some content in my page.html depending if an boolean is true or false. So I've seen that you could create things like this with the `<ng-content>`but somehow this didn't work out. I get this error: `Error: Template parse errors: <ng-content> element cannot have content.` I also notice that there has to be some way to delete the old content.
page.html
<ion-card>
<!-- content to move away when bool true-->
</ion-card>
<div *ngIf="!checked">
<ng-content>
<ion-card>
<!-- new content when bool false-->
</ion-card>
</ng-content>
</div> | Would having two separate conditionals work for you?
<ion-card *ngIf="checked">
<!-- content to move away when bool true-->
</ion-card>
<ion-card *ngIf="!checked">
<!-- new content when bool false-->
</ion-card>
If that does not work, you could use a _switch_
<div [ngSwitch]="checked">
<ion-card *ngSwitchCase="true">
<!-- content to move away when bool true-->
</ion-card>
<ion-card *ngSwitchCase="false">
<!-- new content when bool false-->
</ion-card>
</div> | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 2,
"tags": "javascript, html, angular, ionic4"
} |
ArcPy Changing Spatial Database Connection
We have moved some servers which had ArcGIS application and SDE on it to another server and the IP has changed. Now when I want to open my .mxd file it tries to connect to remote SDE with old connection settings and opening old works but really takes long time, consequently I want to change my database connection in .mxd file.
Is there any fast way to change SDE settings programmatically with not opening the .mxd file in ArcMap?
import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Users\arc\Desktop\election2011.mxd")
brklist = arcpy.mapping.ListBrokenDataSources(mxd)
print brklist
Above code really takes along time. without this code i can open my .mxd file with same time above code and can change manually... | We had this same problem with really sucks. The MXD tries for 15 minutes to find the old server before giving up. We got around this problem by giving a new server the old SDE server's IP address. The new server has nothing to do with GIS or databases. However, the MXD tries to connect then gives up right away once it sees that the SDE data source is no longer there. The MXD opens quickly with the broken layer icons so you can fix the data source on your own. | stackexchange-gis | {
"answer_score": 1,
"question_score": 3,
"tags": "arcmap, enterprise geodatabase, arcpy"
} |
VB.NET IsNothing() Not Working as Expected?
I have a query like so:
Dim clcexists = (From p In dbContext.Signatures _
Where p.StudentID = people_id _
And p.ContractType = "clc" _
Order By p.ID Descending _
Select p)
Later I check whether any rows exist in clcexists using IsNothing like so:
If IsNothing(clcexists) Then ' If no CLC is on file.
clcfirst = Date.Now.Subtract(year)
clcdate = clcfirst
Else ' If CLC is on file.
clcfirst = clcexists.FirstOrDefault()
clcdate = clcfirst.SignatureDate
End If
But IsNothing() is not functioning like I expect. There is no row in the results table, but it is still acting as if there is and going to the Else clause. Help? | You might want to use `Any` instead:
If Not clcexists.Any() Then ' no CLC is on file.
clcfirst = Date.Now.Subtract(year)
clcdate = clcfirst
Else ' If CLC is on file.
clcfirst = clcexists.FirstOrDefault()
clcdate = clcfirst.SignatureDate
End If | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "asp.net, vb.net"
} |
Pass parameter client to server-side with RIA services
I'm using RIA Services with EF and a Silverlight UI and the built-in validation framework. Problem is the following:
The validation rules differ slightly based on user-input client-side, consider this simple scenario.
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (validation_mode == Modes.Normal)
{
// do normal validation
}
else
{
// do admin validation
}
}
I'd like a way to pass the 'validation_mode' to RIA services, server-side. Can i somehow pass it to the ValidationContext.Items collection? Perhaps I'm going about this the wrong way?
Thanks in advance! | You can add the validation_mode to the ValidationContext:
ValidationContext.Items.Add(new KeyValuePair<object,object>("validation_mode", validation_mode)); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": ".net, silverlight, wcf, entity framework, wcf ria services"
} |
Why the file id, in telegram bot, not work after some days?
I am using telegram API and create php telegram bot. For sending video file with `sendVideo` method, use `file_id` like `BAADBAADbwADhd7gCEpUooz4V5Q1Ag`. But after some days this `file_id` not worked and I have to upload this video file again. What is the problem? | as you can read in this link:
> Can I count on file_ids to be persistent?
>
> For the moment, file_ids for your bot's outgoing files may be recycled after several thousand files have been sent. This may be changed in the future. Inbound file_ids can be treated as persistent.
so if you send a file from your server to telegram user (over the bot), the returned `file_id` can't be permanent. you can forward the file from user to bot and save `file_id` instead of that. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 3,
"tags": "api, telegram, telegram bot, php telegram bot"
} |
How to reload page with new data in Node.js
I'm using express-handlebars as my template engine and I have created an 'Article' template. I have 5 articles in total. I need to show the user each article but randomly. How would I create a 'Next' button that could reload the page with a new article?
I have thought of using a cookie in the browser and implementing some sort of array within it to decide the next article to be shown (the array will be randomised). As with loading the articles, I have thought of creating a new page for each article and then redirecting the user to a random page when the click 'next', but that wouldn't be making much use of the template engine.
I don't have code to show as I'm looking for a concept that would work.
I want the user to open my website, be shown a random article, click next and another article appear. I don't want each user to have the same sequence of articles (obviously with many users this is impossible but I'd like to minimise it). | For 5 articles,
1\. track the articles already read by a user via cookies
2\. add a query parameter to the article template link like `randon=1` so as to respond back with a random article and another parameter `not_in=*already read article ids*` to exclude these ones. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "javascript, node.js, express handlebars"
} |
Sonos API Redirect URI
I have a question about the Sonos API authentication redirect URI. In previous projects I have used a redirect URI that my native application can intercept. Such as `myApp://auth-code`. That does not appear to be possible with the Sonos API as it expects the redirect URI to be publicly routable and HTTPS. Must I have my own server that sits between my native client and the Sonos API? I have a feeling I may be missing something simple here. Thanks for your time. | Just have a dummy endpoint e.g. firebase cloud function that does a redirect to your own custom scheme, e.g., location.href="myapp-scheme://..."
make sure to append the query parameters.
you can also avoid opening an external browser by embedding a safari webview. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 4,
"tags": "sonos"
} |
this is giving me a parse error
the code giving me the parse error
$sql = INSERT INTO 'tdrilslt_ramen'.'awnsers' ('name', 'choices');
the whole code
<?php
include 'database.php';
try{
$name = $_POST['name'];
$sql = INSERT INTO 'tdrilslt_ramen'.'awnsers' ('name', 'choices');
$q = $conn->prepare($sql);
$q->execute(array(
':name '=> $name,
':choices ' => $choices));
}catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit;
}
?> | You are using the wrong identifiers for your db/table.
It should be backticks (note the quotes you are presently using)
Plus, you are using PDO and using quotes for your column names `('name', 'choices')` that is incorrect. They should be `:` placeholders:
$sql = "INSERT INTO `tdrilslt_ramen`.`awnsers` (:name, :choices)"; | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": -4,
"tags": "php, pdo"
} |
get_users() timeout on big userbase -- options to divide query?
We run a daily cron that gets **all** the users' data and updates their values. The problem is that get_users() is timing out because of the big userbase. Yes, I can update the `php.ini` file and increase the timeout limit, but it would only delay the inevitable.
So, potential solution is to `get_users()` in batches. For example, on the first batch, we get the users with ID 1-1000. Is the best approach to use the `include` parameter and list 1-1000 IDs in an array? Seems quite desperate.
What other options are there for scenarios like these? | You are on the right track with the batch idea. You'll need a combination of parameters in your get_users() call. A combination of the "number" and "offset" parameters should get you what you need. In the example below $count is a reference to the batch that's currently running.
<?php
// inside a loop where $count is the number of times the loop has run
$args = array(
'number' => 1000,
'offset' => $count * 1000,
);
get_users($args)
?>
UPDATE: $count would start at 0.
The first time through the loop you'd get a set of 1000 users starting from the first user in the database because 0 * 1000 = 0 (no offset)
The second time through the loop you'd get another set of 1000 users starting from the 1001st user in the database because 1 * 1000 = 1000 (i.e. skip the first 1000 results and retrieve the next set)
Your loop should continue for as long as you have results being returned. | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 1,
"tags": "users"
} |
Set a variable into the result from an equation from 2 tables
Hi everyone I want to create a trigger that will automaticly set the field "Total_Commande" with that equation "contenu_commande.quantite* produit.prix_unitaire". It means (quantity*unit price) But the thing is I am not sure how to do this because I need to take the price from the other table. So I tried something but I really dont think this the right way. Anyone have a clue ?
Thank you :)
CREATE OR ALTER TRIGGER AjoutTotal
on contenu_commande
after insert
as
begin
update Total_Commande
set Total_Commande = (SELECT contenu_commande.quantite*produit.prix_unitaire
FROM contenu_commande
JOIN produit ON produit.no_produit = contenu_commande.no_produit)
where no_commande in (SELECT no_commande FROM inserted)
end``` | something like this, didn't test but It should work:
CREATE OR ALTER TRIGGER AjoutTotal
on contenu_commande
after insert
as
begin
update
contenu_commande
set
Total_Commande = contenu_commande.quantite*produit.prix_unitaire
FROM contenu_commande
JOIN produit
ON produit.no_produit = contenu_commande.no_produit)
where
no_commande in (SELECT no_commande FROM inserted)
end | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "sql"
} |
$f^*f_*(\mathcal{F})$ is surfective if $\mathcal{F}$ is generated be global sections
Suppose $\mathcal{F}$ is a sheaf of module on $X$,$f:X\to Y$,suppose $\mathcal{F}$ is generated by global sections. Is $f^*f_*(\mathcal{F})\to \mathcal{F}$ is surjective ?
To check on stalks, $f^*f_*(\mathcal{F})_x \cong f_*(\mathcal{F})_{f(x)} \to \mathcal{F}_x$, and it became messy..
And is there counterexample or is this condition necessary? | Let's call $F \in \mathsf{Mod}(X)$ good if $f^* f_* F \to F$ is an epimorphism.
$1.$ Step: $f^* G$ is good for every $G \in \mathsf{Mod}(Y)$. In fact, then the map is a _split_ epimorphism by the triangle identities of the adjunction between $f_*$ and $f^*$.
$2.$ Step: If $F'$ is a quotient of $F$ and $F'$ is good, then $F$ is good. This follows from the obvious commutative diagram.
$3.$ Step: If $F$ is generated by global sections, then $F$ is good. This is because $F$ is a quotient of a direct sum of copies of $\mathcal{O}_X = f^* \mathcal{O}_Y$, so that we may apply Steps 1 and 2. | stackexchange-math | {
"answer_score": 2,
"question_score": 4,
"tags": "algebraic geometry"
} |
Beginner: Need to find better way to get something done
I am working out of the Learn Python the Hard Way book and I have a very beginner question. I am trying to get it so that the code below does not have to go through such a weird way to check if a number was given, also, I want numbers that don't have 1 or 0 to be valid.
def gold_room():
print("The room is full of gold, how much do you take?")
choice = raw_input("> ")
if "0" in choice or "1" in choice:
how_much = int(choice)
The idea that I had was to get it to check if choice was an integer, and if so then trigger the code, but I can not figure out how to do this. I am sure the answer is very simple, and I'm sorry for such a basic question. Thank you for your help! | If you are looking only for non-negative integers, than `choice.isdigit()` will suffice. It returns `True` or `False`, depending on whether `choice` consists of all digits or not. Complete solution:
def gold_room():
choice = raw_input("The room is full of gold, how much do you take? ")
if choice.isdigit():
return int(choice)
else:
return None | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "python"
} |
Deploy Flask app with FastCGI, unexpected application root
I deployed my website made with flask to bluehost following the tutorial here. Namely I used apache and fastcgi. In the my application.fcgi file, I have:
#! /home2/wandonye/python/python34/envs/flask/bin/python
project = "vshare"
from flup.server.fcgi import WSGIServer
from vshare import create_app
application = create_app()
WSGIServer(application).run()
But then every link generated by url_for has an extra myapplication.fcgi in it. So instead of having "www.mydomain.com/signin" I got "www.mydomain.com/myapplication.fcgi/signin".
Feels like my PROJECT_ROOT is changed.
I used to deploy the website on my own computer with apache+uWSGI without any problem.
Is there anything special about fastcgi I should keep in mind? How can I remove the unwanted "myapplication.fcgi" in my links. | I eventually find a solution here
The problem is essential to fcgi, not about apache setup. So the only way to work around it is to change the string coming from url_for, delete the unwanted “xxx.fcgi” | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "apache, flask, fastcgi, bluehost"
} |
How to see which analytic table is bound to the dashboard in wso2 das
In **WSO2 DAS** , I have created a Dashboard conatining a Gadget to display the analytic table as a bar chart. But when I try to get the json of the Dashboard and the gadget, It does not contain any inform on which analytic table/stream is bound with the gadget.
Please let me know on how to find out which analytic table is bound to the gadget in the dashboard.
Thanks in advance!! | First of all, I assume that you have created gadgets using "Gadget Wizard" (if not please let me know)
Then the analytic table name can be found in the following configuration file.
gadget_folder/js/gadgetconf.js
In above configuration file, there will be an attribute called 'datasource' and that points to the actual analytics table.
Thanks,
Upul | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "wso2, wso2 das"
} |
In OpenERP, Import and Export menu not shown
I'm learning **OpenERP**. I created a new **Database** but I want to **import csv file** but not seeing it's menu. Can Any one help me where from I get?
Thanks in Advance,
Cheers | Following step try it.
* **Setting Menu => Configuration => General Settings**
* You See the **Import / Export menu**. Now mark it **True** and than go your place where you want to import or Export file.
Hope you will see the what you desire. ;-) | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "openerp 7"
} |
Class Extension Java
I have class A, and class B ( extends A ). I'm attempting to call out methods from class B, when B is cast as A. Is this possible?
Ex.
A myObject = new B();
myObject.myMethodFoundInB(param); | You can do it by casting back to B, ie:
A myObject = new B();
((B)myObject).myMethodFoundInB(param);
or, more safely:
A myObject = new B();
if (myObject instanceof B) {
((B)myObject).myMethodFoundInB(param);
} | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "java, extend"
} |
ANDROID_SDK_HOME , a system variable or user variable?
I tried setting **ANDROID_SDK_HOME** variable in following way :-
**Control panel -> Advanced system setting -> Environment variables -> ....**
After that I got two options whether to create `ANDROID_SDK_HOME` variable as a **SYSTEM VARIABLE** or a **USER VARIABLE**. And what should the **VALUE** of this variable be.
Pictorial answers will be deeply appreciated. | Whether it should be a system or user variable depends on a few specific factors. A system variable applies to all user (and service) accounts on your computer, while a user variable applies to only your Windows user account. If your Windows user account is the only one used for Android development, then a user variable is appropriate.
The value of this variable should point to the location where you extracted the Android SDK on your computer. If you used the installer and not the ZIP file, the environment variable should already be set.
\b' , expand = False).dropna().tolist()
This helps extract all items which have "8 Number followed by s followed by 2 more numbers" like 01234567s12 or 98765432s23
But i want to do something opposite that is input the product ID and get its regex. The product ID can be anything say ABC123456 or C234-D456
So is there a code which can help me get the regex ? | I used `re` module to do this .
import re
text ="12345678S00"
y=""
for i in range(0,len(text)):
r=re.match('[a-zA-Z]',text[i])
if r!=None:
y+='s'
r=re.match('[0-9]',text[i])
if r!=None:
y+='\d'
r=re.match('[.,_=&*()%^@$!#-]',text[i])
if r!=None:
y+='\S'
\d\d\d\d\d\d\d\ds\d\d #output | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -3,
"tags": "python, regex, python 3.x"
} |
SQL Server query questions
I have two tables, `tblRooms` and `tblReservations`. Each table has a `UnitId`.
When a room in `tblRooms` is reserved for a specific date, a record in is created in `tblReservations` with the `UnitId` and the reservation date.
How would I write a SQL query to list all the rooms in `tblRooms` that do not have a reservation on a specific date in `tblReservations`? | Use `LEFT JOIN`:
SELECT t1.*
FROM tblRooms t1
LEFT JOIN tblReservations t2
ON t1.UnitId = t2.UnitId AND
t2.reservation_date = '2017-01-30'
WHERE t2.UnitId IS NULL | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": -1,
"tags": "sql server"
} |
JqueryUI Tooltip : Show tooltip of div when focus on a field in another div
I have a form with tooltips that appears when the mouse hover on the label. I'd like the same tooltip (same position, same text) to also appear on focus of the associated input field.
<div>
<div title='hello world'>hello world</div>
<div> <input name="test" /></div>
</div>
I don't want to add a `title="..."` in the `<input>` because in my real case scenario the tooltip are bigger and it would make the UI look messy, so I want to trigger the tooltip of the `<div>hello world</div>` on focus of the `<div><input></div>`
I created a dummy example here : < | I hope you do not mind using a library to achieve that. Instead of independent/indie libraries, you can use jQueryUI's tooltip functionality.
jQueryUI Tooltip
<div>
<div id="label" title='hello world'>hello world</div>
<div> <input id="test-input" name="test" /></div>
</div>
$(function() {
$( document ).tooltip();
});
$('#test-input').hover(function(){
$( "#label" ).tooltip( "open" );
}); | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "javascript, jquery, jquery ui"
} |
Is it possible to use "Cover" as page number in PDF using Acrobat?
I know that we can create a "Cover" as page number in PDF for example using TeX.
But for an existing PDF file, is it possible to change a page number to the text "Cover"? I have Acrobat installed.
Thanks. | You can change the name of the pages in Adobe Acrobat Pro and use custom words instead of numbers only. You can also rename and adjust all the sections' page name independently if you want.
* * *
In Acrobat Pro, open your preference panels and go in the "Page Display" options.
**Check the box "Use Logical page Numbers"**
=\frac{2}{\sqrt\pi}\int^x_0e^{-t^2} dt$$
Here is the question:
> Show that the odd function erf is bounded, by using the fact that:$$e^{-t^2} \le te^{-t^2} , t \ge1$$ Remark: The normalisation of erf is chosen so that: $$ \lim_{x→∞}\mathrm{erf}(x) = 1.$$
I think that in order to show that the error function is bounded I need to do a substitution into the error function, however I am not sure how to go from there. | We have immediately:
$$erf(x)=\frac{2}{\sqrt\pi}\int^x_0e^{-t^2} dt \le \frac{2}{\sqrt\pi}\left[\int_0^1 1 dt +\int^x_1 te^{-t^2} dt\right]=\frac{2}{\sqrt\pi}\left[1-\frac{1}{2}\int_1^x \frac{d}{dt}(e^{-t^2})dt\right]$$
By the fundamental theorem of calculus, the last part is equal to:
$$\frac{2}{\sqrt\pi}\left[1 -\frac{1}{2}\left(e^{-x^2} - e^{-(1^2)} \right) \right] \le \frac{2}{\sqrt\pi}\left[1 -\frac{1}{2}\left(0 - 1 \right) \right] \le \frac{3}{\sqrt{\pi}}=constant$$
This concludes the proof. | stackexchange-math | {
"answer_score": 1,
"question_score": 1,
"tags": "error function"
} |
Let $\{w_1, w_2,\dotsc,w_n\}$ be an orthonormal basis for $\mathbb{R}^n$. Prove that, for any vectors $u$ and $v$ in $\mathbb{R}^n$.
I'm trying to prove $$u+v= (u·w_{1} + v·w_{1})w_{1} + \dotsb + (u·w_{n} + v·w_{n})w_{n}.$$
I'm not sure how to go about this problem. | Since $(w_1,...,w_n)$ is a basis, for every $u$ there is a unique sequence $(u_1,...,u_n)$ of scalars such that $u=\sum_{i=1}^n u_iw_i.$
Since $(w_i,w_j)=0$ when $j\ne i$ we have $(u,w_j)=\sum_{i=1}^nu_i(w_i,w_j)=u_j(w_j,w_j).$
Since $w_j$ is a basis vector we have $w_j \ne 0$ so $(w_j,w_j)\ne 0.$ So $(u,w_j)=u_j(w_j,w_j)\implies u_j=\frac {(u,w_j)}{(w_j,w_j)}.$
As this is for every $j,$ we have $u=\sum_{j=1}^n \frac {(u,w_j)}{(w_j,w_j)}w_j.$
The formula in your Q, when $u=w_i$ (for any $i$) and $v=0,$ is $w_i=\sum_{j=1}^n(w_i,w_j)w_j=(w_i,w_i)w_i.$ This is false unless $(w_i,w_i)=1$ because $w_i\ne 0$.
If $(w_1,...,w_n)$ is an orthonormal basis then $u=\sum_iu_iw_i=\sum_i\frac {(u,w_i)}{(w_i,w_i)}w_i=\sum_i(u,w_i)w_i,$ with a corresponding formula for $v,$ and the sum of these formulae is $u+v.$ | stackexchange-math | {
"answer_score": 3,
"question_score": 1,
"tags": "linear algebra, proof writing, vectors, orthogonality"
} |
display /admin/builds/blocks in several page drupal
how to moderate for /admin/builds/blocks because i have 150 blocks and this loaded page is very slow , can i this page show in several page? or show any region blocks display in page? | 1. You could use Views Hacks module which would let you create a custom view of the blocks.
2. You could use the increasingly popular Context module which would allow you to do _some_ configuration without needing the /admin/build/blocks
3. You could try out this experimental module. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "drupal, drupal blocks"
} |
A differential form to compute the k-volume of a k-parallelogram in n dimensions
Computing the k-volume of a k-parallelogram (i.e. a parallelogram spanned by k n-dimensional vectors) in n dimensions is straightforward: Let $P=[\overrightarrow{v_1},...,\overrightarrow{v_k}]$, then the k-volume is equal to $\sqrt{det(P^{T}P)}$. For instance, if n=3 and k=2, then this formula reduces to the norm of the cross-product and thus gives the 2-volume (area) of the parallelogram spanned by two 3-D vectors.
Now this fact is very useful when trying to find the k-volumes of manifolds (e.g. areas of 2-D surfaces in 3-D) by integration.
My question is, is there differential form or a form field that would serve the same purpose? In $\mathbb{R}^3$ for instance, the elementary 2-forms give you the signed area of the "projection" of the 2-parallelogram onto (x,y) or (x,z) or (y,z) planes depending on the form you use, but not the area of 2-parallelogram living in the space. | No, you need to know what plane $\vec n\cdot\vec x=0$ your parallelogram in $\mathbb R^3$ lies in to write down the $2$-form that gives oriented area of the parallelogram. One of the distinguishing features of complex (differential) geometry is that there is, for each $k=1,\dots,n$, a $2k$-form on $\mathbb C^n$ that gives the $(2k)$-dimensional area form on _every_ $k$-dimensional complex subspace. | stackexchange-math | {
"answer_score": 3,
"question_score": 4,
"tags": "linear algebra, multivariable calculus, differential forms"
} |
Finland - SIM Card provider with data plans
I will be visiting Finland for 1 month near the end of this month, for a business trip. I would like to know how easy it is to get a SIM card with a data plan right after I land at the Helsinki Airport; and perhaps some recommendations on which providers have the best coverage. Price is not really a concern, I just need to ensure that the data access is very stable. I would be happy to hear your thoughts.
I went through a few mobile provider websites by googling it, but unfortunately I cannot read Finnish.
Thanks. | There are three major networks in Finland Elisa, DNA and Telia. All of them have a really good coverage in the whole country and unless you're going to a specific place in the countryside I wouldn't worry too much about the coverage. Coverage maps for all the operators are here Elisa, DNA and Sonera. The best and probably only place at the airport to buy a SIM-card is R-kioski for which you can see details here < (Should be google translatable) | stackexchange-travel | {
"answer_score": 3,
"question_score": 3,
"tags": "internet, data plans, finland, mobile operators"
} |
Jhipster Gateway / Service usage
Within Jhipster the documentation states:
> **Generating entities in a microservices architecture**
>
> If you choose to generate the entity from a microservice, you will need to enter the path to this microservice on your local computer, and then JHipster will generate the front-end code on the gateway.
No lets say I have multiple Gateways. Does this mean if I have a common Microservice Application. I create the Microservice Application entity then run the generator within each Gateway that would use this service?
Is this the intent of the generator? | Yes, you can have multiple gateways which use the same microservice. As you said, you will have to run the generator within each Gateway and enter the path for your microservice.
The main intent was having one gateway communicating with multiple microservices. | stackexchange-stackoverflow | {
"answer_score": 5,
"question_score": 0,
"tags": "spring cloud, jhipster"
} |
how to make email templates in Joomla?
I want to make a email template to use in Joomla back-end. does it possible? how? I looked up at Joomla docs and didn't find my answer. I use Joomla 2.5.7. | Firstly upgrade your Joomla version to the latest 2.5.x version
As for the e-mail template, you will need to install a component that allows such a feature, like a Newsletter component. I personally would recommend JNews, however more can be found at the following link:
<
Hope this helps | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 0,
"tags": "joomla"
} |
Read region from very large image file in Java
Is there a Java library that can read regions of very large image (e.g. JPEG) files (> 10,000 x 10,000 pixels) without keeping the whole image in memory.
Or alternatively, which Java library is capable of handling very large image files with a minimum of overhead. | Standard ImageIO allows you to read regions of (large) images without reading the entire image into memory first.
Rectangle sourceRegion = new Rectangle(x, y, w, h); // The region you want to extract
ImageInputStream stream = ImageIO.createImageInputStream(input); // File or input stream
Iterator<ImageReader> readers = ImageIO.getImageReaders(stream);
if (readers.hasNext()) {
ImageReader reader = readers.next();
reader.setInput(stream);
ImageReadParam param = reader.getDefaultReadParam();
param.setSourceRegion(sourceRegion); // Set region
BufferedImage image = reader.read(0, param); // Will read only the region specified
} | stackexchange-stackoverflow | {
"answer_score": 12,
"question_score": 10,
"tags": "java, image processing, jai"
} |
Group query for months
I have this table.
+------------------------+--------------------+-----+
| id |mydate |value||
+------------------------+------+-----+-------------+
| 1 |2018-06-18 18:34:09 |50 |
| 2 |2018-06-18 12:34:09 |50 |
| 3 |2018-08-18 13:34:09 |10 |
| 4 |2018-08-18 14:34:09 |10 |
| 5 |2018-09-18 16:34:09 |20 |
| 6 |2018-09-18 17:34:09 |10 |
+------------------------+--------------------+-----+
I would like a Query to get something similar Group for months
I would like a consultation to achieve this
|mydate |value|
+---------------+
June |100 |
August |20 |
September |30 |
**in case it is not possible with MySQL. (It could be in PHP)** | You should use `sum`, `group by`, and `MONTHNAME` to get the result you need.
select sum(value), MONTHNAME(mydate) as month
from test
group by month
~~If you require the text version of the months you could swap that in PHP.~~
< | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "php, mysql, mysqli"
} |
posting url in bibliography in overleaf as reference
I have to post a link to this website < as a reference, I am using in my documentation. I see in my template in overleaf I wrote in the file BIBeusflat2019.bib
@misc{microsoft,
author =
title =Discover and manage shadow IT in your network
url ="
}
but then when I compile the pdf I do not get the url as reference link in pdf . I am using a template here <
So how do I post a link to URL in this case? | Go the .cls file of the template
and change
\RequirePackage{graphicx}
to
\RequirePackage{graphicx, hyperref, url}
this adds the required packages. Now go to the .bib file an add your entry as
@misc{microsoft,
author = {Microsoft},
title = {Discover and manage shadow IT in your network},
howpublished = "\url{
}
now you can cite this ref in your .tex using
\cite{microsoft} | stackexchange-tex | {
"answer_score": 0,
"question_score": 0,
"tags": "bibliographies, cross referencing, back referencing"
} |
JQUERY, div with a fixed height (with a scrollbar) how to animate until it grows to no longer need a scroll bar?
JQUERY, div with a fixed height (with a scrollbar) how to animate until it grows to no longer need a scroll bar?
I have a div on a page with a CSS height:200px setting, which makes the DIV have a vertical scroll bar, which allows the user to scroll through a bunch of text.
I would like to animate the DIV to expand in height until all content in the div is shown, meaning no more scroll bar
I tried the following:
$("#view-container").animate({"height": "auto"}, "slow");
but that didn't work while this does:
$("#view-container").animate({"height": "1000px"}, "slow");
problem with that is the text size in the DIV is variable. Ideas?
Thanks | What you can do:
Set the height to `auto`, then record the `offsetHeight`. Change the height back to what it was immediately - the users won't see the change at all as browsers are single threaded.
Then use jQuery (or not) to animate to that recorded height.
Example:
var vc = document.getElementById('view-container');
var vcold = vc.style.height;
vc.style.height = 'auto';
var vcheight = vc.offsetHeight;
vc.style.height = vcold;
$("#view-container").animate({"height": vcheight + "px"}, "slow"); | stackexchange-stackoverflow | {
"answer_score": 3,
"question_score": 0,
"tags": "jquery, jquery ui, jquery animate, slidedown"
} |
BigDecimal multiply by zero
I am performing a simple multiplication with BigDecimal and I have found some strange behaviour when multiplying by zero (multiplying by zero is correct in this use-case).
Basic maths tells me that anything multiplied by zero will equal zero (see:Zero Product Property and Multiplication Properties)
However, the following code will consistently fail with the same error:
assertEquals(new BigDecimal(0), new BigDecimal(22.3).multiply(new BigDecimal(0)));
>
> java.lang.AssertionError:
> Expected :0
> Actual :0E-48
>
Is this an inaccuracy with BigDecimal or is there some niche branch of maths that I'm missing somewhere?
Notes: JDK 1.6.0_27 running in IntelliJ 11 | You can't use the `equals()` method to compare `BigDecimals`, like this assertion does. That is because this equals function will compare **_the scale_**. If the scale is different, `equals()` will return false, even if they are the same number mathematically.
You can however use `compareTo()` to do what you want:
As @assylias points out, you should also use the `new BigDecimal("22.3")` constructor to avoid double precision issues.
BigDecimal expected = BigDecimal.ZERO;
BigDecimal actual = new BigDecimal("22.3").multiply(BigDecimal.ZERO);
assertEquals(0, expected.compareTo(actual));
There is also a method called `signum()`, that returns -1, 0 or 1 for negative, zero, and positive. So you can also test for zero with
assertEquals(0, actual.signum()); | stackexchange-stackoverflow | {
"answer_score": 84,
"question_score": 58,
"tags": "java, bigdecimal, numerical analysis, rounding error"
} |
select field from table in another field from another table
I want this in mysql:
SELECT * FROM Table1 Where Field1=searchword
OR Field2=searchword
OR Field3=searchword
OR ((SELECT filedx FROM Table2 WHERE fieldxx = Field1) = searchword)
Where The Field1 in 2nd select is from 1st select statment. | I'm not quite sure what you want, but it looks like you want to match your `searchword` against `Table1.Field2`, `Table1.Field3` and `Table2.filedx`. Tables are linked by `fieldxx=Field1`. In that case you can do simple outer join:
SELECT * FROM Table1
LEFT OUTER JOIN Table2 ON (fieldxx=Field1)
WHERE
Field1=searchword
OR Field2=searchword
OR Field3=searchword
OR filedx=searchword; | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "mysql, sql, select"
} |
How to compute the average of a column in a CSV file?
I would like to compute the average of a certain column in a CSV file with column separator ";". How can I do this with Linux command line tools such as awk?
Example:
foo;1;test
bar;3;hello
Average of column `2` is `2`. | A quick search for "bash average" turned up as the first result: Compute simple average using AWK
Tidied up for your use case, it's:
$ awk -F';' '{sum+=$2; ++n} END { print "Avg: "sum"/"n"="sum/n }' < /tmp/yourdata
Avg: 4/2=2 | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 1,
"tags": "linux, bash"
} |
Rails ActiveStorage scope for when file is attached
When using ActiveStorage, how do you create a scope for when files are attached.
For example:
class Check < ActiveRecord::Base
has_one_attached :image
end
I want something like `Check.has_attached_image` to return only records where there is an existing attached image.
I know that `ActiveStorage` provides a `with_attached_image` scope. But that doesn't seem to be working:
` irb(main):009:0> Check.with_attached_image.to_sql => "SELECT \"checks\".* FROM \"checks\"" ` | Main purpose of the scope `with_attached_image` is to avoid N+1 queries (to include the attached blobs in your query).
To return only records where there is an existing attached image, you can create a scope in the `Check` model like this:
`scope :has_attached_image, -> { joins(image_attachment: :blob) }`
Update from comments:
`scope :has_attached_image, -> { joins(:image_attachment) }` | stackexchange-stackoverflow | {
"answer_score": 17,
"question_score": 10,
"tags": "ruby on rails, ruby, ruby on rails 5, rails activestorage"
} |
Specifying iterator value in stable_sort function
I am using the below code to sort rectangles. In the stable_sort function, how can I specify the iterator values other than boundRect.begin and boundRect.end. I want to sort the elements between index 5 to 10. How can I specify these in the stable_sort function? Please guide me.
stable_sort( boundRect.begin(), boundRect.end(), compareX_rect );
bool compareX_rect(const Rect & a, const Rect &b) {
return a.x <= b.x;
} | Since `stable_sort` requires random access iterators, you can do simple addition on the iterators:
stable_sort(boundRect.begin()+5, boundRect.begin()+10, /* ... */
Unless you're dealing with an ancient (pre-C++11) compiler, you can use a lambda expression for the comparison as well:
stable_sort(boundRect.begin()+5, boundRect.begin()+10,
[](const Rect & a, const Rect &b) { return a.x < b.x; });
This not only shorter and easier to read, but will often be faster as well (not that it's likely to matter when you're only sorting 5 elements). | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 0,
"tags": "c++11, stable sort"
} |
Why is this random generator always output the same number
I don't get why it outputs the same number every time even though it should output a different number each time. rand() % 10 + 1, should output a number between 1 to 10 randomly but my code just outputs the same exact 5 number each time.
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int v1;
for(v1=0; v1 < 10; v1++) {
v1 = rand() % 10 + 1;
cout << v1 << endl;
}
return 0;
} | You need to use this
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(nullptr));
int v1;
for(v1=0; v1 < 10; v1++) {
v1 = rand() % 10 + 1;
cout << v1 << endl;
}
return 0;
} | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 0,
"tags": "c++"
} |
How to write Haskell array strategies
I want to write a strategy to evaluate items in an array in parallel. The old strategies had `parArr` to do this (see here). But this is not found in the new Control.Parallel.Strategies module.
E.g. parallel list evaluation: `map f myList `using` parList rdeepseq`
I would want to be able to do something like: `amap f myArr `using` parArr rdeepseq`, where `amap` is from Data.Array.Base and applies a function to each of the elements (sequentially).
The following seems to work but I wonder if it is doing it right, and want to know how I could define my own `parArr`.
This works: `amap ((+1) `using` rpar) $ Array.array (0,4) [(0,10),(1,20),(2,30),(3,40),(4,50)]` | For a previous question, I wrote a parallel evaluation strategy for the vector package. That should be a good place to start. You can see the code on hackage in the vector-strategies package.
I don't have time to give a full answer - perhaps I'll edit this later. Feel free to comment with extra questions and direction. | stackexchange-stackoverflow | {
"answer_score": 4,
"question_score": 5,
"tags": "arrays, haskell"
} |
Hyperledger Fabric 1.4.9 new peer syncing with more than 500k Block Height
I have a question in Hyperledger Fabric network with 2-Orgs and 1 peer each and my block height is 500k and now I want to add another new peer for my Org1. Now my question is, if I add a new peer and make that new peer as anchor peer for Or1, any issues will be there for transactions during the blocks syncing with the new peer.
I'm using Fabric version 1.4.9 | I have followed the below steps and it worked:
* Created a new Peer and added it to the channel for syncing the Blocks.
* Once the sync is completed, verify the Block height in peer logs.
* Add the new Peer to Anchor peers.
* Install chaincode on the new peer.
* Update the connection Profile.
* Invoke a couple of transactions from the client application and verify the transactions.
The above steps resolve my issue which I have logged in my question above. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "synchronization, hyperledger fabric, hyperledger, block, peer"
} |
Orientation from magnetometer data
I saw lot of topics with the same title but answers are different.
I have a magnetometer in my phone which give me the components of magnetic field in direction of X, Y, Z.
Which of the following angles can be determined using datas of magnetometer? Roll, pitch, yaw? And how?
Thank you, Robert | With a magnetometer alone convention would say you could calulate pitch and yaw. Assuming the z axis of the magnetometer points north. If the device was pointed perpendicular to the north vector then it would be able to calculate roll. As I understand it. | stackexchange-stackoverflow | {
"answer_score": 0,
"question_score": 0,
"tags": "get, orientation, euler angles, magnetometer"
} |
iPhone backup & restore does not restore our app's data on rare occasions
We have an iPhone app with several thousand users, and we've had one or two users saying that after a full backup & restore procedure within iTunes, the data for our app was lost.
All the data (photos & SQLite DB) are stored in the documents area of the app. I've tested this thoroughly with our devices and it works absolutely fine.
Can anyone think of a reason for this, or has anyone experienced this before? | I have this problem too - sometimes iTunes goes berserk and deletes data. Most apps are not important enough for people to complain, but if yours is you will hear about it. As it seems, you do.
My theory is that something goes wrong in iTunes and it uninstalls the app deleting the data, and then reinstalls it back - fresh and minty.
One thing I can suggest is storing data in both Keychain and Documents folder, and looking in both of these places. When an app is uninstalled the keychain is NOT cleaned up, at least not right away. However when backup is restored to a different device keychain is not carried along, so Documents is still a must.
The other option is to encourage online backup with user's permission. Of course you need to control access so that's a bit of a bother. | stackexchange-stackoverflow | {
"answer_score": 1,
"question_score": 1,
"tags": "iphone, itunes"
} |
Self-hosted blog Admin Panel Forwarding to WP.com
I was goofing with the settings (first problem) in the "General" tab of my wp-admin panel on my self-hosted blog.
There are two settings: Wordpress.com URL and Blog URL (or something). They were both originally set to my self-hosted `www.domain.com/blog`. I thought if I changed the Wordpress.com URL to an empty blog that I set up on Wordpress `www.myblog.wordpress.com` that it would simply connect the two blogs so that my site went into the Wordpress.com directory.
**This did not happen.**
Now, if I visit MY self-hosted URL, I see my blog, but it's clearly missing a stylesheet. And now I can't access the admin panel of my own blog. I don't know what happened.
Can I remedy this? Is there a file on my server where I can just edit the line that I changed and switch it back to what it should be? | This is sort of two questions in one, but to solve your first problem and get your blog working again you need to edit your MySQL database. If you have access to PhpMyAdmin open that up and find the `wp_options` table. Inside the table there are two values to change `siteurl` and `home` are the names I believe. Change these both to ` or whatever the appropriate link is and this hould get things working again.
The second question, if I am understanding correctly, is how do you cross post from a self-hosted WP install to a WP.com install simultaneously? | stackexchange-wordpress | {
"answer_score": 2,
"question_score": 0,
"tags": "wordpress.com hosting"
} |
Convergence of $\prod_{n=1}^{\infty} (1 - z^n)$ when $|z| = 1$
Clearly, $\prod_{n=1}^{\infty} (1 - z^n)$ converges to $0$ when $1 - z^{n_0} = 0$ for some $n_0$.
Suppose $z$ is a complex number with $|z| = 1$ and $1 - z^{n} \ne 0$ for all $n$.
I think $\prod_{n=1}^{\infty} (1 - z^n)$ diverges, but it is not clear how to prove this.
I know that $\prod_{n=1}^{\infty} (1 - z^n)$ converges to a non-zero number iff $\sum_{n=1}^{\infty} -z^n$ converges absolutely. Hence, if $\prod_{n=1}^{\infty} (1 - z^n)$ converges, it must converge to $0$. It is not clear how to proceed from here.
I would appreciate any hints/pointers for proving (or disproving) that $\prod_{n=1}^{\infty} (1 - z^n)$ is divergent. | If the product converges to a non-zero number then $1-z^{n } \to 1$ so $z^{n} \to 0$ as $ n \to \infty$. But $|z^{n}|=1$ so the product does not converge (to a non-zero number) for any $z$ on the unit circle.
[Convergence of an infinite product to $0$ is considered as divergence]. | stackexchange-math | {
"answer_score": 3,
"question_score": 0,
"tags": "complex analysis, infinite product"
} |
Does TQuery.Unprepare close the query result in Delphi?
I wonder whether in Delphi calling
Query1.Unprepare;
implicitly closes Query1, if it was previously active. Such that e.g. calling Next on it will fail.
You might say, just go ahead and try but I did on a 64-bit Windows 7 system and had all sort of problems with it until finally my BDE Administrator seems to be completely broken. So I decided to just ask this questions before I start to find out, how I can get BDE running on my system ;-) | You can not use `Prepare`/`Unprepare` on an open dataset. you need to close it first.
unit DBTables;
...
procedure TQuery.SetPrepared(Value: Boolean);
begin
if Handle <> nil then DatabaseError(SDataSetOpen, Self);
...
// SDataSetOpen = 'Cannot perform this operation on an open dataset'; | stackexchange-stackoverflow | {
"answer_score": 7,
"question_score": 3,
"tags": "delphi, bde"
} |
Do I really need twho different Exchange servers 2007|2010?
Given am Exchange Server 2003 running on a dedicated server on a LAN protected by a Linux in DMZ, Microsoft says that if you upgrade, you should install two different servers (meaning two boxes, two licenses of Windows Server and two installations of Exchange) with different Exchange "server role".
Exchange is installed in a safe LAN, there is a Linux relay in DMZ that feeds messages to Exchanges and gets from it the messaged to be delivered on the Net (smart relay).
The mail traffic is about 2000 Internet messages/day and probably another 2000 msg/day sent by local users within the organization. The servers hosts 200 users. | We just deployed Exchange 2010 with single server & configured the hub role to be Internet facing as per this info: link text | stackexchange-serverfault | {
"answer_score": 3,
"question_score": 1,
"tags": "exchange, installation, deployment"
} |
Sphere intersection Stuck
I have two spheres that are bounded by spheres for collision detection. I do not want them to intersect. My intersection works. But it gets stuck. Once the function returns true, I cannot get it out. I tried
collideBool = ObjectOne.Intersect(ObjectTwo);
if(collide == true)
{
leftright = leftright;
updown = updown;
}
else
{
if(GetAsyncKeyState(VK_RIGHT))
leftright -= dt;
if(GetAsyncKeyState(VK_LEFT))
leftright += dt;
if(GetAsyncKeyState(VK_DOWN))
updown += dt;
if(GetAsyncKeyState(VK_UP))
updown -= dt;
}
collide = false;
My sphere gets stuck. What is a way around this? | Check for collision against the new position and undo if it would cause a collision.
float oldleftright = leftright, oldupdown = updown;
if(GetAsyncKeyState(VK_RIGHT))
leftright -= dt;
if(GetAsyncKeyState(VK_LEFT))
leftright += dt;
if(GetAsyncKeyState(VK_DOWN))
updown += dt;
if(GetAsyncKeyState(VK_UP))
updown -= dt;
bool collide = ObjectOne.Intersect(ObjectTwo);
if (collide)
{
leftright = oldleftright;
updown = oldupdown;
}
collide = false; | stackexchange-gamedev | {
"answer_score": 1,
"question_score": 1,
"tags": "collision detection"
} |
How to pass a named function as a parameter (scriptblock)
Let's take the classic first-order functions example:
function Get-MyName { "George" }
function Say-Hi([scriptblock]$to) {
Write-Host ("Hi "+(& $to))
}
This works just fine:
Say-Hi { "Fred Flintstone" }
this does not:
Say-Hi Get-MyName
because Get-MyName is evaluated, not passed as a value itself. How do I pass Get-MyName as a value? | You have to pass Get-Myname as a scriptblock, because that's how you've defined the variable type.
Say-Hi ${function:Get-MyName} | stackexchange-stackoverflow | {
"answer_score": 10,
"question_score": 5,
"tags": "powershell, scriptblock"
} |
Can I change an Adobe Air application icon in actionscript?
I'm trying to make an application in adobe air where you can externally load icons into the application. Can I change the window application icon in actionscript? | Have you read this documentation or this documenrtation?
It look as is code like this will do it:
NativeApplication.nativeApplication.icon.bitmaps =
[bmp16x16.bitmapData, bmp128x128.bitmapData];
You'll have to get the bitmapData from the image you want to use, though. | stackexchange-stackoverflow | {
"answer_score": 2,
"question_score": 1,
"tags": "apache flex, flash, actionscript, icons, window"
} |
Is there a Ruby-Way™ to handle this kind of loop?
I am trying print section titles for grouped elements in a flat array. I would only like the section title to appear _once_ per group.
The example below works, but it feels pretty inelegant for Ruby. I'm certain there must be a better way to do this ;)
#!/usr/bin/ruby
foo = [1,1,1,1,2,2,2,3,3]
i = 0;
f = foo[i]
comp = f
while(i < foo.count) do
puts "Section #{f}";
while(f == comp) do
puts f
i += 1
f = foo[i]
end
comp = f
end
* * *
Desired output
Section 1
1
1
1
1
Section 2
2
2
2
Section 3
3
3
* * *
I was hoping there was some kind of `Array#current` or `Array#next` instance methods, but it looks like Ruby Array objects don't keep an internal iterator. | foo.group_by{|e| e }.each do |header, group|
puts "Section #{header}"
puts group.join("\n")
end | stackexchange-stackoverflow | {
"answer_score": 8,
"question_score": 1,
"tags": "ruby, design patterns, loops"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.