INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
Delete rows that does not match elements in an array
Good day! I'm having some problems of updating my csv file (I'm using pandas). I want the code to delete a row in the csv file if the row element is the same as my defined array
For example if I have the following rows in my csv file:
and 2
hi 3
or 4
is 5
hello 6
and the defined array a is given by:
a = ['and', 'or', 'is']
d = {}
for k, v in reader.values:
if a == k:
break
else:
d[k] = int(v)
reader is the name of the variable I used to open the csv file using pandas
I'm expecting a dictionary where the word listed in the array would not be stored in d. I'm expecting this kind of output:
{'hi':3, 'hello': 6}
As I checked on the output, the words listed in the array a is still included in the dictionary. I hope you could help me, thank you!
|
using `df.replace()` to replace the list `a` with `nan` and then `dropna()` to get a `dict()`:
#replace 0 with first col name
d=dict(df.replace(a,np.nan).dropna(subset=[0]).values)
* * *
{'hi': 3, 'hello': 6}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, pandas, rows"
}
|
Thread information block under x64
I need to get the max and min stack from the the TIB on x64 platform (I know that I need to replace the FS register with the GS register.) On x86 platform I can use this table and find the correct offset
Do you know where I can find the table for x64 platform?
|
Here's a program that works on x86 and x64.
#include <windows.h>
#include <stdio.h>
void main()
{
PNT_TIB ptib = (PNT_TIB)NtCurrentTeb();
#ifdef _AMD64_
printf("Stack base: %08I64X, limit: %08I64X\n",
ptib->StackBase, ptib->StackLimit);
#else
printf("Stack base: %08X, limit: %08X\n",
ptib->StackBase, ptib->StackLimit);
#endif
}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "windows, assembly, 64 bit, windows 7 x64"
}
|
Get AJAX return, concat and build an table
i'm not able to assign my AJAX return as variable to concat.
Here is the code:
function GetSex() {
$.ajax({
url: '/SEX/GetAllSex/',
success: function (data) {
console.log(data);
}
});
}
function GetUsers() {
var Pistas = null;
$.ajax({
url: '/Users/GetAllUsers/',
success: function (data) {
console.log(data)
}
});
}
I want to concat the results, so that's what i'm doing:
var Sex = GetSex();
var Users = GetUsers();
var x = Users.concat(Sex);
It says that Sex and Users variable is undefined!
I don't understand.
Thanks in advance =)
|
Well,
I just didn't declare the variables before:
Final code was like:
var Sex;
var Users;
function GetSex() {
$.ajax({
url: '/SEX/GetAllSex/',
success: function (data) {
Sex = data;
console.log(data);
}
});
}
function GetUsers() {
var Pistas = null;
$.ajax({
url: '/Users/GetAllUsers/',
success: function (data) {
Users = data;
console.log(data)
}
});
}
Thank you anyway.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, arrays, asp.net mvc 4"
}
|
How to get POST variables and data without a form?
I would like to use something like this ` and then perform an action if "pebble" is the data for the key variable. What I have right now for code is
<?php
$key = $_POST['key'];
if($key == "pebble") {
$file = fopen("index.txt","w");
echo fwrite($file, "Hello pebble!");
fclose($file);
}
?>
but this doesn't seem to work. I am assuming that is because it isn't posting but rather passing through variables. Can someone help with how to post the data through without needing an HTML form?
|
You would need to use `GET` instead of a `POST`
if you're wanting to use `
You could also use:
`$key = $_REQUEST['key'];` instead of `$key = $_POST['key'];`
Using `$_REQUEST` will allow you to keep your (handler) code intact, should you ever want to change your form's method from `GET` to `POST` and vice-versa.
However, using `GET` could hold a security risk down the road, should you want to implement it for a DB, if proper measures are not taken to properly sanitize/escape user input.
**General rule of thumb:** Never trust user input.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "php"
}
|
the function, "queue", can it only be executed once?
here's my code
$('.project, .list').click(function(){
$( ".c3_home" ).addClass('c3_left2').delay(400).queue(function(){
$(this).addClass('c3_right');
});
});
$('#back').click(function(){
$('.c3_home').removeClass('c3_right c3_left2');
});
on the first two clicks, the classes are added and removed but on the third click, only the c3_left is added while c3_right is not being added.
|
You have to clear the queue:
$( ".c3_home" ).clearQueue().addClass('c3_left2').delay(400).queue(function(){
$(this).addClass('c3_right');
});
You could try using finish(): (jq 1.9 >) {which is supposed to clear all elements in queue}
$( ".c3_home" ).finish().addClass('c3_left2').delay(400).queue(function(){
$(this).addClass('c3_right');
});
As suggested by Kevin, try that too:
$( ".c3_home" ).addClass('c3_left2').delay(400).queue(function(next){
$(this).addClass('c3_right');
next();
});
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "jquery, queue, addclass, removeclass"
}
|
Identify Http Request using FileSystemWatcher
I am using `FileSystemWatcher` class in a console application, for Encrypting files within the directory.so that if i paste/create a file inside the directory the `FileSystemWatcher` will detect it and hence it is encrypted using suitable function call. so that i can did the encryption without affecting the normal work flow.
Now my question is that, How can i detect `http:` request to any of the files inside the `watcher` so that i can decrypt the file through a parallel console application. is there any possibility to do like this?
|
Using a parallel console application for `decrypting` is probably not the best thing to do (why a console application? A service seems more suitable), but you can monitor any HTTP request to a certain directory using `IIS` or another web server.
No HTTP requests will be served unless the server has been set up as (some kind of) web server, in which case decryption can be done upon arrival of requests. In `IIS` this is the `HttpRequestHandler`.
This won't add extra security though, if that is your aim. A file send over HTTP that is decrypted prior to sending over the wire can eavesdropped by a man-in-the-middle attack. If you want to protect your file and have stronger security than SSL and secure authentication, you should send the files encrypted and have the clients decrypt them locally (this approach is used, for instance, when you download software or movies from some companies).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "c#, vb.net, encryption, console application, filesystemwatcher"
}
|
Google Maps not loading after publishing on play store even after updating SHA 1 fingerprint for release key
A newbie here to google maps api and android app development. I am facing some strange issue and struggling with this from two days. I have developed an app in which I have used Google maps. I have launched the app to play store. The google map loads perfectly fine when I install the signed apk directly to mobile but not when I install through play store.
I have updated google maps api console with release key SHA 1 fingerprint. I am not able to find any solutions online also and did not get any support from google support team also. Somebody please help!
|
If u have enabled the App Signing Feature in the Developer Console, then it's clearly written in the documentation that the Upload Certificate is only needed by Google for authentication and that upload certificate is removed before installing the application on the user's phone. So, u also need to give the App Signing Certificate SHA under the key which you have enabled for Google Maps API. The App Signing Page is as I have attached the screenshot for your convenience... In the image I have marked which you need to give as **additional** credentials
);
Why it happens that generateInitialObj() is being called twice? I've added logging to generateInitialObj() and I've just noticed it. It seems to be happening at the very begining of the component's life cycle. I though, that once react obtains a value from there, it's gonna remain in there for good. No need to re-obtain it. Any ideas?
|
It's a JavaScript technicality. There's nothing React can do to prevent `generateInitialObj` from being called on every single render. To account for this, React supports the following API instead:
const [obj, setobj] = useState(() => generateInitialObj());
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 6,
"tags": "reactjs, react hooks"
}
|
(jquery) Circle buttonset?
Can I Have circle-shape buttonset (use in radio button) from jqueryUI?
as I get from jqueryUI, its shape is rectangle/square.
for example id I have 4 radio button a b c d I want every radio have circle shape
|
I think the author is talking about Button/Radio that generates `buttonset()` method. That's funny but I think the best option to make radio buttons generated with jQueryUI rounded is to add them a new CSS style similar to:
.rounded-corners {
-moz-border-radius: 1em;
-webkit-border-radius: 1em;
border-radius: 1em;
}
Happy if that will help you with your non trivial problem :)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, jquery, html, css"
}
|
Can't perform get request with axios and ReactJS
I am developing a web application with ReactJS and I want to perform a GET request with axios. First I tried with the following line:
axios.get("
//Code
});
But I got the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
Later I tried to add a header to solve the problem
axios.get(" {headers:{'Access-Control-Allow-Origin': '*'}}).then(data=>{
//code
});
But the problem persisted. What is wrong?
|
The default for crossDomain is as follows:
false for same-domain requests, true for crossDomain requests
If you are making a same domain json request, and your site may redirect the request to another domain to serve the response (via HTTP 3XX), then you should set the crossDomain property to true so the response can be read by your calling script.
This gives you the advantage of retrieving JSON when making same origin requests, and the functionality of JSONP when making cross-origin requests. If CORS is active on the domain you redirect to then you can set jsonp: false in the request options.
axios.get(" crossDomain: true }).then(data=>{
//Logic of your code
});
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "reactjs, cors, axios"
}
|
Is there a way to detect if a user is on a wifi connection with php or javascript?
Cant seem to find any info on this, but was wondering if there is any way to detect if a user is on a wifi connection, specifically public wifi, using javascript, or php?
|
No, there isn't, there is nothing in the IPv4 nor the HTTP transport that even hints at what kind of connection is used, except for the underlying protocol itself, which is usually IPv4 and HTTP.
No, IPv6 doesn't include this information either.
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 9,
"tags": "php, javascript"
}
|
JavaFX. AutoResize ComboBox при изменении Scene
**Вопрос:** как сделать расширяемый ComboBox? Чтобы при расширении окна мышкой, ComboBox тоже расширялся. Требуется чтобы обязательно слева от ComboBox был Label.
**Код:** (fxml)
<?import javafx.scene.control.ComboBox?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.*?>
<HBox maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" xmlns=" xmlns:fx="
<children>
<AnchorPane>
<children>
<Label text="Label" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" />
</children>
</AnchorPane>
<AnchorPane>
<children>
<ComboBox AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" />
</children>
</AnchorPane>
</children>
</HBox>
|
AnchorPane для таких задач не подходит. Вам необходимо использовать другой контейнер, например, BorderPane.
Пример fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns=" xmlns:fx="
<left>
<Label text="Label" BorderPane.alignment="CENTER" />
</left>
<center>
<ComboBox maxWidth="1.7976931348623157E308" prefWidth="150.0" BorderPane.alignment="CENTER" />
</center>
</BorderPane>
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java, javafx"
}
|
Division by zero with arrays
Alright, I have an array from a server query on a game server that holds information. I made a progress bar that shows the current amount of players. The percentage of this progress bar is calculated like this
<span style="width: ' . $data['gq_numplayers'] / $data['gq_maxplayers'] * 100 . '%;"></span>
Now, if the server is offline I get problems as the array is empty and the division will be 0/0 and causes error. How do I bypass/solve this?
|
Perhaps the use of an `if` statement would be the solution.
i.e.
if ($data['gq_maxplayers'] == 0) {
echo '<span style="width: 0%;"></span>';
} else {
echo '<span style="width: ' . $data['gq_numplayers'] / $data['gq_maxplayers'] * 100 . '%;"></span>';
}
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 0,
"tags": "php, html, arrays"
}
|
How to write a constant time function to copy the most significant bit to all bits
I'd like to write a function, in C, which takes the MSB of `uint8_t`, and if it's set, returns `0xFF` and if not `0x00`. In short, which returns an integer where all the bits are set to the same value as the MSB.
But I'd like to do it in a completely constant time way, no branches, no array offsets, just mathematical operations which are guaranteed to always touch the same number of bits. And ideally, without any undefined behavior. How can this be done?
|
How about:
#define uint8_msb_to_all_bits(x) (0xFF * ((x) >> 7))
or even better:
#define uint8_msb_to_all_bits(x) (-((x) >> 7))
The way these both work is that, if `x` is an 8-bit unsigned integer, then `x >> 7` is 1 if the MSB of `x` is set, and 0 otherwise. All that remains is then mapping 1 to 0xFF, which can be done either by multiplication, or, in this particular case, simply by negating the number.
(Yes, negating an unsigned number is well defined in C.)
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 9,
"tags": "c, cryptography, bit manipulation"
}
|
Django ORM for counting reference from ForeignKey
I have two models: `Industry` and `Employer`, as per below:
class Industry(models.Model):
name = models.CharField(max_length=255, unique=True)
class Employer(models.Model):
industry = models.ForeignKey(Industry)
name = models.CharField(max_length=255, unique=True)
The problem is that not all of the industries have employers yet... I want to get a list of all industries that have atleast one employer mapped to them, rather than getting them all. Is this possible with the ORM not with just regular SQL? I tried to find this in the django docs and coudlnt..
|
This is a classic problem for Django Annotations
Try:
from django.db.models import Count
Industry.objects.annotate(num_employers=Count('employer').filter(num_employers__gt=0)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "django, django orm"
}
|
Finding the maximum value of $abcdef$ given certain conditions of the divisibility of ab, abc, abcd, ...
What is the largest possible integer $abcdef$ that can be formed from the digits $1,2,3,4,5,6$ each used exactly once if abcdef is divisible by 6, abcde is dividible by 5, abcd by 4, abc by 3, and ab by 2?
By reason and elimination,
e=5
b,d,f can be 2,4,6
a,c can be 1,3
Is there a shorter way than just checking the divisibility of the 12 possibilities formed here to 6? Or am I just left with substitution and checking?
|
For $abcdef$ to be divisible by $6$, $f$ must be even and $a+b+c+d+e+f$ divisible by $3$ (which it is). Similarly $d$ and $b$ are even, and that will leave $a, c, e$ to be odd.
For $abcde$ to be divisible by $5$, $e$ must be $5$.
For $abcd$ to be divisible by $4$ when $c$ is odd, $d$ must be even but not divisible by $4$. Thus $d$ is $2$ or $6$.
For $abc$ to be divisible by $3$, $a+b+c$ is divisible by $3$. Now we already know $a$ and $c$ are $1$ and $3$ (not necessarily in that order), so $b+1$ is divisible by $3$. The only possibility is $b=2$. And then $d=6$ and $f=4$.
Thus the only numbers satisfying the constraints are $123654$ and $321654$.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "algebra precalculus, number theory, optimization, divisibility"
}
|
how do I use propositional equivalence laws to simplify?
I have two statements that are supposed to simplify to the same answer:
1) (not(p or q) or not(p or not q))
2) ((p or q) implies (not p and q))
how do these simplify using the equivalence laws of propositional logic into the same answer? I have found using truth tables I get (not P) for both, but I cannot figure out how using the laws.
|
Maybe these derivations will help:
**1)**
$$\begin{align} \neg (p \lor q) \lor \neg(p \lor \neg q) &\iff \neg((p\lor q) \land (p\lor \neg q) ) \tag{De Morgan} \\\ &\iff \neg(p \land( q \lor \neg q) ) \tag{$\land$ distributes over $\lor$} \\\ &\iff \neg(p) \tag{$A \land \sf{True} \iff A$} \\\ &= \neg p \\\ \end{align}$$
**2)**
$$\begin{align} (p \lor q) \to (\neg p \land q) &\iff \neg(p \lor q) \lor (\neg p \land q) \tag{$A\to B\iff \neg A\lor B$} \\\ &\iff (\neg p \land \neg q) \lor (\neg p \land q) \tag{De Morgan} \\\ &\iff \neg p \land (\neg q \lor q) \tag{$\land$ distributes over $\lor$} \\\ &\iff \neg p \tag{$A \land \sf{True} \iff A$} \\\ \end{align}$$
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "discrete mathematics"
}
|
C# not recognizing a string sent to powershell somehow
I want to remove an email alias from a mailbox which is selected by the user.
string removeAlias = "Set-Mailbox \"" + userLabel.Text + "\" -EmailAddresses @{remove=\"" + textBox2.Text + "\"}";
However, this does not work and I am not getting any error. Also, the following code works to add an email alias:
string setAlias = "Set-Mailbox \"" + userLabel.Text + "\" -EmailAddresses @{add=\"" + alias + "\"}";
I still cant figure out why this does not work. Any help would be really appreciated.
|
for any one facing such trouble. There was a whitespace in my alias string and so Powershell was not accepting it. I used the following to get rid of whitespaces:
selectedAlias = Regex.Replace(selectedAlias, "[\n\r\t]", "");
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, powershell"
}
|
cocoa spread kashrus lapesach leniency
I have a tub of Hashahar H'aole (sic) "special cocoa spread" (" _k'rem muvchar limricha_ "), a product of Israel exported to be marketed in the States. Its listed ingredients are "sugar, vegetable oil, low fat coca, vanillin and flavor". (Presumably _coca_ is a typo.) It has the _hechsher_ of the _Badatz Eda Hacharedis_ " _rak limos hashana_ " (i.e., not for _Pesach_ ), and of the Orthodox Union even for _Pesach_. I'm curious what _kula_ (halachic leniency) the OU is relying on (for this product) that the _Eda Hacharedis_ does not rely on.
|
The Eda only gives Hashgacha on Pesach Matza and simple ingredients (sugar, oil, honey, etc.), no prepared products at all. It is interesting to note that the Eda gives a Hashgacha on Mei Eden only L'Ymos HaShana!
|
stackexchange-judaism
|
{
"answer_score": 3,
"question_score": 3,
"tags": "passover, food, hechsher certification"
}
|
How can I get off the OS X beta track?
I’m on OS X Yosemite — I upgraded earlier, using a developer build.
Now I keep getting pre-release seeds for OS X updates, but I don’t want them. How can I opt out of this and mark my computer as a candidate for only stable releases?
|
On `System Preferences → App Store` you have an option called `Your computer is set to receive pre-releases Software Update seeds`, use the button `Change` and select `Do Not Show Pre-release Updates`.
|
stackexchange-superuser
|
{
"answer_score": 9,
"question_score": 6,
"tags": "macos, osx yosemite"
}
|
What is the measure of the segment AP, if $AB = 5$ and $BC = 3$?
For reference: \\\OF = R \triangle OFQ (isosceles ~rectangle) \implies FQ = R\sqrt2\\\ \triangle PAO \sim \triangle PCQ \implies \frac{2R}{PA}=\frac{PC}{R}=\frac{CQ}{AO}\\\\\measuredangle FPC =\measuredangle FQC\\\ \triangle PFQ\sim\triangle QCB $
I didn't see the usefulness of the PG semicircle
|
We write $AP =x$.
$\triangle APO \sim \triangle QPC$. So, $\frac{R}{x} = \frac{x+8}{2R}$
$2R^2 = x (x+8) \tag1$
$AQ = AP$ and as $BQ$ is angle bisector of $\angle AQC$, $QC = \frac{3x}{5}$
Applying Pythagoras in $\triangle ACQ$,
$ \left(\frac{3x}{5}\right)^2 + (x+8)^2 = 4R^2 = 2x (x+8) ~ $ (from $1$)
Solving for $x$, we get $x = 10$
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 0,
"tags": "geometry"
}
|
Take SQL input in PHP and output query results to the page
Basically I'm looking to create a page using PHP that will take SQL input, and output the results returned by the DB (MySQL). This is not for a production website (I understand the security implications). It's more for learning and practice. Kind of like the SQL console section of phpMyAdmin, or even similar to what sqlzoo.net can do (I think they are using perl, but I'd like to do it in PHP). Is there a practical way to accomplish this?
For example, how can I create a page in PHP/HTML to display a table of results when I don't know how many columns the query will return?
Also, what is the most practical way to allow a visitor to this web page to restore the DB to a default state with the original data? (e.g. create a sql dump of the original state and make a button that runs it? or is there a better way?)
Thanks!
|
Use `*` in your SQL query to fetch all columns and loop over the results from mysql_fetch_row() or mysql_fetch_assoc() with `foreach`. Besides that, have you thought of using the mysql CLI ? It's useful for those requirements. This question should be more specific than it is now.
"create a sql dump of the original state and make a button that runs it?" - Yes. But make sure you drop/delete the existing data.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, mysql"
}
|
In grails need to change a field in a domain class to nullable after I have already gone to production
I have a domain class with a string field that I am changing to nullable. In DataSource.groovy I have the mode set to "update." Is there any way to make grails alter the MySql without changing to "create" or "create-drop." I need the data in the MySql.
Follow up question: I can do this change by hand with the line "ALTER TABLE myProject_my_domain_class MODIFY the_string varchar(20) NULL;" Is this acceptable practice? Also I have the same problem with a field linking to another domain class:
class myDomainClass {
MyOtherDomainClass otherThing
}
changing to
class myDomainClass {
MyOtherDomainClass otherThing
static constraints = {
otherThing(nullable:true)
}
}
If the manual SQL ALTER is the only way, what is the correct way to write the SQL command so that I preserve the Key index between domain classes?
|
Have you tried the Database Migration Plugin?
<
The process of using it is a bit more manual than just setting dbCreate="update", but it gives you much greater control, and it picks up on changes like making a column nullable. In addition, you can check even your small schema changes into your version control system, so you have a record of the changes that you make.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "sql, grails, null, nullable, alter table"
}
|
How to use ignore padding on an element in a div
I have text and `<hr>` alternating vertically in a div and I added `padding-left` to the div but I don't want the horizontal rule between the words to be affected by the padding.
Is there a way exclude them?
.menuoptions {
height:30px;
width:225px;
color:#666;
line-height:30px;
font-weight:bold;
padding-left:10px;
}
I tried `.menuoptions hr {...}` and adding negative padding, but to not much surprise, it didn't work.
Example: Fiddle
|
You can't exclude them per se, and negative padding is a no-no, but you can use negative margins on the `<hr>`
See updated fiddle
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "css, positioning, padding"
}
|
UTC_TIMESTAMP() to user defined timezone?
I am storing timestamps in my db using UTC_TIMESTAMP().
I want to output them based on user selected timezone. I tried writing a small function to do this, however, it does not output correctly.
// Date/time converter
function convertTZ($date, $tz, $tzFormat)
{
$date = new DateTime($date);
$date->setTimezone(new DateTimeZone($tz));
return $date->format($tzFormat);
}
echo $_SESSION['dtCurrLogin'].'<br />';
echo convertTZ($_SESSION['dtCurrLogin'], 'UTC', 'F j, Y @ g:i:s a e');
dtCurrLogin from db = 2013-09-12 01:23:45
the above outputs :
2013-09-12 01:23:45 September 12, 2013 @ 5:23:45 am UTC
Obviously this is not correct as I went from UTC to UTC so they should be equal. If I change to output EST then it shows 1:23:45 am, but of course that would not be right either.
|
Didn't realize I needed to specify incoming timezone... using the following worked for me...
function convertTZ($date_time, $from_tz, $to_tz, $format_tz)
{
$time_object = new DateTime($date_time, new DateTimeZone($from_tz));
$time_object->setTimezone(new DateTimeZone($to_tz));
return $time_object->format($format_tz);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "unix timestamp, timestamp with timezone"
}
|
For what component should I add KeyListener?
I have a GUI.
This GUI class extends JFrame.
In top of the screen there is a JLabel with some text.
In the center of the screen there is a JPanel, and n x n JButtons were added to this JPanel.
I need a KeyListener to react if I press a key.
For what component (JFrame, JLabel, JPanel, JButtons) should I add the KeyListener to work my program normally?
|
> For what component should I add KeyListener?
* you can to use Keylistener for (is designated)
1. prehistoric AWT Component (Swing based on AWT)
2. for more than 3 keyPressed in the same time or to determine the order
3. but then is for Swing JComponents better to use KeyEventDispatcher or AWTEventListener (both react to singnals from keyboard)
* otherwise use KeyBindings (e.g. Swing JComponents uses KeyBindings internally)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "java, swing, awt, keylistener, jcomponent"
}
|
Windows 7 - CMD command to keep cmd open after executing
For some reason I cannot open the cmd. I created a simple bat file that does `dir` but it immediately closes the cmd as well. Is there a way I can keep the cmd open with some command?
|
Adding `pause` at the end of the batch script should keep it open until you press any key to continue.
|
stackexchange-superuser
|
{
"answer_score": 6,
"question_score": 0,
"tags": "windows 7, command line"
}
|
Not understanding a step in proving $P\leftrightarrow Q = (P\wedge Q)\vee (\neg P \wedge \neg Q)$
I'm struggling to see a transition step in proving that: $P\leftrightarrow Q = (P\wedge Q)\vee (\neg P \wedge \neg Q)$. Starting with the former:
1. $\neg(P\wedge \neg Q) \wedge \neg(Q \wedge \neg P)$ (Conditional laws)
2. $(\neg P \vee Q) \wedge (\neg Q \vee P)$ (Demorgan's)
3. $((\neg P \vee Q) \wedge \neg Q) \vee ((\neg P \vee Q) \wedge P)$ (Distributive)
4. $(\neg P \wedge \neg Q) \vee (Q \wedge P)$ **This is the step I don't understand, stepping from 3 to 4**
5. $(P \wedge Q)\vee (\neg P \wedge \neg Q)$ (Commutative)
As in the list of steps, the step from 3 from 4 is opaque to me. I don't understand the gymnastics that the solution steps through to get there.
Because the $(\neg P \vee Q)$ is nested in those paranthesis and the fact that there is a different operation, they cannot use associativity to trivially move the parenthesis around.
|
If you distribute once more you get $$ (\neg P \land \neg Q) \lor (Q\land \neg Q) \lor (\neg P\land P) \lor (Q\land P) $$ Then just remove the contradictions.
|
stackexchange-math
|
{
"answer_score": 7,
"question_score": 2,
"tags": "logic, propositional calculus"
}
|
Passing PHP objects and methods as strings to FormAPI
When working with objects, how do you pass a method to the FormAPI's [['#after_build']]( feature?
For example, how can I pass $myObject->_my_after_build_function to [['#after_build']](
* * *
**Non-OOP exampe of what I would like to accomplish:**
$form['#after_build'][] = '_my_after_build_function';
|
`$form['#after_build']` is handled from the following code, contained in form_builder().
if (isset($element['#after_build']) && !isset($element['#after_build_done'])) {
foreach ($element['#after_build'] as $function) {
$element = $function($element, $form_state);
}
$element['#after_build_done'] = TRUE;
}
Differently from other cases, Drupal doesn't use function_exists() to check if the function exists. This means that using the following code works, since PHP 5.2.3.
$form['#after_build'][] = 'MyClass::_my_after_build_function';
As side note, it would work also with closures.
$build_function = function($element, $form_state) {
// …
};
$form['#after_build'][] = $build_function;
|
stackexchange-drupal
|
{
"answer_score": 1,
"question_score": 0,
"tags": "forms"
}
|
Flashgot alternative for Firefox quantum
Flashgot doesn't work with quantum anymore, I want a similar extension which would work with uGet on Linux.
Basically an extension that would let me click on a download link and open it with uGet.
|
I downloaded this
<
wget
sudo sh install_uget_chrome_wrapper.sh
Then this extension, and it worked, for now there's no other option.
|
stackexchange-softwarerecs
|
{
"answer_score": 3,
"question_score": 3,
"tags": "gratis, firefox, download manager"
}
|
How to create multiples directories fom a vector?
I would like to create multiples directories from a vector.
**I have this vector:**
vector <- c(1, 2, 3)
**And I have tried this:**
dir.create(c("A/B/C/", vector))
**But I didn't get the expected directories:**
* A/B/C/1
* A/B/C/2
* A/B/C/3
**How can I do it?**
|
We can use `paste` and use a loop `sapply` as the `?dir.create` documentation says
> path - a character vector containing a single path name
sapply(paste0("A/B/C/", vector), dir.create)
### data
vector = c(1, 2, 3)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "r, directory"
}
|
Cargar div dentro de otro
Tengo un div por ejemplo este
<div class="div1">
<h1>Titulo</h2>
<p>texto</p>
</div>
entonces quiero saber si con js se div1 se puede cargar dentro de otro div osea algo asi
<div class="div2">ç
<div class="div1">
<h1>Titulo</h2>
<p>texto</p>
</div>
</div>
Gracias
|
Para hacer lo que pides, tienes que mover los elementos de un item a otro. Para eso existe la función **appendTo()** en `JQuery` que lo hace.
function generarDiv(){
document.body.innerHTML += "<div id='segundoDiv'></div>";
$("#divPadre").appendTo("#segundoDiv");
}
#divPadre, #segundoDiv{
border: solid 1px;
padding: 10px;
}
<script src="
<div id="divPadre">
<h3>Titulo</h3>
<p>texto</p>
<button type="button" onClick="generarDiv();">Generar Div</button>
</div>
* * *
_Ya como nota, una vez que ejecutes la función, la bloquería de alguna manera para no causar ningún error._
|
stackexchange-es_stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, html"
}
|
Why does a spring mass system oscillate?
For simply harmonic motion, acceleration $= -\omega^2 x$, where $\omega$ is the angular frequency.
Within limits of Hooke's law, the restoring force on the spring is given by
$$F= -k \cdot x$$
This force fits the simple harmonic motion condition with $k=\omega^2m$.
But, we have $F = 0$ for $x=0$.
If I displace block (of some mass) attached to a spring (massless) rightward (on horizontal plane), and then release it, it would accelerate leftward because of above spring force.
But at the moment when $x=0$, $F=0$ and thus $a=0$.
Then why does the spring block system experience simple harmonic motion?
Or why would the block accelerate farther leftward if there is no force on it?
I'm confused.
|
> Or why would the block accelerate farther leftward if there is no force on it?
Assuming the spring-mass system is horizontal then you are right: at $x = 0$ there is no net force on the block which means net acceleration is also zero. But you are forgetting that the block (mass) has certain velocity at that point and it keeps moving until negative acceleration provided by the spring restoring force stops it completely.
> Then why does the spring block system experience simple harmonic motion?
Because of inertia of the block (mass) connected to the spring.
> For simply harmonic motion, acceleration $= -\omega^2 x$, where $\omega$ is the angular frequency.
This is correct. From $F = -kx$ it follows that acceleration depends on the spring elongation $x$ which is defined as a sine function (harmonic oscillation). Therefore, the acceleration of the block itself is also a sine function.
|
stackexchange-physics
|
{
"answer_score": 7,
"question_score": 4,
"tags": "newtonian mechanics, harmonic oscillator, spring"
}
|
Saving object with child objects from different context
I'm currently working on an app using EF 4.1 Code First and have a question about how to save a new object with child objects from another context. The Context is stored in request mode.
I create a new object called 'Vacancy'. The user is then prompted to add locations to the Vacancy's collection of locations. The locations are pulled through the context and preferably I would like to avoid saving locations added to the Vacancy back to the database until the user is finished which could potentially be after several postbacks.
Problem is that the Locations are from a context that does no longer exist so trying to save my vacancy will throw an error.
I'm sure this is a common problem and I hope there is a good way to handle this.
Kind regards,
|
You must detach each entity you want to store (probably in session) among multiple requests.
context.Entry(loadedEntity).State = EntityState.Detached;
You should be also able to completely avoid this if you turn off proxy creation for loading of these entities and load them as no tracking.
context.Configuration.ProxyCreationEnabled = false; // This should generally be enough
var loadedEntity = context.Entities.AsNoTracking().FirstOrDefault(...);
Be aware that during the save you will have to tell EF that those entities are existing one by again correctly setting their state otherwise EF will try to insert them again.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "entity framework, entity framework 4, entity framework 4.1, code first"
}
|
What is the name of the set defined by nonnegative linear combinations of a set of vectors?
In $\bf R^d$ I have $n$ vectors $\vec x_1, ..., \vec x_n$. The object in question is the set of points (with origin $\vec 0$) that can be formed as a linear combination of these vectors _with only nonnegative coefficients_.
What is the name of this shape? (I have a different question on how it can be determine, without solving obvious matrix equations, if a point $\vec v$ is inside or outside (or on the hull) of this shape, and I hope I can find something on the net about it once I know the proper name for this thing).
|
Those special linear combinations are called conical combinations, and the resulting set is called the conical hull of those vectors. The conical hull is always a convex cone.
|
stackexchange-math
|
{
"answer_score": 6,
"question_score": 4,
"tags": "linear algebra, geometry"
}
|
Problem saving time in rails
I have an application which save datetime using Time.now, but when I retrieves it and compare with Time.now again it not the same format and result in unexpected result.
What should I do to always make this time standard all the time.
Thanks,
|
Rails treats time in a special way because time zone support in Ruby was deemed insufficient, i.e. Ruby Time instances only work with UTC and `ENV['TZ']` A Time object persisted in ActiveRecord will therefore look quite different to the return value of `Time.now`. To get on the same page as Rails use `Time.zone.now`
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "ruby on rails, datetime"
}
|
What is meaning of precision in this line?
Quote: "This agrees with the relativistic predictions to a precision of about 1.6%". This is the statement, but what does it exactly mean? Does it mean that 'The Theory predicts 100 units and experiments found 1.6 units. OR Does it means that 'Ths theory predicts 100 units and experiments found 100-1.6=98.4?
Which of the above explanation is true?
|
If the theoretical prediction is $100$, then the measured value lies between $100-1.6$ and $100+1.6$.
(If it were measured as $1.6$ the theory predicting $100$ isn't very good, is it?)
|
stackexchange-physics
|
{
"answer_score": 4,
"question_score": -1,
"tags": "terminology, measurements, error analysis"
}
|
How print two different select results
import sqlite3
con = sqlite3.connect('/path/to/file.pf')
cur = con.cursor()
cur.execute('select something from table1') #1st select
cur.execute('select something_else from table2') #2nd select
rows = cur.fetchall()
for r in rows:
print r
I only get the results from the first `SELECT`.
How can I include the rows from the second `SELECT` as well?
|
Use two separate cursors, or create a `UNION` select to produce _one_ result.
Two separate cursors can be chained together with `itertools.chain()`:
from itertools import chain
cur1 = con.cursor()
cur1.execute('select something from table1') #1st select
cur2 = con.cursor()
cur2.execute('select something_else from table2') #2nd select
for row in chain(cur1, cur2):
print row
Note that you don't have to call `cursor.fetchall()`; iteration can be done over the rows directly.
A `UNION` select requires that your selects return the same number of columns:
cur = con.cursor()
cur.execut('''\
select something from table1 -- 1st select
union
select something_else from table2 -- 2nd select
''')
for row in cur:
print row
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, python 2.7, sqlite"
}
|
buy the others / buy different ones
Do these sentences have the same meaning? Are they interchangeable?
> Don’t buy these headphones, **buy the others**.
>
> Don’t buy these headphones, **buy different ones**.
|
The **others** refers to headphones that are already specified (by the definite article). So the people involved are already aware of the others in question. Person A is advising person B to buy the other headphones that they are considering.
**Different ones** merely means ones different to these. There is no reference to which ones might be different or how they might be different. Person A is not advising person B on which alternatives are preferable. In effect, the statement is saying **don't buy these ones; buy other ones**. (Note the absence of the definite article.)
So they don't mean the same thing; and they are not interchangeable.
|
stackexchange-ell
|
{
"answer_score": 1,
"question_score": 0,
"tags": "phrase meaning"
}
|
How does this integer encoding work?
In this code golf question, there is a python answer that encodes the lengths of all integers from 1 to 99 in english to a big number:
7886778663788677866389978897746775667552677566755267756675527886778663788677866355644553301220112001
To get the length of `n`, you just have to calculate `3 + (the_big_number / (10**n)) % 10`. How does this work?
|
`(the_big_number / (10^n)) % 10` pulls out the `n`th least significant digit of the big number, so the lengths are just stored starting with the length of "zero" (1+3=4) at the far right, and following over to the length of "ninety-nine" (7+3=10) at the far left.
The shortest English numbers are three letters ("one", "two", "six", "ten"), so each length is stored with an offset of three. The longest prior to 100 are 9 + 3 = 12 letters (e.g. "seventy-eight"), so each number can be stored as a single digit.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "language agnostic, encoding, biginteger, mathematical optimization"
}
|
Initialize List<> with some count of elements
let's say I have a simple `List<bool>`. I want to initialize it and add e.g 100 elements to it. To do so, I can do:
var myList = new List<bool>();
for (int i = 0; i < 100; i++)
{
myList.Add(false);
}
but it's not the most elegant approach. Is there any built-in method to simplify it ? I don't want any loops, just for curiosity
|
Using Enumerable.Repeat
var myList = Enumerable.Repeat(false, 100).ToList();
which
> Generates a sequence that contains one repeated value.
|
stackexchange-stackoverflow
|
{
"answer_score": 45,
"question_score": 19,
"tags": "c#, list"
}
|
Does this strong regularity property hold?
A common result regarding regular cardinals is the following strong closure property:
> **Theorem** : If $\pi$ is a regular cardinal, then, for every function $f: \pi \to \pi$, there is some nonzero ordinal $\gamma < \pi$ so that $\forall \delta < \gamma (f(\delta) < \gamma)$.
This follows easily from $\textrm{cof}(\pi) = \pi$. Now, akin to the step from "every normal function has a fixed point" to "every class of normal functions has common fixed points", could we characterize the following _stronger_ property of regular cardinals?
> **Conjecture** : If $\pi$ is a regular cardinal, then for every finite set $F$ of functions $\pi \to \pi$, there is some nonzero ordinal $\gamma < \pi$ so that $\forall \delta < \gamma \forall f \in F (f(\delta) < \gamma)$.
|
Let $F=\\{f_\alpha:\pi\to\pi\mid \alpha<\delta\\}$ for some $\delta<\pi$.
Let $G=\\{g_\alpha:\pi\to\pi\mid \alpha<\delta\\}$ where $g_\alpha(x)=\max(\sup f_\alpha''x, x)$.
Lastly, let $C=\\{c_\alpha\subseteq\pi\mid \alpha<\delta\\}$ where $c_\alpha$ is the set of $g_\alpha$-fixed point.
Each $c_\alpha$ is a club, so $\bigcap C$ is a club, but if $x\in \bigcap C$ it is the fixed point of all of $g_\alpha$, hence $f_\alpha'' x\subseteq x$
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "set theory"
}
|
position element on another with jQuery UI position
Heyho again, I have two elements and want to position one of it relative to the second one :-) I found and would like to use "jquery ui .position()" for that. Here is what I got:
<div id="testparent">Parent</div>
<div id="testchild">Child</div>
#testparent{
position: absolute;
margin:100px auto auto auto;
width:300px;
height:120px;
background:lime;
}
#testchild{
margin:auto;
width:60px;
height:90px;
background:yellow;
}
$('#testchild').position({
of: $('#testparent'),
my: "left top",
at: "left bottom",
offset: "0 3"
});
I want the testchild to be positioned above/under the testparent. The problem is, that I do NOT want to position it horizontally relative to the parent but just vertically!! Is that possible :-)??
|
That's not possible with only the `my` and `at` options, because specifying a single value will apply to both `left` and `top`.
You can, however, specify a function in the using option, and that function will be called to perform positioning. If you ignore the `left` property and only update `top`, you can achieve what you want:
$("#testchild").position({
my: "left top",
at: "left bottom",
of: "#testparent",
offset: "0 3",
using: function(props) {
$(this).css("top", props.top);
}
});
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "jquery, jquery ui, position"
}
|
One entity to many entities symfony
With doctrine on symfony, looking to an entity linked to multiple entities on a single remaining column. For example :
Entity **engine** extend two entities
* Entity **plane**
* Entity **car**

