qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
sequence | response
stringlengths 0
115k
|
---|---|---|---|---|
50,882,897 | This is a simple problem that is hard for me to put into words because I'm not too familiar with Python's syntax. I have a class called "Quadrilateral" that takes 4 points, and I'm trying to make a method called "side\_length" that I want to use to compute the length of the line between two of the vertices on the quadrilateral:
```
import math
class Point:
x = 0.0
y = 0.0
def __init__(self, x=0, y=0):
self.x = x
self.y = y
print("Point Constructor")
def to_string(self):
return "{X: " + str(self.x) + ", Y: " + str(self.y) + "}"
class Quadrilateral:
p1 = 0
p2 = 0
p3 = 0
p4 = 0
def __init__(self, p1=Point(), p2=Point(), p3=Point(), p4=Point()):
self.p1 = p1
self.p2 = p2
self.p3 = p3
self.p4 = p4
print("Quadrilateral Constructor")
def to_string(self):
return "{P1: " + self.p1.ToString() + "}, " + "{P2: " + self.p2.ToString() + "}, " + \
"{P3: " + self.p3.ToString() + "}," + "{P4: " + self.p4.ToString() + "}"
def side_length(self, p1, p2):
vertex1 = p1
vertex2 = p2
return math.sqrt((vertex2.x - vertex1.x)**2 + (vertex2.y - vertex1.y)**2)
def perimeter(self):
side1 = self.side_length(self.p1, self.p2)
side2 = self.side_length(self.p2, self.p3)
side3 = self.side_length(self.p3, self.p4)
side4 = self.side_length(self.p4, self.p1)
return side1 + side2 + side3 + side4
```
Right now I'm calling the side\_length method by explicitly telling it to use the quadrilateral's points, but is there a way to implicitly use just "p1" and "p2" without the need to tell it to use the quadrilateral's points (I'm using q.p1 and q.p2 when I just want to use p1 and p2 and imply python to use the quadrilateral's points)? I've realized it's basically a static method, and I want it to use the class fields rather than take in any point.
```
q = Quadrilateral(p1, p2, p3, p4)
print(q.to_string())
print("Side length between " + q.p1.to_string() + " and " + q.p2.to_string() + ": " + str(q.side_length(q.p1, q.p2)))
print("Perimeter is: " + str(q.perimeter()))
```
I also have other redundancy issues- like are there better ways to go about initially defining the points p1, p2, p3, p4 in the quadrilateral class, and is there a simpler way to compute the perimeter of the quadrilateral? | 2018/06/15 | [
"https://Stackoverflow.com/questions/50882897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9948429/"
] | Is you looking for multiple index slice ?
```
df.loc[pd.IndexSlice['bar',:],:]
Out[319]:
0 1 2 3
bar one 0.807706 0.07296 0.638787 0.329646
two -0.497104 -0.75407 -0.943406 0.484752
``` |
39,988 | The `Devices menu` -> `CD/DVD Devices` contains `VBoxGuestAdditions.iso`
**But ticking the above menu option doesn't show any menu to select anything from.**
The `kernel-devel` is already there.
The host is `openSUSE 11.3` 64 bit. The guest is `Slackware 13.37` 32 bit.
What's the way round now? | 2012/06/04 | [
"https://unix.stackexchange.com/questions/39988",
"https://unix.stackexchange.com",
"https://unix.stackexchange.com/users/8706/"
] | You should try [Redmine](http://www.redmine.org/).
>
> Some of the main features of Redmine are:
>
>
>
> ```
> Multiple projects support
> Flexible role based access control
> Flexible issue tracking system
> Gantt chart and calendar
> News, documents & files management
> Feeds & email notifications
> Per project wiki
> Per project forums
> Time tracking
> Custom fields for issues, time-entries, projects and users
> SCM integration (SVN, CVS, Git, Mercurial, Bazaar and Darcs)
> Issue creation via email
> Multiple LDAP authentication support
> User self-registration support
> Multilanguage support
> Multiple databases support
>
> ```
>
>
(from Redmine homepage)
There is also a lot of plugins to extend it, and if there isn't a plugin that you need you can create your own easily. ;) |
18,423,853 | I want to validate url before redirect it using Flask.
My abstract code is here...
```
@app.before_request
def before():
if request.before_url == "http://127.0.0.0:8000":
return redirect("http://127.0.0.1:5000")
```
Do you have any idea?
Thanks in advance. | 2013/08/24 | [
"https://Stackoverflow.com/questions/18423853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1113655/"
] | Use [urlparse (builtin module)](http://docs.python.org/2/library/urlparse.html). Then, use the builtin flask [redirection methods](http://flask.pocoo.org/docs/api/?highlight=redirect#flask.redirect)
```
>>> from urlparse import urlparse
>>> o = urlparse('http://www.cwi.nl:80/%7Eguido/Python.html')
>>> o
ParseResult(scheme='http', netloc='www.cwi.nl:80', path='/%7Eguido/Python.html',
params='', query='', fragment='')
>>> o.scheme
'http'
>>> o.port
80
>>> o.geturl()
'http://www.cwi.nl:80/%7Eguido/Python.html'
```
You can then check for the parsed out port and reconstruct a url (using the same library) with the correct port or path. This will keep the integrity of your urls, instead of dealing with string manipulation. |
258,422 | I have developed two web services. The main service is a RESTful service (using DB), and another UI service that uses the RESTful service.
Say I want to test the UI for now (integration tests), every test will makes changes in the prod DB. More then that, if in the RESTful service, there are one-way functions for security reasons. I mean that functions that can not be revert (Say if mark item as 'done', I can't edit or delete it anymore)?
This things are very logical, the most websites I know have the same situation. All these websites are not testable? | 2014/10/08 | [
"https://softwareengineering.stackexchange.com/questions/258422",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/110245/"
] | First of all, you shouldn't be testing against your production database. If you ever need to rerun your tests after the application has gone live (and you *will* need to do that), you run a serious risk of losing or corrupting data that is vital to the business.
So, instead of testing against the production database, you test against a test database (which should structurally be a copy of the production one). Then you can also add facilities to your test harness to reset that test database to a known state just before or after running a particular test.
This way, you can test the correct (inter-)operation of the two web services.
If the correct operation of the RESTful service can be presumed, you can also opt for a fake/mock of the RESTful service, which gives all the expected responses for the particular test, but doesn't actually persist anything. |
1,684 | Conosco che alcune parole, come "dito", hanno due forme ("dito", "dita") e due significati: possono avere due articoli determinativi?
Per esempio:
>
> la dita
>
>
> il dita
>
>
> | 2014/02/11 | [
"https://italian.stackexchange.com/questions/1684",
"https://italian.stackexchange.com",
"https://italian.stackexchange.com/users/134/"
] | In italiano ogni nome appartiene a un genere, maschile o femminile. Alcuni nomi cambiano genere passando dal singolare al plurale, l'esempio più famoso è
>
> *il carcere*, *le carceri*
>
>
>
e *i carceri* non è comunemente accettato. Più frequente è il doppio genere al plurale:
1. *il braccio*, *le braccia* (del corpo), *i bracci* (in senso figurato);
2. *il dito*, *le dita* (della mano), *i diti* (in senso collettivo);
3. *il muro*, *i muri* (in senso proprio), *le mura* della città.
Ci sono vari altri esempi. Una parola che può avere “doppio genere” è *fila*
1. *la fila* è quella che si fa all'ufficio postale; oppure *la fila indiana* quando si cammina uno dietro l'altro;
2. *le fila* è il plurale di *filo* in senso figurato: si dice *i fili del telefono*, ma *le fila della congiura*.
Questo *le fila* è proprio il plurale di *filo*, perché si pensa alla congiura come “trama di un tessuto”. |
28,492 | How does IE register ActiveX controls for use in the browser?
Does it just run regsvr32 for the DLL? | 2009/08/24 | [
"https://superuser.com/questions/28492",
"https://superuser.com",
"https://superuser.com/users/2503/"
] | ActiveX components register themselves, triggered by a well known DLL entry point (`DllRegisterServer`).
`regsvr32` is just a wrapper around loading the DLL and calling that entry point. Other tools can do this directly. Installers sometimes just directly update the registry (having recorded the changes to make when building the installer). |
94,357 | I'm using i8n to host a bilingual site and I only like to display the inactive language in the top bar. What php code do I need to detect the current language so I place the inactive language in the template?
Thanks:
```
<a href=
<?php
global $language;
if (($language -> name) == 'English') {
print "\"http://www.mangallery.net/fr\"".">french";
} else {
print '"http://www.mangallery.net"'.">english";
}
?>
</a>
``` | 2013/11/15 | [
"https://drupal.stackexchange.com/questions/94357",
"https://drupal.stackexchange.com",
"https://drupal.stackexchange.com/users/23730/"
] | Use the global variable `$language`
<https://api.drupal.org/api/drupal/developer%21globals.php/global/language/7> |
35,059,719 | I have created a channel on Azure Media Services, I correctly configured it as an RTMP channel and streamed a live video with Android + FFMpeg libraries.
The problem is the client end-point latency.
I need a maximum latency ~2 seconds, but now I have about ~25 seconds!
I'm using Azure Media Player in a browser page to stream the content.
Do you know a configuration of the client/channel which can reduce the latency?
Thanks | 2016/01/28 | [
"https://Stackoverflow.com/questions/35059719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2014144/"
] | ```
Label dynamiclabel = new Label();
dynamiclabel.Location = new Point(38, 30);
dynamiclabel.Name = "lbl_ques";
dynamiclabel.Text = question;
//dynamiclabel.AutoSize = true;
dynamiclabel.Size = new System.Drawing.Size(900, 26);
dynamiclabel.Font = new Font("Arial", 9, FontStyle.Regular);
``` |
44,123,504 | I hope to make some Class D heritage and implements all properties and methods of Interfaces A,B and C. Please help-me with an example in Delphi.
I use Delphi Xe7
**How One class Implement Many Interfaces?**
I'm trying something like:
```
Unit1
Type
IRefresher = Interface
['{B289720C-FFA4-4652-9F16-0826550DFCF9}']
procedure Refresh;
function getRefreshed: boolean;
property Refreshed:Boolean read getRefreshed;
End;
```
---
```
Unit2
Type
IRecorder = Interface
['{AB447097-C654-471A-A06A-C65CE5606721}']
procedure Reader;
procedure Writer;
end;
```
---
```
Unit3
ICustomer=Interface ['{F49C0018-37DA-463D-B5B4-4ED76416C7D4}']
procedure SetName(Value:String);
procedure SetDocument(Value:String);
function getName:String;
function getDocument:String;
End;
```
---
```
Unit4
Uses Unit1,Unit2,Unit3;
TGovernmentCustomer = class(TInterfacedObject, ICustomer, IRecorder,
IRefresher)
a: String;
public
{$REGION 'Customer'}
procedure SetName(Value: String); override;
procedure SetDocument(Value: String);
function getName: String; override;
function getDocument: String; override;
{$ENDREGION}
{$REGION 'Recorder'}
procedure Reader; override;
procedure Writer; override;
{$ENDREGION}
{$REGION 'Refresher'}
procedure Refresh; override;
function getRefreshed: boolean; override;
{$ENDREGION}
End;
```
It not works, because of many errors, such as 'Refresh not found in base class', | 2017/05/22 | [
"https://Stackoverflow.com/questions/44123504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6695319/"
] | Try this:
```
success: function (result) {alert(JSON.stringify(result)); }
```
From the error you have posted in comments below, it appears Dictionary is not serializable. Try setting `AllowGet` as mentioned in other answers. If doesn't work, you will need to convert Dictionary to some other object that is serializable. Or you may follow this to serialize Dictionary to json in your controller.
[How do I convert a dictionary to a JSON String in C#?](https://stackoverflow.com/questions/5597349/how-do-i-convert-a-dictionary-to-a-json-string-in-c) |
15,941,999 | Can I set some space inside 'EditText' in the beginning and at the end? If possible, then how? Actually, I have done some customization on my 'EditText' view and now it shows like this, as shown in the below image:
![Emulator screen shot](https://i.stack.imgur.com/SoUOZ.png)
In my case, as you see, in my "description" field, the word "Description" starts from the very beginning, which doesnt look attractive, I want to keep some space in the beginning and at the end of the EditText's text. And also i want to set this, at the run time as this editText views are set on the runtime after a selection from the spinner. Can i achieve this? | 2013/04/11 | [
"https://Stackoverflow.com/questions/15941999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1739882/"
] | Use `padding left` like
`editText.setPadding (int left, int top, int right, int bottom);` |
13,670,253 | The past 3 days I've tried to get this simple example to work but whatever I try I just can't seem to understand where I'm going wrong...
HTML:
```
<input type="text" id="textEntry" /> <button>Go</button>
<ul id="list">
<li>Text from the input field will appear below</li>
</ul>
```
jQUERY:
```
$('button').click(function() {
$enteredText = $('#textEntry').val();
if($enteredText.length === 0) {
alert('PLace an item in the field box');
} else {
$newListItem = $('<li/>').html($enteredText).appendTo('#list');
}
});
$('li').live('mouseover mouseout', function(event) {
if(event.type == mouseover) {
$(this).css('background-color', 'yellow');
} else {
$(this).css('backgorund-color', 'transparent'); }
});
```
Ultimately what I'm looking to do is have a user input an item into the text field which would then append itself to the existing list (this works - no issues). The user can then hover over a specific entry causing the background to turn yellow on mouseover and transparent on mouseout (the issue).
Any help would be swell.
Thanks. | 2012/12/02 | [
"https://Stackoverflow.com/questions/13670253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/933252/"
] | If the schema contains serial or sequence columns, you should reset these to the max value that occurs in the corresponding column. (normally you should not import the serials from a file, but give them the freedom to autoincrement.)
For all imported tables you should identify the sequence fields and run the following code on them. (substitute your schema name for "sch", your table name for "mytable" and your id column name for "id")
```
WITH mx AS ( SELECT MAX(id) AS id FROM sch.mytable)
SELECT setval('sch.mytable_id_seq', mx.id) AS curseq
FROM mx
;
``` |
488,019 | For most ML models we say they suffer from high bias or high variance, then we correct for it. However, in DL do neural networks suffer from the same concept in the sense that they initially have high bias or high variance and then you correct through regularization and/or dropout? I would argue they initially suffer from high variance and they overfit the data. Then you correct through regularization, add dropout, image pre-processing in the case of CNNs, etc. Is this train of thought correct? | 2020/09/18 | [
"https://stats.stackexchange.com/questions/488019",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/72773/"
] | In general NNs are prone to overfitting the training set, which is case of a [high variance](https://datascience.stackexchange.com/questions/45578/why-underfitting-is-called-high-bias-and-overfitting-is-called-high-variance). Your train of thought is generally correct in the sense that the proposed solutions (regularization, dropout layers, etc.) are tools that control the bias-variance trade-off. |
9,327,400 | I've create a c# winforms form,
It has a bunch of labels positioned and a flowlayoutpanel.
on certain occasions i set one of the labels and the flowlayoutpanel to visible =false.
As a result i want all labels beneath them to be pushed up - at the moment there is a gap where they were.
Also, I'd like the flowlayoutpanel to grow and shrink depending on the number of items it has.
at the moment it is just the size i set it to be in the designer.
please can you help with these 2 issues.
Thanks | 2012/02/17 | [
"https://Stackoverflow.com/questions/9327400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/66975/"
] | If I got you correctly, I would suggest using a TableLayoutPane with two rows. The top row will contain a docked panel with all the controls that may be hidden. The bottom row will contain a docked panel with all the rest.
Set the top row's SizeType to AutoSize and the bottom row's to 100%.
When you want to hide the controls, set the top panel's Visible property to false. Now, because the top row is AutoSized it will shrink to nothing, causing the bottom row to "jump" up. |
192,935 | I want to say :
>
> Analysis **conducted at a** insurance company showed that...
>
> or
>
> Analysis **into a** insurance company showed that...
>
>
>
What is the best way to phrase this? | 2014/08/23 | [
"https://english.stackexchange.com/questions/192935",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/89164/"
] | I would make it slightly less passive:
*"An analysis performed by the insurance company ..."*
or other material to indicate *who* performed the analysis and *where* it was performed as well as the issue being analyzed. If you or your associates performed the analysis, you might phrase it:
*"An analysis performed by the authors into insurance company policies...'* |
52,259,592 | We are hosting our website in Azure. During the deployment(TFS) we will do the below Steps as the part of the deployment pipeline.
1. Stop the WebApp
2. Deploy Web App Service
3. Start the WebApp
After the 1st step, if anyone tries to access our website, then by default Azure will return the below page
[![enter image description here](https://i.stack.imgur.com/zXQzr.jpg)](https://i.stack.imgur.com/zXQzr.jpg)
We really don't want our users to show this page during the outage. We are planning to show our own outage image/page in such case.
Is there is any way to achieve this?
Since Azure Web Apps in a Paas model, I'm wondering how to do this?
Any inputs Appreciated! | 2018/09/10 | [
"https://Stackoverflow.com/questions/52259592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7073340/"
] | Messing with `sys.path` is rarely a good idea.
Since your plan seems to be to use both `foo` and `test` from `notebooks` (that will probably just contain Jupyter notebooks), the cleanest solution would be to install `foo` and `test` as packages.
Remove the `__init__.py` from your top level directory and `notebooks`, since you will not want to import them. Then add a `setup.py` to your top level directory. Since your tests are specific to `foo`, you should either rename them `foo_test` or move them into `foo` itself.
A minimal `setup.py` would look like this
```
from setuptools import setup
setup(name='foo',
version='0.1',
description='descroption of fo',
author='you',
author_email='your@mail',
packages=['foo','test_foo])
```
Then you can simply `pip install -e .` in your top level directory and it will be installed into your current virtualenv. If you are not using virtualenvs, you should `pip install --user -e .` |
52,819,018 | This code should count the number of prime numbers based on user input. If user input is 10, then I should get 4. However, I only get 0. Why does the second loop not run?
```
#include<stdio.h>
#include<math.h>
int main()
{
int N;
scanf("%d", &N);
int numprime;
numprime = 0;
int P=1;
for (P; P<N; P++)
{
if (P%2==0)
continue;
int e = sqrt(P);
for (int j=3;j<=e;j+=2)
{
if (P%j!=0)
{
numprime = numprime + 1;
}
else
{
continue;
}
}
}
printf("%d", numprime);
}
``` | 2018/10/15 | [
"https://Stackoverflow.com/questions/52819018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10502481/"
] | `flex-direction: column`
========================
The major problem (besides some bad syntax on background shorthand) is that the `flex-direction` was at default which is `row` (horizontal). The flex items (`.logo` and `.copy`) are stacked vertically thus the `flex-direction` should be `column`.
---
Demo
----
**Details commented in demo**
```css
html,
body {
/* Always set the font on html */
font: 700 16px/1.5 Verdana;
width: 100%;
height: 100%;
}
.flex {
/*
shorthand for background goes in this order:
position (center) repeat (no-repeat) size (cover)
and there's no slash "/"
*//*
no-repeat is the only one kept
*/
background: url('https://i.imgur.com/5OLUUfp.png')no-repeat;
/*
The sidebar is always top to bottom
*/
min-height: 100%;
/*
The width was 100vw which is 100% of viewport which I'm assuming
is wrong since a sidebar should only cover a portion of the
viewport.
*/
width: 320px;
/*
By default flex-direction is row (horizontal flow)
*/
display: flex;
/*
The flex items (.logo and .copy) are vertical, so the flex-
direction should be column. flex-flow is a combination of
flex-direction and flex-wrap
*/
flex-flow: column nowrap;
justify-content: center;
align-items: center;
}
.logo {
/*
This pushes the footer.copy down to the bottom
*/
margin: auto;
}
img {
display: block;
width: 90%;
}
.copy {
font-size: 0.875rem;
color: #FFF;
/*
This property is given to individual tags that will break
away from vertical flow of align-items
*/
align-self: flex-end;
margin-right: 10px
}
```
```html
<aside class="flex">
<figure class="logo">
<img src="https://i.imgur.com/cx6bov9.png">
</figure>
<footer class='copy'>© copyright 2018</footer>
</aside>
``` |
20,852,167 | I am new to php. I have tried the following code to redirect the page when sign In button is clicked, but it is not happening. please help me editing the code. probably, there is an error in header() function. Have I used the header() function correctly?
```
<body>
<?php
$emailErr = $passwordErr = "";
$email = $password = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["email"])) {
$emailErr = "*Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address syntax is valid
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",$email)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["password"])) {
$passwordErr = "*Password is required";
} else {
$password = test_input($_POST["password"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
include("signInform.php");
if($_POST["sign"])
{
header('Location:signInform.php');
}
?>
<br/><br/><br/><br/><br/>
<h1>WELCOME</h1>
<h2>Please, Register Yourself!</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label>E-mail:</label><br />
<input type="text" name="email"/>
<span class="error"> <?php echo $emailErr;?></span>
<br />
<label>Password:</label><br />
<input type="password" name="password"/>
<span class="error"> <?php echo $passwordErr;?></span>
<br /><br />
<input type="submit" value="Register"/><br/>
<p>If already a user, Sign in! </p>
<input type="submit" value="Sign In" name="sign"/><br/>
</form>
</body>
``` | 2013/12/31 | [
"https://Stackoverflow.com/questions/20852167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3131191/"
] | Add `@ob_start();` top of the page,
```
if (isset($_POST["sign"])) {
header('Location:signInform.php');
}
``` |
12,025,173 | Here is the main problem:
```
dig maktabkhooneh.info +trace
```
works perfectly fine and returns the right answer.
```
dig maktabkhooneh.info
```
(without +trace) returns:
```
; <<>> DiG 9.8.1-P1 <<>> maktabkhooneh.info
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 58716
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 0
```
What could be the reason? I was reading [this](https://serverfault.com/questions/65499/dig-trace-resolves-while-without-doesnt). Is it the only possible reason that I changed domain data 12hrs ago? Isn't there any other possible reason for `SERVFAIL`?
**extra info:**
I have two BIND servers working on 168.144.251.73 (master) and 168.144.92.50 (slave).
and on the master I have:
```
$TTL 300
maktabkhooneh.info. IN SOA ns1.maktabkhooneh.info.
admin.maktabkhooneh.info. (
2012060201 ; Serial
86400 ; Refresh
7200 ; Retry
3600000 ; Expire
300 ) ; Minimum
maktabkhooneh.info. IN A 168.144.97.83
maktabkhooneh.info. IN NS ns1.maktabkhooneh.info.
maktabkhooneh.info. IN NS ns2.maktabkhooneh.info.
ns1 IN A 168.144.251.73
ns2 IN A 168.144.92.50
www IN CNAME maktabkhooneh.info.
``` | 2012/08/19 | [
"https://Stackoverflow.com/questions/12025173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1380812/"
] | `dig +trace` follows the whole chain from the beginning - it queries root servers, then .info servers then your namservers. Thus it avoids any caching resolvers, and also avoids propagation issues.
`dig +notrace` (the default) queries your default DNS resolver (on Linux, whatever specified in `/etc/resolv.conf`).
There's some problem with that resolver - maybe it's misconfigured, maybe it has old data in its caches, maybe it can not reach your authoritative nameservers, etc. |
38,574,785 | I need to extract values from the below JSON response I am receiving from a web service response.
```
{"ns4:SearchSA_PartyReturn": {
"xmlns:ns1": "urn:cs-base",
"xsi:type": "ns4:SearchSA_PartyReturn",
"ns4:object": {
"xmlns:ns2": "urn:co-base",
"recordCount": 3,
"xmlns:ns0": "urn:cs-rest",
"ns3:item": [
{
"ns3:SA_Party": {
"ns3:partyName": "Akorn New Jersey Inc",
"ns3:partyStatus": "ACTIVE",
"ns2:rowidObject": 20011,
"ns3:SAC_Address": {
"ns3:item": {
"ns3:city": "QUE",
"ns3:state": "N",
"ns2:rowidObject": 20011,
"ns3:postalCode": -4,
"ns3:addressType": "P",
"ns3:country": "US",
"ns3:addressLine": "RD"
},
"pageSize": 10,
"firstRecord": 1,
"searchToken": "SVR1.TD3V"
},
"ns3:partyType": "Pharma",
"ns3:SAC_Person": {
"ns3:item": {
"ns3:firstName": "DO",
"ns2:rowidObject": 11,
"ns3:lastName": "MA",
"ns3:middleName": "R",
"ns3:personType": 2
},
"pageSize": 10,
"firstRecord": 1,
"searchToken": "SVR1.TD3U"
}
},
"ns3:changeSummary": {
"logging": false,
"xmlns:sdo": "commonj.sdo"
}
},
{
"ns3:SA_Party": {
"ns3:partyName": "Akorn New Jersey Inc",
"ns3:partyStatus": "ACTIVE",
"ns2:rowidObject": 20047,
"ns3:SAC_Address": {
"ns3:item": {
"ns3:city": "SC",
"ns3:state": "N",
"ns2:rowidObject": 20047,
"ns3:postalCode": 12,
"ns3:addressType": "B",
"ns3:country": "US",
"ns3:addressLine": "OTT STET"
},
"pageSize": 10,
"firstRecord": 1,
"searchToken": "SVR1.TD3X"
},
"ns3:partyType": "Pharma",
"ns3:SAC_Person": {
"ns3:item": {
"ns3:firstName": "GE",
"ns2:rowidObject": 47,
"ns3:lastName": "HA",
"ns3:middleName": "B",
"ns3:personType": 2
},
"pageSize": 10,
"firstRecord": 1,
"searchToken": "SVR1.TD3W"
}
},
"ns3:changeSummary": {
"logging": false,
"xmlns:sdo": "commonj.sdo"
}
},
{
"ns3:SA_Party": {
"ns3:partyName": "Cig Na Ltd",
"ns3:partyStatus": "ACTIVE",
"ns2:rowidObject": 20040,
"ns3:SAC_Address": {
"ns3:item": {
"ns3:city": "JA",
"ns3:state": "NY",
"ns2:rowidObject": 20040,
"ns3:postalCode": 1,
"ns3:addressType": "P",
"ns3:country": "US",
"ns3:addressLine": "QUR"
},
"pageSize": 10,
"firstRecord": 1,
"searchToken": "SVR1.TD3Z"
},
"ns3:partyType": "Insurance",
"ns3:SAC_Person": {
"ns3:item": {
"ns3:firstName": "A",
"ns2:rowidObject": 40,
"ns3:lastName": "Q",
"ns3:personType": 2
},
"pageSize": 10,
"firstRecord": 1,
"searchToken": "SVR1.TD3Y"
}
},
"ns3:changeSummary": {
"logging": false,
"xmlns:sdo": "commonj.sdo"
}
}
],
"pageSize": 10,
"firstRecord": 1
},
"xmlns:ns3": "urn:co-ors",
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xmlns:ns4": "urn:cs-ors"
}}
```
Can anyone help me with a javascript/jquery to extract `ns3:SA_Party` with its corresponding children `ns3:SAC_Address` and `ns3:SAC_Person`. (SA\_Party is the parent with two children SAC\_Address and SAC\_Person). I need the underlying attribute, too. | 2016/07/25 | [
"https://Stackoverflow.com/questions/38574785",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6116467/"
] | It looks like you're trying to get `document.getElementById("setting").value` but the actual ID is "Setting" as per
```
<select name="Setting">
<option value="Office">Office</option>
<option value="HOPD">HOPD</option>
</select>
```
Try changing the getElementById to `document.getElementById("Setting").value`
EDIT
====
Ok, I made a JSFiddle for you:
<https://jsfiddle.net/dktoxtne/1/>
Let me know if that works! I don't remember all I changed, but I do remember you need to change the `name="Setting"` to `id="Setting"` and a few other things. |
58,567,334 | I'm trying to turn a Huffman tree and a stream of bits into a list of characters plus a boolean indicating whether or not the output consumed all the input bits. Here's an example:
```
decode xyz_code [True,False,True,True,True,False,False,True] =
("yzyx",False)
```
Here's what I have so far, but it doesn't work. What's going wrong? Help!
```
data BTree a = Leaf a | Fork (BTree a) (BTree a) deriving (Show, Eq)
decode :: BTree a -> [Bool] -> ([a], Bool)
decode _ [] = ([],True)
decode (Leaf v) [bs] = ([v], bs)
decode (Fork left right) (b:bs)
| b = decode right bs
| otherwise = decode left bs
``` | 2019/10/26 | [
"https://Stackoverflow.com/questions/58567334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12276493/"
] | I think no, Authorization server is out of their roadmap. Starting from november the 13th every class in spring security which worked with Authorization server features become deprecated.
[Spring Security OAuth 2.0 Roadmap Update](https://spring.io/blog/2019/11/14/spring-security-oauth-2-0-roadmap-update#no-authorization-server-support) (here the answer on you question) |
74,370 | I have an Ubuntu 6.06 server that needs to be replaced by an Ubuntu 9.04 server clean setup, I already copied the entire samba file server directory to the new 9.04 server using rsync. I need to know how to migrate the existing user accounts (machine accounts) to the new server so as when I physically transfer the connections everything will be ok and I don't have to manually enter `smbpasswd -a <user>` on the new server.
```
passdb backend = tdbsam
```
network workstations accessing the share are either vista or xp. | 2009/10/14 | [
"https://serverfault.com/questions/74370",
"https://serverfault.com",
"https://serverfault.com/users/-1/"
] | ```
passdb backend = tdbsam
```
means you have your samba accounts in a `passdb.tdb` file in `SAMBA_DIR/private`.
As long as you copy it with rsync you are fine.
There are two caveats:
* Unix users: a samba user has to be a unix user as well, so you have to copy all files @churnd told you;
* timing: machine account are updated every time, so you need a super fresh rsync. In a perfect world, you should stop old server, rsync, start new server. |
71,435,759 | I am trying to add a new recipe to install new packages in my image. I need the next packages libnfc5 libnfc-bin libnfc-examples, I have found these packages in this page: <http://ftp.de.debian.org/debian/pool/main/libn/libnfc/>, so I am using the next commands to install the packages:
* devtool add libnfc5 <http://ftp.de.debian.org/debian/pool/main/libn/libnfc/libnfc5_1.7.1-4+b1_armhf.deb>
* devtool build libnfc5
* devtool deploy-target libnfc5 root@my-ip
I am not sure if is necessary modify the .bb file generate: libnfc5\_1.7.1-4+b1.bb, and one time that I execute deploy-target which is necessary to do in my device, Do I need to install the library? | 2022/03/11 | [
"https://Stackoverflow.com/questions/71435759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18352597/"
] | `PIVOT` relational operator is an option:
Sample data:
```
SELECT *
INTO Company
FROM (VALUES
(1, 'Frodo B (manager), Gandalf G (director), Batman C (cleaner)'),
(2, 'John Doe (secretary), Mark Jacobs (manager), Lilly Hopes (director), Rihanna Williams (cleaner), Maddy James (supervisor), Merry Poppins (HR)'),
(3, 'Rick Ross (cleaner)'),
(4, 'Orlando Bloom (manager), Keira Knightly (secretary)')
) d (Id, Team)
```
Statement:
```
SELECT *
FROM (
SELECT c.Id, LTRIM(s.[value]) AS [Name], p.Position
FROM Company c
CROSS APPLY STRING_SPLIT(c.Team, ',') s
JOIN (VALUES
('cleaner'), ('director'), ('manager'), ('supervisor'), ('secretary'), ('HR'), ('owner')
) p (Position) ON CHARINDEX(p.Position, s.[value]) > 0
) t
PIVOT (
MAX(Name)
FOR Position IN ([cleaner], [director], [manager], [supervisor], [secretary], [HR], [owner])
) p
```
Result:
| Id | cleaner | director | manager | supervisor | secretary | HR | owner |
| --- | --- | --- | --- | --- | --- | --- | --- |
| 1 | Batman C (cleaner) | Gandalf G (director) | Frodo B (manager) | | | | |
| 2 | Rihanna Williams (cleaner) | Lilly Hopes (director) | Mark Jacobs (manager) | Maddy James (supervisor) | John Doe (secretary) | Merry Poppins (HR) | |
| 3 | Rick Ross (cleaner) | | | | | | |
| 4 | | | Orlando Bloom (manager) | | Keira Knightly (secretary) | | |
For SQL Server versions before 2016 (but with XML support), you may split the stored text using well-known XML technique:
```
SELECT *
FROM (
SELECT c.Id, LTRIM(s.[value].value('.', 'varchar(1000)')) AS [Name], p.Position
FROM (
SELECT *, CAST('<x>' + REPLACE(Team, ',', '</x><x>') + '</x>' AS XML) AS XmlTeam
FROM Company
) c
CROSS APPLY c.XmlTeam.nodes('./x') s ([value])
JOIN (VALUES
('cleaner'), ('director'), ('manager'), ('supervisor'), ('secretary'), ('HR'), ('owner')
) p (Position) ON CHARINDEX(p.Position, s.[value].value('.', 'varchar(1000)')) > 0
) t
PIVOT (
MAX(Name)
FOR Position IN ([cleaner], [director], [manager], [supervisor], [secretary], [HR], [owner])
) p
``` |
66,986,874 | Have some data stored in different directory paths in databricks file system. Need to rename some folders. Is it possible to rename folders in DBFS? If so, what's the command? | 2021/04/07 | [
"https://Stackoverflow.com/questions/66986874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8500105/"
] | You can use `mv` with `%fs` magic, or `dbutils.fs` to do this. This command is used for renaming and/or moving files and directories
`%fs mv -r /path/to/folder /path/to/new_folder_name`
the `-r` is to do recursive move with directories.
It's documented in the [dbutils](https://docs.databricks.com/_static/notebooks/dbutils.html). There is also more info [here](https://docs.databricks.com/data/databricks-file-system.html#dbfs-and-local-driver-node-paths). |
73,695,925 | I'm going nuts trying to connnect in Selenium4 to Chrome instance on a localhost.
I invoked chrome from bash using
```
$ /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=6666 --user-data-dir=/Users/h/Desktop/MY/chrome-profile
```
and next i tried to connect from Selenium4
```
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
# opt = Options()
# opt.add_experimental_option("debuggerAddress", "localhost:6666")
# opt.add_argument("debuggerAddress", "localhost:6666")
# opt.add_debuggerAddress("localhost:6666")
# opt.add_debugger_address("localhost:6666")
# web_driver = webdriver.Chrome(options=opt)
# chrome_options = Options()
# chrome_options.add_experimental_option("debuggerAddress", "localhost:6666")
# driver = webdriver.Chrome(chrome_options=chrome_options)
# driver.get('https://www.google.com')
path = '/Users/h/Desktop/MY/webdrivers/chrome/105.0.5195.52/chromedriver'
# driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=opt)
# service = Service(executable_path=ChromeDriverManager().install())
# driver = webdriver.Chrome(service=service, options=chrome_options)
# driver.get('https://www.example.com/')
service = ChromeService(executable_path=path, port=6666) # i tried with local path and ChromeDriverManager
driver = webdriver.Chrome(service=service)
driver.get('https://www.example.com/')
```
i think i tried all possible options:
* prepending http:// to localhost throws an error,
* using chrome\_options=chrome\_options throws a deprecation warning, pointing i should use >options=<, and seems to have no effect on the browser in localhost,
* trying to launch webdriver from a local file, and currently suggested ChromeDriverManager. Both work. Until i want to specify options.
i also looped through the example i found on ~20 websites, incl. github bug reports - where people claim their code worked until VSCode upgraded.
I guess my question is - is there anything wrong with how i try to pass the chrome options, or did i actually encounter a bug ?
======
Edit:
that is a full error trace:
```
---------------------------------------------------------------------------
WebDriverException Traceback (most recent call last)
Input In [10], in <cell line: 29>()
22 # driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=opt)
23
24 # service = Service(executable_path=ChromeDriverManager().install())
25 # driver = webdriver.Chrome(service=service, options=chrome_options)
26 # driver.get('https://www.wp.pl/')
28 service = ChromeService(executable_path=path, port=6666) #at this line you can use your ChromeDriverManager
---> 29 driver = webdriver.Chrome(service=service)
30 driver.get('https://www.example.com/')
File ~/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/chrome/webdriver.py:69, in WebDriver.__init__(self, executable_path, port, options, service_args, desired_capabilities, service_log_path, chrome_options, service, keep_alive)
66 if not service:
67 service = Service(executable_path, port, service_args, service_log_path)
---> 69 super().__init__(DesiredCapabilities.CHROME['browserName'], "goog",
70 port, options,
71 service_args, desired_capabilities,
72 service_log_path, service, keep_alive)
File ~/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/chromium/webdriver.py:92, in ChromiumDriver.__init__(self, browser_name, vendor_prefix, port, options, service_args, desired_capabilities, service_log_path, service, keep_alive)
89 self.service.start()
91 try:
---> 92 super().__init__(
93 command_executor=ChromiumRemoteConnection(
94 remote_server_addr=self.service.service_url,
95 browser_name=browser_name, vendor_prefix=vendor_prefix,
96 keep_alive=keep_alive, ignore_proxy=_ignore_proxy),
97 options=options)
98 except Exception:
99 self.quit()
File ~/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py:270, in WebDriver.__init__(self, command_executor, desired_capabilities, browser_profile, proxy, keep_alive, file_detector, options)
268 self._authenticator_id = None
269 self.start_client()
--> 270 self.start_session(capabilities, browser_profile)
File ~/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py:363, in WebDriver.start_session(self, capabilities, browser_profile)
361 w3c_caps = _make_w3c_caps(capabilities)
362 parameters = {"capabilities": w3c_caps}
--> 363 response = self.execute(Command.NEW_SESSION, parameters)
364 if 'sessionId' not in response:
365 response = response['value']
File ~/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/webdriver.py:428, in WebDriver.execute(self, driver_command, params)
426 response = self.command_executor.execute(driver_command, params)
427 if response:
--> 428 self.error_handler.check_response(response)
429 response['value'] = self._unwrap_value(
430 response.get('value', None))
431 return response
File ~/opt/anaconda3/lib/python3.9/site-packages/selenium/webdriver/remote/errorhandler.py:207, in ErrorHandler.check_response(self, response)
205 value = response['value']
206 if isinstance(value, str):
--> 207 raise exception_class(value)
208 if message == "" and 'message' in value:
209 message = value['message']
WebDriverException: Message:
``` | 2022/09/12 | [
"https://Stackoverflow.com/questions/73695925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18995273/"
] | You can use the format below:
```
PARSE_DATETIME('%m/%d/%Y %l:%M %p', "7/13/2022 9:46 AM")
```
The output:
[![parse_datetime_output](https://i.stack.imgur.com/i07A9.png)](https://i.stack.imgur.com/i07A9.png) |
72,506,798 | Hello there I try to align some text in a container to the left but it won't work even when there is free space. As you can see there is some free space directly next to the image which isn't used for no reason. Right here I show you a picture and also the style. Thanks in advance if anyone can help.
![enter image description here](https://i.stack.imgur.com/DTEG9.png)
```css
.text-wrapper-overview {
position: inherit;
left: 100px;
width: 65%;
}
.user-name {
position: inherit;
margin: 5px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
font-size: large;
font-weight: bold;
}
.last-message {
position: inherit;
height: 20px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin: 5px;
font-size: small;
}
.timestamp-overview {
position: inherit;
margin: 5px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
font-size: small;
font-weight: normal;
}
```
```html
<div id={this.name} className="chat-overview" onClick={()=>this.renderChat()}>
<img className="round-image" src="https://i.pravatar.cc/200"></img>
<div className="text-wrapper-overview">
<p className="user-name">{this.name}</p>
<p className="last-message">{this.lastMessage.text}</p>
<p className="timestamp-overview">{this.lastDate}</p>
</div>
<div className="notification">10+</div>
</div>
``` | 2022/06/05 | [
"https://Stackoverflow.com/questions/72506798",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17032453/"
] | You could use interfaces with default implementations which were introduced in C# 8. Then you could derive from these interfaces.
Here's an example of how you could you provide default implementations for the `MoveForward()` and `StartBroadcast()` methods:
```cs
public interface IVehicle
{
void MoveForward()
{
// your code
}
void PerformUniqueAbility();
}
```
```cs
public interface IRadioSignalBroadcaster
{
void StartBroadcast()
{
// your code
}
void PerformUniqueBroadcastingAbility();
}
``` |
3,051,606 | I need to find minimum point of hanging rope with two known points $p\_1, p\_2$ (start and end point of the rope) and known rope length.
I want to model all rope shapes with different length and start and end point.
Do I have to use numerical methods?
Does it have any closed form solution?
Known $\to L,(x\_1,y\_1), (x\_2,y\_2)$ then $a=$?
I use a general catenary equation like below:
$$
f(x)= a\cosh\left(\frac {x-b}a\right)+c\\
L= a\sinh\left(\frac{x\_2}{a}\right)-a\sinh\left(\frac{x\_1}{a}\right)
$$ | 2018/12/24 | [
"https://math.stackexchange.com/questions/3051606",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/629130/"
] | Starting from @Cesareo answer, considering
$$L^2-v^2 = 4a^2\sinh^2\left(\frac{h}{2a}\right)$$ let $x=\frac{h}{2a}$ to make the equation
$$\frac{L^2-v^2}{h^2}=\frac{\sinh^2(x) }{x^2}\implies k=\sqrt{\frac{L^2-v^2}{h^2}}=\frac{\sinh(x) }{x}$$
Consider that you look for the zero of $$f(x)=\frac{\sinh(x) }{x}-k$$ It varies very quickly. Then, it would be better to look for the zero of
$$g(x)=\log \left(\frac{\sinh (x)}{x}\right)-\log(k)$$ which is much better conditioned.
**Edit**
To get a starting value $x\_0$ for Newton method, using Padé approximant built at $x=0$
$$\frac{\sinh (x)}x\simeq \frac{7 x^2+60}{60-3 x^2} \implies x\_0=\frac{2 \sqrt{15} \sqrt{k-1}}{\sqrt{3 k+7}}$$ which would be good for $1 \leq k \leq 3$.
For larger values of $k$
$$\frac{\sinh (x)}x\simeq \frac{e^x}{2 x}\implies x\_0=-W\_{-1}\left(-\frac{1}{2 k}\right)$$ where appears Lambert function.
The table below shows some results
$$\left(
\begin{array}{ccc}
k & x\_0 & x \\
1.25 & 1.18125 & 1.18273 \\
1.50 & 1.61515 & 1.62213 \\
1.75 & 1.91663 & 1.93300 \\
2.00 & 2.14834 & 2.17732 \\
2.25 & 2.33550 & 2.37963 \\
2.50 & 2.49136 & 2.55265 \\
2.75 & 2.62398 & 2.70395 \\
3.00 & 2.73861 & 2.83845 \\
& & \\
3.00 & 2.83315 & 2.83845 \\
3.25 & 2.95545 & 2.95952 \\
3.50 & 3.06642 & 3.06962 \\
3.75 & 3.16801 & 3.17058 \\
4.00 & 3.26169 & 3.26380 \\
4.25 & 3.34861 & 3.35037 \\
4.50 & 3.42970 & 3.43117 \\
4.75 & 3.50567 & 3.50693 \\
5.00 & 3.57715 & 3.57823
\end{array}
\right)$$
**Edit**
Looking at [this question](https://math.stackexchange.com/questions/1068912/solving-sinhax-bx/1068927#1068927) (which I did not remember - problem of age, I guess), I noticed that I was able to generate a quite good estimates building at $x=0$ the $[3,4]$ Padé approximant of $\sinh(x)-k x$.
From this, I considered building the $[3,2n]$ Padé approximants which write
$$\sinh(x)-k x=x \frac{(1-k)+a^{(n)}\_1 x^2 }{1+\sum\_{m=1}^n b\_m x^{2m} }$$ leading to an approximate solution
$$x=\sqrt{\frac {k-1}{a^{(n)}\_1 }}$$ For sure, this was done using a CAS. The longest result able to fit on a single line corresponds to $n=6$ and the result is
$$x=\frac{\sqrt{6} \sqrt{(k-1)(105 k^5+60705 k^4+1365738 k^3+5507466 k^2+5665509 k+1414477 )}}{\sqrt{3 k^6+6120 k^5+307017 k^4+2586544 k^3+5952621 k^2+4301640
k+860055}}$$ which seems to be very good even for large values of $k$ (checked up to $k=500$). |
28,078,756 | So I've typed a command (pacman -S perl-) and I hit tab and see that there are a whole bunch of completions (about 40), and I realize that I want to run every single completion (so I don't accidentally install from CPAN what is already a builtin).
How do I run all completions of a command?
BONUS: How do I run more than one and less than all of the commands (without typing them in individually)?
Example situation (the actual situation):
```
XXXXXXXXXXXXXXXXX ❯❯❯ pacman -S perl-<Tab> ⏎
-- packages --
perl perl-IPC-Run3
perl-ack perl-libwww
perl-Archive-Zip perl-Locale-Gettext
perl-Authen-SASL perl-LWP-MediaTypes
perl-Benchmark-Timer perl-LWP-Protocol-https
perl-Capture-Tiny perl-MailTools
perl-common-sense perl-MIME-tools
perl-Compress-Bzip2 perl-Mozilla-CA
perl-Convert-BinHex perl-Net-DNS
perl-Crypt-SSLeay perl-Net-HTTP
perl-DBI perl-Net-IP
perl-Digest-HMAC perl-Net-SMTP-SSL
perl-Encode-Locale perl-Net-SSLeay
perl-Error perl-Path-Class
perl-Exporter-Lite perl-Probe-Perl
perl-ExtUtils-Depends perl-Regexp-Common
perl-ExtUtils-PkgConfig perl-Socket6
perl-File-Copy-Recursive perl-Sys-CPU
perl-File-Listing perl-TermReadKey
perl-File-Next perl-Test-Pod
perl-File-Which perl-Test-Script
perl-Getopt-Tabular perl-TimeDate
perl-HTML-Parser perl-Try-Tiny
perl-HTML-Tagset perl-URI
perl-HTTP-Cookies perl-WWW-RobotRules
perl-HTTP-Daemon perl-XML-LibXML
perl-HTTP-Date perl-XML-NamespaceSupport
perl-HTTP-Message perl-XML-Parser
perl-HTTP-Negotiate perl-XML-SAX
perl-IO-HTML perl-XML-SAX-Base
perl-IO-Socket-INET6 perl-XML-Simple
perl-IO-Socket-SSL perl-YAML
perl-IO-stringy perl-YAML-Syck
``` | 2015/01/21 | [
"https://Stackoverflow.com/questions/28078756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2851917/"
] | Here is my own solution to deal with,
* To apply matching for completion results.
* To insert all the completion matches into the command line.
* To activate menu selection and select the completion more than one.
---
**To apply matching for completion results**, it could be done with the [`_match`](http://zsh.sourceforge.net/Doc/Release/Completion-System.html#index-_005fmatch).
Here is an example `~/.zshrc`:
```sh
# below is same as the zsh default effect
# zstyle ':completion:*::::' completer _complete _ignored
zstyle ':completion:*::::' completer _complete _match _ignored
# I don't like expand-or-complete to <Tab>, so I moved it to <C-x><Tab>
bindkey '^I' complete-word
bindkey '^X^I' expand-or-complete
```
Now, it could be ok to use `*`s to get the effects like this:
```
% ls m*e* ;# I have some local files that matches the glob.
main.epro mem.c mem.pro modentry.c module.o modules.stamp
makepro.awk mem.epro mem.syms module.c module.pro
math.epro mem.o mkmakemod.sh module.epro module.syms
% git m*e*<Tab>
;# This prompts completions rather than expands the local files
;# like this:
% git merge
merge -- join two or more development histories together
merge-base -- find as good a common ancestor as possible for a merge
merge-file -- run a three-way file merge
merge-index -- run merge for files needing merging
merge-one-file -- standard helper-program to use with git merge-index
merge-tree -- show three-way merge without touching index
mergetool -- run merge conflict resolution tools to resolve merge conflicts
mktree -- build tree-object from git ls-tree formatted text
m*e*
```
**To insert all the compliteon matches into the command line**, it cloud be done with the [`all-matches`](http://zsh.sourceforge.net/Doc/Release/Completion-System.html#index-_005fall_005fmatches). If you have the below snippets in your `~/.zshrc`:
```sh
zle -C all-matches complete-word _my_generic
zstyle ':completion:all-matches::::' completer _all_matches
zstyle ':completion:all-matches:*' old-matches only
_my_generic () {
local ZSH_TRACE_GENERIC_WIDGET= # works with "setopt nounset"
_generic "$@"
}
bindkey '^X^a' all-matches
```
typing `Tab` then `Control-x`,`Control-a` inserts the completion matches to the command line.
For example:
```
% vim string.<Tab>
string.c string.epro string.syms
;# then hit <C-x><C-a>
% vim string.c string.epro string.syms
```
**To activate menu selection and select the completion more than one**, it could be done by customizing `menuselect` keymap.
([From `zhmodules(1)` 22.7.3 Menu selection](http://zsh.sourceforge.net/Doc/Release/Zsh-Modules.html#Menu-selection))
```sh
zstyle ':completion:*' menu select=0
zmodload zsh/complist
bindkey -M menuselect "^[a" accept-and-hold
bindkey -M menuselect '^[^[' vi-insert
```
This activete menu selection for the completion results. During the menu selection is active, typing `M-a` (or `Esc-a`) inserts the selected entry and advances the "menu cursor" to next entry.
For example session:
```
% ls sig*
sigcount.h signals.h signals.syms signames.o signames1.awk
signals.c signals.o signames.c signames.pro signames2.awk
signals.epro signals.pro signames.epro signames.syms
% vim sig<Tab> ;# this lists the matches
sigcount.h signals.epro signals.syms signames.epro signames1.awk
signals.c signals.h signames.c signames.syms signames2.awk
;# hitting <Tab> second time, the "menu cursor" appears and
;# the first entry will be activated
;# Note: "[[]]" denotes the "menu cursor" here
% vim sigcount.h
[[sigcount.h]] signals.epro signals.syms signames.epro signames1.awk
signals.c signals.h signames.c signames.syms signames2.awk
;# then hit <M-a>(Esc a)
;# "sigcount.h" is now in the command line and
;# the "menu cursor" points "signals.c" now.
% vim sigcout.h signals.c
sigcount.h signals.epro signals.syms signames.epro signames1.awk
[[signals.c]] signals.h signames.c signames.syms signames2.awk
;# then <Tab><Tab>
% vim sigcount.h signals.h
sigcount.h signals.epro signals.syms signames.epro signames1.awk
signals.c [[signals.h]] signames.c signames.syms signames2.awk
```
So, you could select multiple entries in the completion results to hit `M-a`(or `Esc-a`) as you like.
*Below paragraph is not bad to know.*
In this expample configration, hitting `Esc``Esc` (we did `bindkey -M menuselect '^[^[' vi-insert` in the above snippets) while the menu selection is active, it allows us to interactively limit the completion result based on input patterns.
```
;# activate "menu selection" and hit <Esc><Esc>,
;# the "interacitve:" mode will be shown at this point.
% vim sig*
interactive: sig[]
[[sigcount.h]] signals.epro signals.syms signames.epro signames1.awk
signals.c signals.h signames.c signames.syms signames2.awk
;# hitting "*awk" while interactive is activetad,
;# it colud limit the completion to "sig*awk"
% vim sig*awk
interactive: sig[]
[[signames1.awk]]signames2.awk
sig*awk
```
*I'm not sure I describe correctly, so here is the portion of the zsh doc for the menu selection's "interactive mode".*
>
> vi-insert
>
>
> this toggles between normal and interactive mode; in interactive mode the keys bound to self-insert and self-insert-unmeta insert into the command line as in normal editing mode but without leaving menu selection; after each character completion is tried again and the list changes to contain only the new matches; the completion widgets make the longest unambiguous string be inserted in the command line and undo and backward-delete-char go back to the previous set of matches
>
>
> -- [`zhmodules(1)` 22.7.3 Menu selection](http://zsh.sourceforge.net/Doc/Release/Zsh-Modules.html#Menu-selection)
>
>
>
---
It could be fine to see also [`edit-command-line`](http://zsh.sourceforge.net/Doc/Release/User-Contributions.html#index-edit_002dcommand_002dline) for dealing with quite big command line buffers.
---
Now on my debian system, I can get the below effect:
```
# apt-get install perl-*<Tab><C-x><C-a><C-w>
;# ⇓
# apt-get install perl-base perl-byacc perl-cross-debian perl-debug perl-depends perl-doc perl-doc-html perl-modules perl-stacktrace perl-tk
``` |
344,872 | It hadn’t properly registered yet with Arthur that the council wanted to knock it down" - what's the meaning of register with someone here? | 2016/08/26 | [
"https://english.stackexchange.com/questions/344872",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/193168/"
] | This would be dependent on whether the speaker was referring to the group/entity of the Club or to the location of Sunnyside Country Club.
For instance if you removed the words 'Sunnyside' and 'Country' and just left the word Club, a speaker would be more likely to choose the term "to".
I was accepted for membership to the club.
One might then wonder as to which 'club' you are referring, so it is necessary for the speaker to use the Proper Name.
Once the proper name is used however, it also has the interchangeable reference to the location of Sunnyside Country Club. If the speaker was referring to the location they would more commonly use 'at' in this sentence.
I was accepted for membership at Sunnyside Country Club. (as in over at their location, where they meet.) |
96,015 | Can you help me to find and count sub-sequences of consecutive, identical integer members of a long list (at least 1000 members)? By sub-sequences I mean runs like `0, 0` or `5, 5, 5`. | 2015/10/02 | [
"https://mathematica.stackexchange.com/questions/96015",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/34540/"
] | If the `List` is named `lst`, then
```
rept = Cases[Split[lst], z_ :> z /; Length[z] > 1]
```
finds all runs of repeated integers, and
```
Length[rept]
```
finds the number of them. Applied to
```
lst = {1, 2, 3, 3, 4, 5, 5, 5, 6, 4}
```
they give
```
(* {{3, 3}, {5, 5, 5}} *)
(* 2 *)
```
If only the number of repeated runs is desired, then
```
Count[Split[lst], z_ /; Length[z] > 1]
```
can be used. For instance,
```
SeedRandom[5];
Table[Count[Split[RandomInteger[{0, 9}, 10^i]], z_ /; Length[z] > 1], {i, 1, 6}]
(* {2, 9, 93, 890, 9063, 90270} *)
``` |
66,802 | And in particular, when you play with 2 players do you deal out all the cards the from the deck? Or is there some undealt part that players draw from during the game? I mean, if you deal them all then you'll just know what's in your opponent's hand?
This is going to sound trivial, but actually it's part of this theory/hypothesis I have for this anime/manga series [The Quintessential Quintuplets](https://en.wikipedia.org/wiki/The_Quintessential_Quintuplets), where I think the game Sevens(/Fan Tan/Domino) is symbolic of something in the series (namely something to do with the number 7). My thought is that the card game Sevens (and thus the number 7) is so important that it even leads to a mistake like this. So if this were a mistake, then it's possible that Sevens is really important. Or something.
* Actually there have been previous discussions of the game Sevens in this series. See: [The importance of "Sevens"](https://www.reddit.com/r/5ToubunNoHanayome/comments/axlujo/the_importance_of_sevens/)
From S02E12 of [The Quintessential Quintuplets](https://en.wikipedia.org/wiki/The_Quintessential_Quintuplets)
[![enter image description here](https://i.stack.imgur.com/ys4dD.jpg)](https://i.stack.imgur.com/ys4dD.jpg)
The 2 kids pictured above, a young Nakano and the young Fuutarou, are playing
* in the English dub version: 'Sevens'. (This is also in the English subtitles for the Japanese version.)
* in the original Japanese version: '[Shichi Narabe (7並べ)](https://en.wikipedia.org/wiki/Domino_(card_game)#Japan)', which is what Wikipedia calls a(/the?) Japanese variation of Sevens. In the upper right part of the Wikipedia page, you can see that it says 3-8 players, so I guess that includes the Japanese Sevens.
You can even see how the cards are laid out that they really are playing (some variation of) Sevens.
Other notes:
1. I've read only a bit of the manga, but I'm pretty sure no other kids were playing with the 2.
2. Additionally, Sevens has been played earlier in the series ([S01E09](https://i.stack.imgur.com/RReaF.jpg) where it's still Shichi Narabe [7並べ], but it's translated as 'Fan Tan' instead of 'Sevens', again by both the English dub and the subtitles for the original Japanese), but there were at least 3 players then. | 2022/05/14 | [
"https://anime.stackexchange.com/questions/66802",
"https://anime.stackexchange.com",
"https://anime.stackexchange.com/users/4484/"
] | **Yes, it is possible to play *Shichi Narabe* with only 2 players.**
First of all, there is no exact requirement for the number of players, though most sites recommend at least 3 or 4 players:
* [English Wikipedia](https://en.wikipedia.org/wiki/Domino_(card_game)): 3-7 (intro body) / 3-8 (infobox)
* [Japanese Wikipedia](https://ja.wikipedia.org/wiki/7%E4%B8%A6%E3%81%B9#%E4%BA%BA%E6%95%B0): **theoretically 1-20+**, preferably 4-10
* [Nico Nico Pedia](https://dic.nicovideo.jp/a/%E4%B8%83%E4%B8%A6%E3%81%B9) (Japanese): usually 3-5
* [Magic Door](https://magicdoor.jp/seven-rows/) (Japanese): preferably 3-4, **2 is not recommended**
* [Trump Stadium](https://playingcards.jp/game_rules/sevens_rules.html) (Japanese): 3-8 (summary) / 4-7 (online in-game setting)
* [Trump & Board Game Rule Book](https://sojudo.net/gamerule/trump/shichinarabe) (Japanese): 3-7
* [Introduction to Trump Games from Small to Large Amount of Players](http://trampgame.blog.jp/archives/5937554.html) (Japanese): 3-8
* [Sites about Killing Time](https://xn--68jza6c6j4c9e9094b.jp/category21/entry427.html) (Japanese): **2 is possible**, usually 3, preferably 4-6
(Emphasis added)
Japanese Wikipedia also mentioned an optional rule for games with **2-3 players** called [combo](https://ja.wikipedia.org/wiki/7%E4%B8%A6%E3%81%B9#%E3%82%B3%E3%83%B3%E3%83%9C), so it acknowledged that there is also a variation for 2 players.
Thus, while it is still possible to play with only 2 players, there are a few reasons why it is not really recommended. Magic Door mentioned in short that it is because both players know each other cards (because all the cards are dealt). A more thorough discussion on [Yahoo! Chiebukuro](https://detail.chiebukuro.yahoo.co.jp/qa/question_detail/q10113941205) (Japanese) explained further that since both players know each other cards, it is [a perfect information game](https://en.wikipedia.org/wiki/Perfect_information) and the winner can already be decided since the beginning, given both players play perfectly. In the end, it becomes a game to play without mistakes instead of a game of strategy. |
19,970,356 | We can extract distinct value set from a list by using following code
```
List<Person> distinctPeople = allPeople
.GroupBy(p => new {p.PersonId, p.FavoriteColor} )
.Select(g => g.First())
.ToList();
```
Assume person has PersonId, FavoriteColor, age, address, etc..... My requirement is I would like to get a separate list which should contain distinct filter data only such as PersonId, FavoriteColor not others. What is the command for that, Assume I can create a small class which contain PersonId, FavoriteColor only | 2013/11/14 | [
"https://Stackoverflow.com/questions/19970356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2288789/"
] | As other devs mentioned email clients do not load external css, so you have to inline it. Inlining css manually is poor decision. There are libraries to inline css. One of them is [django-inlinecss](https://github.com/roverdotcom/django-inlinecss "django-inlinecss"). You can keep you code exactly as it is. All you need to do is to install django-inlinecss and to change "deposit\_email.html". I do not know how it looks, because you have not publish it, so I give you example of simple header like email template I used before with success.
```html
{% load inlinecss %}
{% inlinecss "css/email.css" %}
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<table class="body">
<tr>
<td class="center" align="center" valign="top">
<center>
<table class="row header">
<tr>
<td class="center" align="center">
<center>
<table class="container">
<tr>
<td class="wrapper last">
<table class="twelve columns">
<tr>
<td>
<img src="your_header_link">
</td>
<td class="expander"></td>
</tr>
</table>
</td>
</tr>
</table>
</center>
</td>
</tr>
</table>
<table class="container">
<tr>
<td>
<table class="row">
<tr>
<td class="wrapper last">
<table class="twelve columns">
<tr>
<td>
{% block content %} Email {% endblock %}
<td class="expander"></td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</center>
</td>
</tr>
</table>
</body>
</html>
{% endinlinecss %}
```
Not much going on here. First line loads inlinecss tag.
```
{% load inlinecss %}
```
Second line starts html, which will be css inlined. It also load email.css which can be any static file in your django project.
```
{% inlinecss "css/email.css" %}
```
After that table based template which has header and body with django block 'content'.
Final line is
```
{% endinlinecss %}
```
Which ends inlinecss. As you can see I inline my entire template. I recommend to have one or more parent email templates, which contain template structure and than to use template inheritance for particular emails. In that way you need to specify template and inline your css once.
Last but not least. In order for table template to play nicely you need email.css styles. CSS is a bit big, but simple in nature. Add your own styles on top of that.
```css
#outlook a {
padding: 0;
}
body {
width: 100% !important;
min-width: 100%;
-webkit-text-size-adjust: 100%;
-ms-text-size-adjust: 100%;
margin: 0;
padding: 0;
}
.ExternalClass {
width: 100%;
}
.ExternalClass,
.ExternalClass p,
.ExternalClass span,
.ExternalClass font,
.ExternalClass td,
.ExternalClass div {
line-height: 100%;
}
#backgroundTable {
margin: 0;
padding: 0;
width: 100% !important;
line-height: 100% !important;
}
img {
outline: none;
text-decoration: none;
-ms-interpolation-mode: bicubic;
width: auto;
max-width: 100%;
float: left;
clear: both;
display: block;
}
center {
width: 100%;
min-width: 580px;
}
a img {
border: none;
}
p {
margin: 0 0 0 10px;
}
table {
border-spacing: 0;
border-collapse: collapse;
}
td {
word-break: normal;
-webkit-hyphens: auto;
-moz-hyphens: auto;
hyphens: auto;
border-collapse: collapse !important;
}
table, tr, td {
padding: 0;
vertical-align: top;
text-align: left;
}
hr {
color: #d9d9d9;
background-color: #d9d9d9;
height: 1px;
border: none;
}
/* Responsive Grid */
table.body {
height: 100%;
width: 100%;
}
table.container {
width: 580px;
margin: 0 auto;
text-align: inherit;
}
table.row {
padding: 0px;
width: 100%;
position: relative;
}
table.container table.row {
display: block;
}
td.wrapper {
padding: 10px 20px 0px 0px;
position: relative;
}
table.columns,
table.column {
margin: 0 auto;
}
table.columns td,
table.column td {
padding: 0px 0px 10px;
}
table.columns td.sub-columns,
table.column td.sub-columns,
table.columns td.sub-column,
table.column td.sub-column {
padding-right: 10px;
}
td.sub-column, td.sub-columns {
min-width: 0px;
}
table.row td.last,
table.container td.last {
padding-right: 0px;
}
table.one {
width: 30px;
}
table.two {
width: 80px;
}
table.three {
width: 130px;
}
table.four {
width: 180px;
}
table.five {
width: 230px;
}
table.six {
width: 280px;
}
table.seven {
width: 330px;
}
table.eight {
width: 380px;
}
table.nine {
width: 430px;
}
table.ten {
width: 480px;
}
table.eleven {
width: 530px;
}
table.twelve {
width: 580px;
}
table.one center {
min-width: 30px;
}
table.two center {
min-width: 80px;
}
table.three center {
min-width: 130px;
}
table.four center {
min-width: 180px;
}
table.five center {
min-width: 230px;
}
table.six center {
min-width: 280px;
}
table.seven center {
min-width: 330px;
}
table.eight center {
min-width: 380px;
}
table.nine center {
min-width: 430px;
}
table.ten center {
min-width: 480px;
}
table.eleven center {
min-width: 530px;
}
table.twelve center {
min-width: 580px;
}
table.one .panel center {
min-width: 10px;
}
table.two .panel center {
min-width: 60px;
}
table.three .panel center {
min-width: 110px;
}
table.four .panel center {
min-width: 160px;
}
table.five .panel center {
min-width: 210px;
}
table.six .panel center {
min-width: 260px;
}
table.seven .panel center {
min-width: 310px;
}
table.eight .panel center {
min-width: 360px;
}
table.nine .panel center {
min-width: 410px;
}
table.ten .panel center {
min-width: 460px;
}
table.eleven .panel center {
min-width: 510px;
}
table.twelve .panel center {
min-width: 560px;
}
.body .columns td.one,
.body .column td.one {
width: 8.333333%;
}
.body .columns td.two,
.body .column td.two {
width: 16.666666%;
}
.body .columns td.three,
.body .column td.three {
width: 25%;
}
.body .columns td.four,
.body .column td.four {
width: 33.333333%;
}
.body .columns td.five,
.body .column td.five {
width: 41.666666%;
}
.body .columns td.six,
.body .column td.six {
width: 50%;
}
.body .columns td.seven,
.body .column td.seven {
width: 58.333333%;
}
.body .columns td.eight,
.body .column td.eight {
width: 66.666666%;
}
.body .columns td.nine,
.body .column td.nine {
width: 75%;
}
.body .columns td.ten,
.body .column td.ten {
width: 83.333333%;
}
.body .columns td.eleven,
.body .column td.eleven {
width: 91.666666%;
}
.body .columns td.twelve,
.body .column td.twelve {
width: 100%;
}
td.offset-by-one {
padding-left: 50px;
}
td.offset-by-two {
padding-left: 100px;
}
td.offset-by-three {
padding-left: 150px;
}
td.offset-by-four {
padding-left: 200px;
}
td.offset-by-five {
padding-left: 250px;
}
td.offset-by-six {
padding-left: 300px;
}
td.offset-by-seven {
padding-left: 350px;
}
td.offset-by-eight {
padding-left: 400px;
}
td.offset-by-nine {
padding-left: 450px;
}
td.offset-by-ten {
padding-left: 500px;
}
td.offset-by-eleven {
padding-left: 550px;
}
td.expander {
visibility: hidden;
width: 0px;
padding: 0 !important;
}
table.columns .text-pad,
table.column .text-pad {
padding-left: 10px;
padding-right: 10px;
}
table.columns .left-text-pad,
table.columns .text-pad-left,
table.column .left-text-pad,
table.column .text-pad-left {
padding-left: 10px;
}
table.columns .right-text-pad,
table.columns .text-pad-right,
table.column .right-text-pad,
table.column .text-pad-right {
padding-right: 10px;
}
/* Block Grid */
.block-grid {
width: 100%;
max-width: 580px;
}
.block-grid td {
display: inline-block;
padding: 10px;
}
.two-up td {
width: 270px;
}
.three-up td {
width: 173px;
}
.four-up td {
width: 125px;
}
.five-up td {
width: 96px;
}
.six-up td {
width: 76px;
}
.seven-up td {
width: 62px;
}
.eight-up td {
width: 52px;
}
/* Alignment & Visibility Classes */
table.center, td.center {
text-align: center;
}
h1.center,
h2.center,
h3.center,
h4.center,
h5.center,
h6.center {
text-align: center;
}
span.center {
display: block;
width: 100%;
text-align: center;
}
img.center {
margin: 0 auto;
float: none;
}
.show-for-small,
.hide-for-desktop {
display: none;
}
/* Typography */
body, table.body, h1, h2, h3, h4, h5, h6, p, td {
color: #222222;
font-family: "Helvetica", "Arial", sans-serif;
font-weight: normal;
padding: 0;
margin: 0;
text-align: left;
line-height: 1.3;
}
h1, h2, h3, h4, h5, h6 {
word-break: normal;
}
h1 {
font-size: 40px;
}
h2 {
font-size: 36px;
}
h3 {
font-size: 32px;
}
h4 {
font-size: 28px;
}
h5 {
font-size: 24px;
}
h6 {
font-size: 20px;
}
body, table.body, p, td {
font-size: 14px;
line-height: 19px;
}
p.lead, p.lede, p.leed {
font-size: 18px;
line-height: 21px;
}
p {
margin-bottom: 10px;
}
small {
font-size: 10px;
}
a {
color: #2ba6cb;
text-decoration: none;
}
a:hover {
color: #2795b6 !important;
}
a:active {
color: #2795b6 !important;
}
a:visited {
color: #2ba6cb !important;
}
h1 a,
h2 a,
h3 a,
h4 a,
h5 a,
h6 a {
color: #2ba6cb;
}
h1 a:active,
h2 a:active,
h3 a:active,
h4 a:active,
h5 a:active,
h6 a:active {
color: #2ba6cb !important;
}
h1 a:visited,
h2 a:visited,
h3 a:visited,
h4 a:visited,
h5 a:visited,
h6 a:visited {
color: #2ba6cb !important;
}
/* Panels */
.panel {
background: #f2f2f2;
border: 1px solid #d9d9d9;
padding: 10px !important;
}
.sub-grid table {
width: 100%;
}
.sub-grid td.sub-columns {
padding-bottom: 0;
}
/* Buttons */
table.button,
table.tiny-button,
table.small-button,
table.medium-button,
table.large-button {
width: 100%;
overflow: hidden;
}
table.button td,
table.tiny-button td,
table.small-button td,
table.medium-button td,
table.large-button td {
display: block;
width: auto !important;
text-align: center;
background: #2ba6cb;
border: 1px solid #2284a1;
color: #ffffff;
padding: 8px 0;
}
table.tiny-button td {
padding: 5px 0 4px;
}
table.small-button td {
padding: 8px 0 7px;
}
table.medium-button td {
padding: 12px 0 10px;
}
table.large-button td {
padding: 21px 0 18px;
}
table.button td a,
table.tiny-button td a,
table.small-button td a,
table.medium-button td a,
table.large-button td a {
font-weight: bold;
text-decoration: none;
font-family: Helvetica, Arial, sans-serif;
color: #ffffff;
font-size: 16px;
}
table.tiny-button td a {
font-size: 12px;
font-weight: normal;
}
table.small-button td a {
font-size: 16px;
}
table.medium-button td a {
font-size: 20px;
}
table.large-button td a {
font-size: 24px;
}
table.button:hover td,
table.button:visited td,
table.button:active td {
background: #2795b6 !important;
}
table.button:hover td a,
table.button:visited td a,
table.button:active td a {
color: #fff !important;
}
table.button:hover td,
table.tiny-button:hover td,
table.small-button:hover td,
table.medium-button:hover td,
table.large-button:hover td {
background: #2795b6 !important;
}
table.button:hover td a,
table.button:active td a,
table.button td a:visited,
table.tiny-button:hover td a,
table.tiny-button:active td a,
table.tiny-button td a:visited,
table.small-button:hover td a,
table.small-button:active td a,
table.small-button td a:visited,
table.medium-button:hover td a,
table.medium-button:active td a,
table.medium-button td a:visited,
table.large-button:hover td a,
table.large-button:active td a,
table.large-button td a:visited {
color: #ffffff !important;
}
table.secondary td {
background: #e9e9e9;
border-color: #d0d0d0;
color: #555;
}
table.secondary td a {
color: #555;
}
table.secondary:hover td {
background: #d0d0d0 !important;
color: #555;
}
table.secondary:hover td a,
table.secondary td a:visited,
table.secondary:active td a {
color: #555 !important;
}
table.success td {
background: #5da423;
border-color: #457a1a;
}
table.success:hover td {
background: #457a1a !important;
}
table.alert td {
background: #c60f13;
border-color: #970b0e;
}
table.alert:hover td {
background: #970b0e !important;
}
table.radius td {
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
}
table.round td {
-webkit-border-radius: 500px;
-moz-border-radius: 500px;
border-radius: 500px;
}
/* Outlook First */
body.outlook p {
display: inline !important;
}
/* Media Queries */
@media only screen and (max-width: 600px) {
table[class="body"] img {
width: auto !important;
height: auto !important;
}
table[class="body"] center {
min-width: 0 !important;
}
table[class="body"] .container {
width: 95% !important;
}
table[class="body"] .row {
width: 100% !important;
display: block !important;
}
table[class="body"] .wrapper {
display: block !important;
padding-right: 0 !important;
}
table[class="body"] .columns,
table[class="body"] .column {
table-layout: fixed !important;
float: none !important;
width: 100% !important;
padding-right: 0px !important;
padding-left: 0px !important;
display: block !important;
}
table[class="body"] .wrapper.first .columns,
table[class="body"] .wrapper.first .column {
display: table !important;
}
table[class="body"] table.columns td,
table[class="body"] table.column td {
width: 100% !important;
}
table[class="body"] .columns td.one,
table[class="body"] .column td.one {
width: 8.333333% !important;
}
table[class="body"] .columns td.two,
table[class="body"] .column td.two {
width: 16.666666% !important;
}
table[class="body"] .columns td.three,
table[class="body"] .column td.three {
width: 25% !important;
}
table[class="body"] .columns td.four,
table[class="body"] .column td.four {
width: 33.333333% !important;
}
table[class="body"] .columns td.five,
table[class="body"] .column td.five {
width: 41.666666% !important;
}
table[class="body"] .columns td.six,
table[class="body"] .column td.six {
width: 50% !important;
}
table[class="body"] .columns td.seven,
table[class="body"] .column td.seven {
width: 58.333333% !important;
}
table[class="body"] .columns td.eight,
table[class="body"] .column td.eight {
width: 66.666666% !important;
}
table[class="body"] .columns td.nine,
table[class="body"] .column td.nine {
width: 75% !important;
}
table[class="body"] .columns td.ten,
table[class="body"] .column td.ten {
width: 83.333333% !important;
}
table[class="body"] .columns td.eleven,
table[class="body"] .column td.eleven {
width: 91.666666% !important;
}
table[class="body"] .columns td.twelve,
table[class="body"] .column td.twelve {
width: 100% !important;
}
table[class="body"] td.offset-by-one,
table[class="body"] td.offset-by-two,
table[class="body"] td.offset-by-three,
table[class="body"] td.offset-by-four,
table[class="body"] td.offset-by-five,
table[class="body"] td.offset-by-six,
table[class="body"] td.offset-by-seven,
table[class="body"] td.offset-by-eight,
table[class="body"] td.offset-by-nine,
table[class="body"] td.offset-by-ten,
table[class="body"] td.offset-by-eleven {
padding-left: 0 !important;
}
table[class="body"] table.columns td.expander {
width: 1px !important;
}
table[class="body"] .right-text-pad,
table[class="body"] .text-pad-right {
padding-left: 10px !important;
}
table[class="body"] .left-text-pad,
table[class="body"] .text-pad-left {
padding-right: 10px !important;
}
table[class="body"] .hide-for-small,
table[class="body"] .show-for-desktop {
display: none !important;
}
table[class="body"] .show-for-small,
table[class="body"] .hide-for-desktop {
display: inherit !important;
}
}
```
PS Resulting email html is to messy to publish, but basically it will put all your css properties as inline properties on html tags. |
3,377,238 | There is the circle group which is specifically a set of points comprising the boundary of the unit disc in the complex plane which turns out to be a compact set.
However, is the set of points forming a circle of any arbitrary radius also compact in the complex plane? | 2019/10/01 | [
"https://math.stackexchange.com/questions/3377238",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/709298/"
] | Sure. Any two circles in the complex plane are homeomorphic. So, if one of them is compact, then all of them are. |
18,746,129 | I am trying to make a `left outer join` query that also has a `custom comparator`.
I have the following lists:
```
List<ColumnInformation> list1;
List<ColumnInformation> list2;
```
These hold information about an SQL column (datatype, name, table, etc). I have overrided `Equals` for the class, and made a `operator ==` and `operator !=`.
I understand how to [make a left outer join](https://stackoverflow.com/a/5491381/1043380):
```
var leftOuterJoin = from l1 in list1
join l2 in list2 on l1.objectID equals l2.objectID into temp
from l2 in temp.DefaultIfEmpty(new { l1.ID, Name = default(string) })
select new
{
l1.ID,
ColumnName1 = l1.Name,
ColumnName2 = l2.Name,
};
```
And I understand how to make and use a custom `IEqualityComparer`:
```
public class ColumnComparer : IEqualityComparer<ColumnInformation>
{
public bool Equals(ColumnInformation x, ColumnInformation y)
{
return x == y; //this uses my defined == operator
}
public int GetHashCode(ColumnInformation obj)
{
return 1; //forcing the join to use Equals, just trust me on this
}
}
ColumnComparer cc = new ColumnComparer();
var joinedList = list1.Join(list2,
x => x,
y => y,
(x, y) => new {x, y},
cc);
```
My question is: **How can I do both a left outer join and use my comparator at the same time**?
As far as I know, the query syntax does not have a keyword for a comparator, and the extension method does not have anything for the `into` keyword.
I do not care if the result is in query syntax or extension methods. | 2013/09/11 | [
"https://Stackoverflow.com/questions/18746129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1043380/"
] | The way you do that is with a `GroupJoin` and `SelectMany` (to flatten the results):
```
ColumnComparer cc = new ColumnComparer();
var joinedList = list1
.GroupJoin(list2,
x => x,
y => y,
(x, g) => new {x, g},
cc)
.SelectMany(
z => z.g.DefaultIfEmpty(),
(z, b) => new { x = z.x, y = b }
);
``` |
59,397 | As established [in a previous question](https://chemistry.stackexchange.com/q/31276), coordination compounds typically have a *field split* between the $\mathrm{t\_{2g}}$ and the $\mathrm{e\_g}$ d-orbitals.[1] This energy difference can be explained by the crystal field theory which assumes negative point-charges approaching a complex and destabilising orbitals pointing towards said point charges.
Commonly, the energy difference between the lower and higher orbitals is referred to by the relative value of $\Delta$ or the equally relative value of $10~\mathrm{Dq}$.
The latter is of interest to me. It is clearly used as a (relative) unit, because *ligand field stabilisation enthalpies* (LFSE’s) are typically given in values of $\mathrm{Dq}$ — e.g. $\ce{[Cr(H2O)6]^3+}$ (hexaaquachromium(III)) has an LFSE of $-12~\mathrm{Dq}$. But what does $\mathrm{Dq}$ mean and what does it derive from?
---
**Note:**
[1]: This is explicitly considering the octahedral case. Tetrahedral compounds split the d-orbitals into $\mathrm{t\_2}$ and $\mathrm{e}$. This distinction is, however, not relevant to the question. | 2016/09/20 | [
"https://chemistry.stackexchange.com/questions/59397",
"https://chemistry.stackexchange.com",
"https://chemistry.stackexchange.com/users/7475/"
] | I currently happen to have the book by Figgis that Max mentioned. Chapter 2 is devoted to a mathematical formulation of crystal field theory, which I did not bother reading in detail because I do not understand any of it. *(The corollary is: If you have a better answer, please post it!)* It seems that both $D$ and $q$ are collections of constants defined in such a way so as to make the octahedral splitting equal to $10Dq$. In particular it is defined that
$$D = \frac{35ze}{4a^5}$$
and
$$q = \frac{2e\langle r^4\rangle}{105}$$
where $ze$ is the charge on the ligands (in crystal field theory, the ligands are treated as point charges), $a$ is the distance of the ligands from the central ion, and $\langle r^4 \rangle$ is the mean fourth power radius of the d electrons in the central ion.
These quantities can be derived from first principles (that is precisely what crystal field theory is about) and lead to the expression of the crystal field electrostatic potential in Cartesian coordinates:
$$\mathbf{V}\_{\mathrm{oct}} = D\left(x^4 + y^4 + z^4 - \frac{3r^4}{5}\right)$$
I followed some references given in the book which ultimately ended up in one of the papers in porphyrin's comment: [*Phys. Rev.* **1932,** *31,* 194](http://journals.aps.org/pr/pdf/10.1103/PhysRev.41.194). There's more discussion there.
In particular, as far as I can tell, it seems that $D$ is called that simply because it is a quartic term in the potential (the first three terms having coefficients of $A,B,C$), and $q$ is called that because it is related to a series of constants $p\_J$ which depend on the total spin quantum number $J$ (consistent with $p$ and $q$ being commonly used letters for mathematical constants).
---
Just to clear up any potential confusion with porphyrin's comment which at first glance seems to be missing one $r^4$ term in the electrostatic potential, the above article writes:
>
> It is sufficient to write the potential $V = D(x^4+y^4+z^4)$ since this can be made to satisfy Laplace's equation by adding a function of $r^2$ (viz. $-3Dr^4$). [The addition of this term] corresponds to superposing a spherically symmetrical field, and merely shifts all levels equally.
>
>
>
There's still a factor of $1/5$ missing compared to the expression above, but I'm not particularly inclined to figure out how it arises, and I don't think it is of much importance anyway since the only difference is effectively to shift the zero of energy. |
26,632,644 | I am newbie to java db coding...
This is my java code
```
Connection conn = null;
Statement stmt = null;
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection("jdbc:mysql://localhost/EMP",USER,PASS);
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
```
This is the exception I am getting :
```
ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/tiles].[default]] (http-localhost-127.0.0.1-8080-1) Servlet.service() for servlet default threw exception: java.net.ConnectException: Connection refused: connect
```
I am mySQL server also running and contains simple table named EMP. I am not interpreting the get connection URL comppletely. Can anyone explain it briefly?
Thanks. | 2014/10/29 | [
"https://Stackoverflow.com/questions/26632644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1079065/"
] | You are using the wrong driver for the database. Every database (MySQL, PostgreSQL, SQL Server, Oracle etc.) has a different driver which is what connects between JDBC and the particular database's communication protocol.
You need the Microsoft SQL Server driver. You can download and install it from here if you don't already have it: [Microsoft down page for JDBC 4.0 driver](http://www.microsoft.com/en-us/download/details.aspx?id=11774).
And here are the [instructions](http://technet.microsoft.com/en-us/library/ms378526%28v=sql.110%29.aspx) on how to add the jar to your classpath, and what URL to use. Note that in JDBC 4.0 and above, the `forName` is not necessary anymore. |
3,367,553 | Is $S$ linearly dependent on $\textsf V = \mathcal{F}(\Bbb R,\Bbb R)$ and $S = \{t, e^t ,\sin(t)\}$.
How to prove that a set of functions are linearly dependent? | 2019/09/24 | [
"https://math.stackexchange.com/questions/3367553",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/708009/"
] | Here is a another way to skin the cat:
Suppose $\alpha\_1 t + \alpha\_2 e^t + \alpha\_3 \sin t = 0$ for all $t$.
If we differentiate twice and set $t = 0$, we get $\alpha\_2 e^{\pi \over 2} = 0$ and so $\alpha\_2 = 0$.
If we differentiate twice and set $t = -{\pi \over 2}$, we get $\alpha\_3 = 0$.
Finally, set $t=1$ to get $\alpha\_1 = 0$.
Hence $S$ is linearly independent. |
16,917,821 | I'm trying to implement simple ScopedExit class. Here's the code:
```
#include <iostream>
#include <functional>
template<class R, class... Args>
class ScopedExit
{
public:
ScopedExit(std::function<R(Args...)> exitFunction)
{
exitFunc_ = exitFunction;
}
~ScopedExit()
{
exitFunc_();
}
private:
std::function<R(Args...)> exitFunc_;
};
template<>
class ScopedExit<void>
{
public:
ScopedExit(std::function<void ()> exitFunction)
{
exitFunc_ = exitFunction;
}
~ScopedExit()
{
exitFunc_();
}
private:
std::function<void ()> exitFunc_;
};
void foo()
{
std::cout << "foo() called\n";
}
class Bar
{
public:
void BarExitFunc(int x, int y)
{
std::cout << "BarExitFunc called with x =" << x << "y = " << y << "\n";
}
};
int main()
{
Bar b;
std::cout << "Register scoped exit func\n";
{
ScopedExit<void, int, int> exitGuardInner(std::bind(&Bar::BarExitFunc, &b, 18, 11));
}
ScopedExit exitGuardOutter(foo);
std::cout << "About to exit from the scope\n";
return 0;
}
```
So, there are a couple of questions:
1. How to pass exit's function arguments to it? For example, I bind BarExitFunc with two integer arguments: 18 and 11. So how can I pass it to the exitFunc\_ in the destructor? I think I need something like invoke function with std::forward<>.
2. gcc 4.7.2 (from ideone.com) complains about exitGuardOutter. It says:
>
> prog.cpp:60:16: error: missing template arguments before ‘exitGuardOutter’
>
>
> prog.cpp:60:16: error: expected ‘;’ before ‘exitGuardOutter’
>
>
>
Thanks in advance. | 2013/06/04 | [
"https://Stackoverflow.com/questions/16917821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644350/"
] | >
> How to pass exit's function arguments to it? For example, I bind BarExitFunc with two integer arguments: 18 and 11. So how can I pass it to the exitFunc\_ in the destructor?
>
>
>
I can see no reason whatsoever to pass arguments to `exitFunc_` at call time in the destructor. Whatever you do, you'll have to provide those arguments upfront in the `ScopedExit` constructor anyway.
The most straightforward way is simply to use a `function<R()>` and `bind` any required arguments at the definition site like you're already doing:
```
ScopedExit<R> guard(std::bind(someFunction, someArg, otherArg));
```
This allows you to get rid of the variadic template arguments altogether and simplifies your template *a lot*.
---
Now, if what is bothering you is that you have to type `std::bind` and you would rather use such a syntax:
```
ScopedExit<R> guard(someFunction, someArg, otherArg);
```
Really, I don't see the point since it makes the template more complicated, but why not... Just bind/forward the arguments in the constructor itself and still store a `function<R()>`:
```
template<typename... Args>
ScopedExit(std::function<R(Args...)> exitFunction, Args&&... args)
{
exitFunc_ = std::bind(exitFunction, std::forward<Args>(args)...);
}
```
Now you systematically `bind` the function even if there are no arguments to bind, so you may want to specialize your class to avoid this useless `bind` when there are no arguments. This is left as an exercise.
---
>
> gcc 4.7.2 (from ideone.com) complains about exitGuardOutter
>
>
>
This is because `foo` isn't a `std::function` and the compiler can't deduce the correct template arguments. As already mentioned by @ForEveR you could just define your guard variable as `ScopedExit<void> guard(foo);`.
Or, **wrapping it all up** and keeping in mind what I first said (`bind` is best left out of your template and used at the definition site of your guard) you could just get rid of `std::function` in the constructor and generalize for any functor (which, BTW, is how the Standard library does whenever it needs a functor/callback). For storage you can just use `std::function<void()>` since it accepts non-void return types too:
```
class ScopedExit
{
public:
template<typename Functor>
ScopedExit(Functor exitFunction)
{
exitFunc_ = exitFunction;
}
~ScopedExit()
{
exitFunc_();
}
private:
std::function<void()> exitFunc_;
};
int foo() { return 0; }
struct Bar {
void bye(int, int) {}
};
struct Baz {
void operator ()() {}
};
int main() {
const std::string what = "lambda!";
ScopedExit guard1([&]() { std::cout << "yay a " << what << std::endl; });
ScopedExit guard2(foo); // note how std::function<void()> accepts non-void return types
Bar b;
ScopedExit guard3(std::bind(&Bar::bye, &b, 1, 2));
ScopedExit guard4(Baz());
}
```
Note how your original variadic template class has now become a flexible non-template class with just a templated constructor whose template argument is deduced automatically, and which accepts almost[see note below] any kind of functor you can think about.
---
**Note:** I said *almost* any functor because this doesn't work with default arguments:
```
void foobar(int = 0) {}
ScopedExit guard5(foobar); // error: too few arguments to function
```
Even if you stored a `Functor` directly instead of a `std::function<void()>` you wouldn't be able to make use of the default arguments anyway (the signature of `foobar` is still `void(int)` even with a default argument) so one always has to handle this corner-case at the definition site with something like:
```
void foobar(int = 0) {}
ScopedExit guard5([]() { foobar(); });
``` |
656,271 | I am using Bluez bluetooth Manager, after I send the files from my Android device to the Laptop which contains Linux Mate with the standard File System. I cannot seem to find the files which a received in this manner. The Bluez documentation does not specify where do these files go. | 2015/08/04 | [
"https://askubuntu.com/questions/656271",
"https://askubuntu.com",
"https://askubuntu.com/users/431035/"
] | Grub allows you to password protect its config and console, as well as individual operating system entries. Please note that this *will not* stop dedicated individuals, especially the ones that know what they are doing. But I assume you know that. Lets get started.
generate a password hash..
--------------------------
You could store your grub password in plain text but that is entirely insecure and anyone that had access to your account could quickly figure it out. To prevent this we hash the password using the `grub-mkpasswd-pbkdf2` command, like so:
```
user@host~ % grub-mkpasswd-pbkdf2
Enter password:
Reenter password:
PBKDF2 hash of your password is grub.pbkdf2.sha512.10000.63553D205CF6E...
```
While you type your password no characters will show in the terminal, this is to prevent people looking over your shoulders, etc. Now, copy the entirety of your hash with `Ctrl`+`Shift`+`C`.
protecting the config, console..
--------------------------------
Run:
```
sudo nano /etc/grub.d/40_custom
```
This will create a new configuration file called `40_custom` in grub's configuration directory. Now add the lines:
```
set superusers="username"
password_pbkdf2 username hash
```
Where `username` is a username of your choice and `hash` is the hash we generated in the last command. Press `Ctrl`+`O` and then `Ctrl`+`X` to save and quit. Run:
```
sudo update-grub
```
To finalize the changes. Now, when anyone attempts to edit the grub configuration or access a grub console it will prompt them for a username and password.
password protecting operating system entries..
----------------------------------------------
Currently the only method to achieve this I can find is to edit the `/boot/grub/grub.cfg` manually. This is only temporary however as any new kernel update will rewrite this file and your passwords will be gone (note that this doesn't effect the console/editing password we set above). All other methods I have found so far are extremely out of date and I can no longer get them to work.
I've asked the grub mailing list if there is a newer method and will edit this answer as soon as I find out. |
2,793,312 | When we use the cylindrical coordinate system $(r, \theta, z)$ where $r$ is the distance from the point in the $xy$-plane, $\theta$ is the angle with the $x$ axis and $z$ is the heigth. As can been seen in the picture
[![enter image description here](https://i.stack.imgur.com/lKIQb.png)](https://i.stack.imgur.com/lKIQb.png)
I hav a vector field described by $(0,U\_{\theta}(r),U\_z)$ but how can the angle differ when $r$ is always zero?
When $r$ is zero, then there is no difference between different angles. Or am i wrong?
Some help would be great. | 2018/05/23 | [
"https://math.stackexchange.com/questions/2793312",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/221950/"
] | **Hint:**
You discover the rules by working backwards.
First consider polynomials, say of the third degree, like $ax^3+bx^2+cx+d$. The first derivative is a second degree polynomial, so that the LHS of a first order equation would yield
$$\alpha y+\beta y'=\alpha ax^3+(\alpha b+3\beta a)x^2+(\alpha c+2\beta b)x+(\alpha d+\beta c),$$ another cubic polynomial. Similarly,
$$\alpha y+\beta y'+\gamma y''=\alpha ax^3+(\alpha b+3\beta a)x^2+(\alpha c+2\beta b+6\gamma c)x+(\alpha d+\beta c+2\gamma b)$$ also third degree.
Now it is clear that for a linear equation of any degree, if the RHS is a polynomial of degree $d$, there will be another polynomial of degree $d$ which is a solution.
---
For an exponential function, $e^{ax}$,
$$\alpha y+\beta y'+\gamma y''=(\alpha +\beta a+\gamma a^2)e^{ax}$$ so that an exponential RHS is obtained from an exponential solution.
---
You can play the same game with RHS of the form $e^{ax}\sin bx$ and $e^{ax}\cos bx$.
If you are familiar with complex numbers, you can even take a shortcut by considering $e^{(a+ib)x}$, which combines the two functions in one. |
477,931 | How can I create a table like this in Latex?
[![enter image description here](https://i.stack.imgur.com/4MYki.png)](https://i.stack.imgur.com/4MYki.png)
I have tried but it didn't work. I need also that it is enumerated so that it appears in the List of Tables. It doesn't matter if it is not coloured, as long as the first two rows are bold.
```
\begin{center}
\begin{tabular}{ |c|c|c|c|c| }
\hline
\multicolumn{5}{|c|}{Number of cells per type} \\
\hline
a& b& c& d& e\\
\hline
44 & 39 & 7 & 32 &22 \\
\hline
\end{tabular}
\end{center}
``` | 2019/03/05 | [
"https://tex.stackexchange.com/questions/477931",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/182855/"
] | I suggest you to use `booktabs` for professional tables.
```
\documentclass[11pt,openright]{book}
\usepackage{array}
\newcolumntype{C}{>{\centering\arraybackslash}X}
\renewcommand{\arraystretch}{1.2}
\usepackage{booktabs}
\usepackage{tabularx}
\usepackage{caption}
\begin{document}
\listoftables
\chapter{My chapter}
\begin{table}[htb]\centering
\caption{Your table\label{tab:yourtab}}
\begin{tabularx}{.5\linewidth}{ |C|C|C|C|C| }
\hline
\multicolumn{5}{|c|}{\bfseries Number of cells per type} \\
\hline
\bfseries a& \bfseries b& \bfseries c& \bfseries d& \bfseries e\\
\hline
44 & 39 & 7 & 32 &22 \\
\hline
\end{tabularx}
\end{table}
\begin{table}[htb]\centering
\caption{My suggestion\label{tab:mytab}}
\begin{tabularx}{.5\linewidth}{*5C}
\toprule
\multicolumn{5}{c}{\bfseries Number of cells per type} \\
\midrule
\bfseries a& \bfseries b& \bfseries c& \bfseries d& \bfseries e\\
\midrule
44 & 39 & 7 & 32 &22 \\
\bottomrule
\end{tabularx}
\end{table}
\end{document}
```
[![enter image description here](https://i.stack.imgur.com/7IC07.png)](https://i.stack.imgur.com/7IC07.png)
[![enter image description here](https://i.stack.imgur.com/eg5I0.png)](https://i.stack.imgur.com/eg5I0.png) |
923,813 | Show that it is not true in general that
(i) for any sets A,B, one has P(A union B) is a subset of P(A) union P(B)
Show that it is true in general that
(ii) for any sets A , B , one has P(A) union P(B) is a subset of P(A union B).
For part (i) and part (ii), can you help me verify my proof? i didnt use elements for my answers as the question is to show in general so i did it this way.
(i) For any sets A , B ,
Consider the case A is not a subset of B.
Then , A union B will have more elements than A and more elements than B. Hence the power set of A union B will contain a set that has more elements than A or B.
Hence, P(A union B) is not a subset of P(A) union P(B).
(ii) I got 4 cases to consider.
Consider both the case A is not a subset of B and A is not equal to B.
Then, both cases will have the same argument that A union B will have more elements than A and more elements than B. Hence, the power set of (A union B) will contain a set that has more elements than A or B. Hence, P(A) union P(B) is a subset of P(A union B).
Consider the case A is a subset of B.
If A is a subset of B, thus A union B = B. Therefore, all the elements in A union B will be inside B. Thus the power set of (A union B) will be the same as the power set of B.
Also since A is a subset of B, elements in A will be in B as well. Therefore, Power set of A is a subset of Power set of B. Since Power set of A is a subset of Power set of B, power set of (A union B) equals to power set of B, thus, P(A U B) = P(B) = P(A) U P(B),
hence P(A) U P(B) is a subset of P(A U B).
Consider the case B is a subset of A.
If B is a subset of A, thus A U B = A. Therefore all the elements in A U B will be in A. Thus the power set of ( A U B ) will be the same as P ( A ).
Also , since B is a subset of A, elements in B will be in A as well. Therefore, P( B ) is a subset of P ( A ). Since P(B) is a subset of P(A), P(A) U P(B) = P(A).
Thus, P(A U B) = P(A) = P(A) U P(B),
hence P(A) U P(B) is a subset of P(A U B).
*Do i need to consider the case of null sets?* | 2014/09/08 | [
"https://math.stackexchange.com/questions/923813",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/174559/"
] | Easier way to prove part two: set inclusion. The proof is mostly definition chasing.
Let $S \in \mathbf{P}[A]\cup \mathbf{P}[B]$. Then either $S \subseteq A$ or $S \subseteq B$. In either case, $S \in \mathbf{P}[A \cup B]$ by noting that $$S \subseteq A \implies S \subseteq A \cup B \implies S \in \mathbf{P}[A \cup B]$$
And symmetrically for $S \subseteq B$. |
26,017,705 | I have an azure website and database. I'm running an ASP.NET MVC 4 / EF 5 app localy and trying to put some data to the azure database before to deploy the app. But I have a TargetInvocationException : {"The ASP.NET Simple Membership database could not be initialized. For more information, please see <http://go.microsoft.com/fwlink/?LinkId=256588>"}
Keyword not supported : server
This is the connection string that I get from my azure dashboard :
```
<add name="myconstring" connectionString=Server=tcp:myserver.database.windows.net,1433;Database=mydatabase;User ID=cdptest@myserver;Password=******;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.EntityClient" />
```
I tried this I got "Keyword not supported : data source"
```
<add name="myconstring" connectionString="Data Source=myserver.database.windows.net;Initilal Catalog=mydatabase;User ID=cdptest@myserver;Password=*****;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.EntityClient"/>
``` | 2014/09/24 | [
"https://Stackoverflow.com/questions/26017705",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2660758/"
] | The following works for me:
```
<add name="coupdpoAPEkowswAEntities" connectionString="Server=tcp:myserver.database.windows.net,1433;Database=mydatabase;User ID=cdptest@myserver;Password=*****;Trusted_Connection=False;Encrypt=True;Connection Timeout=30;" providerName="System.Data.EntityClient"/>
```
Use Server instead of Data Source, and specify the protocol and the port, and use Database instead of Initial Catalog |
37,097,643 | The server hosting the api is returning http for absolute urls even though the page was loaded using https, does this have something to do with django rest framework? because there doesn't seem any obvious way to remedy this.
It's the url field in the Meta class that is relevant
```
class NewsSerializer(serializers.HyperlinkedModelSerializer):
user = UserSerializer(read_only=True)
source = serializers.CharField(source='get_source_url', read_only=True)
comments_count = serializers.IntegerField(read_only=True)
date_added = serializers.CharField(source='humanize_date_added',
read_only=True)
is_owner = serializers.SerializerMethodField()
user_voted = serializers.SerializerMethodField()
favorited = serializers.SerializerMethodField()
image = serializers.SerializerMethodField()
def create(self, validated_data):
user = self.context['request'].user
story = News(user=user, **validated_data)
story.save()
return story
def get_is_owner(self, obj):
user = self.context['request'].user
if user.is_active and user == obj.user:
return True
return False
def get_user_voted(self, obj):
user = self.context['request'].user
if user.is_active:
return obj.user_voted(user)
return None
def get_favorited(self, obj):
user = self.context['request'].user
if user.is_active:
return obj.is_favorite(user)
class Meta:
model = News
fields = ('id', 'link', 'title', 'text', 'source', 'user',
'date_added', 'image', 'comments_count', 'url',
'upvotes', 'downvotes', 'user_voted', 'type',
'is_owner', 'favorited')
read_only_fields = ('date_added')
```
i am not sure if it has to do with nginx but i have this in the config
```
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
``` | 2016/05/08 | [
"https://Stackoverflow.com/questions/37097643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1567198/"
] | You need to make sure nginx forwards the client's request scheme because it'll make a regular http request to Django. You'll need to add the following line to your vhost definition:
```
proxy_set_header X-Forwarded-Proto $scheme;
``` |
28,768,715 | For a project I am working on, one of the things we're implementing is something that we have code for in some of my teams older ASP.NET and MVC projects - an `Application_Error` exception catcher that dispatches an email to the development team with the exception experience and most relevant details.
Here's how it looks:
**Global.asax:**
```
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
string path = "N/A";
if (sender is HttpApplication)
path = ((HttpApplication) sender).Request.Url.PathAndQuery;
string args = string.Format("<b>Path:</b> {0}", path);
// Custom code that generates an HTML-formatted exception dump
string message = Email.GenerateExceptionMessage(ex, args);
// Custom code that sends an email to the dev team.
Email.SendUnexpectedErrorMessage("Some App", message);
}
```
One "minor" problem, though - when I intentionally have a part of the code throw an exception in order to test this mechanism...
```
public static void GetMuffinsByTopping(string topping)
{
throw new Exception("Test Exception!", new Exception("Test Inner Exception!!!"));
// Actual repository code is unreachable while this test code is there
}
```
The front-end JavaScript is immediately intercepting an HTTP 500 request, but the global.asax.cs code noted above is not being reached (I set a breakpoint on the first executing line of the method.)
**Question:** In what way can I get the "old" `Application_Error` handler to dispatch error emails, so that our team's developers can more easily debug our application? | 2015/02/27 | [
"https://Stackoverflow.com/questions/28768715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1404206/"
] | Abstract out your error handling logic from `Application_Error` into its own function. Create a [Web API exception filter](http://www.asp.net/web-api/overview/error-handling/exception-handling).
```
//register your filter with Web API pipeline
//this belongs in the Application_Start event in Global Application Handler class (global.asax)
//or some other location that runs on startup
GlobalConfiguration.Configuration.Filters.Add(new LogExceptionFilterAttribute());
//Create filter
public class LogExceptionFilterAttribute : ExceptionFilterAttribute
{
public override void OnException(HttpActionExecutedContext context)
{
ErrorLogService.LogError(context.Exception);
}
}
//in global.asax or global.asax.cs
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
ErrorLogService.LogError(ex);
}
//common service to be used for logging errors
public static class ErrorLogService
{
public static void LogError(Exception ex)
{
//Email developers, call fire department, log to database etc.
}
}
```
Errors from Web API do not trigger the Application\_Error event. But we can create an exception filter and register it to handle the errors. Also see [Global Error Handling in ASP.NET Web API 2](https://www.asp.net/web-api/overview/error-handling/web-api-global-error-handling). |
6,091,451 | So I have this code that pops up a file chooser and reads the file:
```
JFileChooser chooser = new JFileChooser();
File file = null;
int returnValue = chooser.showOpenDialog( null ) ;
if( returnValue == JFileChooser.APPROVE_OPTION ) {
file = chooser.getSelectedFile() ;
}
if(file != null) {
String filePath = file.getPath();
}
// String filePath (that's what i'm trying to input) = "Users/Bill/Desktop/hello.txt";
try {
ReadFile files = new ReadFile(***);
String[] lines = files.OpenFile();
```
the three asterisks (*\**) represent the class path of the file to be read. What should I put there if I want to read the file? Before this, I hard-coded the class-path and passed it in and it worked, but now, the class-path can be whatever the user chooses. Thanks for your help! | 2011/05/22 | [
"https://Stackoverflow.com/questions/6091451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/765039/"
] | I don't know what your `ReadFile` thing is, but it looks like it takes a string representing the file path. In which case, you probably want to give it `file.getPath()`. |
17,525,935 | i have created an application called "xyz.msi" and installed. Now i created another application called "abc.msi" and trying to install.
But my question is if "xyz.msi" is installed already then it shouldn't allow to install "abc.msi".
Thanks in advance | 2013/07/08 | [
"https://Stackoverflow.com/questions/17525935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2560586/"
] | Take a look at the [Upgrade table](http://msdn.microsoft.com/en-us/library/windows/desktop/aa372379%28v=vs.85%29.aspx). You can use this to define the search criteria along with the msidbUpgradeAttributesOnlyDetect attribute to cause your action property to be assigned the ProductCode property that is found. Then you can use your action property in the [LaunchCondition table](http://msdn.microsoft.com/en-us/library/windows/desktop/aa369752%28v=vs.85%29.aspx) to prevent installation. |
45,935,003 | I have a string pipe of values, which I want to modify. the string pipe has a range from 0-5 values, so I made the following:
```js
new Vue({
el: '#app',
data: {
valuesString: ""
},
computed: {
values: {
get() {
var values = this.valuesString ? this.valuesString.split("-") : [];
if(values.length < 5)
values.push(null);
return values;
},
set(values) {
this.valuesString = values.filter(value => value).join("-")
}
}
}
});
```
```html
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<div id="app">
<div v-for="(value, i) in values" :key="i">
<select v-model="values[i]" style="width: 200px">
<option></option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<br>
<span>valuesString: {{ valuesString }}</span>
<br>
<span>values: {{ values }}</span>
</div>
```
The problem now is, that the setter of my computed `values` property getn't called.
my usecase is a filter like a categories filter. I get the `valuesString` as parameter from my router. The user should be able to select 1-5 categories to filter. every time the filter changes the router paramter should change and a new empty select should appear until there are 5 categories set. | 2017/08/29 | [
"https://Stackoverflow.com/questions/45935003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1826106/"
] | I'm not entirely sure I understand what you are looking for, but I think this will do the trick:
* Parse the piped string and place it in an array
+ See the computed property unpiped
* loop through the array and place the value in the selectbox
+ the loop should occur on the . The result is bound to valuesString
* The selected value should be pushed to a results array and the selectbox should be cleared.
+ see the pushValues method.
[Jfiddle example](https://jsfiddle.net/retrogradeMT/mxgtqdep/)
```
<div id="app">
<div>
<select v-model="valuesString" @change="pushValues" style="width: 200px">
<option v-for="p in unpiped">{{p}}</option>
</select>
</div>
<br>
<span>valuesString: {{ valuesString }}</span>
<br>
<span>unpiped: {{ unpiped }}</span>
<br>
<span>results: {{ results }}</span>
</div>
```
JS:
```
new Vue({
el: '#app',
data: {
valuesString: "",
piped: "1|2|3|4|5",
results: []
},
computed: {
unpiped(){
var v = this.piped.split("|");
return v;
},
},
methods: {
pushValues: function(){
this.results.push(this.valuesString)
this.valuesString = ""
}
}
});
``` |
3,755,892 | Does anyone know if there is an extension or plugin for Visual Studio ( any version ) that will recognize Perl syntax highlighting? I want to edit the Perl files in my vs projects, but it gets hard to read sometimes. Thanks. | 2010/09/20 | [
"https://Stackoverflow.com/questions/3755892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/387203/"
] | [Visual Studio Update 1 RTM](http://blogs.msdn.com/b/visualstudio/archive/2015/11/30/visual-studio-update-1-rtm.aspx) now (2015) has Perl support, along with Go, Java, R, Ruby, and Swift. |
8,626,880 | On Android when I am mapping an address on a Mapview I have to wait for that action to return and then my user is given control back so I was wondering how can I send that function of to another thread?
```
mapLocationButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mapCurrentAddress(); //Send this function to new thread
}
});
```
How can this be done? And how will the new thread respond when it's done? | 2011/12/24 | [
"https://Stackoverflow.com/questions/8626880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/690851/"
] | Android provides the AsyncTask class to do that. Read <http://developer.android.com/reference/android/os/AsyncTask.html> |
83,697 | In X-Men Origins, Scott Summers lost his eyes, which were then put into Deadpool. After this event, in X-Men 1 through X-Men 3 Scott was still able to fire lasers, implying that the mutant ability was not related to the eyes? Yet Deadpool was able to fire the lasers with Scott's eyes. In addition Deadpool was able to control if he shot the beam, whereas Cyclops had to keep his eyes closed or adjust his visor.
Why is Deadpool able to shoot lasers with eyes and Cyclops without? Why is Deadpool able to control the lasers without the technology Cyclops has? | 2015/03/12 | [
"https://scifi.stackexchange.com/questions/83697",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/42794/"
] | >
> Why is Deadpool able to shoot lasers with eyes and Cyclops without? Why is Deadpool able to control the lasers without the technology Cyclops has?
>
>
>
Because Cyclops origin story involves trauma (either mental psychological trauma, or actual head injury) that prevents him from controlling his powers. His brother Havok, who has similar enough powers as Scott that they can attack each other and it won't hurt, does not have this problem. This is why Scott needs Ruby-Quartz glasses or the visor to absorb the blasts which are always on.
>
> The early accounts in the X-Men comics use flashbacks to tell the origin story of Scott parachuting from his parents' plane. The flashbacks are often told from various narrative perspectives and place different emphasis on the events of this period. Scott's poor control over his power have been attributed to events in his childhood. In Uncanny X-Men #156, Scott's parachute caught fire and Scott struck his head upon landing. This caused brain damage to Scott which is responsible for his poor control over his optic blasts. Several origin stories do not feature the head injury account with X-Men Origins: Cyclops #1 being the most recent. The head injury account has also been retconned in Astonishing X-Men Vol. 2 as being due to a self-imposed mental block he made as a child to deal with the traumatic events of his life. With the help of Emma Frost, Scott is able to briefly bypass his own mental block and control his powers, though he reveals that his control is waning and temporary. [wikipedia]
>
>
>
As for Origins, you misunderstand what it is that happens in the movie, which is also pulled from the comics. Comic Deadpool is not a mutant, but his origins involve receiving a **COPY** of Wolverine's mutant healing factor. In the movie, this still happens. Notice that Wolverine was not deprived a healing factor, or his claws, yet Deadpool has both. He received copies of Wolverine's and Cyclops' powers (along with Wraith's teleportation and Bradley's technopathy). This somehow involved surgery of the optic nerves. Scott at no point had his eyes removed. The bandages suggest a biopsy or surgery of the eyes that need to heal.
The reason Deadpool can use the optic blasts without the glasses is because he lacks the trauma that Scott received. |
3,101,684 | Been back and forth on this recently. Trying to attach a SSH tunnel from a localhost port on my machine to an internal port on the other side of an Internet accessible SSH server using Putty. Putty does not check if the port is available. Before I open the Putty connection, I would like to verify the port is free.
It works fine if the port is available, but I need a sure fire way to guarantee the port is not open at the time I check it in my code. I have used various methods with bad results. I am currently using the following code:
```
bool IsBusy(int port)
{
IPGlobalProperties ipGP = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] endpoints = ipGP.GetActiveTcpListeners();
if (endpoints == null || endpoints.Length == 0) return false;
for (int i = 0; i < endpoints.Length; i++)
if (endpoints[i].Port == port)
return true;
return false;
}
```
I have uTorrent installed on the computer. When I attempt to use port 3390, it fails because uTorrent is listening on that port via TCP. Is there a way to ensure TCP is not in use at all on a given port? | 2010/06/23 | [
"https://Stackoverflow.com/questions/3101684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/344271/"
] | There will always be a race condition if you are checking with one program and expecting to use the port in another. If you were doing everything from within one program You can create a socket and bind to port 0 and the system will select a free port for you so you will never clash with another process. |
5,900,627 | I am trying to pass an object from one page to another page using `<asp:hyperlink>` without any success. I was trying to invoke a C# method and put that object into a session but then I realized you can't invoke a method using `<asp:hyperlink>`. Then I thought about using `<asp:linkbutton>` but then I need to open the new webpage in a new window.
How can I go about doing this properly? Are there any other good alternatives? | 2011/05/05 | [
"https://Stackoverflow.com/questions/5900627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/386195/"
] | >
> Then I thought about using `<asp:linkbutton>` but then I need to
> open the new webpage in a new window.
>
>
>
You do not need to open a new window... add this to your server side `LinkButton` handler:
```
<asp:LinkButton id="btnYourLinkButton" runat="server"
OnClick="btnYourLinkButton_Click">Test</asp:LinkButton>
protected void btnLogout_Click(object sender, System.EventArgs e)
{
var someObject = GetYourDataWithSomeFunction();
Session["YourData"] = someObject; // saves to session
Response.Redirect("yourNewUrl.aspx");
}
```
This will store the value in the `Session` and redirect to a new page in the same window.
EDIT:
If you **need** to open in a new window then do the same thing as outlined above but instead of doing a `Response.Redirect` add the `window.open` javascript call to your page that is served up to open the new window:
```
ScriptManager.RegisterStartupScript(this, this.GetType(), "AUTOOPEN",
"window.open('yourNewUrl.aspx', '_blank');", true);
```
Optionally you could just add an ajax call to your click method to setup the `Session` server side and then trigger the redirect based on your ajax call complete. |
24,342,687 | I am trying to clear a session. Below is a little sample code I wrote to check with `SessionStatus`.
```
@Controller
@SessionAttributes(value={"sessAttr1","sessAttr2","sessAttr3"})
public class SessionController {
@RequestMapping(value="index")
public ModelAndView populateSession(){
ModelAndView modelView = new ModelAndView("home");
modelView.addObject("sessAttr1","This value is added in a session 1");
modelView.addObject("sessAttr2","This value is added in a session 2");
modelView.addObject("sessAttr3","This value is added in a session 3");
return modelView;
}
@RequestMapping(value="home1")
public String populateHomeSession(SessionStatus status){
status.setComplete();
return "home1";
}
}
```
When `home1` screen is displayed, I can still see the session objects not getting cleared. If I try this: `${sessAttr1 }` then I can read the session values in `home1` screen.
Please clarify why is it not working.
**EDIT**
I an using `<a href="home1">Next</a>` to navigate from one screen to another. Does it have something to do with this isse I am facing? | 2014/06/21 | [
"https://Stackoverflow.com/questions/24342687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1317840/"
] | `setComplete` is used to mark a session attribute as not needed *after* the request has been processed by the controller: It does not immediately modify the session, and it overall sounds like it's a poor fit for your use case. It's intended to be used in a situation like a POST where the data is intended to be used during the present request, but should not be used in the future.
<http://forum.spring.io/forum/spring-projects/web/108339-problem-with-sessionattribute-and-sessionstatus> |
54,616,879 | I have a file directory `music/artist/{random_name}/{random_music}.ogg`
There's a lot of folder in `{random_name}` and different kind of music title `{random_music}`.
So, I wanted to rename the `{random_music}.ogg` to `music.ogg`. Each `{random_name}` folder only have one .ogg files.
I've tried with the Bash scripts for hours but didn't managed to find out.
```
for f in ../music/artist/*/*.ogg
do
echo mv "$f" "${f/.*.ogg/music.ogg}"
done
```
It only rename the file on my current dir, which will ask for replace/overwrite.
My goals is, I wanted to rename all the `{random_music}.ogg` files to `music.ogg` with their respective directories for example,
`music/artist/arai/blue.ogg` to `music/artist/arai/music.ogg`
`music/artist/sako/sky.ogg` to `music/artist/sako/music.ogg` | 2019/02/10 | [
"https://Stackoverflow.com/questions/54616879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8061434/"
] | Your pattern replacement is incorrect. Because all your paths start with `..`, `.*.ogg` actually matches *the entire path*, so *every* file gets turned into `music.ogg` in your current directory.
You want `${f/\/*.ogg/music.ogg}` instead, or better yet, `${f%/*}/music.ogg`. That's the rough equivalent of `"$(dirname "$f")"/music.ogg`. |
6,346 | I hope to observe planets like Jupiter and Saturn, and moons. I am a novice when it comes to telescopes and I know images in magazines are not taken with at least 12-inch telescope in a middle of nowhere. Is it possible to view Saturn in little yellowish and Mars in little reddish using following telescopes? I am going to buy one of them. **Which one is worth more for the money with the price difference?**
I am living in Sri Lanka (a country close to the equator) in a suburban city.
**Option 1**
EQ-Reflecting telescope
* Aperture: 135mm
* Focal length: 800mm Focal ratio: f/6
* Max power: 265x when the air is steady
* Price: 300USD approx
* Link: <http://www.ksonoptics.com:8081/Product/PrdDtls/121/>
**Option 2**
EQ-Reflecting telescope
* Aperture: 114mm
* Focal length: 900mm Focal ratio: f/8
* Max Power: 228x when the air is steady.
* Price: 220USD approx
* Link: <http://www.ksonoptics.com:8081/Product/PrdDtls/119/> | 2014/09/13 | [
"https://astronomy.stackexchange.com/questions/6346",
"https://astronomy.stackexchange.com",
"https://astronomy.stackexchange.com/users/2410/"
] | Go with Option 1 (135mm) as it has bigger light collecting area, i.e. diameter of primary mirror. It will enable you to see faint objects and it will also help you to see the dim objects under a greater zoom eyepiece, e.g. 4mm or 10mm.
Also, don't fool yourself with the bigger numbers advertized by telescope vendors like 238X zoom or 300X zoom.
First, these are zooming power using Barlow lenses also the more you zoom in on any object, the less light you gather on the mirror and hence objects will look much fainter in appearance. I will suggest the 10mm eyepiece with a 135mm telescope (Option 1) will be sufficient for you to observe planets like Jupiter, its Galilean satellites, Saturn's rings and also many Messier objects like Andromeda Galaxy M31, the Honey Bee Cluster, and open star clusters in the Auriga constellation.
Also bear in mind that you live in a country area closer to sea like here in India and the weather will be hot and humid.
So ask the vendor about special coating which protects the mirror from rusting (spots on mirror due to moisture) during the humid monsoon season as at least for 4 months it will be humid. |
123,285 | I have a 20 amp circuit going directly from the panel to the kitchen with 20 amp receptacles and subsequent 12 gauge wire. There are only 4 outlets on that circuit (one being a GFI). I am installing under-cabinet lights and lights above the sink, well within the total amperage and volts allowed for the 20 amp circuit. I will use the 12 gauge wire to power the 15amp single pole switches and go to the lights with 14 gauge wire. Can I connect the 14 gauge neutral to the 12 gauge already in the box or should I just run 12 gauge to the lights for the neutral and connect??.... thank you in advance for your input | 2017/09/13 | [
"https://diy.stackexchange.com/questions/123285",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/75416/"
] | Switches are not circuit breakers (overcurrent protection). They cannot protect wire and do not make it ok to use smaller wire past them.
If any 14AWG wire is used, you must downgrade the breaker to 15A, and downgrade the countertop receptacles to 15A. The other wire can remain 12AWG. This will mean it is not one of the two mandatory 20A circuits for countertop receptacles and you may need to add a circuit.
There is another reason not to put kitchen lights on receptacle circuits. An appliance trip will plunge the cook into darkness. |
7,238,330 | I have following code
```
$.ajax({ type: 'POST',
url: 'index.jsp',
data: 'id=111',
dataType: 'jsonp',
success: function(data) {
alert(data.result);
},
error: function( err1, err2, err3 )
{
alert('Error:' + err3 )
}
});
```
I am returning response as callback parameter generated with argument of json . like this
```
jQuery16105097715278461496_1314674056493({"result" : "success"})
```
This works absolutely fine in FF . In IE 9 it goes to error function and shows
```
"Error: jQuery16105097715278461496_1314674056493 was not called" .
```
when I see F12 . I see a warning which says .
```
SEC7112: Script from http://otherdomain.com
index.jsp?callback=jQuery16105097715278461496_1314674056493
&eid=111&_=1314674056493
was blocked due to mime type mismatch
```
![enter image description here](https://i.stack.imgur.com/Az4rZ.png)
![enter image description here](https://i.stack.imgur.com/AUw6T.png)
![enter image description here](https://i.stack.imgur.com/3FiX1.png) | 2011/08/30 | [
"https://Stackoverflow.com/questions/7238330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/608576/"
] | try adding a contentType
```
$.ajax({
type: 'POST',
url: 'index.jsp',
data: {id:'111'},
contentType: "application/json; charset=utf-8",
dataType: 'jsonp',
success: function(data) {
alert(data.result);
},
error: function( err1, err2, err3 )
{
alert('Error:' + err3.status );
alert(err1.responseText);
}
});
```
here is a good article <http://msdn.microsoft.com/en-us/library/gg622941%28v=vs.85%29.aspx> |
25,948,218 | My java project has files which have same name but different cases (Test.java & test.java). I have setup a case sensitive file system on my mac and am able to view/edit them via CLI. However, Intellij Idea does not regard them as different and compilation fails. How can I fix Intellij Idea to honor cases for a file name?
Thanks | 2014/09/20 | [
"https://Stackoverflow.com/questions/25948218",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/367890/"
] | I filed a support request at JetBrains. Here is the answer:
>
> add "idea.case.sensitive.fs=true" to bin/idea.properties file (<https://intellij-support.jetbrains.com/entries/23395793> ), perform File | Invalidate Caches and restart the IDE.
>
>
>
It solved the issue for me.
update: 2015-02-14 / Idea 14.0.3
It is no longer sufficient to add the property to the idea.properties file. Add `-Didea.case.sensitive.fs=true` to "Settings | ... | Java Compiler | Additional command line parameters". |
963,370 | I'm trying to install the SSRS data connector for my CRM4 implementation.
I'm using the [Method 2: Modify the Install-config.xml file from this page](http://support.microsoft.com/kb/947060). But keep getting the same error message:
>
> Unable to validate SQL Server Reporting Services Report Server
> installation. Please check that it is correctly installed on the local
> machine.
>
>
>
I've added the following to my XML file.
```
<reportserverurl>http://SSRS-Server/Reportserver$MYORG_MSCRM</reportserverurl>
<instancename>MYORG_MSCRM</instancename>
```
Anyone know what is still wrong?
I tried several instance names but they all don't work either.
I can access my SSRS server by going to `http://SSRS-Server/Reports` and it will give a list of all services running there.
Any help would be much appreciated. | 2009/06/08 | [
"https://Stackoverflow.com/questions/963370",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You may need to post more details regarding this issue:
1) The 2nd method described in this link : [here](http://support.microsoft.com/kb/947060) is used when the Reporting Server database is installed using the SQL Server named instance. Are you installing the Reporting Server database in the default instance or named instance ?
2) If you are using default instance, you might not need to use custom XML, you can just run the installer without requiring the input XML file.
3) What is the architecture of your CRM implementation ? is the CRM Application, SQL server and Reporting Server resided in the same server ? or different server ?
Hope this helps. |
3,873,110 | I have a table with two number columns, and a unique constraint over them both. I would like to insert a new pair of values UNLESS the pair already exists. What is the simplest way to do this?
If I do
```
insert into TABLE values (100,200)
```
and the pair already exists I get a ORA-00001 error, so I would like to do something like
```
insert or update into TABLE values (100,200)
``` | 2010/10/06 | [
"https://Stackoverflow.com/questions/3873110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/64082/"
] | You can use [MERGE](http://psoug.org/reference/merge.html) |
4,162,930 | Let it be $\alpha=1+\sqrt[3]{5}\,i$ and $f(x)$ the minimal polynomial of $\alpha$ in $\mathbb{Q}$.
Is $\mathbb{Q}(\alpha)$ the splitting field of $\alpha$?
I generally know how to deal with splitting field when the roots are simple but I dont know how to deal with this or in general when minimal polynomial aren't that easy to handle with.
Are there any properties or theorems that help as criterions to determine whether we have a splitting field or not? (if there is anything more general that covers not only this case I would be more than pleased to note them down)
I hope I didn't spell the question wrong and thanks in advance | 2021/06/04 | [
"https://math.stackexchange.com/questions/4162930",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/918258/"
] | For your example, let $\beta=\sqrt[3]5i$, then we have $\beta^6=-25$. Clearly $\beta$ has degree 6 over $\mathbb Q$, and its conjugates are given by $\beta\zeta^k$, $k=0,\dots,5$, where $\zeta=\frac{1+\sqrt3i}2$ is a primitive sixth root of unity. Therefore, the extension $\mathbb Q(\beta)/\mathbb Q$ is not Galois, because $\zeta$ is not contained in $\mathbb Q(\beta)$.
If $\mathbb Q(\alpha)$ is the splitting field, then it must be a Galois extension, but $\mathbb Q(\alpha)=\mathbb Q(\beta)$. In general, the extension of the form $\mathbb Q(\sqrt[n]m)$ can be dealt with in the same way. |
20,981,466 | I'm facing problem with jquery
here is my code
```
<script type='text/javascript' src='jquery-1.10.2.min.js'></script>
<script type="text/javascript">
$(function() {
$(".more2").click(function() {
var element = $(this);
var msg = element.attr("id");
$.ajax({
type: "POST",
url: "insta2.php",
data: "lastmsg="+ encodeURIComponent(msg),
success:function (data) {
$("#morebutton").replaceWith(data);
}
});
return false;
});
});
</script>
<span class="more" id="morebutton">
<a id="1" class="more2" title="Follow" href="#" style="color:#000">
Read More
</a>
</span>
```
and here is insta2.php
```
<?php
if(isset($_POST['lastmsg']))
{
$a= $_POST['lastmsg'];
$a = $a++;
?>
<br>
<span class="more" id="morebutton">
<a id="<?php echo $a;?>" class="more2" title="Follow" href="#" style="color:#000">
<?php echo $a;?> Read More
</a> </span>
<?php }?>
```
my jquery only one 1 set and after that every click not working
is there any way to continue counting ?
like this
Read More
1 Read More
2 Read More
3 Read More
4 Read More
and so on... | 2014/01/07 | [
"https://Stackoverflow.com/questions/20981466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/69821/"
] | Looking at the [source](https://github.com/thquinn/DraggableGridView) you provided, the `DraggableGridView` class is already under `src`. So adding the jar that contains the same is redundant and dex will complain about duplicate definitions.
To fix it, just remove the `DraggableGridView.jar` from your project. |
34,379,584 | I shoul use setText() but how should I use it instead of System.out.println()?
I want to print the result in a TextView. The code is a json reader. sorry I need to write some text to let me post my question.
```
public class JsonReader extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("http://www.w3schools.com/json/myTutorials.txt");
System.out.println(json.toString());
System.out.println(json.get("display"));
//TextView tv = (TextView) findViewById( R.id.tv );
//tv.setText(json.toString());
//tv.setText(json.get("display"));
}
```
} | 2015/12/20 | [
"https://Stackoverflow.com/questions/34379584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5184742/"
] | You will need to print the result in a TextView if you want to view the result on phone instead of LogCat console as suggested by johnrao07.
To print result in a TextView first add a TextView widget in activity\_main.xml layout file.
```
<TextView
android:id="@+id/text_view_id"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
Then JsonReader.java class main function instead of `System.out.println(json.toString());` call `((TextView) findViewById(R.id.text_view_id)).setText(json.toString());` |
39,041,257 | How optimize an API call in symfony?
I call with Guzzle bundle, but the time in some situations is very long.
In client application call a function from the server.
In server application extract the objects from the database and send back to the client.
In client creat the new object with properties from server respons. | 2016/08/19 | [
"https://Stackoverflow.com/questions/39041257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | One of the ways to improve your API calls is to use caching. In Symfony there are many different ways to achieve this. I can show you one of them (`PhpFileCache` example):
In **services.yml** create cache service:
```
your_app.cache_provider:
class: Doctrine\Common\Cache\PhpFileCache
arguments: ["%kernel.cache_dir%/path_to/your_cache_dir", ".your.cached_file_name.php"]
```
(Remember, you need `Doctrine` extension in your app to work)
Then pass your caching service `your_app.cache_provider` to any service where you need caching:
Again in your **services.yml**:
```
some_service_of_yours:
class: AppBundle\Services\YourService
arguments: ['@your_app.cache_provider']
```
Finally, in your service (where you want to perform API caching):
```
use Doctrine\Common\Cache\CacheProvider;
class YourService
{
private $cache;
public function __construct(CacheProvider $cache)
{
$this->cache = $cache;
}
public function makeApiRequest()
{
$key = 'some_unique_identifier_of_your_cache_record';
if(!$data = $this->cache->fetch($key))
{
$data = $provider->makeActualApiCallHere('http://some_url');
$this->cache->save($key, serialize($data), 10800); //10800 here is amount of seconds to store your data in cache before its invalidated, change it to your needs
}
return $data; // now you can use the data
}
}
```
This is quite GENERIC example, you should change it to your exact needs, but idea is simple. You can cache data and avoid unnecessary API calls to speed things up. Be careful though, because cache has drawback of presenting stale(obsolete) data. Some things can (and should) be cached, but some things don't. |
86,352 | ```
> CREATE TABLE test(foo FLOAT);
> INSERT INTO test VALUES(1.2899999);
> SELECT * FROM test;
+------+
| foo |
+------+
| 1.29 |
+------+
```
While it's obvious that FLOAT is not a precise data type, it is still rounding this data too arbitrarily. Let's check if it's actually able to store it:
```
> ALTER TABLE test MODIFY foo DOUBLE;
> SELECT * FROM test;
+--------------------+
| foo |
+--------------------+
| 1.2899998426437378 |
+--------------------+
```
Whoops, only the 7th digit got corrupted due format limitations. Is there a way to prevent overzealous rounding in this situation, short of converting the column to DOUBLE? | 2014/12/16 | [
"https://dba.stackexchange.com/questions/86352",
"https://dba.stackexchange.com",
"https://dba.stackexchange.com/users/9479/"
] | I hate precision-based issues. I dealt with one before: [Data Truncated for Column](https://dba.stackexchange.com/questions/4091/data-truncated-for-column/4094#4094)
You may have do the ALTER TABLE manually
```
CREATE TABLE test_new LIKE test;
ALTER TABLE test_new MODIFY foo DOUBLE;
INSERT INTO test_new (foo) SELECT CONVERT(foo,DOUBLE) FROM test;
RENAME TABLE test TO test_old,test_new TO test;
DROP TABLE test_old;
```
or
```
CREATE TABLE test_new LIKE test;
ALTER TABLE test_new MODIFY foo DOUBLE;
INSERT INTO test_new (foo) SELECT CONVERT(foo,DECIMAL(10,7)) FROM test;
RENAME TABLE test TO test_old,test_new TO test;
DROP TABLE test_old;
```
or
```
CREATE TABLE test_new LIKE test;
ALTER TABLE test_new MODIFY foo DOUBLE;
INSERT INTO test_new (foo) SELECT FORMAT(foo,7) FROM test;
RENAME TABLE test TO test_old,test_new TO test;
DROP TABLE test_old;
```
Not sure what will happen, but give it a try and see what happens. |
34,494 | I have a data-set of genetic variants which I'm trying to use as predictors for a simple phenotype, and for starters I use a binary logistic regression in SPSS. I have around 900 individuals, and for each individual around 50 variations and a phenotype.
However, I get an unreasonably high amount of removed values when I run the analysis (there is some missing variants data all over the entire table), i.e., only around 50% of my measurements are actually used, and I can't find the exclusion-cut-off SPSS uses for this anywhere.
Does anyone know the cut-off that SPSS employs in this? Or does it remove a measurement once it finds a single missing variant? | 2012/08/17 | [
"https://stats.stackexchange.com/questions/34494",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/12259/"
] | SPSS removes cases [list-wise](http://en.wikipedia.org/wiki/Listwise_deletion) by default, and in my experience this is the case for the majority of statistical procedures. So if a case is missing data for any of the variables in the analysis it will be dropped entirely from the model. For generating correlation matrices or linear regression you *can* exclude cases pair-wise if you want (I'm not sure if that is ever really advised), but for logistic and generalized linear model regression procedures this isn't an option. Hence you may want to look at techniques for imputing missing data.
Below are some resources I came up quickly for missing data analysis in SPSS;
* User [ttnphns](https://stats.stackexchange.com/users/3277/ttnphns) has a macro for hot-deck imputation on his [web site](http://rivita.ru/spssmacros_en.shtml). I also see [Andrew Hayes](http://www.afhayes.com/spss-sas-and-mplus-macros-and-code.html) has a macro for hot-deck imputation.
* Raynald Levesque's site has a set of example syntax implementations of various [missing values procedures](http://spsstools.net/SampleSyntax.htm#WorkingWithMissingValues). Including another implementation of hot-deck imputation!
* SPSS has various tools in-built for imputing missing values. See the commands `MVA`, `RMV`, and `MULTIPLE IMPUTATION`. See the [Missing Values Analysis](http://publib.boulder.ibm.com/infocenter/spssstat/v20r0m0/index.jsp?topic=%2Fcom.ibm.spss.statistics.help%2Fidh_miss.htm) section in the HELP documentation.
I'm not quite sure what is available in base and what are available as add-ons. I believe the `MULTIPLE IMPUTATION` command is an add-on, but the others are part of the base package. and the `MVA` commands are add-ons, but the `RMV` procedure is part of the base package.
For more general questions about missing data analysis, peruse the tag [missing-data](/questions/tagged/missing-data "show questions tagged 'missing-data'"). |
74,309,944 | I have a db like this:
```
tibble(Q1 = c("0","A"),
Q2 = c("A","A"),
Q3 = c("0","A"),
C1 = c("A","0")
) -> DB
```
I aim to add a new column which is a count of how many `"0"` are detected in the row when the column starts with `"Q"`.
In this case, this column would be like
```
DB %>%
mutate(S = c(2,0))
``` | 2022/11/03 | [
"https://Stackoverflow.com/questions/74309944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17122831/"
] | ```r
DB %>%
rowwise() %>%
mutate(S = sum(c_across(starts_with("Q")) == "0")) %>%
ungroup()
# # A tibble: 2 x 5
# Q1 Q2 Q3 C1 S
# <chr> <chr> <chr> <chr> <int>
# 1 0 A 0 A 2
# 2 A A A 0 0
``` |
20,928,413 | I am getting odd redirection in general. It works in development but not production. Here are the responses for an update. The same things happens on a create.
DEVELOPMENT
```
Redirected to http://localhost:3000/trackers
Completed 302 Found in 43ms (ActiveRecord: 18.7ms)
Started GET "/trackers" for 127.0.0.1 at 2014-01-06 06:41:02 -0600
```
PRODUCTION
```
Redirected to http://example.com/trackers
Completed 302 Found in 218ms (ActiveRecord: 63.9ms)
Started GET "/" for [IP} at 2014-01-05 20:15:33 +0000
```
routes.rb (pertinant)
```
trackers GET /trackers(.:format) trackers#index
POST /trackers(.:format) trackers#create
new_tracker GET /trackers/new(.:format) trackers#new
edit_tracker GET /trackers/:id/edit(.:format) trackers#edit
tracker GET /trackers/:id(.:format) trackers#show
PUT /trackers/:id(.:format) trackers#update
DELETE /trackers/:id(.:format) trackers#destroy
```
Here is my tracker controller
```
class TrackersController < ApplicationController
before_filter :authenticate_user!
load_and_authorize_resource
def create
@tracker = params[:tracker]
@user = current_user
if @user.trackers.create(@tracker)
redirect_to trackers_path, :notice => "New Tracker Created!"
else
redirect_to trackers_path, :notice => "Tracker Could not be created."
end
end
def update
@tracker = Tracker.find(params[:id])
if @tracker.update_attributes(params[:tracker])
redirect_to trackers_path, :notice => "Tracker Updated!"
else
redirect_to trackers_path(params[:id]), :notice => "Unable to Update Tracker"
end
end
end
```
NGINX
```
upstream unicorn{
server unix:/tmp/unicorn.legalleads.sock fail_timeout=0;}
server {
listen 80;
server_name example.com;
return 301 https://$host;}
server {
listen 443 default;
server_name example.com;
root /home/a/apps/legalleads/public;
try_files $uri/index.html $uri @unicorn;
ssl on;
ssl_certificate /etc/nginx/ssl/com.crt;
ssl_certificate_key /etc/nginx/ssl/server.key;
location ^~ /assets/ {
gzip_static on;
expires max;
add_header Cache-Control public;
}
location @unicorn {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://unicorn;
}
error_page 500 502 503 504 /500.html;
client_max_body_size 4G;
keepalive_timeout 10;
}
``` | 2014/01/05 | [
"https://Stackoverflow.com/questions/20928413",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1938097/"
] | `$scope.$digest()` is what processes all of the `$watch` events that are on the current and children scope. It essentially manually tells the scope to check if a scope variable has changed. You don't generally want to use this when you are inside of a controller or a directive, because the `$scope.$apply()` function calls the `$digest` anyway and it is called when you mutate a scope variable.
Checkout this [link](https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$digest) for an example. |
13,279,390 | Write a program that reads in a series of first names and eliminates duplicates by storing them in a Set. Allow the user to search for a first name.
(Trust me, I am not taking any Java classes. So, not my homework).
My issue is to implement this: **Allow the user to search for a first name.**
Everything else works, just the search feature.
*My Code so far....*
```
package com.Sets;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
public class DuplicateElimination {
public static void main(String[] args) {
// Write a program thats ask for first names and store it in an array.
String fName;
Scanner input = new Scanner(System.in);
String[] names = new String[10];
for (int i = 0; i < names.length; i++) {
System.out.println("Enter First Name: ");
names[i] = input.nextLine();
}
// Printout that array as a list.
List<String> list = Arrays.asList(names);
// Initial Array Elements
System.out.printf("%s ", list);
System.out.println();
// Calling removeDuplicates method
removeDuplicates(list);
}
// Make a method called removeDuplicates.
private static void removeDuplicates(Collection<String> values) {
// Implement a Hashset in it.
Set<String> set = new HashSet<String>(values);
// Printout a non-duplicate list of elements.
for (String value : set) {
System.out.printf("%s ", value);
}
System.out.println();
}
// Make a method to search for a first name.
public static void searchForName(Collection<String> names) {
String someName;
Set<String> set = new HashSet<String>(names);
Scanner input = new Scanner(System.in);
for (int i = 0; i <= 10; i++) {
System.out.println("Search this name: ");
someName = input.nextLine();
}
if (someName ) {
} else {
}
}
}
```
I don't feel confident about my searchForName method... can someone give an idea on how I could make this work? | 2012/11/07 | [
"https://Stackoverflow.com/questions/13279390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1415064/"
] | Use `language.ShowDialog();`. Per [MSDN](http://msdn.microsoft.com/en-us/library/c7ykbedk.aspx), the code following it is not executed until after the dialog box is closed. |
1,600,597 | Suppose the following code:
```
foreach(Item i on ItemCollection)
{
Something s = new Something();
s.EventX += delegate { ProcessItem(i); };
SomethingCollection.Add(s);
}
```
Of course, this is wrong because all the delegates points to the same Item. The alternative is:
```
foreach(Item i on ItemCollection)
{
Item tmpItem = i;
Something s = new Something();
s.EventX += delegate { ProcessItem(tmpItem); };
SomethingCollection.Add(s);
}
```
In this case all the delegates point to their own Item.
What about this approach? There is any other better solution? | 2009/10/21 | [
"https://Stackoverflow.com/questions/1600597",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40441/"
] | UPDATE: There is extensive analysis and commentary on this issue here:
<http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/>
---
This is an extremely frequently reported issue; usually it is reported as a compiler bug, but in fact the compiler is doing the right thing according to the specification. Anonymous functions close over *variables*, not *values*, and there is only a single foreach loop variable. Therefore each lambda closes over the same variable, and therefore gets the current value of that variable.
This is surprising to almost everyone, and leads to much confusion and many bug reports. We are *considering* changing the specification and implementation for a hypothetical future version of C# so that the loop variable is logically declared inside the looping construct, giving a "fresh" variable every time through the loop.
**This would be a breaking change**, but I suspect the number of people who depend on this strange behaviour is quite low. If you have opinions on this subject, feel free to add comments to the blog posts mentioned up the update above. Thanks! |
471,949 | Let's take the function $f(x)=x^{-1}$. My question is this: Is the sum $$\frac{1}{x-a}+\frac{1}{x+a}$$ as $a\rightarrow 0$ near the point $x=0$ equal 0? And how would I proove this anytime I encounter this kind of limit? How would this work with derivatives or integrals? | 2013/08/20 | [
"https://math.stackexchange.com/questions/471949",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/47567/"
] | The quantity you seem to be asking about is $$\lim\_{a\to 0}\frac{1}{x-a}+\frac{1}{x+a}$$ "near" $x=0.$ Well, assuming that $x$ is not $0,$ then this is simply $$\lim\_{a\to 0}\frac{1}{x-a}+\frac{1}{x+a}=\frac1x+\frac1x=\frac2x$$ by continuity. Now, if $x=0,$ then we have $$\lim\_{a\to 0}\frac{1}{x-a}+\frac{1}{x+a}=\lim\_{a\to 0}-\frac{1}{a}+\frac{1}{a}=\lim\_{a\to 0}0=0.$$
This is a good example of why we can't always interchange limits, since $$\lim\_{a\to 0}\lim\_{x\to 0}\frac{1}{x-a}+\frac{1}{x+a}=0,$$ but $$\lim\_{x\to 0}\lim\_{a\to 0}\frac{1}{x-a}+\frac{1}{x+a}$$ does not exist. |
118,606 | I am a 15-year-old female, and I am currently a high soprano. I can currently sing from a low C4 to a high F above the bar. Is there a way I could get higher and become a coloratura soprano or gain an octave? | 2021/11/18 | [
"https://music.stackexchange.com/questions/118606",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/83089/"
] | You already have a full soprano range: C4 to F6. Coloratura is a vocal quality, not a range. Coloratura voices generally have a light quality to them, as opposed to the more powerful voice of a dramatic soprano. Coloraturas specialize in highly decorative passages with lots of runs, trills, and other ornaments.
So coloratura is a skill to develop if you have a lighter-sounding voice. At 15 your vocal color may still be changing, but you'll have to wait and see.
---
Also of interest...
* [Lyrical Contralto vs Dramatic Mezzo-soprano](https://music.stackexchange.com/q/116076/70803)
* [Will my voice get any higher?](https://music.stackexchange.com/q/58355/70803) |
18,529,965 | Is there a way to dump the generated sql to the Debug log or something? I'm using it in a winforms solution so the mini-profiler idea won't work for me. | 2013/08/30 | [
"https://Stackoverflow.com/questions/18529965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11421/"
] | I got the same issue and implemented some code after doing some search but having no ready-to-use stuff. There is a package on nuget [MiniProfiler.Integrations](https://www.nuget.org/packages/MiniProfiler.Integrations/) I would like to share.
**Update V2**: it supports to work with other database servers, for MySQL it requires to have [MiniProfiler.Integrations.MySql](https://www.nuget.org/packages/MiniProfiler.Integrations.MySql/)
Below are steps to work with SQL Server:
1.Instantiate the connection
```
var factory = new SqlServerDbConnectionFactory(_connectionString);
using (var connection = ProfiledDbConnectionFactory.New(factory, CustomDbProfiler.Current))
{
// your code
}
```
2.After all works done, write all commands to a file if you want
```
File.WriteAllText("SqlScripts.txt", CustomDbProfiler.Current.ProfilerContext.BuildCommands());
``` |
2,507,595 | I'm using Google Test Framework to set some unit tests. I have got three projects in my solution:
* FN (my project)
* FN\_test (my tests)
* gtest (Google Test Framework)
I set FN\_test to have FN and gtest as references (dependencies), and then I think I'm ready to set up my tests (I've already set everyone to /MTd (not doing this was leading me to linking errors before)).
Particularly, I define a class called Embark in FN I would like to test using FN\_test. So far, so good. Thus I write a classe called EmbarkTest using googletest, declare a member Embark\* and write inside the constructor:
```
EmbarkTest() {
e = new Embark(900,2010);
}
```
Then , F7 pressed, I get the following:
`1>FN_test.obj : error LNK2019: unresolved external symbol "public: __thiscall Embark::Embark(int,int)" (??0Embark@@QAE@HH@Z) referenced in function "protected: __thiscall EmbarkTest::EmbarkTest(void)" (??0EmbarkTest@@IAE@XZ)`
`1>D:\Users\lg\Product\code\FN\Debug\FN_test.exe : fatal error LNK1120: 1 unresolved externals`
Does someone know what have I done wrong and/or what can I do to settle this?
**EDIT**: *Relevant* code from Embark.h
```
class Embark
{
public:
//Constructor for initial state
Embark(int _id, int _year);
//Destructor
~Embark();
/* ... */
}
``` | 2010/03/24 | [
"https://Stackoverflow.com/questions/2507595",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/241161/"
] | I found the answer to be a rather simple one. After two days of intense headknocking, it's this:
**You have to compile your main project as `.lib` and not `.exe`**
After doing this, all linking went as a bliss. I thought Visual Studio would do this automatically for me, since I declared a dependency to FN from FN\_test: I assumed Visual Studio would create the libs. It didn't.
---
**RANT** (no need to read after this)
Since it's rather rare to link one project that makes an executable to another one which does the same thing, finding references on this kind of issue was somewhat hard. Google searches presented me no useful results. MSDN forums were also unhelpful.
But when you do unit testing on a application, will it be common to have this happening, say, a test project and a application project on the same solution? I have no knowledge about other testing frameworks for C++. I have chosen Google Test Framework for:
1. In Google we trust
2. Great documentation
3. Very simple to use and understand
But, however, it has no much merits on integration. I think other tools would integrate way better to Visual Studio, IDE responsiveness inclusive. But I preferred to suffer now than afterwards. I hope this tool keeps improving, for I liked it. |
23,880,663 | What we take for granted in other languages and almost expect it to work in go, won't work - its almost so natural to do this, so why isn't the compiler happy? Just feeling like bailing out of go sometimes.
The only way to increment the value is to put it in its own separate line?
<http://play.golang.org/p/_UnpZVSN9n>
```
package main
import "fmt"
import "strconv"
func main() {
a := 1
//Evaluate expression and pass into function - won't work
fmt.Println(strconv.Itoa(a++))
//Braces around a++ also won't work
fmt.Println(strconv.Itoa((a++)))
}
``` | 2014/05/27 | [
"https://Stackoverflow.com/questions/23880663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/901460/"
] | `++` and `--` are statements in golang, not expressions |
1,483,068 | The charset is Unicode. I want to write a string of CString type into a file, and then read it out from the file afterwards.
I write the string into a file with CFile::Write() method:
```
int nLen = strSample.GetLength()*sizeof(TCHAR);
file.Write(strSample.GetBuffer(), nLen);
```
Here is the question: I want to obtain the CString from the file containing the content of strSample. How can I do it?
Thank you very much! | 2009/09/27 | [
"https://Stackoverflow.com/questions/1483068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/87955/"
] | ```
UINT nBytes = (UINT)file.GetLength();
int nChars = nBytes / sizeof(TCHAR);
nBytes = file.Read(strSample.GetBuffer(nChars), nBytes);
strSample.ReleaseBuffer(nChars);
``` |
551,535 | Yeah, you probably are reading this question and thinking I'm one of those engineers who hasn't learned about the s-plane. I can assure you I'm not! I know that the transfer function of an RC circuit (Vout/Vin) has a REAL pole, with no imaginary component at s= -1/RC + j0. I am curious what happens when we excite an RC circuit at its TRUE pole, which is a decaying exponential with the expression e^(-t/RC).
Of course, the output of an RC Low-pass filter will never blow up to infinity. But what about the ratio of the output to the input, which after all, is the transfer function I originally defined?
Well, let's take this to LTSpice. Below is what I've simulated:
[![enter image description here](https://i.stack.imgur.com/GChDh.png)](https://i.stack.imgur.com/GChDh.png)
I would expect Vout/Vin to be infinity everywhere, however what I see is a ramp. I suspect I'm missing something about how to properly interpret the magnitude response of my transfer function with its true pole as an input. A time-domain view such as what I have should explain something, but I can't understand why it's a ramp.
If anyone has any intuition behind this question, please let me know. | 2021/03/06 | [
"https://electronics.stackexchange.com/questions/551535",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/257550/"
] | Good question, here's my attempt. You still have to convert your input signal from the time domain to s domain, then do the math, then convert the result back to the time domain. That pole just tells you where the resonance is, the behavior of the resonance is usually "growing infinitely forever" - but the exact behavior needs to be found from doing the math.
Using transforms from: <https://en.wikipedia.org/wiki/Laplace_transform>
$$
\frac{1}{1+sRC}V\_i(s)=V\_o(s)\\
V\_i(t) = V\_{i0}e^{-t/(RC)}=V\_{i0}e^{-t/\tau}\\
V\_i(s) = \frac{V\_{i0}}{1/\tau+s}\\
V\_o(s) = \frac{1/\tau}{1/\tau+s}\frac{V\_{i0}}{1/\tau+s}\\
V\_o(s) = \frac{ V\_{i0}/\tau}{(1/\tau+s)^2}\\
V\_o(t) = (V\_{i0}/\tau)\times t e^{-t/\tau}
$$
Which gives us:
$$
V\_o(t)/V\_i(t) = \frac{(V\_{i0}/\tau)\times t e^{-t/\tau}}{V\_{i0}e^{-t/\tau}}\\
V\_o(t)/V\_i(t) = t\times 1/\tau
$$
Predicting that, in the time domain, the ratio of output to input voltage increases linearly with t. In the s-domain, the ratio is infinity.
EDIT: This actually perfectly matches your result, even the correct slope - except there is an offset of 1 unit on the y axis. My guess is that the simulation found the DC point using \$V\_{i}=1 \text{ V}\$ at \$t<0\$, so changes the math. The above assumes \$V\_{i}=0 \text{ V}\$ at \$t<0\$. So it's pretty much the same, just a little difference because of the initial condition.
If the initial condition was V=1, you can use the superposition principle and add the solution we found (for V=0 until t=0, then decaying) to the solution if V=1 when t was negative and V=0 when t is positive
$$
V\_o(t) = (V\_{i0}/\tau)\times t e^{-t/\tau}+V\_{i0}e^{-t/\tau}\\
V\_o(t)/V\_i(t) = \frac{(V\_{i0}/\tau)\times t e^{-t/\tau}+V\_{i0}e^{-t/\tau}}{V\_{i0}e^{-t/\tau}}\\
V\_o(t)/V\_i(t) = t\times 1/\tau+1
$$
Now it exactly matches what you have! So the simulation does use V=1 for when t is negative, and this should clearly show what's happening. Just because something is infinity in the s domain doesn't mean it is in time. |
7,327,164 | I am developing a node.js app, and I want to use a module I am creating for the node.js server also on the client side.
An example module would be circle.js:
```
var PI = Math.PI;
exports.area = function (r) {
return PI * r * r;
};
exports.circumference = function (r) {
return 2 * PI * r;
};
```
and you do a simple
```
var circle = require('./circle')
```
to use it in node.
How could I use that same file in the web directory for my client side javascript? | 2011/09/06 | [
"https://Stackoverflow.com/questions/7327164",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/101909/"
] | This seems to be how to make a module something you can use on the client side.
<https://caolan.org/posts/writing_for_node_and_the_browser.html>
mymodule.js:
```
(function(exports){
// your code goes here
exports.test = function(){
return 'hello world'
};
})(typeof exports === 'undefined'? this['mymodule']={}: exports);
```
And then to use the module on the client:
```
<script src="mymodule.js"></script>
<script>
alert(mymodule.test());
</script>
```
This code would work in node:
```
var mymodule = require('./mymodule');
``` |
31,424,294 | say I have the following code:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />' +
'data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />' +
'data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />' +
'data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />' +
'<input type="button" id="subUpdated" value="Save">');
```
I there any way to write the HTML code like a simple HTML code , and without the qoutes and the plus signs? | 2015/07/15 | [
"https://Stackoverflow.com/questions/31424294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1798362/"
] | In the current version of JavaScript, you can do this by escaping the newlines at the ends of lines, which is a *bit* better but note that leading whitespace will be included in the string, and you still have to use concatenation to swap in your values:
```
var rightPane = $("#right");
// Draw the right pane
rightPane.html('<h2>' + task.task + '<h2> <hr />\
data1: <input type="text" id="data1" value="' + task.data1 + '" /> <br />\
data2: <input type="text" id="data2" value="' + task.data2 + '" /> <br />\
data1: <input type="text" id="data3" value="' + task.data3 + '" /> <br />\
<input type="button" id="subUpdated" value="Save">');
```
In the next version of JavaScript, "ES6", we'll have *template strings* which can be multi-line and which let you easily swap in text using `${...}`:
```
// REQUIRES ES6
var rightPane = $("#right");
// Draw the right pane
rightPane.html(`
<h2>${task.task}<h2> <hr />
data1: <input type="text" id="data1" value="${task.data1}" /> <br />
data2: <input type="text" id="data2" value="${task.data2}" /> <br />
data1: <input type="text" id="data3" value="${task.data3}" /> <br />
<input type="button" id="subUpdated" value="Save">
`);
```
(Again leading whitespace is included in the string.)
To do that before ES6, you can use any of several templating libraries (Handlebars, Mustache, RivetsJS).
For a really simple version, you could use [the function I wrote](https://stackoverflow.com/a/31368057/157247) for another question. |
102,246 | The elementary "opposite over hypotenuse" definition of the sine function defines the sine of an angle, not a real number. As discussed in the article "A Circular Argument" [Fred Richman, The College Mathematics Journal Vol. 24, No. 2 (Mar., 1993), pp. 160-162. Free version [here](http://www.maa.org/sites/default/files/pdf/mathdl/CMJ/Richman160-162.pdf). Thanks to Aaron Meyerowitz's answer to question [72792](https://mathoverflow.net/questions/72792/who-first-proved-that-the-value-of-c-d-is-independent-of-the-choice-of-circle) for the reference.], angles might be measured either by the area of a sector of unit radius having the angle or by the arc length of such a sector. If the former convention is adopted then it can be proven using a completely unexceptionable Euclidean argument that $\lim\_{x\to 0} \sin(x)/x = 1$.
Also, whichever convention is adopted (or so it seems to me), using completely unexceptionable Euclidean arguments, it is possible to prove the angle addition formulas for sine and cosine. Using these two ideas, it is straightforward to find the derivatives of sine and cosine, and from there one can derive an algorithm for computing digits of sine and cosine (and for computing $\pi$) using the relatively sophisticated mean-value version of Taylor's theorem.
The equivalence of the two definitions of sine (or of angle measurement) apparently depends on something like Archimedes' postulate: "If two plane curves C and D with the same endpoints are concave in the same direction, and C is included between D and the straight line joining the endpoints, then the length of C is less than the length D." (Again, thanks to Aaron Meyerowitz.) Of course, it is just this postulate that Archimedes needed to prove that the area of a circle is equal to the area of a triangle with base the circumference of the circle and height the radius. And something like it is surely necessary to derive any algorithm for computing digits of $\pi$. (Except, and this confuses me a bit, it seems that if we used the area definition of angle, we could derive an algorithm for computing sine without depending on this postulate, and from there we could get an algorithm for computing digits of $\pi$ since $\sin(\pi)=0$.)
I am looking in general for elucidation of the conceptual connections between the ideas I have so far discussed and of their background. But here are two more specific questions.
* First, in what sense is a postulate like Archimedes' needed in the foundations of geometry? (I wonder, in particular, if in a purely formal development we might get by without it, but we would somehow be left without assurance that what we had axiomatized was really geometry.) Also, are more intuitive alternatives to Archimedes' postulate?
* Second, what is really needed to get an algorithm for computing digits of sine? Does it really require such complicated technology as Taylor series? It seems like if one uses the area definition of angle, one might be able to give an algorithm using unexceptionable Euclidean techniques and without so much as invoking the notion of limit. | 2012/07/14 | [
"https://mathoverflow.net/questions/102246",
"https://mathoverflow.net",
"https://mathoverflow.net/users/18805/"
] | I made two corrections in your formula for $D.$ It is now consistent with the 1974 Acta Arithmetica paper.
Some examples. If $\alpha, \beta, \gamma$ are all $0,$ we have a quadratic form, which is required primitive. For positive forms, the proportion of primes represented is a constant times the full count of primes, this is Cebotarev density. See Theorem 9.12 on page 188 of David A. Cox, *Primes of the Form $x^2 + n y^2.$*
In comparison, $X^2 + Y^2 + 1$ represents a constant times $\frac{x}{( \log x )^{3/2}}$ primes up to $x.$ I was not aware of this. Note that this case was proved by [IWANIEC 1972](http://pldml.icm.edu.pl/mathbwn/element/bwmeta1.element.bwnjournal-article-aav21i1p203bwm?q=e38d3128-78b9-4500-a8fc-cae82bd63b64%241&qt=IN_PAGE) where the pdf can be downloaded. He does this special case and improves on estimates of Motohashi.
My understanding is that, for nondegenerate indefinite quadratic forms, that is $aX^2 + b XY + c Y^2$ with $\Delta = b^2 - 4 a c$ nonnegative but not zero or a square, the number of primes $p$ represented and the number of primes $q$ such that $-q$ is represented both obey a Cebotarev-like law. Franz would know details. I am taking primes as positive only. For example, $X^2 - 3 Y^2$ represents all (positive) primes $p \equiv 1 \pmod {12},$ and all $-q$ for positive primes $q \equiv 11 \pmod {12}.$
If, instead, I take a degenerate indefinite form as $X^2 - Y^2,$ I can represent all multiples of $4$ and all odd numbers. So the number of primes up to some positive bound $x$
is just the usual $\frac{x}{\log x}$ from the Prime Number Theorem, without any constant multiplier.
Finally, what happens with $X^2 + Y^2 + 2 X + 1$ or $X^2 - Y^2 + 2 X + 1?$ These can be rewritten with $(X+1)^2 = X^2 + 2 X + 1.$
So, overall, they are saying that two distinct cases give PNT times a constant, either degenerate (representing an entire arithmetic progression containing more than one prime) or a genuine nondegenerate quadratic form, which does not represent any arithmetic progression but may represent all primes in an arithmetic progression (such as $X^2 + Y^2$ and $4n+1,$ which behavior requires very small class number) but in any case follows a Cebotarev-like rule for primes.
As an example without arithmetic progressions, $x^2 + xy + 6 y^2$ and $2x^2 \pm xy + 3 y^2.$ Both represent only primes $23$ and $p$ that satisfy $(p|23) = 1.$ The first represents those for which $z^3 - z + 1$ has a root $\pmod p,$ accounting for $1/6$ of all primes in the long run, the latter pair of forms (both) represent the others, accounting for $1/3$ of all primes. Oh, $23$ itself is represented by the first one.
The other case is like $X^2 + Y^2 + 1,$ representing fewer primes but still infinite.
So, they have managed to put together a number of different cases with two constants. |
27,975,841 | I need to write in a pure JavaScript function which will execute only for 5 seconds and will stop if either one of the following conditions (whichever comes first)
1. 5 seconds has elapsed
2. user inputted a field
I could only do condition 2 but can't figure out how to break the loop after 5 seconds:
```
function beginScanningForItemVer2(){
var userInput= false;
var element;
while (!userInput){
element = document.getElementById("input").value;
if (element != null){
userInput= true;
}
}
}
```
EDIT:
Thanks guys for helping me. Please keep helping me...
It seems I cannot use a while loop for detecting user input because my CPU usage goes up really fast while on the loop. Is there any way to accomplish both of these? Please help me | 2015/01/16 | [
"https://Stackoverflow.com/questions/27975841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4459865/"
] | Javascript tends to be very callback oriented, since by default all the Javascript on a page runs in a single thread, which means that the UI isn't responsive while other code is busy running. So rather than looping in a function and looking for input on each loop, you likely want to register a callback function which will be called when your input element experiences a change -- for example, the `onchange` listener will run your callback whenever the value of the element changes. You could unregister this callback 5 seconds later to stop anything from happening if the user inputs something after the 5 seconds are up.
Sparse example (referencing <http://www.w3schools.com/jsref/event_onchange.asp>):
```
// Set a function to be called when the value of the input element changes.
object.onchange = function() {
valueAfterChange = document.getElementById("input").value;
// Do something with valueAfterChange.
}
// window.setInterval calls a function after a set delay.
window.setInterval(function() {
object.onchange = null;
// Anything else you might want to do after 5 seconds.
}, 5000); // Call this function after 5000 milliseconds == 5 seconds.
``` |
65,047,655 | I am following [this thread](https://stackoverflow.com/questions/7707074/creating-dynamic-button-with-click-event-in-javascript) which shows how to generate DOM elements dynamically.
Suppose I have this snippet that generate a series of buttons:
```
for(var i = 0; i < result.length;i++){
var menuCatButton = document.createElement("button");
menuCatButton.id = "menu-mgt-button-"+result[i];
menuMgtCategoryButtons.appendChild(menuCatButton);
}
```
How do I apply this set of style to all of the newly created buttons?
```
.new-button {
background-color: #4CAF50;
border: 1px solid;
color: white;
text-decoration: none;
display: inline-block;
font-size: 15px;
margin: 4px 20px;
cursor: pointer;
width: 120px;
height:50px;
white-space: normal;
}
.new-button:hover {
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);
}
``` | 2020/11/28 | [
"https://Stackoverflow.com/questions/65047655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10765455/"
] | You can add the class the element using `classList.add()`.
**Demo:**
```js
var result = [1,2];
var menuMgtCategoryButtons = document.getElementById('menuMgtCategoryButtons');
for(var i = 0; i < result.length;i++){
var menuCatButton = document.createElement("button");
menuCatButton.id = "menu-mgt-button-"+result[i];
menuCatButton.textContent = "Button "+result[i]; // add the text to the button
menuCatButton.classList.add('new-button'); // add the class to the button
menuMgtCategoryButtons.appendChild(menuCatButton);
}
```
```css
.new-button {
background-color: #4CAF50;
border: 1px solid;
color: white;
text-decoration: none;
display: inline-block;
font-size: 15px;
margin: 4px 20px;
cursor: pointer;
width: 120px;
height:50px;
white-space: normal;
}
.new-button:hover {
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24),0 17px 50px 0 rgba(0,0,0,0.19);
}
```
```html
<div id="menuMgtCategoryButtons"></div>
``` |
1,659,348 | `For example:`
Suppose we have an impulsive force $f(t)$ lasting from $t=t\_0$ until $t=t\_1$ which is applied to a mass $m$. Then by Newtons Second law we have $$\int\_{t=t\_0}^{t=t\_1}f(t)\,\mathrm{d}t=\int\_\color{red}{t=t\_0}^\color{red}{t=t\_1}m\color{blue}{\frac{\mathrm{d}v}{\mathrm{d}t}}\mathrm{d}t=\int\_\color{red}{v=v\_0}^\color{red}{v=v\_1}m\,\mathrm{d}v=m(v\_1-v\_0)\tag{1}$$
What I can't understand is; What substitution was made to allow the limits marked $\color{red}{\mathrm{red}}$ to change from $t$ to $v$.
I thought it might be due to $$\color{blue}{\frac{\mathrm{d}v}{\mathrm{d}t}}=\frac{\mathrm{d}v}{\mathrm{d}x}\cdot \underbrace{\frac{\mathrm{d}x}{\mathrm{d}t}}\_{\Large{\color{#180}{=v}}}=v\frac{\mathrm{d}v}{\mathrm{d}x}$$ by the chain rule.
But it is something much simpler than this, and I believe I am over-thinking it too much. Could someone please tell me what substitution was made to change the limits marked $\color{red}{\mathrm{red}}$ in equation $(1)$?
---
Edit:
-----
Comments below seem to indicate that one can simply change the limits of integration to make the integral dimensionally correct. But I consider this to be a less rigorous approach, and I was taught that integral limits **must** be changed via a substitution. So I still need to know what substitution was made?
Thanks again. | 2016/02/17 | [
"https://math.stackexchange.com/questions/1659348",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/144533/"
] | The fundamental reason to change the limits of integration is that
the *variable* of integration has changed.
Substitution is an obvious case in which this is likely to occur.
For example, substitute $u = x - 2$ in $\int (x - 2) dx$:
$$
\int\_0^2 (x - 2) dx = \int\_{-2}^0 u\; du.
$$
The intuition I follow on this is that the start of the integral occurs
"when $x=0$" and ends "when $x=2$".
But "when" $x=0$, it must also be true that $u=-2$,
and "when" $x=2$, it must also be true that $u=0$.
So *in terms of $u$,* the integral needs to start
"when $u=-2$" and end "when $u=0$".
A more rigorous treatment would take $x - 2$ as a function over
the domain $[0,2]$ and transform it; but transforming the function
also transforms its domain, so $x - 2$ over the domain $[0,2]$
transforms to $u$ over the domain $[-2,0]$.
*Anything* that changes the integration variable of a definite integral
also has to be reflected in the limits of integration,
because just as with any substitution, you're integrating a (possibly)
different function over a (possibly) different domain.
That is, if the integrand changes from $f(t)dt$ to $h(v)dv$
(even if $h(v)$ is a constant function, as it is in the question),
the integral over $v$ needs to start and end at $v$-values that are
correctly matched to the $t$-values at which the integral over $t$
started and ended.
---
Note that in any change of variables, regardless of whether we achieve it
by first writing down an explicit substitution formula (such as $u = x - 2$),
has to account for the derivative of the new variable of integration
with respect to the old one. For a substitution from $t$ to $u$ via the
equation $u = h(t)$, the derivative of the new w.r.t. the old is
$\dfrac{du}{dt} = h'(t)$
and it is accounted for in the rule
$$
\int g(h(t))\, h'(t)\, dt = g(u)\, du.
$$
As far as I know, a change of variables must not break this rule,
so there must somehow be a substitution $u = h(t)$ that can explain it.
In the integral in the question,
$f(t) = m \dfrac{d^2 x}{dt^2}$.
If $\dfrac{dx}{dt} = v = h(t)$
and if $g$ is the constant function with value $m$,
then $\dfrac{d^2 x}{dt^2} = \dfrac{dv}{dt} = h'(t)$ and $g(h(t)) = m$, so
$$
\int m \frac{dv}{dt} \, dt
= \int g(h(t))\, h'(t)\, dt
= \int g(v)\, dv = \int m \, dv.
$$
The definite integral follows the same rule but also has to make the
corresponding change to the interval of integration:
$$
\int\_{t\_0}^{t\_1} g(h(t))\, h'(t)\, dt
= \int\_{h(t\_0)}^{h(t\_1)} g(v)\, dv;
$$
setting $v\_0=h(t\_0)$ and $v\_1=h(t\_1)$,
$$
\int\_{t\_0}^{t\_1} m \frac{dv}{dt} \, dt
= \int\_{h(t\_0)}^{h(t\_1)} m \, dv
= \int\_{v\_0}^{v\_1} m \, dv.
$$ |
55,011,833 | Other people who have asked this question had answers about downloading Vim from Vim.org, but that website doesn't respond.
Are there other ways to use Vi on Windows? | 2019/03/05 | [
"https://Stackoverflow.com/questions/55011833",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10496528/"
] | Use a mutation observer to watch the list item instead of watching the document as a whole.
```js
// The item we want to watch
var watch = document.querySelector('.active')
// The new observer with a callback to execute upon change
var observer = new MutationObserver((mutationsList) => {
console.log(new Date().toUTCString())
});
// Start observing the element using these settings
observer.observe(watch, { childList: true, subtree: true });
// Some random test function to modify the element
// This will make sure the callback is running correctly
setInterval(() => {
watch.innerHTML = Math.random() * 1000
}, 1000)
```
```html
<ul>
<li class="active"></li>
</ul>
``` |
3,933,744 | When I closed MySql server, how can I understand that mysql server is gone away from my Qt program?
**Edit:**
Here my trial:
When I close MySql, I get these results, and I can't catch that MySql is closed.
My Code Snippet is
```
QSqlQuery query(db);
query.exec("SELECT * From RequestIds");
qDebug()<<query.lastError();
qDebug()<<db.lastError()<<QTime::currentTime();
qDebug()<<db.isOpen();
qDebug()<<db.isValid();
```
and output is:
```
QSqlError(2006, "QMYSQL: Unable to execute query", "MySQL server has gone away")
QSqlError(-1, "", "") QTime("14:22:58")
true
true
```
I don't understand why db.isOpen() returns true. | 2010/10/14 | [
"https://Stackoverflow.com/questions/3933744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/311762/"
] | There is a bug related with QSqlDatabase::isOpen() in Qt.
<https://bugreports.qt.io/browse/QTBUG-223> |
45,852,012 | So in this program, a user is able to create/specify a directory and create a file, given that the file doesn't exist already. when the user is entering a file name, they are required to enter a file extension as well. The problem I am having is how to make the code look for a file extension at the end of the string the user inputs. I went as far as checking for a "." but I am stuck on a way that the program can see if the file has a .json or .txt or anything AFTER the "."
TL;DR
How do I make the code check for a file extension at the end of a string a user has inputted (<- not a word)
Please note that the below code is not complete yet, the condition where I'm stuck at has a comment inside.
```
package filecreator.coolversion;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class FileCreatorCoolversion {
public static Scanner sc = new Scanner(System.in);
public static boolean success = false;
public static String filename;
public static String filedir;
public static File file;
public static File dir;
public static void main(String[] args) throws IOException {
System.out.println("********************************");
System.out.println("* Welcome to File Creator 2.0! *");
System.out.println("********************************");
System.out.println(" ");
while(!success) {
System.out.println("Would you like to create a file? Y/N?");
String usrans = sc.nextLine();
if(usrans.equalsIgnoreCase("y")) {
System.out.println("Proceeding with file creation...");
break;
} else if(usrans.equalsIgnoreCase("n")) {
System.out.println("Exiting Program...");
System.exit(0);
} else if(!usrans.equalsIgnoreCase("y") || !usrans.equalsIgnoreCase("n")) {
System.out.println("That is not a valid answer! Please try again!");
System.out.println(" ");
}
}
while(!success) {
System.out.println(" ");
System.out.println("Please enter a valid filename:");
filename = sc.nextLine();
if(filename.isEmpty()) {
System.out.println("Please enter a file name!");
break;
} else if(filename.contains("/") || filename.contains(":") ||
filename.contains("*") || filename.contains("?") ||
filename.contains("<") || filename.contains(">") ||
filename.contains("|") || filename.contains("\"") ||
filename.contains("\\")) {
System.out.println("Please do not include / \\ : * ? \" < > |");
} else if(!filename.contains(".")) {
System.out.println("Please add a apropriate file extensions");
} else if (filename.) {
//HERE IS WHERE IM STUCK
} else {
System.out.println(" ");
System.out.println("File name \"" + filename + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Where would you like to have your file saved?");
System.out.println("Please enter a valid directory");
while(!success) {
filedir = sc.nextLine();
if(!filename.contains(":")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else if(!filename.contains("\\")) {
System.out.println(" ");
System.out.println("Please enter a valid directory!");
} else {
System.out.println("File directory \"" + filedir + "\" chosen");
break;
}
}
System.out.println(" ");
System.out.println("Creating file...");
}
```
} | 2017/08/24 | [
"https://Stackoverflow.com/questions/45852012",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4902004/"
] | Any selector-only solution requires you to make assumptions about your markup that may or may not be within your control since the specificity of two contextual selectors is always the same regardless of how close the ancestor is to each descendant that is matched, and any solution that makes use of inheriting the actual properties themselves requires you to apply them to the `.red`, `.yellow` and `.blue` sections, which may not be desired. For example, you'd have to apply `background-color` to the sections in order for `background-color: inherit` to work on the descendants, but you may not want the sections themselves to have any background color, so that won't be an option to you.
Custom properties allow descendants to inherit values from their closest ancestors without polluting other properties in this manner, and without other cascading rules getting in the way (competing rules with equally specific contextual selectors, etc). You'll only be able to do this reliably with custom properties for this reason.
```css
.red {
--color: red;
}
.yellow {
--color: yellow;
}
.blue {
--color: blue;
}
input, article, p {
background-color: var(--color);
}
```
```html
<section class="yellow">
<section class="blue">
<form>
<input type="button" value="This should use the blue theme" />
</form>
</section>
<section class="red">
<article>
<p>This should use the red theme</p>
</article>
</section>
<section class="yellow">
<nav>
<p>This should use the yellow theme</p>
</nav>
</section>
<p>This should be yellow.</p>
</section>
``` |
24,774,890 | I am using Codeigniter and I have a function like this .
```
function total_income(){
$data['total_income'] = $this->mod_products->total_income();
echo"<pre>";
print_r($data['total_income']);
}
```
The above code return an array like this.
```
Array
(
[0] => stdClass Object
(
[sub_product_price] => 1000
[quantity] => 1
)
[1] => stdClass Object
(
[sub_product_price] => 1000
[quantity] => 1
)
[2] => stdClass Object
(
[sub_product_price] => 50
[quantity] => 15
)
[3] => stdClass Object
(
[sub_product_price] => 500
[quantity] => 5
)
)
```
Now I want to get the `[sub_product_price]` and **multiply** that value with `[quantity]` .Then I want to get the `array_sum`. I don't have an idea how to do that. Could some one help me It would be grate ,
Cheers!! Rob | 2014/07/16 | [
"https://Stackoverflow.com/questions/24774890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3766509/"
] | ```
$sum = 0;
foreach ($array as $obj) {
$sum += ($obj->quantity * $obj->sub_product_price);
}
``` |
36,688,254 | My question maybe unheard of or may even be impractical.
But, I believe it is practical and acceptable.
**Problem: PHP request and response in background thread.**
Problem constraints:
1. You know it uses POST method.
2. It has two fields fname and lname as html ids that need to be filled.
3. You get response in the same page i.e. index.php .
Pseudocode to solve the problem:
1. Open the website in background. Something like openURL("xyz(dot)com");
2. Read the data sent in html format.
3. Change the value of the fields fname and lname to required fields "Allen" and "Walker."
4. Now, submit the fields back to the server. ( Page has a submit button.)
**Note:** PHP code has a standard if-else check to check for those values. If the field is properly set, it then says "Success" else "Failed"
5. Again, get the response sent by the server.
6. Check if "Success" was returned.
7. If "success" was returned, UPDATE UI thread for saying "JOB done".
Else, "Job failed."
**Note: I am not talking about using a** *WebView*. **Everything happens via a service or AsyncTask**.
---
Now, this is a simple question, and any ideas or a direction is acceptable.
**So, to recap. You have to open a webpage in background, change its field, submit it back and then get the response.**
---
I know we can open a website and get its content. But, I would also like to know if what I said is possible or not. And, I know it is possible. And, that I only lack the knowledge on Java Web API, could you please guide me on this.
Thank You. And, Have a Good day! | 2016/04/18 | [
"https://Stackoverflow.com/questions/36688254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2298251/"
] | use [this link](http://www.androidhive.info/2012/01/android-json-parsing-tutorial/) for best solution of calling web service without using WebView.
In this example fname and lname sent in namevaluepairs we get responce in json formet and parse json and get data also json parse defined in examples. |
105,305 | quick question that's been bugging me lately. When it comes to a songs key specifically major and minor relatives- is it correct to say it can be written in two different keys with the same progression with the progression being written differently? I say this because a lot of times pop songs I see people post the progressions for, (usually 4 chord progressions that do not change during the song) some people list the major key and some list the minor key. For example lets use the song "Wake Me Up" -- A lot of people post the songs progression as a VI, IV, I, V and in the key of D. But other websites classify the song as in the key of Bm with the progression I, VI, III, VII.
My personal opinion would be that the song begins with Bm So I would say it's in the key of Bm following a I, VI, III, VII. If it had started on a D and modulated to Bm I'd say its in the key of D--- I'm I correct in saying this? Can you always class the song in two different keys since you can rewrite the progression differently but use the same chords? pls help :( | 2020/09/30 | [
"https://music.stackexchange.com/questions/105305",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/72239/"
] | The scale/chords are good clues to the key of a song, but at least as important is the *tonal center*. That's not as easy to define but generally it's where the song comes back to a place of less musical tension.
IMHO the chord played when the song in question returns to a "rest" state is A major. Which means I would say the song is in A and the progression is ii - bVII - IV - I. That would suggest that the scale is actually A mixolydian (not pure major or minor), which is not unusual for rock.
The point is that the key of a song is not only about the scale. Learning to hear the tonal center is sometimes more important. |
239,209 | On OS from win 2000 or later (any language) can I assume that this path will always exists?
For example I know that on win xp in some languages the "Program Files" directory have a different name.
So is it true for the System32 folder?
Thanks.
Ohad. | 2008/10/27 | [
"https://Stackoverflow.com/questions/239209",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17212/"
] | You definitely cannot assume that: Windows could be installed on a different drive letter, or in a different directory. On a previous work PC Windows was installed in D:\WINNT, for example.
The short answer is to use the API call GetSystemDirectory(), which will return the path you are after.
The longer answer is to ask: do you really need to know this? If you're using it to copy files into the Windows directory, I'd suggest you ask if you really want to do this. Copying into the Windows directory is not encouraged, as you can mess up other applications very easily. If you're using the path to find DLLs, why not just rely on the OS to find the appropriate one without giving a path? If you're digging into bits of the OS files, consider: is that going to work in future? In general it's better to not explicitly poke around in the Windows directory if you want your program to work on future Windows versions. |
44,951,581 | I have a requirement where in the function takes different parameters and returns unique objects. All these functions perform the same operation.
ie.
```
public returnObject1 myfunction( paramObject1 a, int a) {
returnObject1 = new returnObject1();
returnObject1.a = paramObject1.a;
return returnObject1;
}
public returnOject2 myfunction( paramObject2 a, int a){
returnObject2 = new returnObject2();
returnObject2.a = paramObject2.a;
return returnObject2;
}
```
As you can see above, both the function do the same task but they take different parameters as input and return different objects.
I would like to minimize writing different functions that does the same task.
Is it possible to write a generic method for this that can substitute the parameters based on the call to the function?
paramObject and returnObject are basically two classes that have different variables. They are not related to each other.
My objective is that I do not want to do function overloading since the functions do almost the same work. I would like to have a single function that can handle different input and different return output.
my aim is to do something like this (if possible):
```
public static < E > myfunction( T a, int a ) {
// do work
}
```
The return type E and the input T can keep varying. | 2017/07/06 | [
"https://Stackoverflow.com/questions/44951581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6512806/"
] | Make `interface Foo` and implement this `interface` in both `paramObject1` and `paramObject2` class. Now your method should be look like:
```
public Foo myFunction(Foo foo, int a){
//Rest of the code.
return foo;
}
``` |
37,723,804 | I have to search a contact by name, surname or telephone number.
how can i do that?
I think i can't use java 8 stream in this case...
Another thing... I have to press "2" two times in order to see all the contact list but the if implementation seems right to me.
The code:
```
import java.util.ArrayList;
import java.util.Scanner;
public class Test1 {
public static void main(String args[]) {
Scanner in = new Scanner( System.in );
ArrayList<Contatto> cont = new ArrayList<Contatto>();
int a;
try{
while (true){
System.out.println("Per inserire nuovo contatto premere 1");
System.out.println("Per visionare l'elenco dei contatti premere 2");
System.out.println("Per cercare un contatto premere 3");
a= in.nextInt();
//if you press1 you add new contact
if (a == 1){
cont.add(new Contatto());
}
//if you press2 you'll see all the contact list.
else if (a == 2){
for (Contatto tmp : cont){
String tm = tmp.dammiDettagli(tmp);
System.out.println(tm);
}
}
//if you press 3 you'll be able to search a contact by name or
//surname or telephone number
else if (a == 3){
System.out.println("Cerca contatto:");
}
else {
System.out.println("Inserimento dati errato");
}
}
}finally {
in.close();
}
}
}
```
and this is the public class Contatto:
```
import java.util.Scanner;
public class Contatto {
private String nome;
private String cognome;
private String num_Tel;
Contatto(){
@SuppressWarnings("resource")
Scanner in = new Scanner( System.in );
System.out.println("Creazione nuovo contatto...");
System.out.println("Inserire il nome:");
//set name
setNome(in.next());
System.out.println("Inserire il cognome:");
//set surname
setCognome(in.next());
System.out.println("Inserire il numero di telefono:");
//set telephone number
setNum_Tel(in.next());
}
//method to search contact
public String cercaContatto(String in){
}
public String dammiDettagli(Contatto contatto){
return getNome() +" "+ getCognome() +" "+ getNum_Tel();
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public String getNum_Tel() {
return num_Tel;
}
public void setNum_Tel(String num_Tel) {
this.num_Tel = num_Tel;
}
}
``` | 2016/06/09 | [
"https://Stackoverflow.com/questions/37723804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6444835/"
] | This could be done in Java 8 as next:
```
Optional<Contatto> result = cont.stream().filter(c ->
(nome == null || nome.equalsIgnoreCase(c.getNome()))
&& (cognome == null || cognome.equalsIgnoreCase(c.getCognome()))
&& (num_Tel == null || num_Tel.equals(c.getNum_Tel()))
).findFirst();
```
Assuming that `nome`, `cognome` and `num_Tel` are `String` representing your query's criteria.
If `nome`, `cognome` and `num_Tel` are `Optional<String>` representing your query's criteria, it will then be:
```
Optional<Contatto> result = cont.stream().filter(c ->
nome.map(s -> s.equalsIgnoreCase(c.getNome())).orElse(true)
&& cognome.map(s -> s.equalsIgnoreCase(c.getCognome())).orElse(true)
&& num_Tel.map(s -> s.equals(c.getNum_Tel())).orElse(true)
).findFirst();
``` |
11,276,112 | Does anyone know if its possible to add specific files uncompressed to a Android APK file during the ANT build process using build.xml? All my files live in the *assets* folder and use the same extension. I do realise that i could use a different extension for the files that i don't want to be added compressed and specify, for example:
```
<nocompress extension="NoCompress" />
```
but this currently isn't an option for me.
I tried adding my own *aapt add* step after the *appt package* step in the *package-resource* section in *build.xml*:
```
<exec executable="${aapt}" taskName="add">
<arg value="add" />
<arg value="-v" />
<arg value="${out.absolute.dir}/TestAndroid.ap_" />
<arg value="${asset.absolute.dir}/notcompressed.and" />
</exec>
```
Which did add the file to the APK but it was compressed. :)
Is this possible or is a different extension the only way?
Thanks! | 2012/06/30 | [
"https://Stackoverflow.com/questions/11276112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1184595/"
] | Have a look [here](http://ponystyle.com/blog/2010/03/26/dealing-with-asset-compression-in-android-apps/)
>
> The only way (that I’ve discovered, as of this writing) to control
> this behavior is by using the -0 (zero) flag to aapt on the command
> line. This flag, passed without any accompanying argument, will tell
> aapt to disable compression for all types of assets. Typically you
> will not want to use this exact option, because for most assets,
> compression is a desirable thing. Sometimes, however, you will have a
> specific type of asset (say, a database), that you do not want to
> apply compression to. In this case, you have two options.
>
>
> First, you can give your asset file an extension in the list above.
> While this does not necessarily make sense, it can be an easy
> workaround if you don’t want to deal with aapt on the command line.
> The other option is to pass a specific extension to the -0 flag, such
> as -0 db, to disable compression for assets with that extension. You
> can pass the -0 flag multiple times, and each time with a separate
> extension, if you need more than one type to be uncompressed.
>
>
> Currently, there is no way to pass these extra flags to aapt when
> using the ADT within Eclipse, so if you don’t want to sacrifice the
> ease of use of the GUI tools, you will have to go with the first
> option, and rename your file’s extension.
>
>
> |
62,043,889 | When I tried to use keras to build a simple autoencoder, I found something strange between keras and tf.keras.
```
tf.__version__
```
2.2.0
```
(x_train,_), (x_test,_) = tf.keras.datasets.mnist.load_data()
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = x_train.reshape((len(x_train), 784))
x_test = x_test.reshape((len(x_test), 784)) # None, 784
```
The original picture
```
plt.imshow(x_train[0].reshape(28, 28), cmap='gray')
```
[enter image description here](https://i.stack.imgur.com/J8xc0.png)
```
import keras
# import tensorflow.keras as keras
my_autoencoder = keras.models.Sequential([
keras.layers.Dense(64, input_shape=(784, ), activation='relu'),
keras.layers.Dense(784, activation='sigmoid')
])
my_autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
my_autoencoder.fit(x_train, x_train, epochs=10, shuffle=True, validation_data=(x_test, x_test))
```
training
```
Train on 60000 samples, validate on 10000 samples
Epoch 1/10
60000/60000 [==============================] - 7s 112us/step - loss: 0.2233 - val_loss: 0.1670
Epoch 2/10
60000/60000 [==============================] - 7s 111us/step - loss: 0.1498 - val_loss: 0.1337
Epoch 3/10
60000/60000 [==============================] - 7s 110us/step - loss: 0.1254 - val_loss: 0.1152
Epoch 4/10
60000/60000 [==============================] - 7s 110us/step - loss: 0.1103 - val_loss: 0.1032
Epoch 5/10
60000/60000 [==============================] - 7s 110us/step - loss: 0.1010 - val_loss: 0.0963
Epoch 6/10
60000/60000 [==============================] - 7s 109us/step - loss: 0.0954 - val_loss: 0.0919
Epoch 7/10
60000/60000 [==============================] - 7s 109us/step - loss: 0.0917 - val_loss: 0.0889
Epoch 8/10
60000/60000 [==============================] - 7s 110us/step - loss: 0.0890 - val_loss: 0.0866
Epoch 9/10
60000/60000 [==============================] - 7s 110us/step - loss: 0.0870 - val_loss: 0.0850
Epoch 10/10
60000/60000 [==============================] - 7s 109us/step - loss: 0.0853 - val_loss: 0.0835
```
the decoded image with keras
```
temp = my_autoencoder.predict(x_train)
plt.imshow(temp[0].reshape(28, 28), cmap='gray')
```
[enter image description here](https://i.stack.imgur.com/BUR8Q.png)
So far, everything is as normal as expected, but something is weird when I replaced keras with tf.keras
```
# import keras
import tensorflow.keras as keras
my_autoencoder = keras.models.Sequential([
keras.layers.Dense(64, input_shape=(784, ), activation='relu'),
keras.layers.Dense(784, activation='sigmoid')
])
my_autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')
my_autoencoder.fit(x_train, x_train, epochs=10, shuffle=True, validation_data=(x_test, x_test))
```
training
```
Epoch 1/10
1875/1875 [==============================] - 5s 3ms/step - loss: 0.6952 - val_loss: 0.6940
Epoch 2/10
1875/1875 [==============================] - 5s 3ms/step - loss: 0.6929 - val_loss: 0.6918
Epoch 3/10
1875/1875 [==============================] - 5s 3ms/step - loss: 0.6907 - val_loss: 0.6896
Epoch 4/10
1875/1875 [==============================] - 5s 3ms/step - loss: 0.6885 - val_loss: 0.6873
Epoch 5/10
1875/1875 [==============================] - 5s 3ms/step - loss: 0.6862 - val_loss: 0.6848
Epoch 6/10
1875/1875 [==============================] - 5s 3ms/step - loss: 0.6835 - val_loss: 0.6818
Epoch 7/10
1875/1875 [==============================] - 5s 3ms/step - loss: 0.6802 - val_loss: 0.6782
Epoch 8/10
1875/1875 [==============================] - 5s 3ms/step - loss: 0.6763 - val_loss: 0.6737
Epoch 9/10
1875/1875 [==============================] - 5s 3ms/step - loss: 0.6714 - val_loss: 0.6682
Epoch 10/10
1875/1875 [==============================] - 5s 3ms/step - loss: 0.6652 - val_loss: 0.6612
```
the decoded image with tf.keras
```
temp = my_autoencoder.predict(x_train)
plt.imshow(temp[0].reshape(28, 28), cmap='gray')
```
[enter image description here](https://i.stack.imgur.com/wNey4.png)
I can't find anything wrong, does anyone know why? | 2020/05/27 | [
"https://Stackoverflow.com/questions/62043889",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9909121/"
] | The true culprit is the default learning rate used by [`keras.Adadelta`](https://github.com/keras-team/keras/blob/master/keras/optimizers.py#L401) vs [`tf.keras.Adadelta`](https://github.com/tensorflow/tensorflow/blob/r2.2/tensorflow/python/keras/optimizer_v2/adadelta.py#L63): `1` vs `1e-4` - see below. It's true that `keras` and `tf.keras` implementations differ a bit, but difference in results can't be as dramatic as you observed (only in a different configuration, e.g. learning rate).
You can confirm this in your original code by running `print(model.optimizer.get_config())`.
```py
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow.keras as keras
(x_train, _), (x_test, _) = tf.keras.datasets.mnist.load_data()
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = x_train.reshape((len(x_train), 784))
x_test = x_test.reshape((len(x_test), 784)) # None, 784
###############################################################################
model = keras.models.Sequential([
keras.layers.Dense(64, input_shape=(784, ), activation='relu'),
keras.layers.Dense(784, activation='sigmoid')
])
model.compile(optimizer=keras.optimizers.Adadelta(learning_rate=1),
loss='binary_crossentropy')
model.fit(x_train, x_train, epochs=10, shuffle=True,
validation_data=(x_test, x_test))
###############################################################################
temp = model.predict(x_train)
plt.imshow(temp[0].reshape(28, 28), cmap='gray')
```
```py
Epoch 1/10
1875/1875 [==============================] - 4s 2ms/step - loss: 0.2229 - val_loss: 0.1668
Epoch 2/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.1497 - val_loss: 0.1337
Epoch 3/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.1253 - val_loss: 0.1152
Epoch 4/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.1103 - val_loss: 0.1033
Epoch 5/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.1009 - val_loss: 0.0962
Epoch 6/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.0952 - val_loss: 0.0916
Epoch 7/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.0914 - val_loss: 0.0885
Epoch 8/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.0886 - val_loss: 0.0862
Epoch 9/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.0865 - val_loss: 0.0844
Epoch 10/10
1875/1875 [==============================] - 3s 2ms/step - loss: 0.0849 - val_loss: 0.0830
```
![](https://i.stack.imgur.com/doQTX.png) |
17,357,665 | I have **two tables** for one is `category` and another one is `sub-category`. that two table is assigned to `FK` for many table. In some situation we will move one record of **sub-category** to **main category**. so this time occur constraints error because that **key** associated with other table. so i would not create this **schema**.
so now i plan to **create category** and **sub-category** in same table and **create relationship table** to make relationship between them.
`category table:`
```
id(PK,AUTO Increment),
item===>((1,phone),(2.computer),(3,ios),(4,android),(5,software),(6,hardware)).
```
`relationship table:`
```
id,cate_id(FK),
parentid(refer from category table)===>((1,1,0),(2,2,0),(3,3,1),
(4,4,1),(5,5,2),(5,5,3)).
```
in my side wouldnot go hierarchy level more than three.
if we easily move to subcategory to main category `ex:(4,4,1) to (4,4,0)` without affect any other table. is this good procedure?
if we will maintain millions record, will we face any other problem in future?
have any another idea means let me know? | 2013/06/28 | [
"https://Stackoverflow.com/questions/17357665",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1089410/"
] | There might be a problem if you have multiple levels in the tree, and want to find all the subcategories of any category. This would require either multiple queries, or a recursive one.
You could instead look into the ["Nested Sets"](http://www.codeproject.com/Articles/4155/Improve-hierarchy-performance-using-nested-sets) data-structure. It supports effective querying of any sub-tree. It does have a costly update, but updates probably won't happen very often. If need be, you could batch the updates and run them over night.
```
create table Category (
Id int not null primary key auto_increment,
LeftExtent int not null,
RightExtent int not null,
Name varchar(100) not null
);
create table PendingCategoryUpdate (
Id int not null primary key auto_increment,
ParentCategoryId int null references Category ( Id ),
ParentPendingId int null references PendingCategoryUpdate ( Id ),
Name varchar(100) not null
);
```
---
If you have a small number of categories, a normal parent reference should be enough. You could even read the categories into memory for processing.
```
create table Category (
Id int not null primary key auto_increment,
ParentId int null references Category ( Id ),
Name varchar(100) not null
);
-- Just an example
create table Record (
Id int not null primary key auto_increment,
CategoryId int not null references Category ( Id )
);
select *
from Record
where CategoryId in (1, 2, 3); -- All the categories in the chosen sub-tree
``` |
35,317,633 | I'm trying to write what must be the simplest angular directive which displays a Yes/No select list and is bound to a model containing a boolean value. Unfortunately the existing value is never preselected. My directive reads
```
return {
restrict: 'E',
replace: true,
template: '<select class="form-control"><option value="true">Yes</option><option value="false">No</option></select>',
scope: {
ngModel: '='
}
}
```
and I am calling the directive as
```
<yesno ng-model="brand.is_anchor"></yesno>
```
The select options display and the generated HTML reads as
```
<select class="form-control ng-isolate-scope ng-valid" ng-model="brand.is_anchor">
<option value="? boolean:false ?"></option>
<option value="true">Yes</option>
<option value="false">No</option>
</select>
```
The initial value of the bound model is "false" but it always displays an empty option and per the first option listed in the generated HTML.
Can anybody please advise? | 2016/02/10 | [
"https://Stackoverflow.com/questions/35317633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1298045/"
] | There is no need for a custom sentinel image, or messing with the network. See my [redis-ha-learning](https://github.com/asarkar/spring/tree/master/redis-ha-learning) project using [Spring Data Redis](https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#reference), [bitnami/redis](https://hub.docker.com/r/bitnami/redis) and [bitnami/redis-sentinel](https://hub.docker.com/r/bitnami/redis-sentinel) images. The Docker Compose file is [here](https://github.com/asarkar/spring/blob/master/redis-ha-learning/redis-sentinel.yaml).
My code auto detects the sentinels based on the Docker Compose container names. |
319,327 | ![enter image description here](https://i.stack.imgur.com/MW1Mt.jpg)
This problem has bothered me for quite some time and I can't solve it. I have even tried to make a construction, but it sometimes tips to the left and sometimes tips to the right :).
When we submerge the body in the water the water pushes it up. That is an action. At the same time the body pushes water down. That is a reaction. So the balance should be maintained.
But, since the water level rises the hydrostatic pressure on the bottom is greater so the right side should go down.
There is another similar problem but it's not the same.
Please help. | 2017/03/16 | [
"https://physics.stackexchange.com/questions/319327",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/145936/"
] | The balance will be maintained because there is no EXTERNAL force applied on left or right side. This is because of the same reason you can't push a car while sitting in it! |
11,878,292 | i want to find out total number of android APIs (Classes and Methods) used in my android application source code. but i want to do it programmatically. can any one suggest me how can i do so??
Thanks in Advance | 2012/08/09 | [
"https://Stackoverflow.com/questions/11878292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/631803/"
] | You can do it with [Reflections API](http://code.google.com/p/reflections/).
You can get the list of classes using the following code :
```
Reflections ref = new Reflections("package_name");
Set<Class<?>> classes = ref.getSubTypesOf(Object.class);
```
Then by using the [Class.getDeclaredMethods()](http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getDeclaredMethods%28%29) or [Class.getMethods()](http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#getMethods%28%29) you can get the list of methods. |
47,678,197 | I tried asking this question before but was it was poorly stated. This is a new attempt cause I haven't solved it yet.
I have a dataset with winners, losers, date, winner\_points and loser\_points.
For each row, I want two new columns, one for the winner and one for the loser that shows how many points they have scored so far (as both winners and losers).
Example data:
```
winner <- c(1,2,3,1,2,3,1,2,3)
loser <- c(3,1,1,2,1,1,3,1,2)
date <- c("2017-10-01","2017-10-02","2017-10-03","2017-10-04","2017-10-05","2017-10-06","2017-10-07","2017-10-08","2017-10-09")
winner_points <- c(2,1,2,1,2,1,2,1,2)
loser_points <- c(1,0,1,0,1,0,1,0,1)
test_data <- data.frame(winner, loser, date = as.Date(date), winner_points, loser_points)
```
I want the output to be:
```
winner_points_sum <- c(0, 0, 1, 3, 1, 3, 5, 3, 5)
loser_points_sum <- c(0, 2, 2, 1, 4, 5, 4, 7, 4)
test_data <- data.frame(winner, loser, date = as.Date(date), winner_points, loser_points, winner_points_sum, loser_points_sum)
```
How I've solved it thus far is to do a for loop such as:
```
library(dplyr)
test_data$winner_points_sum_loop <- 0
test_data$loser_points_sum_loop <- 0
for(i in row.names(test_data)) {
test_data[i,]$winner_points_sum_loop <-
(
test_data %>%
dplyr::filter(winner == test_data[i,]$winner & date < test_data[i,]$date) %>%
dplyr::summarise(points = sum(winner_points, na.rm = TRUE))
+
test_data %>%
dplyr::filter(loser == test_data[i,]$winner & date < test_data[i,]$date) %>%
dplyr::summarise(points = sum(loser_points, na.rm = TRUE))
)
}
test_data$winner_points_sum_loop <- unlist(test_data$winner_points_sum_loop)
```
Any suggestions how to tackle this problem? The queries take quite some time when the row numbers add up. I've tried elaborating with the AVE function, I can do it for one column to sum a players point as winner but can't figure out how to add their points as loser.
[![This is the end result (except last column)](https://i.stack.imgur.com/gEdxT.jpg)](https://i.stack.imgur.com/gEdxT.jpg) | 2017/12/06 | [
"https://Stackoverflow.com/questions/47678197",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5434602/"
] | ```
winner <- c(1,2,3,1,2,3,1,2,3)
loser <- c(3,1,1,2,1,1,3,1,2)
date <- c("2017-10-01","2017-10-02","2017-10-03","2017-10-04","2017-10-05","2017-10-06","2017-10-07","2017-10-08","2017-10-09")
winner_points <- c(2,1,2,1,2,1,2,1,2)
loser_points <- c(1,0,1,0,1,0,1,0,1)
test_data <- data.frame(winner, loser, date = as.Date(date), winner_points, loser_points)
library(dplyr)
library(tidyr)
test_data %>%
unite(winner, winner, winner_points) %>% # unite winner columns
unite(loser, loser, loser_points) %>% # unite loser columns
gather(type, pl_pts, winner, loser, -date) %>% # reshape
separate(pl_pts, c("player","points"), convert = T) %>% # separate columns
arrange(date) %>% # order dates (in case it's not)
group_by(player) %>% # for each player
mutate(sum_points = cumsum(points) - points) %>% # get points up to that date
ungroup() %>% # forget the grouping
unite(pl_pts_sumpts, player, points, sum_points) %>% # unite columns
spread(type, pl_pts_sumpts) %>% # reshape
separate(loser, c("loser", "loser_points", "loser_points_sum"), convert = T) %>% # separate columns and give appropriate names
separate(winner, c("winner", "winner_points", "winner_points_sum"), convert = T) %>%
select(winner, loser, date, winner_points, loser_points, winner_points_sum, loser_points_sum) # select the order you prefer
# # A tibble: 9 x 7
# winner loser date winner_points loser_points winner_points_sum loser_points_sum
# * <int> <int> <date> <int> <int> <int> <int>
# 1 1 3 2017-10-01 2 1 0 0
# 2 2 1 2017-10-02 1 0 0 2
# 3 3 1 2017-10-03 2 1 1 2
# 4 1 2 2017-10-04 1 0 3 1
# 5 2 1 2017-10-05 2 1 1 4
# 6 3 1 2017-10-06 1 0 3 5
# 7 1 3 2017-10-07 2 1 5 4
# 8 2 1 2017-10-08 1 0 3 7
# 9 3 2 2017-10-09 2 1 5 4
``` |
47,902,057 | I have a text as follows.
```
mytext = "This is AVGs_ABB and NMN_ABB and most importantly GFD_ABB This is so important that you have to CLEAN the lab everyday"
```
I want to convert it to lowercase, except the words that has `_ABB` in it.
So, my output should look as follows.
```
mytext = "this is AVGs_ABB and NMN_ABB and most importantly GFD_ABB this is so important that you have to clean the lab everyday"
```
My current code is as follows.
```
splits = mytext.split()
newtext = []
for item in splits:
if not '_ABB' in item:
item = item.lower()
newtext.append(item)
else:
newtext.append(item)
```
However, I want to know if there is any easy way of doing this, possibly in one line? | 2017/12/20 | [
"https://Stackoverflow.com/questions/47902057",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | You can use a one liner splitting the string into words, check the words with `str.endswith()` and then join the words back together:
```
' '.join(w if w.endswith('_ABB') else w.lower() for w in mytext.split())
# 'this is AVGs_ABB and NMN_ABB and most importantly GFD_ABB this is so important that you have to clean the lab everyday'
```
Of course use the `in` operator rather than `str.endswith()` if `'_ABB'` can actually occur anywhere in the word and not just at the end. |