* @DiscriminatorColumn(name="discr", type="string")
* @DiscriminatorMap({"car" = "Car", "plane" = "Plane"})
*/
class Vehicle
{
// ...
}
/** @Entity */
class Plane extends Vehicle
{
// ...
}
/** @Entity */
class Car extends Vehicle
{
// ...
}
This solves your problem of having only one foreign key on your Engine table. It also helps you have a more clear code when you have other 'shared' properties (for example a date of manufacture)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "php, symfony, doctrine orm, doctrine"
}
|
Remove value from array by value or key in php
i have an array with structure as following
#items: array:2 [
8 => 46
46 => 7
]
i want to remove the value 46 from the array in order to get an array like this
#items: array:2 [
8,7
]
this is my try
$ary = Auth::user()->friends()->pluck('user_id')->toArray();
$value_to_remove = Auth::id();
$output = [];
$output[] = array_search($value_to_remove, $ary);
$output[] = $ary[$value_to_remove];
error message : {message: "Undefined offset: 46", exception: "ErrorException",…}
|
try something like this
<?php
$ary = [
8 => 46,
46 => 7
];
$value_to_remove = 46;
$output = [];
$output[] = array_search($value_to_remove, $ary);
$output[] = $ary[$value_to_remove];
print_r($output);
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "php, arrays"
}
|
Always rotate in the direction of mouse movement
In my SharpGL application I do a very simple, mouse controlled rotation of the scene.
gl.Rotate(cameraRotation.X, cameraRotation.Y, 0.0f);
where
cameraRotation.Y += MousePosition.X - previousMousePositionX;
cameraRotation.X += MousePosition.Y - previousMousePositionY;
The problem with this is that the x rotation always comes first, so if I rotate the object around the x axis by 180° and then move my mouse left, the object will rotate to the right instead of left (since the y axis is now inverted). Is there a way to change this so that the object always rotates into the mouse movement direction, regardless of its current position? (like netfabb does it for example)
|
Alright, using ArcBall in SharpGL.SceneGraph.Core for my mouse controlled rotations fixed the problem.
Just had to edit the following
if (length > 1.0f)
{
// Get normalising factor.
float norm = 1.0f / (float)Math.Sqrt(length);
// Return normalised vector, a point on the sphere.
newVector = new Vertex(scaledX * norm, scaledY * norm, 0);
}
else
{
// Return a vector to a point mapped inside the sphere.
newVector = new Vertex(scaledX, scaledY, (float)Math.Sqrt(1.0f - length));
}
in ArcBall.MapToSphere so side movements rotate the object around the y axis instead of the z axis. Works as intended now.
|
stackexchange-computergraphics
|
{
"answer_score": 0,
"question_score": 6,
"tags": "opengl"
}
|
JPA EclipseLink Call NamedStoredProcedureQuery with Clob parameter (IN and OUT)
Prompt how better to call the procedure with IN-parameters (Clob) and then parse the OUT-parameters. (Clob)
For JDBC I found this case. How I can impliment it with JPA and EclipseLink
|
Create Clob:
Clob clobR = null;
try {
Connection conn = em.unwrap(Connection.class);
java.sql.Connection con2 = conn.getMetaData().getConnection();
clobR = con2.createClob();
clobR.setString(START_POSITION, data);
} catch (SQLException e) {
e.printStackTrace();
}
Call procedure:
StoredProcedureQuery query = em.createStoredProcedureQuery(name);
query.registerStoredProcedureParameter(paramName, type, mode);
query.setParameter(paramName, value);
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "jpa, stored procedures, eclipselink, procedure, clob"
}
|
Derive an explicit formula for a power series $\sum_{n=1}^\infty n^2x^n$
Could anyone help me find an explicit formula for:
$$ \sum_{n=1}^\infty n^2x^n $$
We're supposed to use: $$\sum_{n=1}^\infty nx^n = \frac{x}{(1-x)^2} \qquad |x| <1 $$
|
We know that the power series for:
$$\sum_{n=1}^\infty nx^n = \frac{x}{(1-x)^2} \qquad |x| <1 $$
In order to find the power series for:
$$ \sum_{n=1}^\infty n^2x^n $$
We differentiate the first summation above:
$$\left(\sum_{n=1}^\infty nx^n\right)' = \sum_{n=1}^\infty n^2x^{n-1} = -\frac{x+1}{{(x-1)}^3} \qquad |x| <1$$
Finally, we multiply by $x$:
$$x\sum_{n=1}^\infty n^2x^{n-1} = \sum_{n=1}^\infty n^2x^{n} = -\frac{x(x+1)}{{(x-1)}^3}$$
|
stackexchange-math
|
{
"answer_score": 9,
"question_score": 4,
"tags": "calculus, sequences and series, power series"
}
|
Using the same switch for two devices of different signal voltage levels
When I press an ON-OFF type switch (SPST), I would like to have a corresponding HIGH or LOW registered on the inputs of both a 5V-level microcontroller as well as a 10V-level device, without damaging either one obviously.
How would I go about achieving this -- should I use a resistive divider?
|
Assuming you have common grounds you can use diodes like this.
!schematic
simulate this circuit - Schematic created using CircuitLab
|
stackexchange-electronics
|
{
"answer_score": 3,
"question_score": 2,
"tags": "switches, voltage divider"
}
|
$\lim\limits_{n \to \infty}{\lfloor x \rfloor + \lfloor x^2 \rfloor + ... + \lfloor x^n \rfloor\over x^n}, 1<x\in \mathbb R^+$
$$\lim\limits_{n \to \infty}{\lfloor x \rfloor + \lfloor x^2 \rfloor + ... + \lfloor x^n \rfloor\over x^n}, 1<x\in \mathbb R^+$$ I have a problem solving this limit.Here is my solution. Let x be an integer, then we have: $$\lim\limits_{n \to \infty}{ x + x^2 + ... + x^n\over x^n} = \lim\limits_{n \to \infty} {(x^n -1)x \over (x - 1) x^n } = \lim\limits_{n \to \infty} {\frac{x^{n+1}}{x^n}-\frac{x}{x^n}\over \frac{x^{n+1}}{x^n} -\frac{x^{n}}{x^n}} = \lim\limits_{n \to \infty} {x - \require{cancel} \cancelto{0}{\frac{x}{x^n}}\over x -1}= {x\over x-1}$$
But I don't know how to solve for non-integer x.
|
You proved that if $x \in \mathbb{N}_{\geq 2}$ the limit is $\frac{x}{x-1}$, but we can actually prove that for any $x>1$ we have $\lim\limits_{n \to \infty} \frac{x+\ldots+x^n}{x^n} = \frac{x}{x-1}$.
$x>1$, then $(x+\ldots+x^n) -n\leq\lfloor x \rfloor + \ldots + \lfloor x^n \rfloor \leq x + \ldots +x^n$, which show us that the limit is again $\frac{x}{x-1}$ (Why?)
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "limits"
}
|
Is it advisable to paint interior walls with a sprayer?
We just purchased a house and before moving in we want to paint all the rooms: 4 bedrooms, living room, kitchen, and family room (2000 sft home). Being we want to be as efficient as possible I had looked into using a power sprayer. I've read both pros and cons on doing this so hoping to seek some answers from people here that have done this before.
So, using a sprayer inside, yes or no? If yes, what tips and precautions would you suggest?
|
Pro: Quick TO PAINT. ONLY.
Con: you have to mask everything, but EVERYTHING, you don't want covered in paint. Floors, windows, toilets, sinks, outlets, switches, lights, the works.
Con: not good if you want more than one color, or yet more masking needed.
Apartment complexes that paint everything white and replace the carpets (and nearly everything is carpeted) afterwards find them "efficient" - most other people get the whole job done a lot faster with a roller and brushes.
|
stackexchange-diy
|
{
"answer_score": 10,
"question_score": 9,
"tags": "painting, spraypainting"
}
|
Test Grunt served pages in Virtualbox
I'm developing some HTML-files using a lot of different libraries, but everything is compiled and served using grunt ('grunt serve'), which fires up my default browser and connects on 127.0.0.1:9000. I can copy/paste that URL into other browsers on my OS (Mac OS X) with no issues.
However, I also need to test in IE, where I normally use VirtualBox with browsers from modern.ie, but the URL is not available on those images (which makes perfect sense as it's a local IP). How do I make those URL's available to my VirtualBox images?
If I use my MAMP setup, I can access the URL's I've configured in my hosts file, but as I'm not using MAMP for this, that won't be an option.
Thanx in advance for any help!
/kim
|
Managed to get it to work, and as hgoebl said, it was a purely networking issue. Basically, I just followed this: < and everything works now.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "node.js, networking, gruntjs, virtualbox"
}
|
Showing the limit is $+\infty$
Let $f(x)$ be continuous and positive on $[0,+\infty)$. Suppose $$\int_0^{+\infty}\frac{1}{f(x)}dx<+\infty. $$ How can one show that $$\lim_{s\to +\infty}\frac{\int_0^{s}f(x)dx}{s^2}=+\infty?$$
|
For $t>0$, we have $$t=\int_t^{2t}\frac 1{\sqrt{f(\xi)}}\sqrt{f(\xi)}d\xi\leq \left(\int_t^{2t}\frac 1{f(\xi)}d\xi\right)^{1/2}\left(\int_t^{2t}f(\xi)d\xi\right)^{1/2}$$ so $$s^2\leq \int_s^{2s}\frac{dx}{f(x)}\cdot \int_s^{2s}f(\xi)d\xi$$ and so $$\frac{\int_0^{2s}f(\xi)d\xi}{s^2}\geq\frac{\int_s^{2s}f(\xi)d\xi}{s^2}\geq \frac 1{\int_s^{2s}\frac{d\xi}{f(\xi)}},$$ and we can conclude, since the fact that $\int_0^{+\infty}\frac{d\xi}{f(\xi)}$ converges implies that $\lim_{s\to \infty}\int_s^{2s}\frac{d\xi}{f(\xi)}=0$.
|
stackexchange-math
|
{
"answer_score": 6,
"question_score": 5,
"tags": "calculus, real analysis"
}
|
Checkmate with Pawn and King
Is it possible to checkmate an opponent with a king and a pawn without the pawn promoting to a queen or rook? I've heard that it is possible, but I don't know what the strategy is.
|
The checkmated king is in one of his corners with one of his bishops on the same rank right beside him (blocking him). The checkmating pawn is in front of the bishop (checkmating the king) with the winning king two squares in front of the checkmated king on the same file protecting his pawn and blocking the checkmated king's move forward. Of course there can be no piece available to capture the checkmating pawn. 
**Edited:**
Example: We have imported JCalendar to our project library, next is to import it to palette using tools-palette-swing/awt components, add from jar, select the JCalendar, select which class from JCalendar you want to use, select the categories (swing control etc), and the selected class will show up in the categories we chose. But mine doesn't showing up at all, netbeans doesn't recognize my class as swing component. But in palette tool my class exists in the selected category but marked as unknown.
|
Any Class you make that extends a Swing Component, is a Swing Component.
Your class should have the `extend` keyword and actually extend such a class instead of being a wrapper.
## Update
To add custom components to netbeans:
* Reusing a JPanel in NetBeans GUI Designer
* How to include custom panel with NetBeans GUI Builder?
* <
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "java, swing, jar"
}
|
How can I verify my mobile number on Twitter?
I can't add my mobile number, because the carrier isn't listed in the device list.
|
Do you mean getting the "Verified Account" badge on your profile? If you do then you can't - it is closed to the public
<
EDIT:
With regards to the mobile verification - if your carrier is not available then read this article <
It means that you will probably be able to send texts to Twitter but not receive any.
|
stackexchange-webapps
|
{
"answer_score": 4,
"question_score": 1,
"tags": "twitter, verification"
}
|
Check if values in matrix matches with values from array and return the matrix index if not
So I have a matrix with a dataset and I would like a function that compares all the values from the matrix with an array to check if the values in the matrix is present in the array and if not returns the index of the value.
I have tried setting up a dobbelt for loop in the
#the array with the values the matrixs values is compared
Grades=np.array([-3,0,2,4,7,10,12])
#the dobbelt for loop
for u in range(0,len(data)):
for j in range(0,len(data.T)):
if not data[u,j] in Grades:
# Error message is printed if a values isn't a found in the array.
print("Error in {}, {}".format(u,j))
I got error in all of the values... Error in 1,2, Error in 1,3, Error in 1,4, Error in 1,5...Error in 10,4, Error in 10,5, Error in 10,6, Error in 10,7
|
As you did not give data in question so I am assuming `data` as `3*3 matrix` but this code will work for every matrix.
Grades=np.array([-3,0,2,4,7,10,12])
data = np.array([[1,2,3], [4,5,6], [7,8,9]])
#the dobbelt for loop
for u in range(data.shape[0]):
for j in range(data.shape[1]):
if data[u,j] not in Grades:
# Error message is printed if a values isn't a found in the array.
print("Error in {} for {} - {}".format(data[u,j], u,j))
Output:
Error in 1 for 0 - 0 # 1 is not present in given array and it's index is (0, 0)
Error in 3 for 0 - 2
Error in 5 for 1 - 1
Error in 6 for 1 - 2
Error in 8 for 2 - 1
Error in 9 for 2 - 2
I hope this would resolve your query.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "python, arrays, numpy, matrix"
}
|
Is a C++ destructor guaranteed not to be called until the end of the block?
In the C++ code below, am I guaranteed that the ~obj() destructor will be called **after** the // More code executes? Or is the compiler allowed to destruct the obj object earlier if it detects that it's not used?
{
SomeObject obj;
... // More code
}
I'd like to use this technique to save me having to remember to reset a flag at the end of the block, but I need the flag to remain set for the whole block.
|
You are OK with this - it's a very commonly used pattern in C++ programming. From the C++ Standard section 12.4/10, referring to when a destructor is called:
> for a constructed object with automatic storage duration when the block in which the object is created exits
|
stackexchange-stackoverflow
|
{
"answer_score": 47,
"question_score": 38,
"tags": "c++, raii"
}
|
Install ssconvert (part of gnumeric) on a server without GNOME
I need to use gnumeric's file conversion tool ssconvert on a server.
The problem is that gnumeric is a gnome application and can't be installed without a desktop installed.
There is also no separate packages for ssconvert, and I can not compile it from source code...
I need this specific conversion tool cause it can covert from Excel XML format to CSV, which I was unable to do with other excel conversion tools.
I am working on a ubuntu 12.04 server. I would appreciate any ideas.
|
I think many of the dependencies for gnumeric are actually "recommended" packages, not real dependencies. Try this:
sudo apt-get install --no-install-recommends gnumeric
For me, this installed about 37MB of packages, most of which were libraries and icon themes, which I felt was tolerable.
|
stackexchange-serverfault
|
{
"answer_score": 11,
"question_score": 15,
"tags": "linux, microsoft excel, csv, conversion"
}
|
Mootools Classes and Binding
I am having trouble accessing both the Class and the current element. How can I have access to both the current element and the Class?
// Class stuff above
fuction1 : function () {
myelements.addEvent('click', this.function2);
},
function2 : function () {
// "this" is the element from function1
this.getParent('div')
// now I need to call another function
// But since the scope is the element, I get an error
// If I bind function two,
// how can I gain access to the element?
this.function3();
}
//Class stuff below
Thanks!
|
Here's a cleaner way. Note that the event is already passed to the method:
var Foo = new Class({
initialize: function() {
this.elements = $$('li').addEvent('click', this.click.bind(this));
},
click: function(e) {
console.log(this); // Foo Class
console.log(e.target); // the clicked this.elements item
}
});
And a working example: <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "class, variables, binding, scope, mootools"
}
|
How to put a JAR file in a Play 2 project and use it?
In Play 1, we can put some JAR files into the `/lib` directory. But there is no such a directory, and I don't find any information to do this.
Play 2 uses repositories, but sometimes I just want a quick and dirty way to use a JAR file. How do I do that?
|
Since Play 2 applications are built using sbt, you can just follow their convention for unmanaged dependencies: put your JAR file in the `lib/` directory.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "dependency management, playframework 2.0"
}
|
How to turn a list of lists to a sparse matrix in R without using lapply?
I have a list of lists resulting from a bigsplit() operation (from package biganalytics, part of the bigmemory packages).
Each list represents a column in a matrix, and each list item is an index to a value of 1 in a binary matrix.
What is the best way to turn this list into a sparse binary (0/1) matrix? Is using lapply() within an lapply() the only solution? How do I keep the factors naming the lists as names for the columns?
|
You might also consider using the Matrix package which deals with large sparse matrices in a more efficient way than base R. You can build a sparse matrix of 0s and 1s by describing which rows and columns should be 1s.
library(Matrix)
Test <- list(
col1=list(2,4,7),
col2=list(3,2,6,8),
col3=list(1,4,5,3,7)
)
n.ids <- sapply(Test,length)
vals <- unlist(Test)
out <- sparseMatrix(vals, rep(seq_along(n.ids), n.ids))
The result is
> out
8 x 3 sparse Matrix of class "ngCMatrix"
[1,] . . |
[2,] | | .
[3,] . | |
[4,] | . |
[5,] . . |
[6,] . | .
[7,] | . |
[8,] . | .
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "r, sparse matrix"
}
|
iOS - iCal rRule in a EKEvent recurrence rule
I have an `iCal` file with a `rRule`: `rRule = "FREQ=WEEKLY;UNTIL=20140425T160000Z;INTERVAL=1;BYDAY=TU,TH";`
I need to put this info in a `EKEvent`:
EKEvent *event;
event.recurrenceRules = ...
I split the `rRule` and save it in `NSArray`:
NSArray * rules = [evento.rRule componentsSeparatedByString:@";"];
event.recurrenceRules = rules;
But an error ocurrs:
-[__NSCFString relationForKey:]: unrecognized selector sent to instance 0x21283350
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString relationForKey:]: unrecognized selector sent to instance 0x21283350'
Can you help me? Thank you for advance.
|
I found the solution using the EKRecurrenceRule+RRULE library, it's very easy to use.
The link : <
Example to use:
NSString *rfc2445String = @"FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=-2"; // The 2nd to last weekday of the month
// Result
EKRecurrenceRule *recurrenceRule = [[EKRecurrenceRule alloc] initWithString:rfc2445String];
NSLog(@"%@", recurrenceRule);
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "ios, objective c, icalendar, rfc2445"
}
|
The stalk of a specialization is a localization of the generization.
So I am trying to prove that in for a scheme locally of finite type over an algebraically closed field, smoothness and regularity are the same thing. I am working in Görtz and Wedhorn. In lemma 6.26, one direction of this fact is shown. The first part of the proof states that we can restrict to closed points because if $x'\in \overline{\\{x\\}}$ is a closed point then $\mathcal O_{X,x}$ is a localization of $\mathcal O_{X, x'}$ and so if the stalk at $x'$ is regular so is the stalk at $x$.
This is stated without any explanation so it might be an elementary fact but I cannot seem to figure it out. Help would be much appreciated.
|
Choose an affine open neighborhood of $x'$ (which then necessarily contains $x$). Then we may assume that $X=Spec(R)$, and $x$ and $x'$ correspond respectively to prime ideals $\mathfrak{p}$ and $\mathfrak{q}$ in $R$, such that $\mathfrak{p}\subset \mathfrak{q}$.
Then $\mathcal{O}_{X,x}=R_\mathfrak{p} = (R_\mathfrak{q})_{\mathfrak{p}R_\mathfrak{q}} = (\mathcal{O}_{X,x'})_{\mathfrak{p}\mathcal{O}_{X,x'}}$, because in general, if $S\subset T$ are multiplicative sets in a ring $R$, then $T^{-1}R = (S^{-1}T)^{-1}(S^{-1}R)$ (the notation is a little heavy, but it just means that to invert all the elements of $T$ you may start by inverting the elements of $S$ and then invert the image of $T$ in that).
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "algebraic geometry, commutative algebra"
}
|
Is there a way to write multiple awk commands on a single line?
Is there a clear method to write the following with pipes avoiding the temp file(s) redirection?
awk '{gsub("Sat ", "Sat. ");print}' Sat.txt >win.txt
awk '{gsub(" 1-0", "");print}' win.txt >loss.txt
awk '{gsub(" 0-1", "");print}' loss.txt >draw.txt
awk '{gsub(" 1/2-1/2", "");print}' draw.txt >$TARGET
|
You can have as many `gsub()` as you want in `awk`. Each one of them will replace `$0`, so every time you will be working with the modified string.
However, note you can compress the `gsub()` into just two of them by using some regular expressions:
awk '{gsub("Sat ", "Sat. "); gsub(/ (1-0|0-1|1\/2-1\/2)/, "")}1' file
# ^^^ ^^^ ^^^^^^^^^
# 1-0 0-1 1/2-1/2
The first one replaces `Sat` with `Sat.` and the second one removes space + either of `1-0`, `0-1` or `1/2-1/2`.
### Test
$ cat a
hello Sat is now and 1-0 occurs there when 0-1 results happen but 1/2-1/2 also
bye
$ awk '{gsub("Sat ", "Sat. "); gsub(/ (1-0|0-1|1\/2-1\/2)/, "")}1' file
hello Sat. is now and occurs there when results happen but also
bye
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "awk"
}
|
Can someone explain what is this code does?
Can anyone please explain what does the this code does? Just confused on the this portion of the code (`this.matrix = new int[rows, cols];`).
class Matrix
{
private int[,] matrix;
public Matrix(int rows, int cols)
{
this.matrix = new int[rows, cols];
}
}
|
That code assigns a class variable called `matrix` a new 2d array that has x number of rows and x number of columns..
Of course these aren't mapped to rows and columns as you would see in excel but basically just saying the first array has `rows` length, and the second `column` length such as..
> row1: col col col
>
> row2: col col col
is a `int[2,3]` as is
> col1: row row row
>
> col2: row row row
This is all done in the constructor of an instance of a `Matrix`
You can find more information here
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 0,
"tags": "c#"
}
|
Use JSONP to load an html page
I'm trying to load an external page using `JSONP`, but the page is an `HTML` page, I just want to grab the contents of it using ajax.
EDIT: The reason why I'm doing this is because I want to pass all the user information ex: headers, ip, agent, when loading the page rather than my servers.
Is this doable? Right now, I can get the page, but jsonp attempts to parse the json, returning an error: `Uncaught SyntaxError: Unexpected token <`
Sample code:
$.post('
$('.results').html(data);
},'jsonp');
I've set up a jsfiddle for people to test with: <
|
<
> Making a JSONP call (in other words, to employ this usage pattern), requires a script element. Therefore, for each new JSONP request, the browser must add (or reuse) a new element—in other words, inject the element—into the HTML DOM, with the desired value for the "src" attribute. This element is then evaluated, the src URL is retrieved, and the response JSON is evaluated.
Now look at your error:
> Uncaught SyntaxError: Unexpected token <
`<` is the first character of any html tag, probably this is the start of `<DOCTYPE`, in this case, which is, _of course_ , invalid JavaScript.
And **NO** , you can't use JSONP for fetching html data.
|
stackexchange-stackoverflow
|
{
"answer_score": 17,
"question_score": 24,
"tags": "javascript, jquery, ajax, jsonp"
}
|
How to break a line in VB6
I need to break this line of code but i do not know how:
sql = "select [ID], [First Name], [Last Name], [Mark 1 ENG], [Mark 2 ENG], [Mark 3 ENG], [Mark 1 MAT], [Mark 2 MAT], [Mark 3 MAT], [Mark 1 SCI], [Mark 2 SCI], [Mark 3 SCI] from Table1 where [Active] <> 'No'"
This is what i mean when i say break:
If txtFirstName.Text = "" Or txtLastName.Text = "" Or txtMarks(0).Text = "" Or txtMarks(1).Text = "" Or txtMarks(2).Text = "" _
Or txtMarks(3).Text = "" Or txtMarks(4).Text = "" Or txtMarks(5).Text = "" Or txtMarks(6).Text = "" Or txtMarks(7).Text = "" _
Or txtMarks(8).Text = "" Then
Where do i put the underscores in this line because wherever i put them it gives me an error.
|
You have to split up the string via concatenation:
sql = "select [ID], [First Name], [Last Name], [Mark 1 ENG], [Mark 2 ENG], " & _
"[Mark 3 ENG], [Mark 1 MAT], [Mark 2 MAT], [Mark 3 MAT], [Mark 1 SCI], " & _
"[Mark 2 SCI], [Mark 3 SCI] from Table1 where [Active] <> 'No'"
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": -1,
"tags": "sql, vb6, line breaks"
}
|
par(mfcol=c(2,1)) and blank second row
I am wondering why the following bit of code doesn't produce the two plots one below the other.
data(mtcars)
library(randomForest)
mtcars.rf <- randomForest(mpg ~ ., data=mtcars, ntree=1000, keep.forest=FALSE,
importance=TRUE)
png("rf1.png", width=6, height=6, units="in", res=100)
par(mfcol=c(2,1))
varImpPlot(mtcars.rf)
plot(mtcars.rf, log="y")
dev.off()
This just produces
!enter image description here
with a blank second row.
|
The problem is that varImpPlot redefines the plotting area, and then resets it to the previous value. This means it acts as if you called `par(mfcol=c(2,1))` _after_ the `varImpPlot` line. If you extract the varImpPlot plotting data you can plot the two dotcharts yourself (you can use `layout` rather than `par` to split the plotting area into different shaped regions):
data(mtcars)
library(randomForest)
mtcars.rf <- randomForest(mpg ~ ., data=mtcars, ntree=1000, keep.forest=FALSE,
importance=TRUE)
varImpData <- varImpPlot(mtcars.rf) # calculate this outside the plot
png("rf1.png", width=6, height=6, units="in", res=100)
layout(matrix(c(1,2,3,3), 2, 2, byrow = TRUE))
dotchart(varImpData[,c(1)])
dotchart(varImpData[,c(2)])
plot(mtcars.rf, log="y")
dev.off()
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "r"
}
|
Is there a modern (eg NoSQL) web analytics solution based on log files?
I have been using **Awstats** for many years to process my log files. But I am missing many possibilities (like cross-domain reports) and I hate being stuck with extra fields I created years ago. Anyway, I am not going to continue to use this script.
Is there a modern apache logs analytics solution based on modern storage technologies like NoSQL or at least somehow ready to cope with large datasets efficiently?
I am primarily looking for something that generates nice sortable and searchable outputs with the focus on web analytics, before having to write my own frontends. (so **graylog2** is not an option)
This question is purely about log file based solutions.
|
Splunk can import Apache logs <
Or review this answer on Stack Overflow
> A relatively recent option is to use Flume to collect the logs and use the MongoDB sink plugin for Flume to write the events to MongoDB.
|
stackexchange-webmasters
|
{
"answer_score": 2,
"question_score": 2,
"tags": "apache2, analytics, logging, static content, apache log files"
}
|
how to get an id from map
import React, { Component } from "react";
class MyPics extends Component {
state = {
Show: false
};
handleClick = () => {
this.setState ({ Show: !this.state.Show });
};
render() {
const IMGS1 = [
{_id: 0, src: "../../../IMG/1.jpg", alt: "IMG0"},
{_id: 1, src: "../../../IMG/2.jpg", alt: "IMG1"},
{_id: 2, src: "../../../IMG/3.jpg", alt: "IMG2"}
];
return (
{
IMGS1.map(({ _id, src, alt }) => (
<img key={_id} src={src} alt={alt} style={IMGStyle} onClick={(this.handleClick = _id => console.log(_id))} />
))
}
);
}
}
export default MyPics;
|
Modify your class method `handleClick` into a currying function, to avoid calling the function immediately in JSX and crashing the app:
handleClick = () => (id) => {
// id is accesible
};
onClick={this.handleClick(_id)}
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": -3,
"tags": "javascript, reactjs"
}
|
iPhone 3.0 SDK, how to test on a 2.2.1 device?
I just installed the latest iPhone SDK 3.0. After I seleced the active SDK as Simulator 3.0 at the drop down overview, the "target" field no longer shows me the 2.2.1 SDK, and defaults to 3.0, resulting in I cannot test on my 2.2.1 device.
What actions should I follow to fix this? Even in the target property my base SDK still appears as device 2.2.1.
|
You cannot run an iPhone application compiled for 3.0 on a device running anything other than 3.0 as it is not backwards-compatible with 2.2.1. You'll need to upgrade your device in order to run 3.0 apps on it.
More specific to the most recent release of the SDK, there is an entry in the release notes that states that this version does not let you compile against any SDK except the 3.0 SDK. I believe the last version that allowed you to do that was 3.0b2. You'll need to roll back to that one or earlier if you want to compile using the 2.2.1 SDK.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "iphone sdk 3.0"
}
|
Using a screen capture program (ffmpeg with uscreencapture in my case) to record a Flash video playing on screen
I'm trying to capture my desktop, precisely a full screen video - think "YouTube video on full screen situation", or if you'd record a programme on iPlayer (or any other content deliverer) - what would you do? Everything's great - got video and audio of the 'full screen video', but the output video is somewhat wobbly/laggy.. it's not right, what I'm trying to say - people don't move smoothly. I think it might have to do with FPS?
Here's the command I'm using:
`ffmpeg -f dshow -i audio="Stereo Mix (Realtek High Defini":video="UScreenCapture" -r 24000/1001 -q 1 out.avi`
Any other programs that'd help me record a full screen playing video cleanly, that'd also help :)
Cheers!
|
Turns out it was a performance issue. Tried to record a full screen video (720p) playing on my screen, on an i7 CPU laptop, and I can't see the output video having this wobbly/laggy look.
Then again, on my desktop computer, when I just play the video on browser, I don't get any lag too. So it becomes laggy during the recording process, and in the output file. So yeah, problem solved.
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 0,
"tags": "audio, video, ffmpeg"
}
|
How do I use MoqSequence
I want to test the order of execution of the methods of three dependencies within a class. That is, check to ensure a method is called on class a, then b and then c and are executed and in that order.
I was going to use the Moq.Sequence library but I have found that sequence testing is now supported out of the box. The only thing is that documentation is very light on the ground about the MoqSequence class, and I cant find a concrete example.
Also, my question is not about whether this is right or wrong specifically, but I believe testing the order of execution is a valid test (bit of a grey area here?)
|
There is bug when using MockSequence on same mock. It definitely will be fixed in later releases of Moq library (you can also fix it manually by changing Moq.MethodCall.Matches implementation).
If you want to use Moq only, then you can verify method call order via callbacks:
int callOrder = 0;
writerMock.Setup(x => x.Write(expectedType)).Callback(() => Assert.That(callOrder++, Is.EqualTo(0)));
writerMock.Setup(x => x.Write(expectedId)).Callback(() => Assert.That(callOrder++, Is.EqualTo(1)));
writerMock.Setup(x => x.Write(expectedSender)).Callback(() => Assert.That(callOrder++, Is.EqualTo(2)));
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c#, unit testing, moq"
}
|
The smallest disc which could contain 11 coins
There are $11$ coins with $1$ unit radius and we are trying to put them inside a big disc with some radius. So
> What is the minimum radius of this disc?
* If this question was asked for $2$ coins, the answer would be obviously $2$ unit radius,
* If was asked for $3$ coins, the answer would be $1+\frac{2}{\sqrt{3}}\cong 2.16$ unit radius as shown below:
:
>  (1994), pp. 15–25, by a proof sufficiently complex that I don't want to reproduce it here.
|
stackexchange-puzzling
|
{
"answer_score": 4,
"question_score": 1,
"tags": "mathematics, geometry"
}
|
Regex pattern to separate string with semicolon and plus
Here I have used the below mentioned code.
MatchCollection matches = Regex.Matches(cellData, @"(^\[.*\]$|^\[.*\]_[0-9]*$)");
The only this pattern is not doing is it's not separating the semicolon and plus from the main string.
A sample string is
[dbServer];[ciDBNAME];[dbLogin];[dbPasswd] AND [SIM_ErrorFound@1]_+[@IterationCount]
I am trying to extract
[dbServer]
[ciDBNAME]
[dbLogin]
[dbPasswd]
[SIM_ErrorFound@1]
[@IterationCount]
from the string.
|
To extract the stuff in square brackets from `[dbServer];[ciDBNAME];[dbLogin];[dbPasswd] AND [SIM_ErrorFound@1]_+[@IterationCount]` (which is what I assume you're be trying to do),
The regular expression (I haven't quoted it) should be
`\[([^\]]*)\]`
You should not use `^` and `$` as youre not interested in start and end of strings. The parentheses will capture every instance of zero or more characters inside square brackets. If you want to be more specific about what you're capturing in the brackets, you'll need to change the `[^\]` to something else.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c#, regex"
}
|
Why can't I assign to a variable being referenced in PHP?
$bar = 7;
$foo =& $bar = 9;
From a technical stand point, wouldn't this be evaluated from right to left? So: $bar = 9; $foo =& $bar
In case anyone is wondering. The reason I'm doing this on one line is to avoid toe nail clippings.
|
The assignment expression `$bar = 9` doesn't return a reference to `$bar` (i.e. the variable itself); instead, it returns the integer value `9`.
Or if you need a quote from the manual:
> The value of an assignment expression is the value assigned. That is, the value of " _$a = 3_ " is 3.
You can't assign a reference directly to a value, only to a variable that holds that value. So your handy one-liner fails spectacularly, and you'll have to split it into two.
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 8,
"tags": "php"
}
|
getting error on vite build in vue3 vite project
I have prepared my vue3 project with vite. In localhost, if I run `npm run dev` it is working properly and running the website file. If I run `npm run build` then it is not working. I have attached the error message as an image. Please check
TIA

vite build --target=es2020
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "vue.js, vuejs3, vite"
}
|
jQuery datepicker's year dropdown pops open and closed in IE8
I'm seeing an issue in IE8 with the Year dropdown in a jQuery datepicker dialog. The dropdown opens when I click on it but only stays open until I release the mouse button. I've only verified it in IE8 and IE9 with compatibility mode enabled, and it happens about 50% of the time I open it. There's a button nearby that seems to gain/lose focus at the same time as the dropdown list has this problem once in a while.
Google did not offer any help. What is happening here, and how do I fix it?
|
A bug concerned with the year and month dropdowns was reported months ago but is still not fixed. It sounds similar to a question I answered a few months ago. Does that help?
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "jquery ui, internet explorer 8, html select"
}
|
How to declare parameters (variables) in a partial view?
Given a spark view named `SomeContainer.spark` that uses a partial view this way:
<SomeContent param1 = "Model.SomeValue"/>
and given a partial view named `SomeContent.spark` that uses the parameter this way:
<div>${param1}</div>
How can I modify `SomeContent.spark` to declare param1 upfront. I want to do that for two reasons:
* Readability: readers will know what the partial view depends on
* To get intellisence for param1 in Visual Studio
I tried to simply declare the same `<var>` in SomeContent.spark but it fails at runtime indicating that that variable already exists.
|
I got the answer from the Spark group. In the partial you can declare a variable using the `<default/>` element:
<default param1="new List<string>()" type="List[[string]]"/>
Not only does it declare the parameter (with the advantages mentioned in my question) but it also gives it a default value which can be used to prevent the partial form getting a NullReferenceException...
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "asp.net mvc, spark view engine"
}
|
how to remove googlemymap water mark from iframe in reactjs
Iam new to reactjs,i want hide the googlemymap watermark....please let me know how to achieve this
<iframe src=" frameborder="0" border="0" width="100%" height="100%" aria-hidden="false" tabindex="0" style={{position:'relative',border:'none',top:'-60px'}} ></iframe>

How can I select dan's messages from 100 messages before the id to 100 messages after? If I just select based on the id column +/- 100 then there is not guaranteed to be 100 on either side because other users's messages may get in the way. I'd like to `SELECT * from table WHERE user = 'dan' and (some clause here) order by id;`
Database is Postgresql
|
Hmmm . . . How about `union all`:
(select m.*
from messages m
where user = 'dan' and id < $id
order by id desc
limit 100
) union all
(select m.*
from messages m
where user = 'dan' and id > $id
order by id asc
limit 100
)
order by id;
This should even be reasonably efficient with an index on `(user, id)`.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "sql, postgresql"
}
|
Differential equations: Global solution on $\Bbb R$
So I want to prove that $x'=f(t,x)$ has global solution on $\Bbb R$ if the follow $2$ conditions are satisfied:
* $|f(t,x)|\le C(1+|x|)$ (linearly bounded) for some $C >0$ and
* if $f(t,x)$ is locally Lipschitz.
I feel like I have to prove that $f(t,x)$ is Lipschitz so that the solution doesn't blow up and then it’s defined on $\Bbb R$. But how can I prove it rigorously? Does the Grönwall lemma help here?
|
From the Grönwall lemma you get that whenever $x$ is defined, $$ |x(t)|\le e^{C|t-t_0|}(1+|x(t_0)|)-1. $$ This bound on the values of the solution prevents any divergence in finite time to happen.
You can use this to extend any solution indefinitely by small patches, or you can use a global version of Picard-Lindelöf that uses a modified norm $$ \|x\|_L=\sup_{|t-t_0|\le T} e^{-2L|t-t_0|}|x(t)| $$ where $L\ge C$ is a Lipschitz constant on $[t_0-T, t_0+T]\times B(0,R)$ with $R=e^{CT}(1+|x_0|)$. The Picard iteration is contractive in this norm, allowing to apply the Banach fixed-point theorem on $C([t_0-T, t_0+T]\to B(0,R))$ directly.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "ordinary differential equations"
}
|
Could not Load NIB for the Third Time?
IN my application i am using this code to Call my First Class Xib.Here is my Code.
-(IBAction)retryagain
{
firstview *sec=[[firstview alloc] initWithNibName:@"firstview" bundle:nil];
sec.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:sec animated:YES];
[sec release];
}
This Code works fine for 6 or 7 minutes after running my application ,but when i call this code after 6 or 7 minute. then my application Crash its give me the following in Console. !enter image description here
Any One can guide me how To solve this problem.any help will be appriated.Thanx in Advance.
|
* _*_ Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle….' with name 'firstview'*
**Answer :**
> It looks like you're trying to instantiate a nib called 'firstview' and it isn't present. Is the nib included as a project member? In project -> Build Phases
>
> Make sure the .xib is added to Copy Bundle Resources
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "iphone, ios, bundle, xib"
}
|
What is meaning of colon in Nisekoi second season name?
Nisekoi second season has a ":" in the name like "Nisekoi:". What is the meaning of that colon?
|
It's become something of a pattern that anime series will have some kind of notation to indicate sequel seasons. Obviously "Season 2" or variations thereof happen a lot (e.g. "Shokugeki no Soma The Second Plate"), but several shows add a small extra detail to the title instead. Besides _Nisekoi:_ , here are a few:
* _Working!!_ became _Working'!!_ became _Working!!!_
* _K-On!_ became _K-On!!_
* _Gintama_ became _Gintama'_ became _Gintama°_ became _Gintama._
|
stackexchange-anime
|
{
"answer_score": 3,
"question_score": 3,
"tags": "anime production, nisekoi"
}
|
Do Zenity system tray notifications not work with Cron?
I'm making a small script in which I make several calls to Zenity. Executing the script manually or executing the commands from the terminal works properly. However, when I run them from Cron they give me problems. To test it, I have put in **crontab** two commands:
export DISPLAY=:0 && zenity --info --text "Window test"
export DISPLAY=:0 && zenity --notification --text "Notification test"
The first command shows an independent notification window with no problem, but the second one, which should show me a floating system tray notification, does not show anything at all only when I run it from **crontab**.
What can I do to make `zenity --notification` work from **crontab** if it works without any problem from another non-graphical TTY?
My system is KDE-Neon 5.19 with Ubuntu 20.04 and Plasma desktop 5.19.4. The version of Zenity is 3.32.0.
|
I added this to my user's crontab; this has been tested with python (notify2 library) and zenity:
DISPLAY=":0.0"
XAUTHORITY="/home/my_username/.Xauthority"
XDG_RUNTIME_DIR="/run/user/1000"
DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus
|
stackexchange-unix
|
{
"answer_score": 2,
"question_score": 2,
"tags": "cron, zenity"
}
|
How to invoke non-void function on window thread
I was using
Invoke((MethodInvoker)(() => SendCommand(_monitorCmd, _monitorOutput)));
to launch `string SendCommand(string cmd, CommandOutput outputTo)` on main window thread but now I also need to read its return value. So I tried:
string rx = Invoke(new Func<string, CommandOutput, string>(
(c, m)=> SendCommand(cmd, _monitorOutput)
));
It compiles but throws TargetParameterCountException.
I fixed it using a delegate:
Func<string, CommandOutput, string> del;
string rx = del.Invoke(cmd, _monitorOutput);
But, please, show me where is my error with the lambda code.
|
You can set a captured variable from inside the lambda
string rx = null;
Invoke(new Action(() => rx = SendCommand(cmd, _monitorOutput)));
Alternatively, you can use the `Delegate` overload, although this is likely to be much slower
string rx = (string) Invoke(
new Func<string, CommandOutput, string>(SendCommand),
_monitorCmd, _monitorOutput);
In this case the arguments must match the parameters _exactly_.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, winforms"
}
|
Fried Spaghetti
Pasta, as far as I'm aware, is always boiled to serve. However, their eastern cousin, noodles, are often fried. Are there any well-known Western (Italian) dishes that use fried fresh pasta, instead of boiling it?
If not, why do you think that's the case? Does pasta not fry well?
|
We used to have fried spaghetti for leftovers growing up. Take cooked spaghetti in sauce and put it in a warm frying pan with a little oil.
I've also had noodle fritters with leftover spaghetti, take undressed spaghetti and dip in a batter, then pan or deep fry. Somewhat like a potato pancake, we would eat them with sour cream.
|
stackexchange-cooking
|
{
"answer_score": 4,
"question_score": 4,
"tags": "frying, pasta, boiling, noodles"
}
|
Limit on number of git branches
I am musing about building a big system on top of git _for various reasons_ but mainly convenience.
But as part of the implementation I would end up making millions of branches and branching and merging between them. Can git actually scale this way? I always hear "Branches are free" but I have to wonder if this is really true x1,000,000? Can git actually create a theoretical unlimited number of branches?
|
Yes, branches are free. Branching and merging is very easy.
The scalability issues mentioned before comes only when synchronizing a vast amount of branches through the network (git fetch, git pull, git push). Locally you shouldn't have any problem.
|
stackexchange-stackoverflow
|
{
"answer_score": 23,
"question_score": 31,
"tags": "git, branch, limit, scaling"
}
|
How to change the session timeout in Jahia?
I need to change the session timeout in a Jahia application. Which property/file should I change to achieve that? Also will that be valid for edit mode also?
Thank you
|
The default session timeout can be changed in the file `jahia_installation/tomcat/webapps/ROOT/WEB-INF/web.xml`
The following configuration has to be set:
<session-config>
<session-timeout>30</session-timeout>
</session-config>
For the users in the edit mode, the session timeout can be set in jahia.properties file under `jahia_installation/digital-factory-config/jahia/jahia.properties`
# This property sets the session lifetime (minutes)
sessionExpiryTime = 60
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "jahia"
}
|
Why does potential-based reward shaping seem to alter the optimal policy in this case?
It is known that _every potential function_ won't alter the optimal policy [1]. I lack of understanding why is that.
The definition:
$$R' = R + F,$$ with $$F = \gamma\Phi(s') - \Phi(s),$$
where, let's suppose, $\gamma = 0.9$.
If I have the following setup:
* on the left is my $R$.
* on the right my potential function $\Phi(s)$
* the top left is the start state, the top right is the goal state
) + (1 + (0.9 * 0 - 100)) = -9$.
And the reward for the blue route is: $(-1 + 0) + (1 + 0) = 0$.
So, for me, it seems like the blue route is better than the optimal red route and thus the optimal policy changed. Do I have erroneous thoughts here?
|
The same $\gamma = 0.9$ that you use in the definition $F \doteq \gamma \Phi(s') - \Phi(s)$ should also be used as the discount factor in computing returns for multi-step trajectories. So, rather than simply adding up all the rewards for your different time-steps for the different trajectories, you should discount them by $\gamma$ for every time step that expires.
Therefore, the returns of the blue route are:
$$0 + (0.9 \times -1) + (0.9^2 \times 0) + (0.9^3 \times 1) = -0.9 + 0.729 = -0.171,$$
and the returns of the red route are:
$$(0 + 0.9 \times 100 - 0) + 0.9 \times (1 + 0.9 \times 0 - 100) = 90 - 89.1 = 0.9.$$
|
stackexchange-ai
|
{
"answer_score": 0,
"question_score": 0,
"tags": "reinforcement learning, reward functions, reward shaping, potential reward shaping"
}
|
Android encode a video starting from a set of images
Any suggestion on how to encode a videoclip starting from a set of images in Android? I've tried JCodec but it is not documented and I was unable to use it. Any other alternative?
|
I think JCodec is properly documented. I had used it successfully in a project few days back. Download the sample app from the below link and you will get an idea.
JCodec android sample project
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "android, video, encode"
}
|
Using visual studio for developing mono applications
How do I use Visual Studio to develop applications on Mono? Is this possible?
|
You just build the applications in Visual Studio, and run them under Mono instead of under .NET. The binaries should be compatible... but you'll need to make sure you don't use any libraries which aren't available in Mono - see the Mono Application Compatibility Guidelines.
(According to that page, you need to turn off incremental builds in Visual Studio though - a point I wasn't aware of before :)
|
stackexchange-stackoverflow
|
{
"answer_score": 24,
"question_score": 29,
"tags": "c#, visual studio, visual studio 2008, mono"
}
|
Allow css through htaccess
Earlier I made a question about creating seo friendly urls. And I got the answer.
Now I have a new problem. When I'm using mod_rewrite in .htaccess file:
RewriteEngine on
RewriteRule ^page/([^/\.]+)/?$ index.php?page=$1 [L]
to create link like: www.myurl.com/page/11
It's working fine. But when im entering the new page with the new lovely URL, I'm not getting any CSS.
I think my .htaccess doesn't allow it. How do I allow this?
|
If you want to have cool URLs, you need to link your CSS/JS and image files from HTML with leading slash (`/`).
<script type="text/javascript" src="/js/web.js"></script>
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "css, .htaccess, mod rewrite"
}
|
Is it possible to close a socket with a shell command?
Is it possible to close a socket by using some sort of shell command/program? I've seen plenty of examples of manipulating sockets using C and other languages but have been unable to find a program dedicated to it.
This is mostly out of curiosity rather than any real need. Although it might be useful for stress-testing my application or closing a tcp socket that I don't want to be open.
I am mainly interested in Linux/Unix, but a way to do this on Windows would be nice also.
|
You can close a socket in sh just like any other file: `exec 42>&-` where 42 is the file descriptor. What you can't do (except in a few shells that provide an extension for it) is open a socket. But of course that closes the socket in the shell, not in another process.
Closing a socket in a running process would disrupt its behavior in a way that the author of the program is not supposed to expect — it's like going in and modifying a piece of memory. Still, it can be done by connecting to the process with a debugger and making it execute a socket closing API call (that would be the `close` or `shutdown` system call on unix).
|
stackexchange-serverfault
|
{
"answer_score": 6,
"question_score": 6,
"tags": "networking, socket, linux networking"
}
|
Extracting substrings in Go
I'm trying to read an entire line from the console (including whitespace), then process it. Using bufio.ReadString, the newline character is read together with the input, so I came up with the following code to trim the newline character:
input,_:=src.ReadString('\n')
inputFmt:=input[0:len(input)-2]+"" //Need to manually add end of string
Is there a more idiomatic way to do this? That is, is there already a library that takes care of the ending null byte when extracting substrings for you?
(Yes, I know there is already a way to read a line without the newline character in go readline -> string but I'm looking more for elegant string manipulation.)
|
It looks like you're confused by the working of slices and the string storage format, which is different from what you have in C.
* any slice in Go stores the length (in bytes), so you don't have to care about the cost of the `len` operation : there is no need to count
* Go strings aren't null terminated, so you don't have to remove a null byte, and you don't have to add `1` after slicing by adding an empty string.
To remove the last char (if it's a one byte char), simply do
inputFmt:=input[:len(input)-1]
|
stackexchange-stackoverflow
|
{
"answer_score": 224,
"question_score": 183,
"tags": "go, substring"
}
|
Commit whole project or commit files?
I used to commit files which I want to group. But one of my colleague said that committing whole working project is better than committing files. I think it makes sense but if I commit like that sometimes I have to commit several different works at once.
What is the best practice to commit?
|
Commit a single unit of work. Otherwise reverting the commit or remerging it elsewhere (different branch) will be painful.
|
stackexchange-softwareengineering
|
{
"answer_score": 28,
"question_score": 6,
"tags": "version control"
}
|
Как растянуть столбцы в qtableView чтобы они заняли все поле виджета вне зависимости от контекста
Как растянуть столбцы в qtableView чтобы они заняли все поле виджета вне зависимости от контекста?
Еще охота автоматическое выравнивание при перемотки.
Версия qt 4.7.8
|
ui->table->horizontalHeader()->setStretchLastSection(true); // растянуть последнюю секцию (это свойство можно задать и просто в дизайнере)
ui->table->horizontalHeader()->setSectionResizeMode(2, QHeaderView::Stretch); // растянуть конкретную секцию
также можно растянуть и последнюю запись вертикально:
ui->table->verticalHeader()->setStretchLastSection(true);
при этом растяжение конкретной секции можно устанавливать только после того как таблица заполнена данными (иначе у нее будет отсутствовать horizontalHeader что приведет к исключению)
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "c++, qt, таблица"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.