qid
int64 1
74.7M
| question
stringlengths 0
70k
| date
stringlengths 10
10
| metadata
list | response
stringlengths 0
115k
|
---|---|---|---|---|
218,076 |
Is an infinite topological direct sum of amenable Banach algebras amenable again?
Can you give me a good reference about this notion?
Thanks
|
2015/09/11
|
[
"https://mathoverflow.net/questions/218076",
"https://mathoverflow.net",
"https://mathoverflow.net/users/27066/"
] |
The OP has now clarified that he or she is asking about $c\_0$-direct sums. To answer the question we need the notion of the amenability constant of a Banach algebra. Everything that follows is probably "folklore", in the sense that
(i) Johnson knew how to do it in 1972 but, due to the different culture at the time of mathematical publication, did not bother formally writing it down in his 1972 monograph *Cohomology in Banach Algebras* or his Amer J. Math article of the same year;
(ii) successive generations of researchers, who take seriously the study of amenability of Banach algebras, will *almost surely* have worked these results out for themselves during their own studies.
Actually, this result might also be somewhere in Runde's book, but I haven't checked. (**UPDATE 2015-11-10:** Tomasz Kania has pointed out that this is Corollary 2.3.19 in Runde's *Lectures on Amenability*.)
**Definition.** Given an amenable Banach algebra $B$, the amenability constant of $B$ is defined to be
$${\rm AM}(B):=\inf \{ \Vert M \Vert\_{(B\widehat\otimes B)^{\*\*}}\;\; \colon \;\;\hbox{$M$ is a virtual diagonal for $B$}\}. $$
(By weak-star compactness, the infimum is actually attained.) We adopt the convention that if $B$ is a non-amenable Banach algebra, ${\rm AM}(B)=+\infty$.
*Remark 1.*
It is an easy exercise to show that if $q:A\to B$ is a surjective homomorphism of Banach algebras then ${\rm AM}(B)\leq \Vert q\Vert^2{\rm AM}(A)$.
**Lemma 2.** Suppose $A$ is a Banach algebra and $(B\_i)\_{i\in \Lambda}$ is a family of closed subalgebras such that $\bigcup\_{i\in\Lambda} B\_i$ is dense in $A$. Then ${\rm AM}(A)\leq \sup\_{i\in\Lambda} {\rm AM}(B\_i)$.
Note that since closed subalgebras of ${\bf M}\_2({\mathbb C})$ can be non-amenable, the inequality in this lemma is usually not an equality.
*Outline of the proof of Lemma 2.* We may assume the RHS of the inequality is finite, bounded above by $C$ say; otherwise there is nothing to prove. Consider $(M\_i)\_{i\in\Lambda}$ where $M\_i$ is a virtual diagonal for $B\_i$ such that ${\rm AM}(B\_i)=\Vert M\_i \Vert$. Then $(M\_i)$ is a net in $(A\widehat{\otimes} A)^{\*\*}$, bounded by $C$; take any weak-star cluster point $M$. Then $\Vert M\Vert\leq C$ and one can check $M$ is indeed a virtual diagonal for $A$. **QED.**
**Lemma 3.**
Let $A\_1$ and $A\_2$ be Banach algebras, and let $B=A\_1\oplus\_\infty A\_2$ i.e. with the norm $\Vert (a\_1,a\_2)\Vert := \max (\Vert a\_1\Vert, \Vert a\_2\Vert)$.
Then ${\rm AM}(B)= \max \{{\rm AM}(A\_1), {\rm AM}(A\_2)\}$.
*Proof of lemma 3.* Since there are contractive, surjective algebra homomorphisms $q\_j:B\to A\_j$ ($j=1,2$) we have ${\rm AM}(B)\geq \max \{{\rm AM}(A\_1), {\rm AM}(A\_2)\}$ by Remark 1. Conversely, using the contractive embedding
$$ (A\_1\widehat\otimes A\_1) \oplus\_\infty (A\_2\widehat\otimes A\_2) \to (A\_1\oplus\_\infty A\_2)\widehat\otimes(A\_1\oplus\_\infty A\_2) $$
and the corresponding embedding at the level of biduals, we can combine a virtual diagonal $M\_1$ for $A\_1$ and a virtual diagonal $M\_2$ for $A\_2$ to get a virtual diagonal $M$ for $A$, which satisfies $\vert M \Vert \leq \max( \Vert M\_1\Vert, \Vert M\_2\Vert)$. **QED.**
**Proposition.** Let $(A\_n)\_{n=1}^\infty$ be a sequence of Banach algebras, and let $A=c\_0{\rm-}\bigoplus\_{n=1}^\infty A\_n$. Then
${\rm AM}(A) = \sup\_n {\rm AM}(A\_n) <\infty$.
*Proof that LHS ≥ RHS.* This is like the proof of Lemma 2, using the contractive surjective homomorphisms $A\to A\_n$ for $1\leq n\leq\infty$, and I omit the details.
*Proof that LHS ≤ RHS.* Let $C=\sup\_n {\rm AM}(A\_n)$; we may assume $C<\infty$, otherwise there is nothing to prove. Now let $B\_n = A\_1 \oplus \dots \oplus A\_n$. By Lemma 3 and induction we know that ${\rm AM}(B\_n)\leq C$, for each $n$. Since $\bigcup\_{n\geq 1} B\_n$ is dense in $A$, applying Lemma 2 completes the proof. **QED.**
---
**OLD answer, before the question was clarified**
Tomek Kania has already pointed out the key "counterexample" (assuming that by infinite topological direct sum you mean what I would call the $\ell^\infty$-direct sum).
I should also point out that there are commutative counterexamples. Indeed, let $A={\ell^\infty}{\rm-}\bigoplus \ell^1({\bf T}\_d)$ where ${\bf T}\_d$ denotes the unit circle equipped with the discrete topology, and the multiplication on $\ell^1({\bf T}\_d)$ is given by convolution. Then, as observed in e.g. Proposition 5.8 of <http://arxiv.org/abs/0708.4195> $A$ quotients onto $M(G\_0)$ where $G\_0$ is the Bohr compactificaton of ${\bf T}\_d$.
If $A$ were weakly amenable, then $M(G\_0)$ would be weakly amenable; but by results of Brown and Moran $M(G\_0)$ has non-zero point derivations, hence is not weakly amenable. Therefore $A$ is not weakly amenable, and in particular cannot be amenable.
|
46,179,420 |
I need, to clear my chartViewers from a layout, but when I do, I can't delete the last widget.
when I test the length of my layout, I get 0 but the widget is still here after update of the layout, as in the picture :
[](https://i.stack.imgur.com/dG8xb.png)
here my code when I delete, the widgets and the graphs
```
print("proceding to delete chart ", chartName, " at : ", indexGraph)
currentGraph = self.charts[indexGraph]
currentWidget = self.chartVs[indexGraph]
self.chartLayout.removeWidget(currentWidget)
self.chartVs.remove(currentWidget)
currentGraph.clearData()
self.charts.remove(currentGraph)
self.chartLayout.update()
#currentWidget.resetCachedContent()
listGraphs.remove(chartName)
self.refreshListWithOpt(self.chartTree, listGraphs, 1, optGraphs)
```
and here is the code where I create the graphs and add it to the layout:
```
self.charts.append(chartClass(patientStr, exp))
print("\nNew Plot chart ", self.charts[lastIndex].name, " length : ", lastIndex )
listGraphs.append(self.charts[lastIndex].name)
print("list Graphs : ", listGraphs)
self.charts[lastIndex].plotJSON(myData.plot(patientStr, exp))
self.chartVs.append(QChartView(self.charts[lastIndex]))
self.chartVs[lastIndex].setRenderHint(QPainter.Antialiasing)
self.chartLayout.insertWidget(0, self.chartVs[lastIndex])
```
Any suggestion?
|
2017/09/12
|
[
"https://Stackoverflow.com/questions/46179420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8264778/"
] |
Here is a [link](http://blogs.adatis.co.uk/jonathoneveoconnor/post/Continuous-Integration-With-TeamCity-Automating-SSIS-Build-and-Deployment) that describes the auto-deployment of packages post check-in into SSISDB catalog. If you have SSIS 2012+ then that would be a way to go. Even if not you would need to modify the target to msdb/SSIS file system.
Coming to your second ask, deploy to SQL Agent. You would need to write another build step to do that step of automation. Make use of [T-SQL code](https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-add-jobstep-transact-sql) and add the package name as a parameter and have it deployed. The thing to remember about this is that SQL Agent job can have numerous job steps doing various tasks.
Say if you are deploying 10 packages of project and your requirement demands that all ten to be part of one SQL Server Agent Job, then design your T-SQL Code accordingly. If you need 10 seperate jobs for these packages then your code needs to do that in that manner.
I would strongly advice doing this as a one-time job. If you have the auto-deployment to create Agent when the package gets changed thereby needing to re-create the job, then you would be losing job history.
|
27,123,304 |
I have come across some unit tests written by another developer that regularly use an overloaded version of `Assert.AreEqual` like so:
```
Assert.AreEqual(stringparamX, stringParamY, true, CultureInfo.InvariantCulture);
```
`stringParamX` is set within the unit test and `stringparamY` will be the result from the system under test.
It is possible hat this code may be ported to other countries and these tests may be executed. However, on having a look at the [MSDN docs for Culture](http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.invariantculture.aspx), I can't help thinking that passing in `CultureInfo.InvariantCulture` is adding some unnecessary complexity here. I'm not sure what kind of impact removing it would have on the tests if executed in other cultures.
In the context of unit testing in my situation, why should I (or not) write asserts like this?
|
2014/11/25
|
[
"https://Stackoverflow.com/questions/27123304",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402421/"
] |
There is no reason to use that overload if you are specifying the culture as `InvariantCulture`, because that is the default.
From [the documentation here](http://msdn.microsoft.com/en-us/library/ms243448.aspx):
>
> The invariant culture is used for the comparison.
>
>
>
Note that there ARE some cases where it would make a difference if you weren't using the `InvariantCulture`, the most notorious being ["The Turkish I problem"](http://haacked.com/archive/2012/07/05/turkish-i-problem-and-why-you-should-care.aspx/).
The following code illustrates the issue:
```
Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR");
Assert.AreEqual("i", "I", true, CultureInfo.CurrentCulture); // This throws.
Assert.AreEqual("i", "I", true, CultureInfo.InvariantCulture); // This doesn't throw.
Assert.AreEqual("i", "I", true); // This doesn't throw.
```
However, note that you will not be affected by that because you are using the invariant culture.
|
10,353,275 |
I'm building out a decommissioning application that will allow an individual to provide an computer name and the utility will go out and purge the computer record from various locations. I'm running into a problem when attempting to delete a computer account from Active Directory. I'm impersonating a service account that only has rights to "Delete All Child Objects" within a particular OU structure. The code below works if I run it with my domain admin account; however fails with an "Access Denied" when I run it with the impersonated service account. I have verified that the permissions are correct within AD as I can launch Active Directory Users and Computers using a "runas" and providing the service account credentials and I can delete computer objects perfectly fine.
Wondering if anyone has run into this before or has a different way to code this while still utilizing my current OU permissions. My gut tells me the "DeleteTree" method is doing more then just deleting the object.
Any assistance would be appreciated.
```
Sub Main()
Dim strAsset As String = "computer9002"
Dim strADUsername As String = "[email protected]"
Dim strADPassword As String = "password"
Dim strADDomainController As String = "domaincontroller.domain.com"
Dim objDirectoryEntry As New System.DirectoryServices.DirectoryEntry
Dim objDirectorySearcher As New System.DirectoryServices.DirectorySearcher(objDirectoryEntry)
Dim Result As System.DirectoryServices.SearchResult
Dim strLDAPPath As String = ""
Try
objDirectoryEntry.Path = "LDAP://" & strADDomainController
objDirectoryEntry.Username = strADUsername
objDirectoryEntry.Password = strADPassword
objDirectorySearcher.SearchScope = DirectoryServices.SearchScope.Subtree
objDirectorySearcher.Filter = "(&(ObjectClass=Computer)(CN=" & strAsset & "))"
Dim intRecords As Integer = 0
For Each Result In objDirectorySearcher.FindAll
Console.WriteLine(Result.Path)
Diagnostics.Debug.WriteLine("DN: " & Result.Path)
Dim objComputer As System.DirectoryServices.DirectoryEntry = Result.GetDirectoryEntry()
objComputer.DeleteTree()
objComputer.CommitChanges()
intRecords += 1
Next
If intRecords = 0 Then
Console.WriteLine("No Hosts Found")
End If
Catch e As System.Exception
Console.WriteLine("RESULT: " & e.Message)
End Try
End Sub
```
|
2012/04/27
|
[
"https://Stackoverflow.com/questions/10353275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1361341/"
] |
If you're on .NET 3.5 and up, you should check out the `System.DirectoryServices.AccountManagement` (S.DS.AM) namespace. Read all about it here:
* [Managing Directory Security Principals in the .NET Framework 3.5](http://msdn.microsoft.com/en-us/magazine/cc135979.aspx)
* [MSDN docs on System.DirectoryServices.AccountManagement](http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.aspx)
Basically, you can define a domain context and easily find users and/or groups in AD:
```
' set up domain context
Dim ctx As New PrincipalContext(ContextType.Domain, "DOMAIN", strADUsername, strADPassword)
' find a computer
Dim computerToDelete As ComputerPrincipal = ComputerPrincipal.FindByIdentity(ctx, strAsset)
If computerToDelete IsNot Nothing Then
' delete the computer, if found
computerToDelete.Delete()
End If
```
The new S.DS.AM makes it really easy to play around with users and groups in AD!
|
21,841,551 |
I have to show all products that contain the word "Transducer" in them. I CANNOT use LIKE. I have tried using contain and I get a invalid relational operator error. I've tried everything I can think of and nothing is working. I'm using SQL Developer 4.
Code:
```
SELECT product_name, name
FROM a_product p JOIN a_item i
ON p.product_id=i.product_id
JOIN a_sales_order so ON i.order_id=so.order_id
JOIN a_customer c ON so.customer_id=c.customer_id
```
Output:
```
PRODUCT_NAME NAME
------------------------------ ---------------------------------------------
Aft Transducer Just Electronics
75 Gauge Wire Line Timelines
Aft Transducer Vollyrite
Nts Transducer Every Mountain
Snyder Lock Switch Shape Up
Nts Transducer Shape Up
Sft Transducer 55 Vollyrite
75 Gauge Wire Line Shape Up
```
I also as I mentioned tried to use contains, but it gave me the error. This is what I used:
```
WHERE contains(product_name, 'Transducer')
```
Which I added after the join statements.
The desired output would look like this:
```
PRODUCT_NAME NAME
------------------------------ ---------------------------------------------
Aft Transducer Just Electronics
Aft Transducer Vollyrite
Nts Transducer Every Mountain
Nts Transducer Shape Up
Sft Transducer 55 Vollyrite
```
|
2014/02/17
|
[
"https://Stackoverflow.com/questions/21841551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2250600/"
] |
If you can't use LIKE because it's a problem for school, an alternative is REGEXP\_LIKE:
```
SELECT product_name, name
FROM a_product p
JOIN a_item i
ON p.product_id = i.product_id
JOIN a_sales_order so
ON i.order_id = so.order_id
JOIN a_customer c
ON so.customer_id = c.customer_id
where regexp_like(product_name, 'Transducer')
```
|
74,271,442 |
Is it easy for people to find "public" google sheets/docs?
Context: Storing some semi-sensitive data (individual user info, of non-sensitive nature) for an app beta-test in google sheets. Planning to migrate to some DB in the future, but for now, just using JavaScript to pull the data directly from the google sheets (since there are visualizations being dynamically updated by the sheets).
|
2022/11/01
|
[
"https://Stackoverflow.com/questions/74271442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12634149/"
] |
Yes, it's easy to get information. Search engines may index and cache the information. Then, there are bots, crawlers and scrapers. Do NOT put (semi)sensitive information in public. Implement [google-oauth](/questions/tagged/google-oauth "show questions tagged 'google-oauth'") properly with [google-sheets-api](/questions/tagged/google-sheets-api "show questions tagged 'google-sheets-api'") to get information. You can also use [service-accounts](/questions/tagged/service-accounts "show questions tagged 'service-accounts'")
|
4,228,044 |
I am reading a [paper](https://arxiv.org/abs/1602.07868) on weight normalization authored by Salimans & Kingma. In this paper, the gradient is split into two parts where $g$ is the norm of $w$ and $v$ is the direction of gradient, the gradient of $v$ calculated as
$$\nabla\_v L = \frac{g}{\|v\|} M \nabla\_wL$$
where $ M := I - \frac{ww^T}{\|w\|^2} $
>
> Because $\Delta v \propto \nabla\_vL (\text{steepest descent/ascent})$, then $\Delta v$ is >necessarily orthogonal to weight $w$ since $M$ project it away from calculating $\nabla\_v L$.
>
>
>
I dont quite get this sentence, why $\Delta v$ must 'necessarily' orthogonal to weight $w$?
Is projection matrix $M$ any special form?
|
2021/08/19
|
[
"https://math.stackexchange.com/questions/4228044",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/809733/"
] |
Note that if $p(x)$ is the characteristic polynomial of $A$, then the characteristic polynomial of $A^{-1}$ is $x^n p(\frac 1x)/\det A$; therefore a necessary condition is that $x^n p(\frac 1x) = p(x) \det A$.
Note also that if $A$ is diagonalizable, then the condition that the reciprocal of every eigenvalue of $A$ is also an eigenvalue of $A$ (respecting multiplicity) is both sufficient and necessary. One can dispense with the diagonalizability assumption if one is willing to consider the blocks in the Jordan canonical form of $A$.
|
22,407,326 |
I have a subclass of NSManagedObject on which there's a "currency" attribute. This attribute is a 3 letters string. When I change it from "USD" to "CAD", and then call `changedValues` on the object, changedValues returns an empty dictionary. Is that the normal behaviour?
I save the managedObjectContext first, then change the attribute, then call changedValues.
This attribute is: not transient, optional, not indexed, no default value.
EDIT: Thx for the help guys I found a bug in my code. Now it works just fine.
|
2014/03/14
|
[
"https://Stackoverflow.com/questions/22407326",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3250560/"
] |
I found a bug in my code. Now it works just fine. ;)
I was using a delegate method to update the object from another viewController. When coming back from that viewController I saved the managedObjectContext in `viewWillAppear` which basically erased the changedValues.
|
32,896,020 |
this is my first question on here so ill try and be as detailed as possible! I am currently creating a HTML form with a select option with options 1 - 4. My aim is to use a Javascript function to create a certain amount of div's depending on which value the user has selected from the form.
For example, if the user has selected option 2, i want to auto generate 2 div containers. Then, if the user chooses to select another option after... the correct amount of divs will then be created.
My select HTML currently looks like this;
```
<select id="select_seasons">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
```
I have created a script which will create a div on button click but this isn't my aim;
```
var number = 2;
document.getElementById('add').addEventListener('click', function(
) {
var newDiv = document.createElement('div');
newDiv.id = 'container';
newDiv.innerHTML = "<label>Episode " + number + " name</label> <input type='text' name='episode'" + number +" /> <label>Episode " + number + " embed</label> <input type='text' /> ";
document.getElementById('contain_form').appendChild(newDiv);
number++;
});
```
I would appreciate it if somebody was to help me with the JS i will need to make this functionality and i hope i've explained myself clearly enough in this post!
Feel free to comment and ask for me details if required.
Thanks in advance,
Sam
|
2015/10/01
|
[
"https://Stackoverflow.com/questions/32896020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5397172/"
] |
You need to bind the `change` event on your `select` element. Something like this:
```js
var divs = [];
document.getElementById('select_seasons').addEventListener('change', function(e) {
var n = +this.value;
for (var i = 0; i < divs.length; i++) {
divs[i].remove();
}
divs = [];
for (var i = 0; i < n; i++) {
var d = document.createElement("div");
d.className = "new";
document.body.appendChild(d);
divs.push(d);
}
});
```
```css
.new {
background-color: red;
width: 100px;
height: 20px;
margin: 1px;
}
```
```html
<select id="select_seasons">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
```
|
1,590,901 |
Prove the inequality:
$$\left(1+\dfrac{1}{\sin a}\right)\left(1+\dfrac{1}{\cos a}\right)\ge 3+2\sqrt{2}; \text{ for } a\in\left]0,\frac{\pi}{2}\right[$$
|
2015/12/27
|
[
"https://math.stackexchange.com/questions/1590901",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/296768/"
] |
By the AM-GM inequality, $$\dfrac{1}{\cos a}+\dfrac{1}{\sin a} \geq 2 \sqrt{\dfrac{1}{\sin a\cos a}}$$
Since $\sin a \cos a = \frac12 \sin(2a) \leq \frac12$, we have $\dfrac{1}{\sin a\cos a}\geq 2$.
Hence $$\left(1+\dfrac{1}{\sin a}\right)\left(1+\dfrac{1}{\cos a}\right) = 1+\dfrac{1}{\cos a}+\dfrac{1}{\sin a}+\dfrac{1}{\sin a\cos a} \\\geq 1+2\sqrt{\dfrac{1}{\sin a\cos a}}+\dfrac{1}{\sin a\cos a}\geq 1+2\sqrt{2} + 2 = 3+ 2\sqrt{2}$$
|
542,428 |
Can anyone identify this connector?
Female part:
[](https://i.stack.imgur.com/iTFuz.jpg)
[](https://i.stack.imgur.com/gnLI1.jpg)
[](https://i.stack.imgur.com/TLYcc.jpg)
[](https://i.stack.imgur.com/7mL0m.jpg)
The crimp parts look like this:
[](https://i.stack.imgur.com/ZYDU8.jpg)
And the male part looks like this:
[](https://i.stack.imgur.com/SYFKi.jpg)
Context:
These came with a Smoothieboard v1.1. I keep messing up the crimp connections, so I want to order some spare connectors. The documentation does not seems to identify them. If there's any sort of site that has a directory of connector types, that would be good to know too.
|
2021/01/13
|
[
"https://electronics.stackexchange.com/questions/542428",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/200654/"
] |
It looks like a “Molex” 4-position connector. It seems to be part connector series “2695” (if you look up ‘Molex 2695’, you get plenty of results). If you go to Molex’s page directly for that part, they even provide a nice “Mates with/use with” section detailing the corresponding headers / crimps / pre-crimped leads).
Here is a link for what I think you want:
[Molex 4-Position female connector](https://www.molex.com/molex/products/part-detail/crimp_housings/0022012041)
|
697,526 |
I want to set up a source code control system that:
1. is networked, so users can access it at work or on the road
2. does not need to provide sharing, lock mode is sufficient
3. there will be only three users and they will never be working with the same code
4. we have no system administrator and not much knowledge in that area so the set up and config must be dead simple.
5. will be installed on a Windows server
6. open source or free
Suggestions please.
|
2009/03/30
|
[
"https://Stackoverflow.com/questions/697526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24989/"
] |
the *SIMPLEST* system is what we here call the "Hey Chris" system. We have a networked drive that everyone can mount, and if you want to edit something you shoud "Hey, Chris, are you working on blahblah.cpp?" and Chris says "Nope." and then you edit blahblah.cpp, and stick it back on the shared drive... If you want versions, just back up the networked drive every night.
I never said it was the BEST system, just the simplest.
|
25,049,968 |
In my localhost (with xammp) CakePHP works fine. After I completed my project and uploaded to my host, it gives me this error:
```
cakephp: Fatal error: Class 'appModel' not found in .../app/Model/Slider.php
```
Model class was called in AppController and AppModel.php (App::uses('appModel', 'Model')) & all is fine in my localhost!
When I am trying to change php version, it gives me the same error, but in php 5.2 doesn't show anything but error, in php5.3, php5.4 and php5.5 it give me the error in the layout (call menus, footer... etc all but data !!
My CakePHP version 2.5.2
I don't do any change or coding inside AppModel and I think that I don't do any change in lib files or something like that.
what is the problem exactly?
|
2014/07/31
|
[
"https://Stackoverflow.com/questions/25049968",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3829518/"
] |
For Python2.7, Use `io.open()` in both locations.
```
import io
import shutil
with io.open('/etc/passwd', encoding='latin-1', errors='ignore') as source:
with io.open('/tmp/goof', mode='w', encoding='utf-8') as target:
shutil.copyfileobj(source, target)
```
The above program runs without errors on my PC.
|
9,999,500 |
I am writing a simple game in XNA where you move a sprite around using WSAD. The problem is if two keys of the same direction are pressed at the same time, the movement cancels out and the character does not move. Is it possible to manually set a key to released to avoid this? Here is the key movement code:
```
if (newKeyState.IsKeyDown(Keys.W))
{
position.Y -= vel;
}
if (newKeyState.IsKeyDown(Keys.S))
{
position.Y += vel;
}
if (newKeyState.IsKeyDown(Keys.A))
{
position.X -= vel;
}
if (newKeyState.IsKeyDown(Keys.D))
{
position.X += vel;
}
```
|
2012/04/03
|
[
"https://Stackoverflow.com/questions/9999500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1150769/"
] |
I had a similar issue a little while back and was able to solve it by changing my IE9 settings. The main things I find that tend to break WatiN are compatibility mode and protected mode. Turn these off. For Protected mode you have to turn it off for each security level.
Not sure if this is the issue but thought I should mention it just in case!
|
32,105,834 |
I want to add an "Always-On-Top"-menuentry to the system menu of all windows (the menu which opens when you right click the titlebar or click the icon). I'd prefer C# or C++, but if worst comes to worst I'll also use VB...
I know there are some applications like Dexpot which do this, but I was unable to find useful source code or free applications which do this for all windows and not just their own.
I also know that there are other ways to achieve this functionality (AutoHotkeys or small programs which live in the system tray and let you select windows which should stay on top), but I'm looking for a more fluent and intuitive way. Ideally I'd add a small pin button to the titlebar, but my guess is that that's much more involved, so I'll stick with the menu variant for now.
Ideas? Thanks!
|
2015/08/19
|
[
"https://Stackoverflow.com/questions/32105834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2061551/"
] |
Use the `AddMenuItems()` method and test using MS-Paint. One thing I noticed is that after the program is closed, the modified system menu becomes wonky. Possibly this is because the events are not coming from the process' UI thread. A possible work-around is in the `ApplicationExit` event to call `GetMenu(hMainWindowHandle, true)`, where true means revert the menu.
```
public static class AlwaysOnTop {
static AlwaysOnTop() {
Application.ApplicationExit += delegate {
try {
foreach (DictionaryEntry de in htThreads) {
Hook h = (Hook) de.Value;
RemoveMenu(h.hMenu, h.uniqueId, 0);
//DeleteMenu(h.hMenu, h.uniqueId, 0);
UnhookWinEvent(h.hWinEventHook);
}
} catch {
}
};
}
private const int EVENT_OBJECT_INVOKED = 0x8013;
private const int OBJID_SYSMENU = -1;
private const int WINEVENT_OUTOFCONTEXT = 0;
private const int MF_STRING = 0x00000000;
private const int HWND_TOPMOST = -1;
private const int HWND_NOTOPMOST = -2;
private const int SWP_NOMOVE = 0x0002;
private const int SWP_NOSIZE = 0x0001;
private const uint MF_UNCHECKED = 0x00000000;
private const uint MF_CHECKED = 0x00000008;
[DllImport("user32.dll")]
private static extern IntPtr GetSystemMenu(IntPtr hWnd, bool bRevert);
[DllImport("user32.dll")]
private static extern bool AppendMenu(IntPtr hMenu, uint uFlags, uint uIDNewItem, String lpNewItem);
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.dll",SetLastError=true)]
private static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventProc lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);
[DllImport("user32.dll", SetLastError = true)]
internal static extern int UnhookWinEvent(IntPtr hWinEventHook);
[DllImport("user32.dll", SetLastError=true)]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
private static extern bool CheckMenuItem(IntPtr hMenu, uint uIDCheckItem, uint uCheck);
[DllImport("user32.dll")]
private static extern bool RemoveMenu(IntPtr hMenu, uint uPosition, uint uFlags);
//[DllImport("user32.dll")]
//private static extern bool DeleteMenu(IntPtr hMenu, uint uPosition, uint uFlags);
private static Hashtable htThreads = new Hashtable();
private static WinEventProc CallWinEventProc = new WinEventProc(EventCallback);
private delegate void WinEventProc(IntPtr hWinEventHook, int iEvent, IntPtr hWnd, int idObject, int idChild, int dwEventThread, int dwmsEventTime);
private static void EventCallback(IntPtr hWinEventHook, int iEvent, IntPtr hWnd, int idObject, int idChild, int dwEventThread, int dwmsEventTime) {
//callback function, called when message is intercepted
if (iEvent == EVENT_OBJECT_INVOKED) {
if (idObject == OBJID_SYSMENU) {
Hook h = (Hook) htThreads[(uint) dwEventThread];
if (h != null && h.uniqueId == idChild) {
bool b = !h.Checked;
if (b)
SetWindowPos(h.hMainWindowHandle, (IntPtr) HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
else
SetWindowPos(h.hMainWindowHandle, (IntPtr) HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE | SWP_NOMOVE);
CheckMenuItem(h.hMenu, h.uniqueId, (b ? MF_CHECKED : MF_UNCHECKED));
h.Checked = b;
}
}
}
}
private class Hook {
public uint uniqueId = 1001;
public IntPtr hWinEventHook;
public IntPtr hMenu;
public IntPtr hMainWindowHandle;
public bool Checked;
}
public static void AddMenuItems() {
Process[] arr = Process.GetProcesses();
foreach (Process p in arr) {
if (p.MainWindowHandle == IntPtr.Zero)
continue;
if (p.ProcessName != "mspaint") // <-- remove or change this line
continue;
IntPtr hMenu = GetSystemMenu(p.MainWindowHandle, false);
if (hMenu == IntPtr.Zero)
continue;
bool b = AppendMenu(hMenu, MF_STRING, 1001, "Always On Top");
uint pid = 0;
uint tid = GetWindowThreadProcessId(p.MainWindowHandle, out pid);
Hook h = (Hook) htThreads[tid];
if (h == null) {
h = new Hook();
h.hMenu = hMenu;
h.hWinEventHook = SetWinEventHook(EVENT_OBJECT_INVOKED, EVENT_OBJECT_INVOKED, IntPtr.Zero, CallWinEventProc, pid, tid, WINEVENT_OUTOFCONTEXT);
h.hMainWindowHandle = p.MainWindowHandle;
htThreads[tid] = h;
}
}
}
}
```
|
15,921,574 |
I build a worklight application. create android app and test this application with local machine , its working fine with emulator.but when i try to test this application with android tablet it through error "The Application failed connecting to the service".
I try to find application-descriptor.xml and fix localhost to `192.168.1.1:8080`
my ip local machine,but it not working.In my tablet I can't to go to `192.168.1.1:8080/console/index.html`
Can anybody help me regarding this issue. how can i fix this one in my worklight android application and run it on my android tablet
|
2013/04/10
|
[
"https://Stackoverflow.com/questions/15921574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2265231/"
] |
Some things to check:
- Are your tablet and your worklight development machine on the same wireless network? (they need to be!)
- Does your computer have a firewall on it which may need configuring to let the traffic through. As a test you could briefly disable the firewall and see if you then have access (subject to disclaimer of the risk involved in disabling the firewall). A test without disabling the firewall would be to try accessing 192.168.1.1:8080 from another desktop/laptop machine on that same subnet.
|
30,346,744 |
I am preparing for an Oracle examination and answered incorrectly to the following question:
>
> the combination abstract private is legal for inner classes
>
>
>
As it turns the answer is true, I answered false, as I could not find any use cases for having an abstract private inner class, that cannot be overridden from subclasses. Can someone explain, why/for what do we have that in the language?
|
2015/05/20
|
[
"https://Stackoverflow.com/questions/30346744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3194545/"
] |
The Java language specification defines the meaning of private members as follows:
>
> Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.
>
>
>
That is, a private inner class is accessible (and may be subclassed) from any code residing in the same source file. For instance, you could do:
```
public class C {
private abstract class A {
abstract void foo();
}
void bar() {
new A() {
@Override void foo() {
// do something
}
}
}
}
```
It is interesting to note that a method declared private can not be overriden, but methods in private classes can be.
|
58,340,926 |
I am trying to use a custom element in my application but after upgrading to the current version of lit-element, I can't seem to find the replacement function for **\_didRender**. I have tried **firstUpdated** and **connectedCallback** with no success. What should I do. The code renders but after rendering and amking an ajax call, I expected the render to be updated but it doesnt
```
import {LitElement, html} from 'lit-element';
import '@material/mwc-formfield/mwc-formfield.js';
import '@material/mwc-checkbox/mwc-checkbox.js'
import '@polymer/iron-ajax/iron-ajax.js';
class FhirActiveStatus extends LitElement{
static get properties() {
return {
/**activeStatus is used to show active status of person true or false. Use this property to show/hide. Default: true */
activeStatus: {type:Boolean},
/**url is used to make AJAX call to FHIR resource. Default: null */
url: {type:String},
/**value is used to take the input value of each field*/
value: {type:Boolean}
}
}
/**default value of properties set in constructor*/
constructor() {
super();
this.activeStatus = 'true';
this.value = false;
}
/**_didRender() was used here after the ajax call had been made*/
async firstUpdated() {
this.shadowRoot.getElementById('ajax').addEventListener('iron-ajax-response', function (e) {
var active = this.parentNode.host;
if (e.detail.response.active) {
active.shadowRoot.querySelector('.activeState').checked = true;
}
else if (!e.detail.response.active) {
active.shadowRoot.querySelector('.activeState').checked = false;
}
else {
this.parentNode.removeChild(this.parentNode.querySelector('#activeDiv'));
}
});
}
render() {
return html`
<div id="activeDiv">
${this.activeStatus !== 'false' ? html`<mwc-formfield class="activeStatus" alignEnd label="ACTIVE STATUS:">
<mwc-checkbox id="active" checked="${this.value}" class="activeState" @click="${e => this.value = e.target.value}"></mwc-checkbox>
</mwc-formfield>` : ''}
</div>
<iron-ajax auto id="ajax" bubbles auto handle-as="json" url="${this.url}"></iron-ajax>
`;
}
}
window.customElements.define('fhir-active-status', FhirActiveStatus);
```
|
2019/10/11
|
[
"https://Stackoverflow.com/questions/58340926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10471519/"
] |
have a look at the LitElement life cycle <https://lit-element.polymer-project.org/guide/lifecycle>
\_didRender() i believe now is **updated()**
|
49,864,528 |
I am trying to automate docx report generation process. For this I am using java and docx4j. I have a template document containing only single page.I would like to copy that page modify it and save it in another docx document.The output report is of multiple similar pages with modification from the template. How do I go about it.
PS : java and docx4j are my first choice but I am open to solutions apart from java and docx4j.
|
2018/04/16
|
[
"https://Stackoverflow.com/questions/49864528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5958785/"
] |
Leaving it up to you to modify the template, here is how you could add one document to the end of another document. Suppose `base.docx` contains "This is the base document." and `template.docx` contains "The time is:", then after executing this code:
```
WordprocessingMLPackage doc = Docx4J.load(new File("base.docx"));
WordprocessingMLPackage template = Docx4J.load(new File("template.docx"));
MainDocumentPart main = doc.getMainDocumentPart();
Br pageBreak = Context.getWmlObjectFactory().createBr();
pageBreak.setType(STBrType.PAGE);
main.addObject(pageBreak);
for (Object obj : template.getMainDocumentPart().getContent()) {
main.addObject(obj);
}
main.addParagraphOfText(LocalDateTime.now().toString());
doc.save(new File("result.docx"));
```
Then `result.docx` will contain something like:
```none
This is the base document.
^L
The time is:
2018-04-16T17:37:13.541984200
```
(Where ^L represents a page break.)
|
2,317,677 |
I am developing the smart device application. There are different screen resolution for different window mobile devices. I want to know that which is the standard screen resolution for windows mobile?
|
2010/02/23
|
[
"https://Stackoverflow.com/questions/2317677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/265103/"
] |
There is no standard.
Many possibilities exist and the recent devices usually have 800x480. Others have: 640x480, 320x240, 320x320, 400x240, etc.
|
69,828,385 |
App.jsx
```
import * as React from 'react';
import * as ReactDOM from 'react-dom';
function render() {
ReactDOM.render(<h2>Hello from React!</h2>, document.body);
}
render();
```
So, right now my friend made a React website that I have to try to port over to an Electron App that I got off of the team's Github. However, when I change the code into this:
App.jsx
```
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import App from './App';
function render() {
ReactDOM.render(<h1>Goodbye</h1>, document.body);
}
render();
```
Nothing changes at all. All that pops up is the "Hello from React!" from earlier. I search throughout all my code files for any other instances of "Hello from React!" with vscode, but I do not see any. Does anyone know why this is happening and what I can do to fix it?
|
2021/11/03
|
[
"https://Stackoverflow.com/questions/69828385",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13948708/"
] |
Ok, so the answer was adding this environment variable :
```
JAVA_OPTS_APPEND=-javaagent:{{path_to_elastic_apm_agent}}
```
this command allows you to launch your java application with options.
|
25,199,553 |
```
text = ['This', 'brand', 'she', 'quenched', 'in', 'a', 'cool', 'well', 'by', 'Which', 'from', 'Love', "'", 's', 'fire']
```
When I do a `' '.join(text)` I get the result;
"This brand she quenched in a cool well by Which from Love ' s fire"
I would like to join "Love ' s" as "Love's" instead of separating them. How can I do that along with the `' '.join(text)`?
|
2014/08/08
|
[
"https://Stackoverflow.com/questions/25199553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1948860/"
] |
You can run a replace after joining. (Replace `" ' "` with `"'"`)
```
' '.join(text).replace(" ' ", "'")
```
|
27,369,502 |
I'm trying to make a vertical social share buttons for a blog post.
-------------------------------------------------------------------
I want the "share\_DIV" position to be fixed after scrolling to a
certain point.
* because the "Share\_DIV" is not supposed to appear on header area, its
position will be absolute and calculated by *jQuery* to let it be under
`*the header*` and `*the title*`, then when you scroll down and reach the text body "share\_DIV" should **start** walking with you while scrolling down to the end of the text body.
So the **share\_DIV** should move vertically on the scroll event, only between START POINT -> END POINT
*share\_DIV has class `.vertical-container` in fiddle code.*
[Fiddle Example](http://jsfiddle.net/markor91/h5t7pgfb/25/) will explain exactly what I need.
How can I get it done with jQuery?
|
2014/12/09
|
[
"https://Stackoverflow.com/questions/27369502",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1015648/"
] |
You don't need to initialize it with a specific size - you can add objects later:
```
NSMutableArray *myArray = [NSMutableArray array];
for (int i = 0; i < 100; i++) {
[myArray addObject:someData];
}
```
There are slight performance gains if you know the size ahead of time:
```
NSMutableArray *myArray = [NSMutableArray arrayWithCapacity:100];
```
But this is optional.
|
214,687 |
I'm looking for a library to save an array of colour data to a PNG file. (That's all there is to it, right? I know very little about the internals of a PNG.)
This is for use in Nintendo DS development, so something lightweight is preferable. I don't need any other fancy features like rotation, etc.
|
2008/10/18
|
[
"https://Stackoverflow.com/questions/214687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55/"
] |
To encode any kind of PNG file, libpng is the way of the walk.
However, on small devices like the DS you really want to store your image data in the format which the display hardware expects. It is technically possible to get libpng working on the platform, but it will add significant overhead, both in terms of loadtimes and footprint.
|
50,247,580 |
I have a keyword like "Click Menu Item" which takes an argument `${menuItem}`.It then clicks on the corresponding menu item making a dynamic locator xpath.
I need to define/set the `LocatorVariables` and their Xpaths in separate `Locators.robot` resource file so that my testcases/keywords are xpaths free.
```
** Keywords ***
Click Menu Item
[Arguments] ${menuItem}
Click Element ${MenuBarLeft_MenuItem}
```
So I want to accept the variable `${menuItem}` in a Global Scope so that it will be accessible in `Locators.robot` Resource file.
Though, I understand this can be achieved by using below:
```
"Set Global Variable ${menuItem} ${menuItem}"
```
but i wanted to know is there an way I can skip this step by automatic defining the scope while accepting the variable in keyword.
Also please let me know if there is a better way to handle dynamic locators for such case.
|
2018/05/09
|
[
"https://Stackoverflow.com/questions/50247580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9340007/"
] |
You should use `object` name in template:
```
{% block content %}
<h3>{{ object.title }}</h3>
<h6> on {{ object.datetime }}</h6>
<div class = "code">
{{ object.content|linebreaks }}
</div>
{% endblock %}
```
Or if you want to use `Tutorial` variable, you need to pass `context_object_name=Tutorials` to the view:
```
path('<int:pk>', DetailView.as_view(
model=Tutorials,
template_name="tutorials/post.html",
context_object_name='Tutorials')),
```
|
22,156,030 |
i accessing google cloud storage by blobstore api, I would like to generate file names automatically instead of create it in the server.
actually i want to do that, because it is hard to me to create a unique file name every time the user upload file.
thank you
|
2014/03/03
|
[
"https://Stackoverflow.com/questions/22156030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3376321/"
] |
If you are using Python you can simply use [UUID](http://en.wikipedia.org/wiki/Universally_unique_identifier) to generate your random filenames like this:
```
import uuid
...
# with dashes
filename = uuid.uuid4()
# or without dashhes
filename = uuid.uuid4().hex
```
|
61,100,105 |
I am attempting to only run an SQL `INSERT` query if the pageID (number) which is pulled through via an AJAX call, is more than what is already in the db. A user essentially clicks on a next button, which shows the correct page content, then calls an AJAX POST request, which fires an SQL statement. Any guidance on the if checking statement would be appreciated as I have hit a brick wall.
**The Next button code:**
```
<a id="next" onclick="savePgID(1,2)">Next</a>
```
**AJAX call:**
```
function savePgID(moduleID, pageID){
$.ajax({
url: "pageAJAX.php",
method: "POST",
data: {moduleID:moduleID, pageID:pageID},
dataType: 'json',
});
}
```
**pageAJAX:**
```
<?php
session_start();
require 'scripts/db.php';
$studentID = $_SESSION['studentID'];
if(isset($_POST['pageID'])) {
$moduleID = $_POST['moduleID'];
$pageID = $_POST['pageID'];
if() {
// Here is where I want to check whether using the moduleID and
// pageID to check if the pageID in the db is less than the page
// user is on. Only if the pageID user is currently on, is
// greater than what they have in db, THEN run the below insert.
} else {
// INSERT Query into DB, this will update the pageID when user clicks next on module
$stmt = $conn->prepare ("UPDATE `studentTakingModule`
SET `pageID` = ?
WHERE `studentTakingModule`.`studentID` = ?
AND `studentTakingModule`.`moduleID` = ? ");
$stmt->bind_param("iii", $pageID, $studentID, $moduleID);
$stmt->execute();
$result = $stmt->get_result();
}
}
?>
```
**NOTE** \*\*\* After an answer has been supplied, I have updated the code to the below, which now never fires the `INSERT` new pageID number into my DB, (even though the current pageID is more than the pageID number in the database):
```
<?php
session_start();
require 'scripts/db.php';
$studentID = $_SESSION['studentID'];
if(isset($_POST['pageID']))
{
$pageID = $_POST['pageID'];
$moduleID = $_POST['moduleID'];
$stmt = $conn->prepare ("SELECT MAX(pageID) as `pageID`, `moduleID` FROM `studentTakingModule` WHERE `studentTakingModule`.`studentID` = ? AND `studentTakingModule`.`moduleID` = ? ");
$stmt->bind_param("ii", $studentID, $moduleID);
$stmt->execute();
$result = $stmt->get_result();
if(!empty($result)) {
$dbPageID = $result[0]['pageID'];
//$dbPageID2 = $row['pageID'];
if($pageID > $dbPageID) {
echo "You have reached the update statement";
// INSERT Query into DB, this will update the pageID when user clicks next on module
$stmt = $conn->prepare ("UPDATE `studentTakingModule` SET `pageID` = ? WHERE `studentTakingModule`.`studentID` = ? AND `studentTakingModule`.`moduleID` = ? ");
$stmt->bind_param("iii", $pageID, $studentID, $moduleID);
$stmt->execute();
$result = $stmt->get_result();
}
}
}
?>
```
|
2020/04/08
|
[
"https://Stackoverflow.com/questions/61100105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11040508/"
] |
you could try to wrap the `activeMQConnectionFactory` in a `CachingConnectionFactory` and utilize the `DefaultJmsListenerContainerFactoryConfigurer` to configure the `JmsListenerContainerFactory`:
```
@Bean
ConnectionFactory connectionFactory() {
return new CachingConnectionFactory(activeMQConnectionFactory());
}
@Bean
public JmsListenerContainerFactory<?> jmsListenerContainerFactory(ConnectionFactory connectionFactory,
DefaultJmsListenerContainerFactoryConfigurer configurer) {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
configurer.configure(factory, connectionFactory);
return factory;
}
```
EDIT start:
could you try changing the `JmsTemplate` to:
```
@Bean
public JmsTemplate jmsTemplate(ConnectionFactory connectionFactory) {
JmsTemplate jmsTemplate = new JmsTemplate();
jmsTemplate.setConnectionFactory(connectionFactory);
jmsTemplate.setPubSubDomain(true);
return jmsTemplate;
}
```
|
56,518,068 |
This is for a homework problem, so I tried to work through it as much as I could before coming here for help. I've got it 95% solved, I just can't figure out the syntax of the last bit or what method I should be using if it's different from what I'm doing now. I can't find any solution to this online that isn't actually my classmates' answers and I'm avoiding clicking on those to see how they completed the problem.
I can return the string without formatting if it only has one element, with only the word 'and' when there are two elements, and I can add commas and the word 'and' when there are more than three elements. However, I can't seem to skip adding the last comma when the array has more than three elements.
```
def oxford_comma(array)
if array.length == 2
array.join(" and ")
elsif array.length > 2
array.insert(-2, "and")
array[0..-1].join(", ")
else
array.join
end
end
```
Here's the error message I'm getting:
```
Failure/Error: expect(oxford_comma(["kiwi", "durian", "starfruit", "mangos", "dragon fruits"])).to eq("kiwi, durian, starfruit, mangos, and dragon fruits")
expected: "kiwi, durian, starfruit, mangos, and dragon fruits"
got: "kiwi, durian, starfruit, mangos, and, dragon fruits"
(compared using ==)
```
|
2019/06/09
|
[
"https://Stackoverflow.com/questions/56518068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10559334/"
] |
When you have just one element in the array, [Array#join](https://ruby-doc.org/core-2.6.3/Array.html#method-i-join) returns the element itself:
```
['a'].join(' and ') #=> "a"
```
So, you could simplify your code prepending `"and "` to the last element when list size is 3 or more or returning `.join(' and ')` if less than 3 elements:
```
def oxford_comma(list)
return list.join(' and ') if list.size < 3
list[-1] = "and " + list[-1]
list.join(', ')
end
```
|
42,657,575 |
I have 3 images and each of them have a div after it. I am trying to adjust all the image's height to be the same as the height of the div after it.
However, all the images are being given the height of the **first** div, not the one after it.
I believe this is because when `$(".text").outerHeight()` is used, it always gets the height of the first `<div class="text">`. I have tried using this `.each` function to resolve this, but to no avail:
```
$('.container').each(function(i, obj) {
$(".container").find('img').css("height", $(".text").outerHeight());
});
```
Here is my full code without the `.each` function:
```js
$(".container").find('img').css("height", $(".text").outerHeight());
```
```css
div.container {
border: 1px solid;
margin-bottom: 30px;
}
img {
float: left;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<img src="https://images-na.ssl-images-amazon.com/images/M/MV5BMzg2Mjg1OTk0NF5BMl5BanBnXkFtZTcwMjQ4MTA3Mw@@._V1_SX300.jpg" alt="RED" />
<div class="text">
<h2>Red</h2>
<p>When his peaceful life is threatened by a high-tech assassin, .</p>
</div>
</div>
<div class="container">
<img src="https://images-na.ssl-images-amazon.com/images/M/MV5BMTAyNzQyNTcwNjVeQTJeQWpwZ15BbWU3MDAwOTQ4Nzk@._V1_SX300.jpg" alt="White House Down" />
<div class="text">
<h2>White House Down (2013)</h2>
<p>While on a tour of the White House with his young daughter, a Capitol policeman springs into action to save his child and protect the president from a heavily armed group of paramilitary invaders.</p>
</div>
</div>
<div class="container">
<img src="https://images-na.ssl-images-amazon.com/images/M/MV5BMTAyNzQyNTcwNjVeQTJeQWpwZ15BbWU3MDAwOTQ4Nzk@._V1_SX300.jpg" alt="White House Down" />
<div class="text">
<h2>White House Down (2013)</h2>
<p>While on a tour of the White House with his young daughter, a Capitol policeman springs into action to save his child and protect the president from a heavily armed group of paramilitary invaders.</p>
</div>
</div>
```
|
2017/03/07
|
[
"https://Stackoverflow.com/questions/42657575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5798798/"
] |
I think you're on the right track. I would split on spaces to get all the words into an array. Then for-loop over the array and, where the index modulo 2 = 1 or 0 (depending on whether you want to alter even or odd words), use the char overload of replace .replace('x', 'y') to change your words. Then you just put the sentence back together
|
2,492,674 |
Assume I have a set of weighted samples, where each samples has a corresponding weight between 0 and 1. I'd like to estimate the parameters of a gaussian mixture distribution that is biased towards the samples with higher weight. In the usual non-weighted case gaussian mixture estimation is done via the EM algorithm.
Is there an implementation (any language is OK) that permits passing weights? If not, how can I modify the algorithm to account for the weights? If not, how to incorporate the weights in the initial formula of the maximum-log-likelihood formulation of the problem?
|
2010/03/22
|
[
"https://Stackoverflow.com/questions/2492674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/292209/"
] |
You can calculate a weighted log-Likelihood function; just multiply the every point with it's weight. Note that you need to use the log-Likelihood function for this.
So your problem reduces to minimizing $-\ln L = \sum\_i w\_i \ln f(x\_i|q)$ (see [the Wikipedia article](http://en.wikipedia.org/wiki/Maximum_likelihood#Principles) for the original form).
|
19,330,441 |
I have an array that I am looping through and pushing specific values to a separate array. EX:
```
first_array = ["Promoter: 8", "Passive: 7"]
```
I want to push every value that is an integer to a separate array, that would look like this in the end:
```
final_array = [8,7]
```
It would be nice for the values in the new array to be integers. I can't think of a way to push all numeric values within a string to a new array, but what would be the best option to do what I am wanting?
|
2013/10/12
|
[
"https://Stackoverflow.com/questions/19330441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2665588/"
] |
```
first_array.map{|a| a.match(/\d+/)}.compact.map{|a| a[0].to_i }
```
* Use a regex to grab the integers,
* compact the blank spaces from the strings with no integers, and
* convert them all to ints
|
21,935,187 |
I receive date as string from web service in following format `2014-02-27T11:17:00.000Z` Could someone tell me how to parse it as Date time object in Java.
I tried parsing it `Date.parse()` but it didn't work properly.
Then I tried date formatter but it crashes the app. Could someone enlighten me please.
|
2014/02/21
|
[
"https://Stackoverflow.com/questions/21935187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3296042/"
] |
```
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Date d = sdf.parse("2014-02-27T11:17:00.000Z");
```
|
47,997,549 |
The data in my table looks like this:
```
date, app, country, sales
2017-01-01,XYZ,US,10000
2017-01-01,XYZ,GB,2000
2017-01-02,XYZ,US,30000
2017-01-02,XYZ,GB,1000
```
I need to find, for each app on a daily basis, the ratio of US sales to GB sales, so ideally the result would look like this:
```
date, app, ratio
2017-01-01,XYZ,10000/2000 = 5
2017-01-02,XYZ,30000/1000 = 30
```
I'm currently dumping everything into a csv and doing my calculations offline in Python but I wanted to move everything onto the SQL side. One option would be to aggregate each country into a subquery, join and then divide, such as
```
select d1_us.date, d1_us.app, d1_us.sales / d1_gb.sales from
(select date, app, sales from table where date between '2017-01-01' and '2017-01-10' and country = 'US') as d1_us
join
(select date, app, sales from table where date between '2017-01-01' and '2017-01-10' and country = 'GB') as d1_gb
on d1_us.app = d1_gb.app and d1_us.date = d1_gb.date
```
Is there a less messy way to go about doing this?
|
2017/12/27
|
[
"https://Stackoverflow.com/questions/47997549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/722950/"
] |
You can use the ratio of SUM(CASE WHEN) and GROUP BY in your query to do this without requiring a subquery.
```
SELECT DATE,
APP,
SUM(CASE WHEN COUNTRY = 'US' THEN SALES ELSE 0 END) /
SUM(CASE WHEN COUNTRY = 'GB' THEN SALES END) AS RATIO
FROM TABLE1
GROUP BY DATE, APP;
```
Based on the likelihood of the GB sales being zero, you can tweak the GB's ELSE condition, maybe `ELSE 1`, to avoid Divide by zero error. It really depends on how you want to handle exceptions.
|
41,506 |
There is a blind test that asks participants to distinguish Coke and Pepsi.
A participant will test 6 cups of drink and tell whether it was Coke or Pepsi.
Assuming that the participant can tell the difference between them, though not perfect,
if he judged that the first three were all Coke,
then he would think it is much more likely that the remaining three would be Pepsi rather than Coke.
Then the last three experiments cannot give precise information about the participant's ability to distinguish.
Such a problem can happen when the participant knows a priori that there would be equal numbers of Coke and Pepsi. Then the experimenter might think of flipping a coin six times to decide which cola is given to the participant.
Then it is possible that all or most of 6 cups are Cokes.
It may be problematic when the participant is good at telling Coke a Coke but not as good at telling Pepsi a Pepsi.
Is there any methods to solve this problem?
|
2012/10/30
|
[
"https://stats.stackexchange.com/questions/41506",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/15997/"
] |
I do think it is a study design problem and a famous one in that some think RA Fisher did not actually realize it in making his famous Lady tasting cups of tea example and one that haunts clinical trials who try to prevent any unblinding of treatment assignment in clinical trials.
A solution suggested from what is done there (choosing block size randomly) is to first randomly choose the ratio of coke to pepsi and then chose the order. Do make the choice of all coke or all pepsi very very low but not zero and then try to get "there is a chance that all will be coke or pepsi” into the informed consent.
|
6,493,630 |
I'm binding an ObservableCollection to a control which has a converter to change its visibility depending on if the collection has any values or not:
Simplified example:
**XAML:**
```
<Window.Resources>
<local:MyConverter x:Key="converter"/>
</Window.Resources>
<Grid x:Name="grid">
<Rectangle Height="100" Width="200" Fill="CornflowerBlue"
Visibility="{Binding Converter={StaticResource converter}}"/>
<Button Content="click"
HorizontalAlignment="Left" VerticalAlignment="Top"
Click="Button_Click"/>
</Grid>
```
**C#:**
```
ObservableCollection<string> strings;
public MainWindow()
{
InitializeComponent();
strings = new ObservableCollection<string>();
grid.DataContext = strings;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
strings.Add("new value");
}
```
When the collection is bound, the Rectangle is visible when there are values and not when the collection is empty. However, if the collection is empty and I add a value at runtime, the Rectangle does not appear (the converter's Convert method isn't even fired). Am I missing something or just trying to ask too much of IValueConverter?
|
2011/06/27
|
[
"https://Stackoverflow.com/questions/6493630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/128837/"
] |
OK, so here's how I got around the problem using a `MultiValueConverter`
The converter now looks like:
```
public object Convert(
object[] values,
Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
{
ObservableCollection<string> strings =
values[0] as ObservableCollection<string>;
if (strings == null || !strings.Any())
return Visibility.Collapsed;
else
return Visibility.Visible;
}
public object[] ConvertBack(
object value,
Type[] targetTypes,
object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
```
And the XAML now looks like:
```
<Rectangle Height="100" Width="200" Fill="CornflowerBlue">
<Rectangle.Visibility>
<MultiBinding Converter="{StaticResource converter}">
<Binding Path="."/>
<Binding Path="Count"/>
</MultiBinding>
</Rectangle.Visibility>
</Rectangle>
```
The C# remains the same :)
|
787,449 |
I have a modem+wireless router that my ISP gave that I use to connect to the internet as well as connect my IP TV box.
I just bought a Time Capsule and I want to use it as the wireless access point. Unfortunately I am having difficulty getting the TC to connect to the internet. I have already turned off the wireless on the ISP router but I am afraid if I mess with any DHCP settings I might lose access to my TV set top box; ditto with bridge mode. However I am open to any suggestion.
Isnt there a way for the TC to connect to the internet over my existing router and use a different IP range to allow wireless devices to connect to it?
|
2014/07/24
|
[
"https://superuser.com/questions/787449",
"https://superuser.com",
"https://superuser.com/users/59789/"
] |
Well, as it turns out there IS a way to do this.
Connect the TC to the ISP's router using an ethernet cable. This will cause the ISP's router to allocate an IP address for it.
Go into your ISP router's settings and find the place where you can reserve an IP. It will probably ask you for the IP and MAC address. You can find these details on the page where the router shows all connected devices.
Next, open the DHCP settings page on the ISP's router and reduce the allocated range. For eg: if the range allocated was from 192.168.1.1 to 192.168.1.253 change the ending address to 192.168.1.150. This is just an example, you can change the end address to anything you want.
After you have done this, go to your TC's internet settings and change the address allocation setting to Static; by default it would have been set to DHCP + NAT. Enter the IP address you reserved in the previous step, here. In all possibility it would already have be filled in.
Next, go to the DHCP page of the TC and change the allocation range to 192.168.1.151 - 192.168.1.250. We are allocating the remaining range to the TC so that it can hand it out to any connected clients.
Restart the ISP's router. Once that is up, restart the TC.
|
11,229,627 |
I have two divs:
```
<div class="dialog large"></div>
```
and
```
<div class="dialog"></div>
```
I have to remove the one with the class "dialog" but keep the one with "dialog large".
If I do `$('dialog').remove();` they are both removed.
Can anyone help me with this?
|
2012/06/27
|
[
"https://Stackoverflow.com/questions/11229627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310276/"
] |
```
$('div.dialog:not(.large)').remove();
```
**[DEMO](http://jsfiddle.net/QStkd/512/)**
### A little explain
`div.dialog` will select `div` with `class=dialog` (in this case both div will select). But
`div.dialog:not(.large)` will exclude those `div` with `class` `large` and remove them.
### Related Refs
* **[:not()](http://api.jquery.com/not-selector/)**
* **[class selector](http://api.jquery.com/class-selector/)**
|
18,711,025 |
i will try to make this as simple as possible.
I have a working GUI with *SELECT, INSERT, DELETE and UPDATE* (**CRUD**) buttons and I am required to use a helper class and NOT just have the code running behind the buttons ect.
But I have NO IDEA what so EVER on how to even start coding this. I don't understand how I can code an action for a button or a label if i'm working in another class.
I have tried doing "ClassNameHere: Form1" but I get an error:
>
> lblInfo is inacessible due to its protection level
>
> cmbTable is inaccessible due to its protection level
>
>
>
I have googled that and tried changing classes to `public` and not public ect ect to no avail.
So I have to get this code (this is just the `SELECT`query)
```
private void fillcomboBox()
{
try
{
conn = new MySqlConnection(connstring);
conn.Open();
MySqlCommand myCommand = new MySqlCommand("SELECT * FROM person", conn);
MySqlDataReader myReader;
myReader = myCommand.ExecuteReader();
cmbTable.Items.Clear();
while (myReader.Read())
{
cmbTable.Items.Add(myReader["personID"] + " | " + myReader["firstName"] + " | " + myReader["lastName"] + " | " + myReader["address"] + " | " + myReader["phoneNumber"] + " | " + myReader["postCode"] + " | " + myReader["dateOfBirth"]);
}
}
catch (Exception err)
{//handle the error with a message
lblInfo.Text = " Error reading the database.";
lblInfo.Text += err.Message; ;
}
finally
{
}
}
```
To work in a different class (the helper class) and be linked to the form so that it works but is not behind the buttons...I hope that makes sense.
But like I said, I have no clue on how to even start coding this.
I would love ANY input, anything at all.
Thank you.
|
2013/09/10
|
[
"https://Stackoverflow.com/questions/18711025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469932/"
] |
```
$("#div-my-table").text("<table>");
$.each(data, function (i, item) {
$("#div-my-table").append("<tr><td>" + item.EncoderName + "</td><td>" + item.EncoderStatus + "</td></tr>");
});
$("#div-my-table").append("</table>");
```
`append` does not output the html directly like that. It appends full elements and won't take broken pieces of html. You want:
```
var $table = $("<table></table>");
$.each(data, function (i, item) {
$table.append($("<tr><td>" + item.EncoderName + "</td><td>" + item.EncoderStatus + "</td></tr>"));
});
$("#div-my-table").append($table);
```
**edit**
To make this a full solution, also you need `$(document)` rather than `$("document")`.
|
13,652,386 |
I have a table of statuses, each of which have a name attribute. Currently I can do:
```
FooStatus.find_by_name("bar")
```
And that's fine. But I'm wondering if I could do:
```
FooStatus.bar
```
So I have this approach:
```
class FooStatus < ActiveRecord::Base
def self.method_missing(meth, *args, &block)
if self.allowed_statuses.include?(meth.to_s.titleize)
self.where("name = ?", meth.to_s.titleize).first
else
super(meth, *args, &block)
end
end
def self.allowed_statuses
self.pluck(:name)
end
end
```
The above code works, but it leads to the following weird behavior:
```
FooStatus.respond_to?(:bar) => false
FooStatus.bar => #<FooStatus name: 'bar'>
```
That's not great, but if I try to implement respond\_to?, I get a recursion problem
```
class FooStatus < ActiveRecord::Base
def self.method_missing(meth, *args, &block)
if self.allowed_statuses.include?(meth.to_s.titleize)
self.where("name = ?", meth.to_s.titleize).first
else
super(meth, *args, &block)
end
end
def self.allowed_statuses
self.pluck(:name)
end
def self.respond_to?(meth, include_private = false)
if self.allowed_statuses.include?(meth.to_s.titleize)
true
else
super(meth)
end
end
end
```
And that gets me:
```
FooStatus.bar => ThreadError: deadlock; recursive locking
```
Any ideas on getting method\_missing and respond\_to to work together?
|
2012/11/30
|
[
"https://Stackoverflow.com/questions/13652386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/648538/"
] |
I agree with Philip Hallstrom's suggestion. If you know allowed\_statuses when the class is built, then just loop through the list and define the methods explicitly:
```
%w(foo bar baz).each do |status|
define_singleton_method(status) do
where("name = ?", status.titleize).first
end
end
```
…or if you need that list of statuses elsewhere in the code:
```
ALLOWED_STATUSES = %w(foo bar baz).freeze
ALLOWED_STATUSES.each do |status|
define_singleton_method(status) do
where("name = ?", status.titleize).first
end
end
```
Clearer, shorter, and far less prone to future breakage and weird rabbit hole conflicts with ActiveRecord like the one you're in.
You can do really cool things with method\_missing and friends, but it's not the first approach to go to when doing metaprogramming. Explicit is usually better when possible.
I also agree with Philip's concernt about creating conflicts with built-in methods. Having a hard-coded list of statuses prevents that from going too far, but you might consider a convention like `FooStatus.named_bar` instead of `FooStatus.bar` if that list is likely to grow or change.
|
191,981 |
Can a civilization be highly evolved as far as culture, ethics, societal norms, laws, language, literature and arts, but not ever come to develop any sort of advanced technology besides main practical techniques for construction and agriculture?
They have a culture-religion that is fully integrated with nature, and they are naturally frugal as they are isolated from the other cultures in their world, and live in a continent that is able to provide all they need to prosper.
EDIT:
Thanks all for all your amazing inputs. I sort of figured out by myself how to solve this issue I had with this civilization. I will explain it in the end.
First, the clarifications:
1. They are not human. They are an intelligent species that evolved from warm-blooded reptiles.
2. They have math (a senary numeric system), literacy (their language is based on clicks like Khoisan), highly developed agriculture, steam, the wheel, levers, pumps, cranes, concrete, highly developed civil engineering and architecture, highly developed metalworks, mining, etc. What I meant by advanced technology was basically war machines, electricity, airplanes, ships, computers, post first industrial revolution technologies.
3. Their philosophical and ethical level is comparable to Ancient Athens/Ancient China but a little more advanced. So, they are basically very enlightened empiricists by nature observation BUT don't have a full empirical scientific method fully developed (and they can't have a western-like scientific method developed, or they will turn to imperialism, conquest and war. That was the main concern behind my question).
4. They have another reptilian species of "companions" (they are "slaves" in the economic sense - work for food and shelter -, but are not slaves in the sense we Americans think of slaves, like some people with another skin color that we can rape, abuse, force to work to death, and beat at will, whenever our White European selves feel frustrated and/or down). That reptilian species has an intelligence comparable to a combination of crows, chimpanzees and dogs. So, they are not able to develop abstract thinking, but are able to learn and execute any sort of tasks the main species need then to do. They also have sets of opposable fingers and toes like the main species.
5. The main species is integrated with nature through their culture/religion as they were essentially hunters gatherers before "the great cataclysm' (something like 70 million years BP). A little before that they had what they call "The 500,000 year march", when they left their original dying (due to basically extinction of resources caused by their own predatory actions) homeland and moved West and then South to this new continent where they been living for 70 million years, totally isolated from the rest of the world. During that "march", their culture of elders/scientists/priests ruling evolved, and they created their literary tradition of passing to the youngsters the knowledge of their whole history, and their nature worshipping religion. One of the main legends is that nature is a live and sentient organism that helps their species by providing and nourishing them.
6. This is another point. They have a culture (like us humans), so instructions needed for survival are not necessarily coded in their DNA like the other animals. They still have some basic survival needs and skills encoded in their DNA (as we still have too, like, for example, fear of spiders, which is not cultural, as all cultures in the world fear spiders), but most of the skills and needs are passed from the elders to the youngsters as culture.
So, I basically figured out how to make them highly culturally advanced while keeping them without developing advanced technology and war machines what would have their culture necessarily changing to expansionism, imperialism, conquest and warmongering.
I basically used two features from their lore, one geographic (their continent is rich in resources, as well as very isolated) and another cultural (their nature-worship religion).
As result, like in Chinese Confucianism, to want to leave their parents/clan homeland is really frowned upon. Whoever leaves their original homeland becomes an outcast and a pariah.
As they have all the resources they need, there is no need to trade for resources with other cultures. And as they worship nature, their local rivers, forests, mines, mountains, so forth, are very important to them, so they cannot be faraway from it, and must respect that nature, so not bring destruction or building anything that does not look able to fit into the natural environment.
As Ming China, they can have a very advanced civilization, but without any need to contact the exterior world. And, unlike Ming China, they don't need to keep a strong military to protect their borders, because they are separated from the other cultures in their world by thousands of miles of open ocean.
Thanks again for all your ideas. And if you have any other ideas that you think would provide any improvement to this way I found to solve this issue I had, I will be really happy to hear them.
|
2020/12/14
|
[
"https://worldbuilding.stackexchange.com/questions/191981",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/81238/"
] |
Technology is a *prerequisite* for civilization
-----------------------------------------------
Civilization means cities. The word in fact [has a common root with city](https://www.etymonline.com/word/civil). To have a city requires a lot of assorted technologies. Building materials. Storage containers. Fire. One of the key ones you've identified is agriculture. In order to have cities, you have to have technologies and capabilities that go beyond strategies that will work for smaller-scale communities. Cities need an external food supply, and they need the wherewithal to get the food from the supply to them.
Efficiency creates more efficiency
----------------------------------
I saw a very interesting proposition, which I can't find right now, that put one of reasons for the increase in the technological progress rate like this:
Very roughly, the rate of technological progress is dependent on the number of people that have surplus time, folks whose immediate demands on their time and attention (subsistence, maintaining infrastructure, manning the army, etc) are not total.
See, creating a new invention takes time, often for little short-term practical benefit. The benefits in the long term are astounding - computers, antibiotics, airplanes - but they can take a *very* long time to be realized. [John Dalton](https://www.britannica.com/biography/John-Dalton/Atomic-theory) discovered the atom around 1800 (although a Greek had hypothesized their existence long before). The first [nuclear power plant](https://en.wikipedia.org/wiki/Nuclear_power#First_nuclear_reactor) - a research reactor - came online in 1942.
So a society has to be well off enough to be able to support folks that do nothing but pursue pie in the sky technological innovation and especially basic research. And the more of those folks you have, the more technology you have.
You can't have a civilization *at all* without people discovering enough technology to make cities work. So you have to have some of them around. And the funny thing is, the more technology you have, the more productivity improves, the society will naturally produce more and more of these folks. (Generally speaking, of course.)
TL;DR yes, technological advancement is a natural consequence of civilization. Necessity is the mother of invention.
|
52,199,086 |
I am working with sas to manipulate some dataset.
I am using the data step to apply some condition to keep columns and filter on some values.
The problem is that I would like to filter on columns that in the end I will not need, so I would like to apply, first, the where clause, and then the keep clause.
The problem is that sas executes, first the keep clause and then where, so when it is trying to apply the where instruction it doesn't find the columns on which it should be applied on. This is my code:
```
data newtable;
set mytable(where=(var1<value)
keep var2);
end;
```
In this case the error is the var1 cannot be found since I decided to keep only var2. I know I can do two data steps, but I would like to do everything in one step only.
How can I achieve this?
|
2018/09/06
|
[
"https://Stackoverflow.com/questions/52199086",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4332914/"
] |
This can be achieved by using the `keep` data set option on the output data set, e.g.(untested):
```
data newtable(keep=var2);
set mytable(where=(var1<value));
end;
```
Alternatively a `keep` statement can be used, e.g. (untested):
```
data newtable;
set mytable(where=(var1<value));
keep var2;
end;
```
|
31,696,681 |
In mathematics we can assume that `sin(t1)` is equal to `t1` for very small angles. How to do that in Matlab?
```
syms t1;
res = sin(t1);
res2= MAGIC(res,t1);
```
I need `MAGIC`to change `res`, such that it becomes `t1`.
Thanks
|
2015/07/29
|
[
"https://Stackoverflow.com/questions/31696681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5168730/"
] |
It is `Input` and not `input`.
[This commit](https://github.com/laravel/laravel/commit/2adbbbd91e9d6e2d569cc56f138b7273efe25651) removed `Input` facade definition from `config/app.php` hence you have to manually add that in to `aliases` array as below,
```
'Input' => Illuminate\Support\Facades\Input::class,
```
Or You can import `Input` facade directly as required,
```
use Illuminate\Support\Facades\Input;
```
|
58,370,647 |
I am using Windows 10 and Windows subsystem for linux.
I have started creating my own Operating System in Assembly and C.
I am following a tutorial.
I got stuck into 2 problems.
Error 1:
When I Link and create bin files, i am getting a warning:
"ld: warning: cannot find entry symbol \_start; defaulting to 0000000000001000"
Does this matter?
Error 2:
After compiling my code, there was no error. But when i boot my operating system, it shows an error: Disk read error!
Please help me.
Boot.asm
```
[org 0x7c00]
KERNEL_OFFSET equ 0x1000
mov [BOOT_DRIVE], dl
mov bp, 0x9000
mov sp, bp
mov si, MSG_REAL_MODE
call print
call load_kernel
call switch_to_pm
jmp $
%include "printstr.asm"
%include "diskload.asm"
[bits 16]
load_kernel :
mov si, MSG_LOAD_KERNEL
call print
mov bx, KERNEL_OFFSET
mov dh, 15
mov dl, [ BOOT_DRIVE ]
call disk_load
ret
[bits 32]
BEGIN_PM :
mov ebx, MSG_PROT_MODE
call print_string_pm
call KERNEL_OFFSET
jmp $
BOOT_DRIVE db 0
MSG_REAL_MODE db " Started in 16 - bit Real Mode " , 0
MSG_PROT_MODE db " Successfully landed in 32 - bit Protected Mode " , 0
MSG_LOAD_KERNEL db " Loading kernel into memory. " , 0
times 510 -( $ - $$ ) db 0
dw 0xaa55
```
diskload.asm
```
disk_load :
push dx
mov ah , 0x02
mov al , dh ;
mov ch , 0x00
mov dh , 0x00
mov cl , 0x02
int 0x13
jc disk_error
pop dx
cmp dh , al
jne disk_error
ret
disk_error :
mov si , DISK_ERROR_MSG
call prints
jmp $
; Variables
DISK_ERROR_MSG db " Disk read error !" , 0
prints:
lodsb
or al, al
jz printdones
mov ah, 0eh
int 10h
jmp prints
printdones:
ret
```
Compiling commands:
```
nasm boot.asm -f bin -o boot.bin
nasm kernel_entry.asm -f elf64 -o kernel_entry.o
gcc -ffreestanding -c kernel.c -o kernel.o
ld -o kernel.bin -Ttext 0x1000 kernel_entry.o kernel.o --oformat binary
cat boot.bin kernel.bin > os.iso
```
|
2019/10/14
|
[
"https://Stackoverflow.com/questions/58370647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I solved the problem by changing the kern after the last character. So now, instead of jumping 40pt, cursor jumps only 1pt (or whatever you set on below method)
```
@objc private func textFieldDidChange() {
guard let text = textField.text else { return }
if text.count == Constant.deviceCodeCharacterCount {
let attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(.kern, value: Constant.deviceCodeCharacterSpacing, range: NSRange(location: 0, length: text.count - 1))
attributedString.addAttribute(.kern, value: 1, range: NSRange(location: Constant.deviceCodeCharacterCount - 1, length: 1))
textField.attributedText = attributedString
}
}
```
[](https://i.stack.imgur.com/0mSae.gif)
|
4,605,722 |
What does the notation $[G : H]$ mean in group theory? Does it mean the same as quotient group? I have seen the above notation a lot while studying group theory but it still remains unclear to me about the meaning of this notation?
|
2022/12/26
|
[
"https://math.stackexchange.com/questions/4605722",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/1129649/"
] |
The index $[G:H]$ is the number of left cosets of $H$ in $G$ and it is the number of right cosets of $H$ in $G$. That those numbers are equal is obvious when $G$ is abelian, but it is true for all groups and this does *not* require $G$ to be finite, so the equality is not fully explained by relying on Lagrange’s theorem for finite groups.
For each left $H$-coset $gH = \{gh : h \in H\}$, inverting its elements gives us
$$\{h^{-1}g^{-1} : h \in H\} = \{hg^{-1} : h \in H\} = Hg^{-1},
$$
which is a right $H$-coset, and sending each $gH$ to $Hg^{-1}$ is a well-defined bijection from the left $H$-cosets to the right $H$-cosets, even if the number of cosets is infinite.
For example, $[\mathbf Z: m\mathbf Z] = m$ for positive integers $m$, $[\mathbf R^\times:\{\pm 1\}]$ is infinite, the positive reals $\mathbf R\_{>0}$ have index $2$ in $\mathbf R^\times$, and the group of real $2\times 2$ matrices with positive determinant ${\rm GL}\_2^+(\mathbf R)$ has index $2$ in the group of real invertible $2\times 2$ matrices ${\rm GL}\_2(\mathbf R)$. That a subgroup of index $2$ is a normal subgroup holds for infinite groups, not just finite groups.
The index, when infinite, should properly be considered as a cardinal number, but typically in a first group theory course you may do very little with subgroup indices when they are infinite, so you might just lump all cases of infinite index together as “$[G:H]=\infty$” in the same way infinite sets $S$ are all lumped together as “$\# S = \infty$” unless there is a good reason to use the more careful notion of cardinal numbers.
|
32,774,235 |
My customers are not receiving SMS to verify their OTP. We have integrated Twilio with Parse and is using it for OTP Authentication. We are based out of India.
We faced this during test account. It never used to send SMS in the night and received all SMS next day morning. Now we are using a paid account and still the same issue i.e. my customer did not get any SMS during night and also not in the morning. Kindly help.
We will not be able to do business if our customers do not receive OTP SMS.
Is this a known issue ?
|
2015/09/25
|
[
"https://Stackoverflow.com/questions/32774235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5373344/"
] |
India is difficult to get text messages to, there are lots of rules and restrictions
Completed a project recently using a Twilio competitor (Clickatell) and it was the very same problem.
Frow Twilio's website:
**Are there limitations on sending SMS messages to Indian mobile devices?**
>
> **3. They are only delivered between the hours of 9 A.M. and 9 P.M. local Indian time**
>
>
> If you’ve been seeing delivery delays when sending to Indian numbers,
> make sure you are making the requests during the operational hours of
> 9 A.M. to 9 P.M., as overnight messages are likely to be cached until
> the next day.
>
>
>
<https://www.twilio.com/help/faq/sms/are-there-limitations-on-sending-sms-messages-to-indian-mobile-devices>
|
35,455,281 |
As per [this document](http://docs.aws.amazon.com/lambda/latest/dg/vpc.html), if I need to access internet resources from my Lambda function with VPC access, I need to set up a NAT gateway.
So I followed [this guide](http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-gateway.html) to set up a NAT gateway. However, at the stage when I need to edit the route tables of my subnet to add an entry with destination: 0.0.0.0/0 and target as my NAT gateway's id, I got an error that
```
An entry with this destination already exists
```
I checked and noticed that for that existing entry, the target was an internet gateway for my VPC. If I replace that entry with the NAT gateway id, I cannot access any of the EC2 instances in that VPC through SSH from the outside world. How can I achieve a solution where all the EC2 instances in this VPC:
* Are accessible only via SSH and the rest of the traffic is blocked
* Are able to completely access other EC2 instances in the same VPC
* Lambda function having access to this VPC can access outside resources like SQS and Kinesis.
|
2016/02/17
|
[
"https://Stackoverflow.com/questions/35455281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3097807/"
] |
You need both the IGW and the NAT gateway for this to work.
In the public subnets (ones you want to reach from outside) point the 0.0.0.0/0 traffic to the IGW gateway. The NAT gateway itself needs to sit in one of these public subnets.
In the private subnets that you want to NAT point 0.0.0.0/0 traffic to the NAT gateway elastic network interface.
If 0.0.0.0/0 is aleady bound to the gateway you need to remove that and add it pointing the NAT gateway.
See:
<http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/vpc-nat-gateway.html>
|
40,823,052 |
I need to create the spacing between the two `<i>` tags, and make a vertical line in between them.
Here is my code:
```css
#wrap {
width: 650px;
margin: 0 auto;
}
#left_col {
float: left;
width: 300px;
}
#right_col {
float: right;
width: 300px;
padding-left: 20px;
}
```
```html
<div id="wrap">
<div id="left_col">
<p>Are you a Developer?</p>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px; padding-top: 20px;">
Register Your Project Online</i>
<br><i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
Wait for Project Approval </i>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
Raise funding in 90 days </i>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
Provide Regular construction updates </i>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
Complete and Sell Project </i>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
Destribute funds to Investor </i>
</div>
```
How can I increase the gaping between the `<i>` tag and add a vertical line at the end of every line?
|
2016/11/26
|
[
"https://Stackoverflow.com/questions/40823052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7183476/"
] |
Like this is one way. I think you want a **vertical** line like this :
```css
#wrap {
width: 650px;
margin: 0 auto;
}
#left_col {
float: left;
width: 300px;
}
#right_col {
float: right;
width: 300px;
padding-left: 20px;
}
.cont i {
text-align: center;
margin: 5px;
padding:5px;
line-height: 25px;
}
.divider {
width: 50%;
height: 50px;
border-right:solid;
border-left-color: black;
}
.divider2 {
width: 50px;
height: 50px;
border-left:solid;
border-left-color: black;
}
```
```html
<div id="wrap">
<div id="left_col" class="cont">
<p>Are you a Developer?</p>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px; padding-top: 20px;">
Register Your Project Online</i>
<div class="divider"></div>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
Wait for Project Approval </i>
<div class="divider"></div>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
Raise funding in 90 days </i>
<div class="divider"></div>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
Provide Regular construction updates </i>
<div class="divider"></div>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
Complete and Sell Project </i>
<div class="divider"></div>
<i class="fa fa-facebook" aria-hidden="true" style="padding-left: 10px;">
Destribute funds to Investor </i>
</div>
</div>
```
I have put two classes `divider` , `divider2`, change and play with width and height and `border-left` and `border-right` to get your desire line.
BTW, You may also want to check [bootstrap timeline](http://bootsnipp.com/snippets/featured/timeline-responsive)
|
32,190,870 |
I have an AngularJS app that is using node.js and Loopbackjs to communicate with a mysql database. I am able to properly show my GET request on the `partial-home.html` aspect of the page, but when I create a new user it returns the following error:
```
POST http://localhost:3000/api/se_users 422 (Unprocessable Entity)
```
Here is my code:
partial-create.html
```
<div class="row">
<div class="col-md-8">
<h1>Create a User</h1>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<form name="create" ng-submit="se_user()">
<div class="form-group">
<label for="user_id">ID</label>
<input type="text" class="form-control" ng-model="user.eid" placeholder="Enter EID">
</div>
<div class="form-group">
<label for="first_nm">First Name</label>
<input type="text" class="form-control" ng-model="user.first_nm" placeholder="Enter First Name">
</div>
<div class="form-group">
<label for="last_nm">Last Name</label>
<input type="text" class="form-control" ng-model="user.last_nm" placeholder="Enter Last Name">
</div>
<div class="form-group">
<label for="email_adr">Email Address</label>
<input type="text" class="form-control" ng-model="user.email_adr" placeholder="Enter Item Type">
</div>
<div class="form-group">
<label for="user_role">Role</label>
<input type="text" class="form-control" ng-model="user.role" placeholder="Enter Status Code">
</div>
<div class="form-group">
<label for="user_active">Active</label>
<div class="radio">
<label>
<input type="radio" name="optionsRadios" id="optionsRadios1" value="Yes" ng-model="user.active" checked>Yes
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="optionsRadios" id="optionsRadios2" value="No" ng-model="user.active">No
</label>
</div>
</div>
<div class="form-group">
<label for="mgr_full_nm">Manager Name</label>
<input type="text" class="form-control" ng-model="user.mgr_full_nm" placeholder="Enter Full Name">
</div>
<div class="form-group">
<label for="mgr_eid">Manager EID</label>
<input type="text" class="form-control focus" ng-model="user.mgr_eid" placeholder="Enter Manager EID">
</div>
<div class="form-group">
<label for="insrt_dt">Insert Date</label>
<input type="date" class="form-control" ng-model="user.insrt_dt" placeholder="Enter Date">
</div>
<div class="form-group">
<label for="insrt_user_id">Insert User EID</label>
<input type="text" class="form-control" ng-model="user.insrt_user_id" placeholder="Enter User EID">
</div>
<div class="form-group">
<label for="upd_dt">Update Date</label>
<input type="date" class="form-control" ng-model="user.upd_dt" placeholder="Enter Update User Date">
</div>
<div class="form-group">
<label for="upd_user_id">Update User EID</label>
<input type="text" class="form-control" ng-model="user.upd_user_id" placeholder="Enter Update User EID">
</div>
<button class="btn btn-primary btn-lg" ng-click="addSe_user()">Create User</button>
<br>
<br>
<pre>
{{user | json}}
</pre>
</form>
</div>
</div>
</div>
```
app.js
```
angular.module('userApp', ['ui.router', 'lbServices'])
.controller('UserController', ['$scope', '$state', 'Se_user', function ($scope, $state, Se_user) {
$scope.users = [];
function getSe_users() {
Se_user
.find()
.$promise
.then(function (results) {
$scope.users = results;
});
}
getSe_users();
$scope.addSe_user = function () {
Se_user
.create($scope.user);
alert('You have created a new user!')
$scope.create.$setPristine();
};
$scope.editSe_user = function(user_id) {
Se_user
.editById(user_id)
.$promise
.then(function (user_id) {
getSe_users();
});
};
$scope.removeUser = function (item) {
Se_user
.deleteById(item)
.$promise
.then(function () {
getSe_users();
});
};
}])
.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('');
$stateProvider
.state('home', {
url: '',
templateUrl: 'partial-home.html',
controller: 'UserController'
})
.state('create', {
url: '/create',
templateUrl: 'partial-create.html',
controller: 'UserController'
})
.state('admin', {
url: '/admin',
templateUrl: 'partial-admin.html',
contoller: 'UserController'
})
}]);
```
|
2015/08/24
|
[
"https://Stackoverflow.com/questions/32190870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5240486/"
] |
Change your create line from
```
Se_user
.create($scope.user);
```
to
```
Se_user
.create($scope.user,
function(newUser) {
console.log(newUser);
// only set pristine here, this
// callback fires on success
$scope.create.$setPristine();
},
function(err) {
console.log(err); // will log the error to the console
}
);
```
The alert shouldn't get in the way of seeing the dev tools output, but this structure makes it easier to get the error response by using the error callback in the call.
The way you have it, the alert that says you have created a new user will fire *immediately after* the ajax call to create the new user is *sent*—not received. There will be some delay for the server to respond so any code you write that depends on the new user being created (or erroring) needs to go inside the callback to the `.create()` method.
See the Loopback Angular $resource docs here: <https://docs.strongloop.com/display/public/LB/AngularJS+JavaScript+SDK#AngularJSJavaScriptSDK-ModelresourceAPI>
**UPDATE:** Chrome console - you should see a stack trace with your 422 error when you inspect the Network call in Chrome Dev tools, like this 401 error:
[](https://i.stack.imgur.com/dANfp.png)
Please edit your original question and post the full text of that trace into it as a code block.
|
414,324 |
I have a cloud masked Landsat 7 image collection. For each image I want to [unmask](https://developers.google.com/earth-engine/apidocs/ee-image-unmask) the bands with their respective mean value.
This works fine, unless an image is completely cloud masked and therefore contains no data.
I tried adapting this [related answer (in JavaScript)](https://gis.stackexchange.com/a/341778/128665) to my needs
```py
start_date = "2018-01-01"
end_date = "2021-12-31"
l7 = (ee.ImageCollection("LANDSAT/LE07/C02/T1_L2")
.filterDate(ee.Date(start_date), ee.Date(end_date))
.filterBounds(aoi)
.map(lambda image: image.clip(aoi))
)
band_names = ['SR_B1', 'SR_B2', 'SR_B3', 'SR_B4', 'SR_B5', 'SR_B7', 'QA_PIXEL']
## fn.cloudmask_LS is a wrapper for a cloud masking procedure similar to this: https://gis.stackexchange.com/q/405056/128665
l7 = l7.select(band_names).map(fn.cloudmask_LS('QA_PIXEL'))
## drop QA_PIXEL band
band_names = [b for b in band_names if not b == 'QA_PIXEL']
l7 = l7.select(band_names)
################################################
## function adapted from the other GIS SE answer
################################################
def mask_with_mean(image):
time = image.get("system:time_start")
meanDict = image.reduceRegion(reducer=ee.Reducer.mean(), geometry=aoi)
outImg = ee.Image(ee.Algorithms.If(
meanDict.values(),
image.unmask(ee.Image.constant(meanDict.values(band_names))),
ee.Image(0).selfMask().set('isNull', True)
))
return outImg.set({"system:time_start":time})
## True is an attempt to get the map function to drop nulls but it doesn't appear to be working.
l7 = l7.map(mask_with_mean, True)
```
But I receive the following error:
>
> ee.ee\_exception.EEException: Error in map(ID=LE07\_169068\_20180128):
> Image.constant: Invalid type for constant image value.
>
> Expected type: Number or Array.
>
> Actual type: Object.
>
> Actual value: null
>
>
>
>
I have tried `meanDict` in the `ee.Algorithm.if` true clause also.
I believe the problem arises because `meanDict` is `null` for an empty image but I don't know how to catch that with the `ee.Algorithm.if`.
|
2021/10/19
|
[
"https://gis.stackexchange.com/questions/414324",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/128665/"
] |
Yes, it is absolutely possible using `GDAL/OGR` through `ogr2ogr` by using `-simplify` option. You should pass a `<tolerance>` value as it is described [on their website.](https://gdal.org/programs/ogr2ogr.html#cmdoption-ogr2ogr-simplify)
Another way is to use `osgeo.ogr.Geometry.Buffer(self, *args, **kwargs)` on which supports arguments to control distance and number of segments.
If your shapes are polylines you can use `shapely->parallel_offset` as well. which has a `round` option.
Good Luck.
|
45,241 |
I am really unsure about how to go about this question and which circuits to consider.
Here's the question:
Determine the value of the current labeled \$i\$ and the voltage labeled \$v\$ at \$t=0+\$, \$t=1.5ms\$, and \$t = 3.0ms\$.
The circuit is as follows:

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fXrbPa.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
Relevant equations:
Ohm's law: \$v = iR\$
Decay in source free RC Circuit \$v(t) = v(0) e^{-t/RC}\$
The attempt at a solution:
\$i(0-) = 0.1 A.\$
Therefore,
\$v\$ across 200 ohm: \$200 \* 0.1 = 20 V\$
Since no current flows through capacitor with constant dc current,
\$v\$ across capacitor: \$20 V @ t < 0\$
\$v\$ across capacitor cannot change immediately as it would require infinite power so \$v\$ across capacitor @ \$t = 0\$ is \$20V\$
Here's where the confusion is: Should I include the 200 ohm resistor in my RC circuit? Why or why not? Also, will my circuit be a source free RC circuit?
Also, what will be the current i through the 200 ohm resistor when t>0?
My last question is a theoretical one: Can a current through a resistor change immediately at one instant of time?
|
2012/10/22
|
[
"https://electronics.stackexchange.com/questions/45241",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/15477/"
] |
The voltage across a capacitor discharging into a fixed resistance decays exponentially. The time constant is RC, where C is the capacitance, and R is the resistance between the terminals of the resistor.
$$
V(t)=V(0)e^{\frac{-t}{RC}} \\
$$
You're right that the capacitor starts at 20V, because that's the voltage across the 200 ohm resistor after the capacitor is charged. So you know V(0), and you know C. All you're missing is R. To analyze that properly, think of the switch as a resistor of 0 ohms when closed, and don't worry about the current source. The parallel combination of a 200 ohm resistor and a 0 ohm resistor is 0 ohms. The series combination of a 50 ohm resistor and a 0 ohm resistor is 50 ohms. So the 50 ohm resistor is the only one that matters when determining your discharge constant.
The current through the 200 ohm resistor depends on the voltage across the 200 ohm resistor. The voltage across the 200 ohm resistor is the same as the voltage across the 0 ohm resistor (the closed switch). V=IR, so what's the voltage across that pair of resistors when the switch is closed?
And yes, the voltage across an ideal resistor can change instantaneously. Keep in mind though, there's no such thing as an ideal resistor in the physical world. Everything has capacitance to everything else.
|
37,726,210 |
My app simply is not showing for Android 6 devices on the Play Store. I tried Google support and they didn't know the problem either.
My manifest doesn't have any specific limitations on API 23 and only GPS for uses-feature, however no device manages to be able to install the app.
```
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xx.xx">
<!-- Maps API needs OpenGL ES 2.0. -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="false" />
<uses-sdk android:minSdkVersion="9" android:targetSdkVersion="23" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.BROADCAST_STICKY" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<permission
android:name="${applicationId}.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="${applicationId}.permission.MAPS_RECEIVE" />
<application
android:name=".applicationclass"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/AppTheme">
<activity
android:name=".splash.SplashContainer"
android:label="@string/app_name"
android:theme="@style/AppThemeNoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".splash.SplashActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" />
<activity
android:name=".home.HomeActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" />
<activity
android:name=".register.WelcomeActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" />
<activity
android:name=".register.RegisterActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" />
<receiver android:name=".services.Pulse" />
<service
android:name="com.google.android.gms.analytics.AnalyticsService"
android:exported="false" />
<receiver android:name="ServiceWakingReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<receiver android:name="com.google.android.gms.analytics.AnalyticsReceiver">
<intent-filter>
<action android:name="com.google.android.gms.analytics.ANALYTICS_DISPATCH" />
</intent-filter>
</receiver>
<receiver android:name="com.google.android.gms.analytics.CampaignTrackingReceiver">
<intent-filter>
<action android:name="com.android.vending.INSTALL_REFERRER" />
</intent-filter>
</receiver>
<service android:name="com.google.android.gms.analytics.CampaignTrackingService" />
<!-- Maps key -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="key" />
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="io.fabric.ApiKey"
android:value="key" />
</application>
</manifest>
```
|
2016/06/09
|
[
"https://Stackoverflow.com/questions/37726210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3335648/"
] |
After chatting with the Google support team, they shared with me the problem.
Their report gave this on a Samsung S5 phone:
```
Missing device feature:
android.hardware.telephony
```
Google Play is marking Android 6.0.x phones as not compatible when using the *android.hardware.telephony*, even if the device has it;
I added this to my manifest and the problem was solved:
```
<uses-permission
android:name="android.permission.CALL_PHONE"
android:required="false" />
<uses-feature
android:name="android.hardware.telephony"
android:required="false" />
```
|
48,256,681 |
I use a open API get the bellow information using its access key:
```
HTTPConnectionPool(host='freeipapi.17mon.cn', port=80): Max retries exceeded with url: /183.11.178.118 (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x103780780>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known',))
{'status': 0, 'address': 'CN|广东|深圳|None|CHINANET|0|0', 'content': {'address_detail': {'province': '广东省', 'city_code': 340, 'street': '', 'city': '深圳市', 'district': '', 'street_number': ''}, 'address': '广东省深圳市', 'point': {'x': '12693451.44', 'y': '2560682.35'}}}
```
You see, the later data `{'status': 0, 'address': 'CN|广东|深圳|None|CHINANET|0|0', 'content': {'address_detail': {'province': '广东省', 'city_code': 340, 'street': '', 'city': '深圳市', 'district': '', 'street_number': ''}, 'address': '广东省深圳市', 'point': {'x': '12693451.44', 'y': '2560682.35'}}}` is my need.
How can I get it?
The code is bellow:
```
import urllib, urllib.request
import json
ak_url="http://api.map.baidu.com/location/ip"
result = requests.get(ak_url,{"ip":"183.11.178.1","ak":BAIDU_IPADDR_AK})
print(result.json()) # There prints the upper data.
```
|
2018/01/15
|
[
"https://Stackoverflow.com/questions/48256681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6523163/"
] |
Your data is actually returned by `result.json()`.
Perhaps you are confused by the extra `HTTPConnectionPool` details.
That could be an indicator that `result.json()` has a custom representation (as in, it implements `__repr__` or `__str__`) and appends that data behind the scenes when printing.
|
25,615,609 |
I tried `[[UIScreen mainScreen] bounds]` to get the screen size of a resizable iPhone on `Xcode 6` simulator. But it doesn't take into account the new screen width and screen height I assign to it.
Is there a better way to get the screen size? Even if I set the screen size to **320x800** the `[[UIScreen mainScreen] bounds]` returns me `(CGRect) $0 = origin=(x=0, y=0) size=(width=768, height=1024)`

|
2014/09/02
|
[
"https://Stackoverflow.com/questions/25615609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3256150/"
] |
Do following
**CGRect Rect=[[UIScreen mainScreen] bounds];**
So it will preserves the bounds in the rect.
try once.
|
3,214,701 |
Determine the conditions on $b\_1$, $b\_2$, $b\_3$, if any, in order to guarantee that the linear system is consistent.
$x + 3y − 2z = b\_1$
$5x − 5y + 4z = b\_2$
$−3x + 11y − 8z = b\_3$.
Consider the system of equations
$x + y + 2z = a $
$x + z = b$
$2x + y + 3z = c$.
Show that in order for this system to be consistent, $a$, $b$, and $c$ must satisfy $c=a+b$.
I need to determine the conditions of the $b$'s. I tried to solve this by using Gauss elimination to convert it into echelon form, but that seems unnecessarily cumbersome to solve this. I was hoping there would be an easier way to do this as well as for the the second part it seems they need the same concept which I don't know. Thank you in advance.
|
2019/05/05
|
[
"https://math.stackexchange.com/questions/3214701",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/656407/"
] |
In general, the condition you are looking for is known (more often than not) as the [Rouché-Capelli theorem](https://en.m.wikipedia.org/wiki/Rouch%C3%A9%E2%80%93Capelli_theorem).
You construct the matrix of the coefficients of the equations $A$; in the first case:
$$ A = \begin{bmatrix}
1 &3& -2\\
5 &-5&4\\
-3&11&-8
\end{bmatrix}.$$
Then, you impose that the rank of $A$ is equal to the rank of the augmented matrix you get by adding the right-hand sife of each equation to each row of $A$; in the first case:
$$ [A|b] = \begin{bmatrix}
1 &3& -2&b\_1\\
5 &-5&4&b\_2\\
-3&11&-8&b\_3
\end{bmatrix}.$$
If $A$ and $[A|b]$ have the same rank, the system has a solution.
|
9,064,298 |
I have used initialization lists a great deal in my C++ programs but wasn't aware that you could allocate memory within them.
So you can do something (as a contrived example) like this:
```
class Test
{
private:
int* i;
int* j;
int count;
int* k;
public:
Test(void) : i(new int), j(new int[10]), count(10), k(new int[count])
{
}
~Test(void)
{
delete i;
delete [] j;
delete [] k;
}
};
```
Are there any issues in doing memory allocation in this way? Regarding the order of initialization here is it safe to have a parameter initialized by one initialized in the same list? i.e. as I allocate `count` before I use it is it safe to use or is there some special initialization order I could fall foul of?
|
2012/01/30
|
[
"https://Stackoverflow.com/questions/9064298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/928502/"
] |
It's not exception-safe. If the `new` for `j` throws an exception then the destructor for `Test` is not called, and so the memory for `i` is not freed.
The destructor of `i` is called if the initializer for `j` throws, it's just that a raw pointer has no destructor. So you could make it exception-safe by replacing `i` with a suitable smart pointer. In this case, `unique_ptr<int>` for `i` and `unique_ptr<int[]>` for `j` would do.
You can rely on the initializers to be executed in their correct order (the order the members are defined, not necessarily the order in the list). They can safely use data members that have already been initialized, so there's no problem with using `count` in the initializer for `k`.
|
59,357,350 |
I have list of codes which are separated by comma, the code contains min of 3 and max of 6 characters including numbers. I have written regex for this. How can I expand my regex to work with 1 or more codes as array or list?
Here is my regex for codes
```
const checkCodes = new RegExp('^[A-Z]+[A-Z0-9]{2,5}$');
```
The above regex works well with single codes
```
codes - "BCD"
```
but not for below line, which I am trying to achieve
```
codes - ["BCD", "VOC123",....1 or more codes]
```
|
2019/12/16
|
[
"https://Stackoverflow.com/questions/59357350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11671255/"
] |
```js
const checkCodes = new RegExp('^[A-Z]+[A-Z0-9]{2,5}$');
let input = ["CODE1", "NOT.A.CODE", "CODE42"];
console.log(input.filter(str => checkCodes.test(str)))
```
|
3,403 |
I'm developing a dashboard for a client, and we have some users who fit into multiple roles within the company, ie. a Project Manager and a Department Manager. In this case they function as two separate roles in the company.
Screen real estate is at a premium, so it is getting VERY difficult to squeeze the dashboard sections from both roles into one dashboard for these mutiple-role users.
What is the best way to deal with this type of situation? Should we give them a toggle to view their dashboard as either a PM or a DM? To me that sort of defeats the purpose of a dashboard, an at-a-glance lazy view of all your pertinent information.
|
2011/02/08
|
[
"https://ux.stackexchange.com/questions/3403",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/3473/"
] |
The point of a dashboard is to give the user pertinent information at a glance. The user's role is a good starting point however there is much more information you could collect to determine what dashboard elements are important to the user.
For example your users may have two roles however seeing both dashboards may not be appropriate for them. They may be a Project Manager 90% of the time and a Department Manager 10%. So to show dashboard elements for both roles with the same importance on screen would not be ideal.
It would be better to give the user the choice of what dashboard elements they wanted to see. For example you could allow them to select a profile from a predefined list or/and they could cherry pick elements form a central store. This approach allows the user to choose what elements are important to them.
Another approach would be for the application to learn about the users habits and build the dashboard elements based on that information. For example the user goes to the Project Manager pages all the time but has never gone to the Department Manager screens. Therefore the application could tailor the dashboard more to a Project Manager with maybe a 'see more' link off to the other dashboard elements.
A combination of all these would also work, allowing the user to pick and choose as they please but also the application suggesting dashboard elements based on their habits. For example if the user is always visiting the Project Manager pages as above but they have not chosen a Project Manager dashboard element the system could suggest that they add one.
|
15,838,495 |
I've implemented a `OnPreferenceChangeListener` on two preference object in my preference page ( extends `PreferenceActivity`)
But ever since the preference value isn't updated upon change,
I even tried using :
```
SharedPreferences sharedPreferences = getSharedPreferences("myCustomSharedPrefs",
Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(preference.getKey(), Integer.parseInt(newValue.toString()));
editor.commit();
```
Where `preference` is the changed preference and `newValue` is the new value...
What am I missing ?
Thanks
|
2013/04/05
|
[
"https://Stackoverflow.com/questions/15838495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1405268/"
] |
You need to return true to get the value updated, see the [Android documentation](http://developer.android.com/reference/android/preference/Preference.OnPreferenceChangeListener.html).
|
61,456,647 |
I am using the code below:
```
$global:accountArray = New-Object -TypeName "System.Collections.ArrayList"
$global:accountArray.Add("0001")
$global:accountArray.Add("0002")
$global:accountArray.Add("0003")
$global:accountArray.Add("0004")
$global:accountArray.Add("0005")
Function Remove-Numbers
{
// This loop only iterates one time
foreach ($n in $global:accountArray) {
$global:accountArray.Remove($n)
}
}
Remove-Numbers
```
I have globally declared `accountArray` variable but when I try to modify that variable in `Function` it only iterates once and loop ends(i.e. it only removes one element), what I am doing wrong?
|
2020/04/27
|
[
"https://Stackoverflow.com/questions/61456647",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6818685/"
] |
You cannot change a collection like ArrayList while iterating its items like that.
If all you want to do is empty the list, use `$global:accountArray.Clear()`
If you want to use a loop, do that by using the element index and go from bottom to top:
```
Function Remove-Numbers {
# use a loop to remove the items. go from last to first
for ($i = $global:accountArray.Count -1; $i -ge 0; $i--) {
$global:accountArray.RemoveAt($i)
}
}
```
Or use the `Remove` method slightly different by letting `$n` not being a member of the list itself, but merely the value it stores:
```
Function Remove-Numbers {
# use a loop to remove the items. Iterate using the value of the item, not the item itself.
foreach ($n in $global:accountArray.ToArray()) {
$global:accountArray.Remove($n)
}
}
```
P.S. the comment character in PowerShell is `#`, not `//`
|
65,283,926 |
I'm working on ejs-grid and I want to toggle(Expand/Collapse) a **child grid** when I click on a row in the grid.
I was able to get the row click functionality working using (rowSelected) attribute but I don't really know how to get the **current state** of a child grid(collapsed or expanded).
My Current Code
```html
toggleChildGrid(event){
const rowIndex = event.rowIndex;
const isCollapsed = true;
if(isCollapsed){
this.grid.detailRowModule.expand(rowIndex);
}
else{
this.grid.detailRowModule.collapse(rowIndex)
}
}
```
I just made the **isCollapsed** variable true but I will like that to be derived dynamically based on the state of the child grid.
|
2020/12/14
|
[
"https://Stackoverflow.com/questions/65283926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14821156/"
] |
Looks like you need to track answers for each monster, and if the are incorrect, do not allow the user to click the monster again. To do this with your current architecture, below I setup an array of answers initially set to null, meaning no answer has been given. Within the click event, we will set the monsterAnswer to be true or false based on the user's response. Hope this helps and welcome!
```js
var monsters = ["slug", "zombie", "wasp"];
var randomForMon = Math.floor(Math.random() * monsters.length);
var randMonster = monsters[randomForMon];
var user_answer = getNumber("answer_input");
var monstersAnswers = [null, null, null];
//when monster clicked, show fighting symbol and change screen
onEvent(randMonster, "click", function() {
const monsterAnswer = monstersAnswers[randomForMon];
if (monsterAnswer === false) {
// don't do anything
return;
}
hideElement("clickMonster_label");
showSymbol();
setTimeout(function() {
setScreen("equation_screen");
}, 1300);
newEquation();
var userAnswer = /* something */
monstersAnswers[randomForMon] = correctAnswer === userAnswer;
});
```
|
47,431,649 |
I am a deep learning and Tensorflow beginner and I am trying to implement the algorithm in this [paper](https://arxiv.org/abs/1611.06345) using Tensorflow. This paper uses Matconvnet+Matlab to implement it, and I am curious if Tensorflow has the equivalent functions to achieve the same thing. The paper said:
>
> The network parameters were initialized using the Xavier method [14]. We used the regression loss across four wavelet subbands under l2 penalty and the proposed network was trained by using the stochastic gradient descent (SGD). The regularization parameter (λ) was 0.0001 and the momentum was 0.9. The learning rate was set from 10−1 to 10−4 which was reduced in log scale at each epoch.
>
>
>
This paper uses wavelet transform (WT) and residual learning method (where the residual image = WT(HR) - WT(HR'), and the HR' are used for training). Xavier method suggests to initialize the variables normal distribution with
```
stddev=sqrt(2/(filter_size*filter_size*num_filters)
```
**Q1. How should I initialize the variables? Is the code below correct?**
```
weights = tf.Variable(tf.random_normal[img_size, img_size, 1, num_filters], stddev=stddev)
```
---
This paper does not explain how to construct the loss function in details . I am unable to find the equivalent Tensorflow function to set the learning rate in log scale (only `exponential_decay`). I understand `MomentumOptimizer` is equivalent to Stochastic Gradient Descent with momentum.
**Q2: Is it possible to set the learning rate in log scale?**
**Q3: How to create the loss function described above?**
I followed this [website](http://www.ritchieng.com/machine-learning/deep-learning/tensorflow/regularization/) to write the code below. Assume model() function returns the network mentioned in this paper and lamda=0.0001,
```
inputs = tf.placeholder(tf.float32, shape=[None, patch_size, patch_size, num_channels])
labels = tf.placeholder(tf.float32, [None, patch_size, patch_size, num_channels])
# get the model output and weights for each conv
pred, weights = model()
# define loss function
loss = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels, logits=pred)
for weight in weights:
regularizers += tf.nn.l2_loss(weight)
loss = tf.reduce_mean(loss + 0.0001 * regularizers)
learning_rate = tf.train.exponential_decay(???) # Not sure if we can have custom learning rate for log scale
optimizer = tf.train.MomentumOptimizer(learning_rate, momentum).minimize(loss, global_step)
```
NOTE: As I am a deep learning/Tensorflow beginner, I copy-paste code here and there so please feel free to correct it if you can ;)
|
2017/11/22
|
[
"https://Stackoverflow.com/questions/47431649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2910704/"
] |
Other answers are very detailed and helpful. Here is a code example that uses placeholder to decay learning rate at log scale. HTH.
```
import tensorflow as tf
import numpy as np
# data simulation
N = 10000
D = 10
x = np.random.rand(N, D)
w = np.random.rand(D,1)
y = np.dot(x, w)
print y.shape
#modeling
batch_size = 100
tni = tf.truncated_normal_initializer()
X = tf.placeholder(tf.float32, [batch_size, D])
Y = tf.placeholder(tf.float32, [batch_size,1])
W = tf.get_variable("w", shape=[D,1], initializer=tni)
B = tf.zeros([1])
lr = tf.placeholder(tf.float32)
pred = tf.add(tf.matmul(X,W), B)
print pred.shape
mse = tf.reduce_sum(tf.losses.mean_squared_error(Y, pred))
opt = tf.train.MomentumOptimizer(lr, 0.9)
train_op = opt.minimize(mse)
learning_rate = 0.0001
do_train = True
acc_err = 0.0
sess = tf.Session()
sess.run(tf.global_variables_initializer())
while do_train:
for i in range (100000):
if i > 0 and i % N == 0:
# epoch done, decrease learning rate by 2
learning_rate /= 2
print "Epoch completed. LR =", learning_rate
idx = i/batch_size + i%batch_size
f = {X:x[idx:idx+batch_size,:], Y:y[idx:idx+batch_size,:], lr: learning_rate}
_, err = sess.run([train_op, mse], feed_dict = f)
acc_err += err
if i%5000 == 0:
print "Average error = {}".format(acc_err/5000)
acc_err = 0.0
```
|
35,444,952 |
I'm currently doing my first steps with SAP HANA Vora on Cloudera Express 5.5.0.
The Vora server is up and running and I would now like to use the Vora spark shell but this is what I get:
```
sh start-spark-shell.sh
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/spark/launcher/Main
Caused by: java.lang.ClassNotFoundException: org.apache.spark.launcher.Main
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: org.apache.spark.launcher.Main. Program will exit.
```
This is how my environment looks like:
```
export LD_LIBRARY_PATH=/opt/cloudera/parcels/CDH/lib/hadoop/lib/native
export JAVA_HOME=/usr/java/default
export HADOOP_PARCEL_PATH=/opt/cloudera/parcels/CDH
export HADOOP_CONF_DIR=/etc/hadoop/conf
export SPARK_HOME=/usr/lib/spark
export SPARK_CONF_DIR=$SPARK_HOME/conf
export PATH=$PATH:$SPARK_HOME/bin
SPARK_DIST_CLASSPATH=$SPARK_HOME/lib/spark-assembly.jar
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/hadoop/lib/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/hadoop/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/hadoop-hdfs/lib/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/hadoop-hdfs/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/hadoop-mapreduce/lib/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/hadoop-mapreduce/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/hadoop-yarn/lib/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/hadoop-yarn/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/hive/lib/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/flume-ng/lib/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/parquet/lib/*
SPARK_DIST_CLASSPATH=$SPARK_DIST_CLASSPATH:$HADOOP_PARCEL_PATH/lib/avro/lib/*
export SPARK_DIST_CLASSPATH
```
|
2016/02/16
|
[
"https://Stackoverflow.com/questions/35444952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1867854/"
] |
The cron job has been running for a while now without any issues, and it is keeping the space usage under control.
I have reduced the parameter to 15 days.
My crontab looks like this:
```
# clean up old files from working directory
0 20 * * * find /<path_to>/bamboo-home/xml-data/build-dir/ -depth -not -path *repositories-cache* -atime +15 -delete
# clean up old backups every Sunday
0 21 * * 0 find /<path_to>/bamboo-home/backups -type f -mtime +28 -delete
# remove any old logs from install directory after 15 days
0 22 * * * find /<path_to>/bamboo/logs/ -type f -mtime +15 -delete
# quick and dirty truncate catalina.out to stop it growing too large (or better still use logrotate)
0 23 * * * cat /dev/null > /<path_to>/bamboo/logs/catalina.out
```
I hope this is useful for others trying to tame bamboo's diskspace usage.
The first job is the important one, the last three are just housekeeping.
N.B. logrotate is not used on catalina.out due to unique circumstances in my companies outsourced linux environment. I would generally recommend logrotate if possible rather than my quick and dirty truncate method - see answer by Jon V.
|
171,748 |
I am trying to plot the solid formed by the intersection of the surface between
```
p1 = Plot3D[1 + x^2 - y^2, {x, -1.2, 1.2}, {y, -1.2, 1.2}]
```
and
```
p2 = Plot3D[3 Log[1 + x^2], {x, -1.4, 1.4}, {y, -1, 1}]
```
I am also trying to get the volume of said solid. I've tried the solution given in [How to plot and find the volume of a solid?](https://mathematica.stackexchange.com/q/39161/57777), but I am only recently starting in this language and can't manage to adapt it to work with my functions. Any help will be apreciated. Thank you.
Here is the code for the two surfaces and its intersection.
[](https://i.stack.imgur.com/JiLGw.png)
|
2018/04/23
|
[
"https://mathematica.stackexchange.com/questions/171748",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/57777/"
] |
Clearly the maximum x extent will be when y==0. Use `Reduce` to find the x extent.
```
Reduce[1+x^2-0^2==3 Log[1+x^2],x]
```
Use `Reduce` to find the y extent for a given x.
```
Reduce[1+x^2-y^2==3 Log[1+x^2],y]
```
Then `Integrate` over the y extent for each x to find the volume.
```
NIntegrate[1+x^2-y^2-3 Log[1+x^2],
{x,-Sqrt[E^(-ProductLog[-1/3])-1],Sqrt[E^(-ProductLog[-1/3])-1]},
{y,-Sqrt[1+x^2-3*Log[1+x^2]],Sqrt[1+x^2-3*Log[1+x^2]]}]
```
In exactly the same way `Plot3D` the volume between them.
```
Plot3D[{1+x^2-y^2,3 Log[1+x^2]},
{x,-Sqrt[E^(-ProductLog[-1/3])-1],Sqrt[E^(-ProductLog[-1/3])-1]},
{y,-Sqrt[1+x^2-3*Log[1+x^2]],Sqrt[1+x^2-3*Log[1+x^2]]}]
```
Check all this very carefully to make certain no mistakes have been made.
|
30,044,954 |
My develop H/W environment is Raspberry Pi2 & VX-1000 camera
My develop S/W environment is Arch linux & c++ & opencv
I could stream on webpage by using mjpg-streamer
with this command `mjpg_streamer -i "./input_uvc.so -d /dev/video0 -n -f 30 -r 320x240" -o "./output_http.so -n -w ./www"`
This run is good. (turns on camera (means turns on led on camera) )
But when I execute the program made by opencv code, it doesn't turn on camera (not turn on led) and the function `cvCaptureFromCAM()` returns `NULL`.
My source code is
```
#include <iostream>
#include <time.h>
#include <opencv/cv.h>
#include <opencv/highgui.h>
using namespace cv;
using namespace std;
int main(int argc,char** argv)
{
char c;
IplImage* frame;
CvCapture* capture;
capture = cvCaptureFromCAM(-1);
if(capture == NULL)
cout << "Strange!!" << endl;
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH , 320);
cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT , 240);
bool bLoop = true;
cout << "Start streaming" << endl;
while (bLoop){
cvGrabFrame(capture); // Get a frame from cam
frame = cvRetrieveFrame(capture, 0); // get a frame from capture
cvSaveImage("save.jpg", frame);
cvWaitKey(33); // wait key input for 33ms
}
cvReleaseCapture(&capture);
cvDestroyAllWindows();
return 0;
}
```
|
2015/05/05
|
[
"https://Stackoverflow.com/questions/30044954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4864919/"
] |
wrap this util method into a Utility class build the jar and put it in classpath of your iReport and whenever you are compiling this jrxml
|
39,556,519 |
I want to create a sass file that the selectors will be attribute selectors.
When I work with class selectors, in most of the cases I will do
```
.parent {
&-child {
}
}
```
which gives me the following css: `.parent-child {}`.
I want to achieve the same thing with attribute selectors:
```
[data-parent] {
&-child {
}
}
```
which I want to become: `[data-parent-child] {}`
someone knows how to achieve this? thanks.
|
2016/09/18
|
[
"https://Stackoverflow.com/questions/39556519",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1926936/"
] |
You can use this `mixin` as a workaround to get the desired result.
```
@mixin child-attribute($child) {
$string: inspect(&);
$original: str-slice($string, 3, -4);
@at-root #{ selector-replace(&, &, "[#{$original}#{$child}]" ) } {
@content;
}
}
```
The code simply does the following
1. **$string** variable is responsible for turning the parent selector to a string using the `inspect` function
2. **$original** variable is responsible for getting the *text* content of the `$string` variable i.e the value `'data-parent'` from `'([data-parent])'`
3. **selector-replace** function then replaces the parent selector with the concatenation of the `$original` variable and `child` variable
When used in the following ways
```
[data-parent] {
@include child-attribute('-child') {
color: green;
}
}
```
The css output
```
[data-parent-child] {
color: green;
}
```
Depending on what you want to achieve, it can also be used like this
```
[grandparent] {
@include child-attribute('-parent') {
color: white;
@include child-attribute('-child') {
color: blue;
}
}
}
```
Which generates the following css
```
[grandparent-parent] {
color: white;
}
[grandparent-parent-child] {
color: blue;
}
```
Hope this helps you
|
65,198,438 |
We have an application in Asp.net Webform. We must use passwordless sign-in using Microsoft Authenticator App. Basically, the user enters samAccountName, and the system must check Microsoft Authenticator App for approval, and based on the response we have to redirect to change the password screen.
We have a login module that validates our username password with the internal Active directory. We cannot implement a new authentication model now. We just need validation using the Microsoft Authenticator app after approval from the app we need to redirect to the change password screen there we will change the AD account password.
Where do I start with? Plz Help give some idea
|
2020/12/08
|
[
"https://Stackoverflow.com/questions/65198438",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8152735/"
] |
The Raw Database returns correct time because DBMS time zone is correct.
but in Eloquent, `created_at` field converts into an `Carbon::class` instance by default.
and `Carbon::class` will use timezone configuration of your app to convert to real time.
so change in laravel `./config/app.php` :
```
'timezone' => 'Asia/Kuala_Lumpur',
```
because i suppose you are in +8 Timezone based on your profile location,
and your reporting time log are 8 hours difference from **UTC** the default time zone config in Laravel.
|
6,034,883 |
I'm just wondering if it is possible..
I have a base class, with a variable called Level. I then derive a class from it, but here Level should be called Points.
Is there any way to rename the Level variable in the derived class?
**Edit** - Excuse me for calling a property a variable. I'm quite new to programming, and especially to classes (Which our teacher doesn't teach us for some reason)
|
2011/05/17
|
[
"https://Stackoverflow.com/questions/6034883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/719392/"
] |
The closest you could get with inheritance would be:
```
class BaseClass
{
protected int Level { get; set; }
}
class SubClass : BaseClass
{
public int Points { get { return Level; } set { Level = value; } }
}
```
But that doesn't actually *expose* BaseClass.Level, since a protected property is only visible to subclasses.
As @Jason explains, a subclass can't obscure the public interface of its base class. If you really wanted to do that, you could *encapsulate* the base in a new object that exposes its properties:
```
class A
{
public Foo { get; set; }
public Bar { get; set; }
public Level { get; set;}
}
class B
{
private A _internalA;
public Foo { get { return _internalA.Foo; } set { _internalA.Foo = value; } }
public Bar { get { return _internalA.Bar; } set { _internalA.Bar= value; } }
public Points { get { return _internalA.Level; } set { _internalA.Level = value; } }
}
```
This is typically referred to as *composition*: B is composed of A, rather than inheriting from it.
|
54,847,976 |
**What happened:**
1. I have multiple objects saved in an arraylist that is saved in a gson string.
2. I change the class of the object (to include more variables and getter/setter methods)
3. Now I run into errors when trying to load the older objects (saved in step 1)
**Things to consider:**
I use gson/json to store the arraylist in an android shared preference. (the shared preference works fine for other values, the error appears to be when converting the string into an arraylist with json/gson)
**My code:**
```
public void loadDataSavedMatches() {
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = prefs.getString("task list", null);
Type type = new TypeToken<ArrayList<TennisMatch>>() {
}.getType();
mTennisMatches = gson.fromJson(json, type);
if (mTennisMatches == null) {
mTennisMatches = new ArrayList<>();
}
Log.i("LOAD DATA", String.valueOf(mTennisMatches));
Log.i("LOAD DATA2", String.valueOf(prefs));
//hashMap
SharedPreferences hashPrefs = getSharedPreferences(HASH_MAP_SHARED_PREFS_FILE, Context.MODE_PRIVATE);
Gson hashGson = new Gson();
String hashJson = hashPrefs.getString("hashString", null);
Type hashType = new TypeToken<HashMap<String, TennisMatch>>() {
}.getType();
item_map = hashGson.fromJson(hashJson, hashType);
if (item_map == null) {
item_map = new HashMap<String, TennisMatch>();
}
}
```
**Error message:**
```
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.myapp, PID: 28341
java.lang.AssertionError: impossible
at java.lang.Enum$1.create(Enum.java:45)
at java.lang.Enum$1.create(Enum.java:35)
at libcore.util.BasicLruCache.get(BasicLruCache.java:54)
at java.lang.Enum.getSharedConstants(Enum.java:211)
at java.lang.Class.getEnumConstants(Class.java:1063)
at com.google.gson.internal.bind.TypeAdapters$EnumTypeAdapter.<init>(TypeAdapters.java:778)
at com.google.gson.internal.bind.TypeAdapters$30.create(TypeAdapters.java:817)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:53)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:53)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.Gson.fromJson(Gson.java:887)
at com.google.gson.Gson.fromJson(Gson.java:853)
at com.google.gson.Gson.fromJson(Gson.java:802)
at com.android.myapp.Activity.loadDataSavedMatches(ItemMatchListActivity.java:282)
at com.android.myapp.Activity.onCreate(ItemMatchListActivity.java:87)
at android.app.Activity.performCreate(Activity.java:6102)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
at android.app.ActivityThread.access$1200(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5593)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.NoSuchMethodException: values []
at java.lang.Class.getMethod(Class.java:664)
at java.lang.Class.getDeclaredMethod(Class.java:626)
at java.lang.Enum$1.create(Enum.java:41)
at java.lang.Enum$1.create(Enum.java:35)
at libcore.util.BasicLruCache.get(BasicLruCache.java:54)
at java.lang.Enum.getSharedConstants(Enum.java:211)
at java.lang.Class.getEnumConstants(Class.java:1063)
at com.google.gson.internal.bind.TypeAdapters$EnumTypeAdapter.<init>(TypeAdapters.java:778)
at com.google.gson.internal.bind.TypeAdapters$30.create(TypeAdapters.java:817)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:53)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:115)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:164)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:100)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory.create(CollectionTypeAdapterFactory.java:53)
at com.google.gson.Gson.getAdapter(Gson.java:423)
at com.google.gson.Gson.fromJson(Gson.java:887)
at com.google.gson.Gson.fromJson(Gson.java:853)
at com.google.gson.Gson.fromJson(Gson.java:802)
at com.android.myapp.Activity.loadDataSavedMatches(ItemMatchListActivity.java:282)
at com.android.myapp.Activity.onCreate(ItemMatchListActivity.java:87)
at android.app.Activity.performCreate(Activity.java:6102)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2403)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
at android.app.ActivityThread.access$1200(ActivityThread.java:165)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1373)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5593)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
```
**Thank you for your help!**
|
2019/02/24
|
[
"https://Stackoverflow.com/questions/54847976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8539070/"
] |
See [Android release APK crash with java.lang.AssertionError: impossible in java.lang.Enum](https://stackoverflow.com/questions/20651575/android-release-apk-crash-with-java-lang-assertionerror-impossible-in-java-lang/20651744), [AssertionError in Gson EnumTypeAdapter when using Proguard Obfuscation](https://stackoverflow.com/questions/15543607/assertionerror-in-gson-enumtypeadapter-when-using-proguard-obfuscation) or <https://github.com/zendesk/sunshine-conversations-android/issues/93>. In `proguard-rules.pro` add:
```
-keepclassmembers enum * {
public static **[] values();
public static ** valueOf(java.lang.String);
}
```
|
39,774,940 |
I wrote a data using influx command (CLI) as follows:
```
CREATE DATABASE mydb
USE mydb
insert test value=1234567890123456789i
```
Then, I read the data using influx command (CLI)
```
> select * from test
name: test
time value
1475129299322514085 1234567890123456789
```
OK. No Problem.
But when I read the data using a JAVA program with influxdb-java-2.3.jar:
```
public static void main(String[] args) {
InfluxDB conn = InfluxDBFactory.connect(DB_URL, DB_USER, DB_PASSWD);
String sql = "SELECT time,value from test";
Query query = new Query(sql, DB_NAME);
QueryResult result = conn.query(query, TimeUnit.NANOSECONDS);
Series series = result.getResults().get(0).getSeries().get(0);
System.out.println(series.getColumns().get(0) + "=" + series.getValues().get(0).get(0) + " " + series.getValues().get(0).get(0).getClass().getName());
System.out.println(series.getColumns().get(1) + "=" + series.getValues().get(0).get(1) + " " + series.getValues().get(0).get(1).getClass().getName());
}
```
The result is:
```
time=1.47512929932251418E18 java.lang.Double
value=1.23456789012345677E18 java.lang.Double
```
Why was *"time"* returned in *"Double"* even though the query option was NANOSECONDS?
Why was *"value"* returned in *"Double"* even though the data was inserted with "i" suffix?
The "value" I am expecting is *1234567890123456789*, not *1234567890123456770* *(=1.23456789012345677E18)*.
How will I be able to get "Long" values without rounding error using influxdb-java.jar?
|
2016/09/29
|
[
"https://Stackoverflow.com/questions/39774940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6900431/"
] |
use MSGPACK Format, on influxdb-java-2.15.jar
```
OkHttpClient.Builder client = new OkHttpClient.Builder();
InfluxDB jsonInfluxDB = InfluxDBFactory.connect(URL, USER, PASSWORD, client, ResponseFormat.JSON);
InfluxDB msgpackInfluxDB = InfluxDBFactory.connect(URL, USER, PASSWORD, client, ResponseFormat.MSGPACK);
//influxDB.setLogLevel(InfluxDB.LogLevel.FULL);
Query query = new Query("SELECT * FROM xxx LIMIT 1", "XXX");
QueryResult jsonResult = jsonInfluxDB.query(query, TimeUnit.NANOSECONDS);
logger.info("{}", jsonResult);
QueryResult msgpackResult = msgpackInfluxDB.query(query, TimeUnit.NANOSECONDS);
logger.info("{}", msgpackResult);
```
Result
```
INFO test - QueryResult [results=[Result [series=[Series [name=mib, tags=null, columns=[time, commodity, country, expiration, high, indicator, instrument, last, low, market, modifier, open, strike, turnover, volume], values=[[1.56937620100001485E18, 300, 96, 20191213, 1.621E7, =, 11, 1.6145E7, 1.592E7, 60, 0, 1.6E7, 0, 55640.0, 2.0]]]], error=null]], error=null]
INFO test - QueryResult [results=[Result [series=[Series [name=mib, tags=null, columns=[time, commodity, country, expiration, high, indicator, instrument, last, low, market, modifier, open, strike, turnover, volume], values=[[1569376201000014846, 300, 96, 20191213, 16210000, =, 11, 16145000, 15920000, 60, 0, 16000000, 0, 55640, 2]]]], error=null]], error=null]
```
|
57,472,014 |
This is the jsp page I'm using.I wrote javascript inside jsp. I have done some validation on form and then ajax call is used. Please check whether I have done something wrong in jsp.
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Register page</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<h3>Student registration form:</h3>
<form action="RegisterController" method="get" id="registerForm" name="stud" >
<table>
<tr>
<td><label>Username:</label></td>
<td><input type="text" name="uname" id="uname"></td><td><label id="nameId"></label></td>
</tr>
<tr>
<td><label>Email id:</label></td>
<td><input type="text" name="email" id="email"></td><td><label id="emailId"></label></td>
</tr>
<tr>
<td><label>Contact No:</label></td>
<td><input type="number" name="contact" id="contact"></td><td><label id="contactId"></label></td>
</tr>
<tr>
<td><label>Address:</label></td>
<td><textarea name="address" rows="3" cols="20" id="address"></textarea></td><td><label id="addressId"></label></td>
</tr>
<tr>
<td>Select City:</td>
<td>
<input type="text" list="city" name="cities" id="cities">
<datalist id="city">
<option value="Mumbai">Mumbai</option>
<option value="Pune">Pune</option>
<option value="Nashik">Nashik</option>
<option value="Solapur">Solapur</option>
</datalist>
</td><td>
<label id="cityId"></label>
</td>
</tr>
<tr>
<td>Gender:</td>
<td><input id="r1" type="radio" name="gender" value="male">Male<input id="r2" type="radio" name="gender" value="female">Female</td><td><label id="genderId"></label></td>
</tr>
<tr>
<td><label>Courses:</label></td>
<td>Java<input id="cb1" type="checkbox" name="course" value="java">Spark<input id="cb2" type="checkbox" name="course" value="spark">Hadoop<input id="cb3" type="checkbox" name="course" value="hadoop">PHP<input id="cb4" type="checkbox" name="course" value="php"></td><td><label id="courseId"></label></td>
</tr>
<tr>
<td>Select Time Preferable</td>
<td>
<select name="batches" id="batches">
<option value="7 am to 8 am">7 am to 8 am</option>
<option value="9 am to 10 am">9 am to 10 am</option>
<option value="11 am to 12 pm">11 am to 12 pm</option>
</select>
</td>
</tr>
</table>
<br>
<input type="submit" value="Register" id="Register"><br><br>
</form>
<a href="index.jsp">Go to login page</a>
</body>
<script type="text/javascript">
$(document).ready(function(){
$('#registerForm').submit(function(es){
es.preventDefault();
var name=$('#uname').val();
var email=$('#email').val();
var contact=$('#contact').val();
var address=$('#address').val();
var city=$('#cities').val();
var gender1=$('#r1').is(":checked");
var gender2=$('#r2').is(":checked");
var cbOne=$('#cb1').is(":checked");
var cbTwo=$('#cb2').is(":checked");
var cbThree=$('#cb3').is(":checked");
var cbFour=$('#cb4').is(":checked");
$('.error').remove();
//validating fields of form
if(name.length<=0){
$('#nameId').after('<span class="error" style="color:red">Enter the Username</span>');
}
if(contact.length!=10){
$('#contactId').after('<span class="error" style="color:red">Enter valid contact number</span>');
}
if(address.length<=0){
$('#addressId').after('<span class="error" style="color:red">Enter the address</span>');
}
if(city.length<=0){
$('#cityId').after('<span class="error" style="color:red">Enter the city</span>');
}
if(!(gender1||gender2)){
$('#genderId').after('<span class="error" style="color:red">Select gender</span>');
}
if(!(cbOne||cbTwo||cbThree||cbFour)){
$('#courseId').after('<span class="error" style="color:red">Select at least one course</span>')
}
if(email.length<=0){
$('#emailId').after('<span class="error" style="color:red">Enter the email</span>');
}
else{
//var regEx=/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
//var regEx=/^\w+@[a-zA-Z]+\.[a-zA-Z]{2,3}$/;
var regEx=/^[a-zA-Z0-9]+@[a-zA-Z]+\.[com]{3}$/;
var validEmail=regEx.test(email);
if(!validEmail){
$('#emailId').after('<span class="error" style="color:red">Enter valid email</span>');
}
}
//data to be passed
var form_data={
username:$('#uname').val(),
email:$('#email').val(),
contact:$('#contact').val(),
address:$('#address').val(),
city:$('#cities').val(),
batch:$('#batches').val()
};
//ajax call goes here
$.ajax({
type: 'GET',
url: './RegisterController',
dataType: 'json',
data: form_data,
success: function(){
console.log("Sucess: ");
},
error : function(message) {
alert("error: "+message);
}
});
});
} );
</script>
</html>
```
I'm creating a registration form and want to transfer data of form using ajax call.I wrote the javascript for it. But Ajax call is triggering error function. I'm not getting what is wrong in the code.
```js
<script type="text/javascript">
$(document).ready(function(){
$('#registerForm').submit(function(es){
es.preventDefault();
var form_data={
username:$('#uname').val(),
email:$('#email').val(),
contact:$('#contact').val(),
address:$('#address').val(),
city:$('#cities').val(),
batch:$('#batches').val()
};
$.ajax({
type: 'GET',
url: 'RegisterController',
data: form_data,
success: function(){
console.log("Sucess: ");
},
error : function(message) {
alert("error: "+message);
}
});
});
} );
</script>
```
Thanks in advance.
|
2019/08/13
|
[
"https://Stackoverflow.com/questions/57472014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11920605/"
] |
you can chnage the class of `white-text` to `text-white` and for background-color add `bg-primary` and also add code for custom color.
```css
.bg-custom{
background-color:#33b5e5 !important;
}
```
```html
<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<h3>Default color</h3>
<h5 class="card-header bg-primary text-white text-center py-4" >Sign in</h5>
<hr/>
<h3>Custom color</h3>
<h5 class="card-header bg-custom text-white text-center py-4" >Sign in</h5>
<hr/>
<h3>With inline css</h3>
<h5 class="card-header text-white text-center py-4" style="background-color:#33b5e5">Sign in</h5>
```
|
546,986 |
$$\int\_0^\frac{\pi}{2}(\sin^3x +\cos^3x) \, \mathrm{d}x$$
How do I compute this? I tried to do the trigonometric manupulation but I can't get the answer.
|
2013/10/31
|
[
"https://math.stackexchange.com/questions/546986",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/101194/"
] |
Hint: $\sin^3 x dx = -\sin^2 xd(\cos x) = (\cos^2 x - 1)d(\cos x)$. Do the same for $\cos^3 x dx$.
|
50,256,184 |
This is just a small portion of the data frame I am working with:
```
id drug start stop dose unit route
2010003 Amlodipine 2009-02-04 2009-11-19 1.5 mg Oral
2010003 Amlodipine 2009-11-19 2010-01-11 1.5 mg Oral
2010004 Cefprozil 2004-03-12 2004-03-19 175 mg Oral
2010004 Clobazam 2002-12-30 2003-01-01 5 mg Oral
```
I have a Stata `do` file, which shows what I am trying to do:
```
replace class = "ACE Inhibitor" if strmatch(upper(drug), "CAPTOPRIL*")
replace class = "ACE Inhibitor" if strmatch(upper(drug), "ENALAPRIL*")
replace class = "ACE Inhibitor" if strmatch(upper(drug), "ENALAPRILAT*")
replace class = "ACE Inhibitor" if strmatch(upper(drug), "FOSINOPRIL*")
replace class = "ACE Inhibitor" if strmatch(upper(drug), "LISINOPRIL*")
replace class = "ACE Inhibitor" if strmatch(upper(drug), "RAMIPRIL*")
replace class = "Acne Medication" if strmatch(upper(drug), "ADAPALENE*")
replace class = "Acne Medication" if strmatch(upper(drug), "ADAPALENE/BENZOYL PEROXIDE*")
replace class = "Acne Medication" if strmatch(upper(drug), "BENZOYL PEROXIDE*")
replace class = "Acne Medication" if strmatch(upper(drug), "BENZOYL PEROXIDE/CLINDAMYCIN*")
replace class = "Acne Medication" if strmatch(upper(drug), "ISOTRETINOIN*")
replace class = "Acne Medication" if strmatch(upper(drug), "ERYTHROMYCIN/TRETINOIN*")
replace class = "Acne Medication/Acute Promyelocytic Leukemia Medication" if strmatch(upper(drug), "TRETINOIN*")
replace class = "Alpha Agonist" if strmatch(upper(drug), "XYLOMETAZOLINE*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "DOXAZOSIN*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "PHENOXYBENZAMINE*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "PHENTOLAMINE*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "PRAZOSIN*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "TAMSULOSIN*")
replace class = "Alpha Blocker" if strmatch(upper(drug), "TERAZOSIN*")
replace class = "Alpha/Beta Blocker" if strmatch(upper(drug), "CARVEDILOL*")
replace class = "Alpha/Beta Blocker" if strmatch(upper(drug), "LABETALOL*")
replace class = "Alpha-1 Agonist" if strmatch(upper(drug), "PHENYLEPHRINE*")
replace class = "Alpha-1 Agonist" if strmatch(upper(drug), "MIDODRINE*")
replace class = "Alpha-2 Agonist" if strmatch(upper(drug), "CLONIDINE*")
replace class = "Alpha-2 Agonist" if strmatch(upper(drug), "DEXMEDETOMIDINE*")
replace class = "Anaesthetic, general" if strmatch(upper(drug), "KETAMINE*")
replace class = "Anaesthetic, general" if strmatch(upper(drug), "THIOPENTAL*")
replace class = "Anaesthetic, local" if strmatch(upper(drug), "BENZOCAINE*")
replace class = "Anaesthetic, local" if strmatch(upper(drug), "BUPIVACAINE*")
replace class = "Anaesthetic, local" if strmatch(upper(drug), "BUPIVACAINE/FENTANYL*")
replace class = "Anaesthetic, local" if strmatch(upper(drug), "TETRACAINE*")
replace class = "Anaesthetic, local" if strmatch(upper(drug), "XYLOCAINE*")
replace class = "Anaesthetic, local/Antiarrythmic" if strmatch(upper(drug), "LIDOCAINE*")
replace class = "Anaesthetic, local/Antiseptic" if strmatch(upper(drug), "HEXYLRESORCINOL*")
replace class = "Anaesthetic, topical" if strmatch(upper(drug), "LIDOCAINE/PRILOCAINE*")
replace class = "Anaesthetic, topical" if strmatch(upper(drug), "PROPARACAINE*")
replace class = "Analgesic" if strmatch(upper(drug), "ACETAMINOPHEN*")
replace class = "Analgesic" if strmatch(upper(drug), "BELLADONNA & OPIUM SUPPOSITORY*")
```
I want to do the same classification in R but I do not know Stata.
Note that drugs can have more than one `class`.
Any advice and help would be greatly appreciated.
|
2018/05/09
|
[
"https://Stackoverflow.com/questions/50256184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Change the code with:
```
[Unit]
Description=Atlassian Bamboo Agent
After=syslog.target network.target
[Service]
Type=forking
User=apps
Group=apps
ExecStart=/apps/bamboo-agent/bin/bamboo-agent.sh start
ExecStop=/apps/bamboo-agent/bin/bamboo-agent.sh stop
[Install]
WantedBy=multi-user.target
```
Then reload and start it (as root or using sudo)
```
systemctl daemon-reload
systemctl start bamboo-agent
```
Res: <https://community.atlassian.com/t5/Bamboo-questions/How-to-I-install-bamboo-agent-as-a-daemon-under-Linux/qaq-p/393880>
|
2,014,099 |
i am trying to use velocity framework on google app engine. i wrote a small program with a main method and tried running it locally. i get the following exception :
```
Exception in thread "main" org.apache.velocity.exception.VelocityException: Failed to initialize an instance of org.apache.velocity.runtime.log.ServletLogChute with the current runtime configuration.
at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:206)
at org.apache.velocity.runtime.log.LogManager.updateLog(LogManager.java:255)
at org.apache.velocity.runtime.RuntimeInstance.initializeLog(RuntimeInstance.java:795)
at org.apache.velocity.runtime.RuntimeInstance.init(RuntimeInstance.java:250)
at org.apache.velocity.app.VelocityEngine.init(VelocityEngine.java:107)
at Main.main(Main.java:10)
Caused by: java.lang.UnsupportedOperationException: Could not retrieve ServletContext from application attributes
at org.apache.velocity.runtime.log.ServletLogChute.init(ServletLogChute.java:73)
at org.apache.velocity.runtime.log.LogManager.createLogChute(LogManager.java:157)
... 5 more
```
Here is my program:
```
import java.io.StringWriter;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
public class Main {
public static void main(String[] args) throws Exception{
/* first, get and initialize an engine */
VelocityEngine ve = new VelocityEngine();
ve.init();
/* next, get the Template */
Template t = ve.getTemplate( "helloworld.vm" );
/* create a context and add data */
VelocityContext context = new VelocityContext();
context.put("name", "World");
/* now render the template into a StringWriter */
StringWriter writer = new StringWriter();
t.merge( context, writer );
/* show the World */
System.out.println( writer.toString() );
}
}
```
the same program runs perfectly fine on a normal eclipse project. what could be the problem?
|
2010/01/06
|
[
"https://Stackoverflow.com/questions/2014099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122466/"
] |
Seems to only be the `ServletLogChute` class that requires the `ServletContext`, Velocity itself can work entirely standalone from a Servlet environment.
Since you obviously don't have a servelt log, try adding the following before you call `ve.init()`:
```
ve.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogChute");
```
...or [check here if you have specific logging requirements](http://velocity.apache.org/engine/releases/velocity-1.6.2/developer-guide.html#Configuring_Logging).
|
204,711 |
We were migrating from [Java 6](http://en.wikipedia.org/wiki/Java_version_history#Java_SE_6_.28December_11.2C_2006.29) to [Java 7](http://en.wikipedia.org/wiki/Java_version_history#Java_SE_7_.28July_28.2C_2011.29). The project is behind schedule and risks being dropped, in which case it will continue to use Java 6.
What are the specific improvements in Java 7 that we could go back to our manager with and convince him it is important to use JDK 7? Looking for bug fixes that I could highlight in Oracle Java 7 (with respect to Java 6). Fixes in security, performance, [Java 2D](http://en.wikipedia.org/wiki/Java_2D)/printing, etc. will be more sellable in my case. Compiler fixes for example, will not of much use.
[I am going through many sites like [Oracle adoption guide](http://docs.oracle.com/javase/7/docs/webnotes/adoptionGuide/), bug database, [questions](https://stackoverflow.com/questions/741082/what-differences-will-java-7-have-from-java-6-and-what-will-it-mean-to-us-java?rq=1) on Stack Overflow].
Update: Thanks for the answers. We rescheduled the update to next release. Closest we got was security. Accepting the highest voted answer.
|
2013/07/13
|
[
"https://softwareengineering.stackexchange.com/questions/204711",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/3005/"
] |
Java 6 has [reached EOL in February this year](http://www.oracle.com/technetwork/java/javase/eol-135779.html#Java6-end-public-updates) and will no longer receive public updates (including security) unless you buy very expensive enterprise support.
That should be all the reason needed.
Besides, overwhelming evidence suggests that backwards compatibility for Java runtimes is excellent. Chances are that you just have to replace the Java 6 installations with Java 7 and all applications will just continue to work without any problems. Of course this is not guaranteed and extensive tests are recommended to confirm that there will indeed be no problems.
|
1,791,622 |
Ok, we have two expressions:
>
> $30x + 1500$
>
> $19x + 9000$
>
>
>
The first thing to note is, the first expression is $100\%$ and the second expression is $0\%$.
The second thing is to note in all of this is, $x$ is infinite in these expressions.
Ok, my main question is where would $23x + 15590$ go in the range as a percent? and how do you prove this? I don't know how but I'll accept any answer that makes sense. Bearing in mind $x$ is infinite, how?
Thank you though, I look forward to your answers.
EDIT: Hello guys, I apologize if that didn't make any sense. I meant in terms of this: [link](https://math.stackexchange.com/questions/51509/how-to-calculate-percentage-of-value-inside-arbitrary-range)
|
2016/05/19
|
[
"https://math.stackexchange.com/questions/1791622",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/339400/"
] |
I guess you mean three values linearly dependent on $x$, say $f(x), g(x), h(x),$ the third one falling between the former two for $x$ big enough; and you are asking about an asymptotic value of the proportion
$$\frac{h-f}{g-f}$$
as $x$ grows to infinity.
That is
$$\begin{align}
\lim\_{x\to\infty}\frac{(23x+15590)-(19x+9000)}{(30x+1500)-(19x+9000)} &
= \lim\_{x\to\infty}\frac{4x+6590}{11x-7500} \\
& = \lim\_{x\to\infty}\frac{4+6590/x}{11-7500/x} \\
& = \frac{4+0}{11-0} \\
& = \frac 4{11} \\
& \approx 0,363636 \\
& \approx 36.4\%
\end{align}$$
For example, here are some values of the fraction defined above:
for $x=10^3\ \,$ it is $\approx 3.025714286$,
for $x=10^4\ \,$ it is $\approx 0.454536586$,
for $x=10^8\ \,$ it is $\approx 0.363644834$ and
for $x=10^{10}$ it is $\approx 0.363636448$.
But please note that the limit value as $x$ grows to infinity is **not** the same as a 'proportion of infinite values'! The former exists and can be calculated, the latter simply does not exist, is undefined.
|
662,190 |
I try to Check the latest Firefox and want to get all hashes in one TXT file.
What I try to do is:
```
sha1sum firefox.tar.gz > sha.txt
```
and I try also:
```
md5sum firefox.tar.gz > sha.txt | sha1sum firefox.tar.gz > sha.txt | sha512sum firefox.tar.gz > sha.txt
```
but only the last in this case the sha512 is printed to the sha.txt.
What am I doing wrong? Please can someone out there help me with this?
|
2015/08/16
|
[
"https://askubuntu.com/questions/662190",
"https://askubuntu.com",
"https://askubuntu.com/users/268803/"
] |
As others have already pointed out the difference between `>` (overwrite) and `>>` (append) redirection operators, i am going to give couple of solutions.
1. You can use the command grouping `{}` feature of `bash` to send the output of all the commands in a single file :
```
{ sha1sum foo.txt ;sha512sum foo.txt ;md5sum foo.txt ;} >checksum.txt
```
2. Alternately you can run the commands in a subshell `()` :
```
( sha1sum foo.txt ;sha512sum foo.txt ;md5sum foo.txt ) >checksum.txt
```
|
12,101 |
I have a Flex 3000 connected via RG-11 coax to a inverted V fan dipole tuned for 40m and 20m on my roof. I have an "ugly" balun up on the mast by the antenna. I further have the feed-line going into a lightning suppressor where the line enters into the house and is connected to my 8 foot ground rod.
I realize that my coax is not 50ohm (it's 75ohm) but I'm operating at 80, 40, and 20m. My SWR is 1.1 on 40m and 1.4 on 20m and my ATU takes care of the rest. My understanding is that this should not be much of a factor on HF. In fact this coax is plenum rated so it has the extra shielding as well so it's very well guarded from external interference. Unless of course that extra shielding is having the reverse effect allowing even more RFI to flow down the shielding as it's acting as a fantastic antenna. Hence why I'm trying to do what I'll explain next...
I'm trying to reduce various RFI on 80m and 40m (some 20m) coming into my shack (and also eliminate RFI going out to various devices by my transmissions) but have not had much success. I'm trying to use ferrite cores to help reduce some of this...
I have these Fair-Rite ferrite cores from www.mouser.ca...
[Mouser Link](https://www.mouser.ca/ProductDetail/Fair-Rite/2631803802?qs=%2Fha2pyFadui69ZHDvBYwaNp1oYkvVAjIv5TPhphggYvPCnPIGmFbbQ%3D%3D)
Which should be these specific cores on the Fair-Rite Site...
[Fair-Rite Link](https://www.fair-rite.com/product/round-cable-emi-suppression-cores-2631803802/)
My understanding is that these are the #31 material as mentioned in numerous documents, not the least of which is Jim Brown's (K9YC) Guide to RFI, Ferrites, Baluns, and Audio Interfacing (often times noted as the "Bible" of RFI finding and reduction)...
I've played with these toroid cores on an off for the past 3 years. I keep coming back to them as I'm hoping to reduce the RFI in my shack. However each time I've tried to use these cores, they've made exactly zero difference.
For example I have a known source of RFI which is a birdie caused by my main 27" monitor (an Apple model). I see this birdie on 80m. I've tried wrapping the power cord multiple times and no luck. Zero effect. However this is just a birdie so I can deal with it.
Another example is when I'm transmitting I hear the RFI over my speakers in the shack. This is a Logitech 5500 system. It all works from a main sub woofer that all the speakers then connect too. I've disconnected all the speakers and still get the RFI through the main woofer. I've wrapped the power cord of the woofer about a dozen times through two cores each. Zero difference on the RFI leaking into the speaker. As mentioned I use a Flex 3000 so having a PC and a speaker is essential. Again I can get around this and use wireless headphones but it's not ideal.
I've also tried a Bifilar choke as detailed in a presentation PDF from K9YC again starting on page 45 here <https://www.qsl.net/w/wa3mej//Articles/K9YC/CoaxChokesPPT.pdf> I have a picture of the one I've made...
[](https://i.stack.imgur.com/MVgrg.jpg)
This was done with #14 THHN wire as detailed in the presentation above on page 47. This was connected to my feed-line on one end and the other end went straight into my flex-3000.
I have various other sources within my house that I'm attempting to deal with but I'm trying to mitigate a few of them with cores. But the cores just seem to make absolutely no difference. Either I've got the wrong cores or I'm missing something and am not doing it correctly? I bought these things and I would've thought I would have at least seen marginal improvements but so far they've been useless.
Any suggestions on what I'm missing?
**UPDATE 1**
Here's some pictures of my antenna setup and my ugly balun. Obviously the height of the antenna is not ideal but this is up on the second floor. I've since added a vertical dipole (Comet 250B) which is not shown. As you can see the balun has coax seal all over it so I'll have to pull all that off and switch out the balun for my ferrite choke. I notice in the pictures that the coax seems to be drooping on my balun which I didn't notice earlier. Could this also be a factor?
I've also included a picture of my new ground setup...
[](https://i.stack.imgur.com/0PmlC.jpg)
Antenna Setup
[](https://i.stack.imgur.com/erWei.jpg)
Ugly Balun
[](https://i.stack.imgur.com/E8ae9.jpg)
New Ground Setup
**Update 2**
I've tried to make a quick and dirty version of the RFI detector that Phil Frost - W8II has pointed out. This is based not he link provided in the first answer below.
Here's a couple of pictures of my detector. It include the snap on ferrite with 10 turns of wire through into a breadboard where I just plugged in the components for now. I'm using a 101 nf cap (I assume that it is nF as there is only the number on it) and a 47 Ω and 100 Ω resistor. You'll see a red LED. I don't have any diodes handy at the moment but have them on order. I thought I would try the LED to see if it would work.
Unfortunately I don't get any reading on my multimeter. I have it set to 200mA and I put the ferrite beside my feed line. It just reads 00.0 all the time when I transmit. I'm not sure if that's good as I don't have any common mode current, or more likely I've done the detector wrong.
Here is a picture of my detector and my multimeter.
[](https://i.stack.imgur.com/cA7yZ.jpg)
Detector
[](https://i.stack.imgur.com/GD9uZ.jpg)
Multimeter
|
2018/10/25
|
[
"https://ham.stackexchange.com/questions/12101",
"https://ham.stackexchange.com",
"https://ham.stackexchange.com/users/13444/"
] |
That does look like a fine core to use, and the photo of your construction looks good. Your coax isn't causing any problems with noise.
Try putting the choke at the *feedpoint*, not at the *radio*, in lieu of the ugly balun you have now. A choke at the radio will do little since the coax shield, connector, and enclosure of the radio already form a continuous shield around all the receiving circuitry.
The objective with the balun is to [eliminate common-mode current on the feedline](https://ham.stackexchange.com/questions/538/using-a-balun-with-a-resonant-dipole). A feedline with common-mode current is part of the radiating and receiving antenna, and since it runs into the shack it's close to all kinds of noise generating electronics. A functional balun suppresses common-mode current on the feedline so only the antenna, which is farther away from noise sources, is the only part radiating or receiving. Often this reduces RFI.
Ugly baluns can be ineffective. Since they are a purely reactive impedance they can't dissipate noise power, only redirect it. In some cases the reactance of the ugly balun combines with the common-mode reactance of the feedline or tower to make a resonant circuit which is worse than no balun. A properly selected ferrite on the other hand has a significant resistive component to its impedance, and thus works in all cases as it can convert noise power to heat.
Fixing RFI problems like you describe can be difficult if you don't know what's working and what isn't. If you aren't certain that feedline common-mode problems have been eliminated, trying to fix a noise source by putting ferrites around it is a futile exercise since all the wiring in your home is part of the antenna.
So I suggest you [measure the common-mode current](https://ham.stackexchange.com/q/1271/218) with the ugly balun, and then with the ferrite choke. You might try different ferrite choke designs to find one that works well. The number of turns, core material, and core geometry make a difference. The [K9YC presentation you referenced](https://www.qsl.net/w/wa3mej//Articles/K9YC/CoaxChokesPPT.pdf) discusses it in some detail. [G3TXQ also has some good data](http://www.karinya.net/g3txq/chokes/). You can use these resources as a starting point for a design and then confirm the results with measurement.
Only after confirming feedline common-mode issues are resolved, go around the house and identify noise sources. Putting ferrites on the cables leaving a noisy device eliminates the "antenna" they use to radiate noise.
|
30,515,377 |
I am writing a c++ code for a Monte Carlo simulation. As such, I need to generate many numbers uniformly distributed between [0,1). I included the following code taken from [here](http://www.cplusplus.com/reference/random/uniform_real_distribution/) to generate my numbers:
```
// uniform_real_distribution
#include <iostream>
#include <random>
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(0.0,1.0);
int main()
{
double number = distribution(generator); //rnd number uniformly distributed between [0,1)
return 0;
}
```
So every time I need a new number, I just call `distribution(generator)`.
I run my Monte Carlo simulation to get many sample results. The results should be normally distributed around the real mean (that is unknown). When I run a chi-square goodness-of-fit test to check if they are normally distributed, my sample results do not pass the test sometimes. The key word here is "sometimes", so this made me think that I called `distribution(generator)` too many times and in the end I lost randomness of the generated numbers. I am talking about 10^11 numbers generated in each simulation.
Could it be possible? What if I reset the distribution with `distribution.reset()` before I call it? Would that solve my problem?
Thanks for any suggestion you may have.
|
2015/05/28
|
[
"https://Stackoverflow.com/questions/30515377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4950486/"
] |
If a random number generator doesn't fail a test sometimes, then the test is too weak. For example, if a test has a 99% degree of confidence, a perfect random number generator should be expected to fail it about 1% of the time.
For example, consider a perfectly fair coin. If you flip it 1,000 times, you will get on average 500 heads. If you want to use this as a test for randomness, you compute the range of values that a fair coin will fall within some percentage of the time. Then you make sure your random number generator doesn't fail the test more often than expected.
Your testing methodology -- expecting a random number generator to pass every test every time -- only works if your tests are *very* weak. That would allow poor random number generators to pass too often and is not a good testing methodology.
True story: A random number generator that I implemented was rigorously tested by [an independent testing lab](http://www.tstglobal.com/services/igaming/). They subjected it to 100 tests, each using millions of samples and testing for various properties. Each test had a 99% degree of confidence. The RNG failed 3 tests, which was within the expected range, and so passed the testing portion of the certification. That an RNG passes these extremely rigorous tests the vast majority of the time demonstrates that it's a very, very good RNG, perhaps perfect. It's hard to write a broken RNG that passes any of these tests ever.
You need to compute the probability that a perfect RNG will fail your test and then see if your RNG shows a failure rate close to that expected.
|
17,928,097 |
I am trying to add a link inside a label in a ListView item template but I can't make it work.
I have this label:
```
<asp:Label runat="server" ID="SummaryLabel" Text='<%# Eval("Summary").ToString().Substring(0,Math.Min(200,Eval("Summary").ToString().Length)) + "... " + "More"%>'/>
```
and I want the word More at the end to be a link to the details page of the item. Tried putting "More" inside an anchor tag and hyperlink but I get badly formed tags. I'd appreciate any help to solving this or suggestions on alternative approaches.
|
2013/07/29
|
[
"https://Stackoverflow.com/questions/17928097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/665351/"
] |
You can do what you want as follows:
```
<asp:Label runat="server" ID="SummaryLabel" Text='<%# Eval("Summary").ToString().Substring(0,Math.Min(200,Eval("Summary").ToString().Length)) + "... " + @"<a href=""Oherpage.aspx"">More</a>"%>'/>
```
Note how the `<a>` is constructed in there... `OtherPage.aspx` would be your link to whatever other page you need to send the user to.
|
51,277,457 |
I have a dictionary as follows
```
my_dict = {
"key_1": "value_1",
"key_2": {
"key_1": True,
"key_2": 1200
}
"key_3": True,
}
```
and in my class
```
@dataclass
class TestClass:
my_dict: typing.Dict[{str, str}, {str, typing.Dict[{str, bool}, {str, int}]}]
```
The above declaration is incorrect.
If I want to add typing for my\_dict what it should be and how to write the structure since I am having different types as values?
|
2018/07/11
|
[
"https://Stackoverflow.com/questions/51277457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1004875/"
] |
You want to use a [`Union`](https://docs.python.org/3/library/typing.html#typing.Union) as the value for the dictionary:
```
from typing import Dict, Union
@dataclass
class TestClass:
my_dict: Dict[str, Union[str, bool, int]]
```
The union informs the typechecker that values in the dictionary must be either `str`s, `bool`s, or `int`s. When getting values, you'll want to use `isinstance` to determine what to do with a value:
```
if isinstance(self.my_dict['a'], str):
return self.my_dict['a'].encode('utf-8')
else isinstance(self.my_dict['a'], bool):
return not self.my_dict['a']
else:
return self.my_dict['a'] / 10
```
If you know that a key will contain a specific type, you can avoid the typechecker's complaints by using `cast`:
```
from typing import cast
value = cast(bool, self.my_dict['some_bool'])
```
|
91,669 |
I have a single select drop down and need to enable the user to clear his selection too.
Is it elegant to do this:
[](https://i.stack.imgur.com/UgB2z.png)
Or, on selection of an option should the drop down be hidden, showing the selected items text along with the `X` mark beside it clicking on which the drop down would be shown again?
|
2016/03/21
|
[
"https://ux.stackexchange.com/questions/91669",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/80261/"
] |
The phrase 'Please select a thing' implies that the user has not selected anything from the dropdown yet. To clear a selection, you can have two alternatives:
1. Add a 'Clear selection' choice in the dropdown.
2. Allow the user to switch back to 'Please select a thing' which will imply that the selection previously made has been undone.
The [x] next to your dropdown confuses me. It seems like it would remove the entire dropdown, instead of just clearing the selection. My suggestion would be to use the dropdown itself for clearing options, staying within recognised UI patterns.
|
70,724,630 |
I've been trying the code below to get the spl-token account address for a specific token in a Solana wallet from the Solana wallet address, but I am having issues getting the result I am looking for. I run:
```
const web3 = require('@solana/web3.js');
(async () => {
const solana = new web3.Connection("https://api.mainnet-beta.solana.com");
//the public solana address
const accountPublicKey = new web3.PublicKey(
"2B1Uy1UTnsaN1rBNJLrvk8rzTf5V187wkhouWJSApvGT"
);
//mintAccount = the token mint address
const mintAccount = new web3.PublicKey(
"GLmaRDRmYd4u3YLfnj9eq1mrwxa1YfSweZYYZXZLTRdK"
);
console.log(
await solana.getTokenAccountsByOwner(accountPublicKey, {
mint: mintAccount,
})
);
})();
```
I'm looking for the token account address in the return, 6kRT2kAVsBThd5cz6gaQtomaBwLxSp672RoRPGizikH4. I get:
>
> { context: { slot: 116402202 }, value: [ { account: [Object],
> pubkey: [PublicKey] } ] }
>
>
>
I can drill down through this a bit using .value[0].pubkey or .value[0].account but ultimately can't get to the information i'm looking for, which is a return of 6kRT2kAVsBThd5cz6gaQtomaBwLxSp672RoRPGizikH4
Does anyone know what is going wrong?
(Note I do not want to use the getOrCreateAssociatedAccountInfo() method, i'm trying to get the token account address without handling the wallets keypair)
|
2022/01/15
|
[
"https://Stackoverflow.com/questions/70724630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17929913/"
] |
ISSUE SOLVED:
I needed to grab the correct \_BN data and convert, solution below.
```
const web3 = require('@solana/web3.js');
(async () => {
const solana = new web3.Connection("https://api.mainnet-beta.solana.com");
//the public solana address
const accountPublicKey = new web3.PublicKey(
"2B1Uy1UTnsaN1rBNJLrvk8rzTf5V187wkhouWJSApvGT"
);
//mintAccount = the token mint address
const mintAccount = new web3.PublicKey(
"GLmaRDRmYd4u3YLfnj9eq1mrwxa1YfSweZYYZXZLTRdK"
);
const account = await solana.getTokenAccountsByOwner(accountPublicKey, {
mint: mintAccount});
console.log(account.value[0].pubkey.toString());
})();
```
|
36,131,129 |
I wasnt quite sure what to call this question but here is what i want to do:
I am currently creating a series geneator for `chartjs` that will help me create my datasets.
now the way i want to do it is by simply using `object keys` to extract data from each element in my array.
Each element of an array could look something like this:
[](https://i.stack.imgur.com/IXl3D.png)
as you can see this object contains other objects inside of them.
This creates a problem because say i want the name of the object `feedback_skill` i would have to do the following:
```
data.forEach(function (x) {
x['feedback_skill']['name']
});
```
Which cannot be hold into one variable.
Now what i could do is pass the following array: `serieKey = ['feedback','name']` suggesting that the first element in the array is the first key and the next element is the variable i want to hit.
However these datasets can have an unlimited number of layers so my question to you guys is:
Is there a smart way of doing this?
|
2016/03/21
|
[
"https://Stackoverflow.com/questions/36131129",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1647457/"
] |
I'm not aware of a native JavaScript way of doing this, but various JavaScript frameworks allow you to access deep-properties from objects like this. For example Dojo has [lang.getObject](https://dojotoolkit.org/reference-guide/1.10/dojo/_base/lang.html#dojo-base-lang-getobject) and I can see that there is a [JQuery plugin](http://benalman.com/projects/jquery-getobject-plugin/) that does something similar, lodash [as well](https://lodash.com/docs#get). If you're not using these frameworks, then you could always create your own util function to perform something similar.
These types of utility function allow you to pass the target as a "dot-notation" property, so you could call:
```
lang.getObject("feedback_skill.name", false, x)
```
Using Dojo for example, but they're all much of a muchness.
|
20,937 |
I recently started playing with reverse macro with my canon 50mm f1.8. A couple things I noticed immediately is:
* Shallow depth of field
* No control over aperture
* difficult to shoot handheld
I believe these are the common problems with this type of shooting
Are there any techniques that I can use to improve/help with Reverse Macro shooting besides buying a Macro lens as they are kind of expensive.
Here is what I've tried so far

ps. I have read [Are there macro focusing techniques for handheld shots?](https://photo.stackexchange.com/questions/18746/are-there-macro-focusing-techniques-for-handheld-shots) but focusing isn't really a problem.
|
2012/03/06
|
[
"https://photo.stackexchange.com/questions/20937",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/3782/"
] |
I've faced similar problems and also was able to overcome a few of them. A few techniques that has proved to be efficient for me are:
* Focus changes even if you move a millimeter. I tried so hard to keep my body as stiff as possible but that did NOT work. So, I just let it go. I start by looking at the blur image through the viewfinder, slowly move forward and start shooting as soon as the image looks clearer, keep shooting and moving all the way upto the point the image becomes blurry again. Do NOT move using your whole body/waist, instead try inhaling and exhaling slowly.
* I always shoot in continuous mode which enables me to increase the chance of getting a better focused shot.
* IS wont work, nor will aperture control. So, you'll need to set the aperture before detaching the lens. I usually use higher than normal ISO to be able to use a higher shutter speed, thus remove any chance of shake blur.
* Not sure if you're using a reverse mount ring, if not, get one asap. It helps a lot and you can concentrate on things other than keeping your lens safe from falling.
* DOF stacking is another technique you can apply. Its true I wasn't able to plan and execute DOF stacking yet, but if you take a lot of pictures of the same subject, chances are you'll find a couple or two which you can use to stack and gain greater DOF.
* Use of external flash is also very helpful and let you use smaller aperture as well as higher shutter speed while keeping the ISO low. Generally you'd like to use a diffuser along with it. Use [this link](http://www.fredmiranda.com/forum/topic/621087) to get an idea about how to make your own DIY lighting setup for better macro shooting.
|
60,786,859 |
I didn't find through searching in internet simple solution for this purpose which can be quickly integrated into my code. I propose my solution.
|
2020/03/21
|
[
"https://Stackoverflow.com/questions/60786859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4403269/"
] |
As this function from time to time, I need in my projects I decided to create a separate function for it. The code of it is below:
```
Function GetFolderNameFromPath(folderPath As String) As String
Dim lastPathSeparatorPosition As Long, folderPathLength As Long, folderNameLength As Long
lastPathSeparatorPosition = InStrRev(folderPath, Application.PathSeparator)
folderPathLength = Len(folderPath)
folderNameLength = folderPathLength - lastPathSeparatorPosition
GetFolderNameFromPath = Right(folderPath, folderNameLength)
End Function
```
|
67,771,195 |
I'm doing a polling method to my API every 5 seconds, to get real-time data. The code below works but after 1 hour of running, the page crash(Aww Snap, with the dinosaur image and error: out of memory). The data I'm collecting is quite large, and I'm expecting that javascript will offload the memory(garbage collection) every time the function is being called again. I can see in the Chrome Task Manager, the memory footprint is growing over time. Is there a way to clear the memory or offload the memory from growing over time?
```
data(){
return{
newdata:[],
};
},
methods: {
loadData:async function () {
try {
let response = await axios.get('/monitoring_data');
if (response.status != 200) {
await new Promise(resolve => setTimeout(resolve, 1000));
await this.loadData();
}else {
// Get the data
this.newdata= response.data.Ppahvc;
// Call loadData() again to get the next data
await new Promise(resolve => setTimeout(resolve, 5000));
await this.loadData();
}
} catch (e) {
await this.loadData();
}
},
},
mounted:function(){
this.loadData();
},
```
|
2021/05/31
|
[
"https://Stackoverflow.com/questions/67771195",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13687251/"
] |
Use a `JOIN` in your query:
```sql
SELECT *
FROM movies_table m
INNER JOIN directors_table d ON d.director_id = m.dir_id
```
And build the array structure in your loop:
```php
while($r = mysqli_fetch_assoc($sth)) {
$rows[] = [
'id' => $r['id'],
'image' => $r['image'],
/* other movie keys you need */
'director' => [
'id' => $r['director_id'],
/* other director keys you need */
]
];
}
```
|
2,616,975 |
I am converting numbers between different bases without issues, but I'm struggling to understand the **why** the method I'm using works.
If I convert $A5$ (base 16) to base 8, I would do the following:
>
> Turn $A5$ into binary (4 bits)
>
>
> $A = 1010$
>
>
> $5 = 0101$
>
>
> $10100101$ (split into three bits) $= 010$ $100$ $101$
>
>
> $010$ = 2
>
>
> $100$ = 4
>
>
> $101$ = 5
>
>
> $A5$ (base 16) $= 245$ (base 8)
>
>
>
I know the answer is correct, but I don't understand why the binary is split into $X$ bits depending on the base, and how the value $X$ is chosen. If it's base 4, for example, how many bits should the binary be separated into when converting?
|
2018/01/23
|
[
"https://math.stackexchange.com/questions/2616975",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/517621/"
] |
This approach only works for bases that are powers of $2$. So, for base $2^k$ you convert to binary by concatenating strings of $k$ bits, one for each base-$2^k$ digit. In the other direction, you convert from base $2$ to base $2^k$ by dividing the binary digits in groups of $k$ (and possibly padding with leading $0$s to get a number of binary digits that is a multiple of $k$).
The explanation is simple once you think that the number represented by a binary numeral $b\_{n-1}\cdots b\_1 b\_0$ is
$$ \sum\_{0 \leq i <n} b\_i 2^i \enspace. $$
If, without loss of generality because of the padding, we assume that $n$ is a multiple of $k$, we can rewrite the summation as
$$ \sum\_{0 \leq i < n/k} \Big( \sum\_{0 \leq j < k} b\_{ik+j} 2^j \Big) (2^k)^i \enspace. $$
Each summation in parentheses is a base-$2^k$ digit.
|
25,856,088 |
I am trying to update a variable using two different functions. I wrote a little C program to demonstrate:
```
#include <stdlib.h>
#include <stdio.h>
void updateHelper(int *x, int y) {
*x = y;
}
void update(int x, int y) {
updateHelper(&x, y);
}
int main(int argc, char *argv[]) {
int num = 0;
update(num, 1);
printf("%d\n", num);
return 0;
}
```
Why is this printing a 0 and not a 1? I can't wrap my head around this. The function that is actually updating the value is indeed passed a reference of the variable(!?). Can someone explain why this happens?
The arguments of update() can not be pointers. Are there any possible work-arounds for this?
|
2014/09/15
|
[
"https://Stackoverflow.com/questions/25856088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2315551/"
] |
You aren't updating the original variable. You're updating the *copy* of that variable that was passed to your `update` function. If you want to update the original variable, change `update` to take it's parameter as a pointer:
```
void update(int* x, int y) {
updateHelper(x, y);
}
```
and in main, pass the address:
```
update(&num, 1);
```
Edit: since you stated the arguments to update cannot be pointers, you will need to either have `update` return the new variable, or use a global variable, or ... In C, the only way to modify a reference to a variable in a function is by using pointers.
|
73,445,292 |
Using a sql query, how can I return an array of json objects that looks like this:
```
{
"result":[
{
"RentBookRegistrationId":1,
"date":"15-08-2022",
"PersonName":"Peter",
"Books":[
{
"name":"Ulysses"
},
{
"name":"Hamlet
}
],
"Processes":[
{
"no":1,
"name":"Online booking"
},
{
"no":2,
"name":"Reserved beforehand"
},
{
"no":4,
"name":"Vending machined used"
}
]
}
]
}
```
From a SQL Server database that looks like this:
Table: **RentBookRegistration**
```
+----+------------+-----------------------------+
| id | date | person |
+----+------------+-----------------------------+
| 1 | 15-08-2022 | {"no": 1, "name": "Peter"} |
+----+-------- ---+-----------------------------+
| 2 | 16-08-2022 | {"no": 2, "name": "Anna"} |
+----+------------+-----------------------------+
| 3 | 17-08-2022 | {"no": 1, "name": "Peter"} |
+----+------------+-----------------------------+
| 4 | 17-08-2022 | {"no": 2, "name": "Mark"} |
+----+------------+-----------------------------+
```
Table: **BookData**
```
+----+------------------------+-----------------------------------------------------------+
| id | rentBookRegistrationId | book |
+----+------------------------+-----------------------------------------------------------+
| 1 | 1 | {"name": "Ulysses", "author": "James Joyce", "year": 1918}|
+----+------------------------+-----------------------------------------------------------+
| 2 | 1 | {"name": "Hamlet", "author": "Shakespeare", "year": 1601} |
+----+------------------------+-----------------------------------------------------------+
| 3 | 2 | {"name": "Dune", "author": "Frank Herbert", "year": 1965} |
+----+------------------------+-----------------------------------------------------------+
| 4 | 3 | {"name": "Hamlet", "author": "Shakespeare", "year": 1601} |
+----+------------------------+-----------------------------------------------------------+
| 5 | 4 | {"name": "Hamlet", "author": "Shakespeare", "year": 1601} |
+----+------------------------+-----------------------------------------------------------+
```
Table: **ProcessData**
```
+----+------------------------+-----------------------------------------------------------+
| id | rentBookRegistrationId | processUsed |
+----+------------------------+-----------------------------------------------------------+
| 1 | 1 | {"no": 1, "name": "Online booking"} |
+----+------------------------+-----------------------------------------------------------+
| 2 | 1 | {"no": 2, "name": "Reserved beforehand"} |
+----+------------------------+-----------------------------------------------------------+
| 3 | 1 | {"no": 4, "name": "Vending machined used"} |
+----+------------------------+-----------------------------------------------------------+
| 3 | 2 | {"no": 1, "name": "Online booking"} |
+----+------------------------+-----------------------------------------------------------+
| 4 | 2 | {"no": 4, "name": "Vending machined used"} |
+----+------------------------+-----------------------------------------------------------+
| 5 | 3 | {"no": 2, "name": "Reserved beforehand"} |
+----+------------------------+-----------------------------------------------------------+
```
The table layout might seems a bit stupid, but they are simplified to make the question straightforward.
This is how far I've come so far:
```sql
select … from RentBookRegistration R where R.PersonName = 'Peter'
```
|
2022/08/22
|
[
"https://Stackoverflow.com/questions/73445292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14505900/"
] |
You had done it pretty much right. All you needed was to use `setInterval` instead of `setTimeout`. Also, you need to store the interval in a variable and clear it on `mouseout` so that the text does not keep changing the color.
```js
let interval;
document.addEventListener('DOMContentLoaded', function listen() {
var logo = document.querySelector('.logo-btn');
logo.addEventListener("mouseover", event => {interval = setInterval(()=>changeColor(event), 500)});
logo.addEventListener("mouseout", event => resetColor(event));
})
function changeColor(event) {
var colors = ["#ff3300", "#fbfb32", "#99ff33", "orange", "magenta", "#3399ff"]
var color = colors[Math.floor(Math.random() * colors.length)];
var logo = event.target;
logo.style.color = color;
}
function resetColor(event) {
var logo = event.target;
logo.style.color = "black";
clearInterval(interval);
}
```
```css
header {
background-color: #fff;
height: 80px;
position: relative;
}
.header-logo {
font-size: 50px;
position: absolute;
bottom: -15px;
left: 40px;
}
.logo-btn {
background-color: transparent;
border: none;
text-align: bottom;
}
```
```html
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<link href="styles.css" rel="stylesheet">
<title>My Webpage</title>
</head>
<body>
<header>
<div class="header-logo">
<a href="x">
<button class="logo-btn">Logo</button>
</a>
</div>
</header>
</body>
</html>
```
|
2,697 |
I have heard both interpretations, for me it would make more sense to be something from the mind as there is no creator God or its opposite in Buddhism, the image of a "temptator creature" like Satan sounds strange when we think about impermanence, on the other hand, some suttas that mention Mara may fit better with the concept of an external creature, I know this interpretation is questionable, so I'm making the question!
|
2014/08/15
|
[
"https://buddhism.stackexchange.com/questions/2697",
"https://buddhism.stackexchange.com",
"https://buddhism.stackexchange.com/users/533/"
] |
Two snippets from suttas refering to Mara as an entity/position:
MN 115:
>
> "But, venerable sir, in what way can a bhikkhu be called skilled in what is possible and what is impossible?"
>
>
> "Here, Ananda, a bhikkhu undersands [...]: "It is possible that a man might occupy the position of Māra [...]"
>
>
>
MN 50:
>
> The venerable Maha Moggallana saw him [Māra] standing there and said: "I see you there too, Evil One. Do not think 'He does not see me.' You are standing against the door bar, Evil One.
>
>
> "It happened once, Evil One, that I was a Māra named Dusi [...]
>
>
>
A sutta where a disciple directly asks what is Māra (SN 23.1):
>
> "Venerable sir, it is said, 'Māra, Māra.' In what way, venerable sir, might Māra be?"
>
>
> "When there is form, Radha, there might be Māra, or the killer, or the one who is killed."
>
>
>
The above are from Nanamoli/Bodhi translations. Bhikkhu Bodhi also writes in a note of the Majjhima Nikaya:
>
> The name means "the Corrupter" or "the Corrupted One". In the Buddhist conception of the universe, the position of Mara, like that of Maha Brahma, is a fixed one that is assumed by different individuals in accordance with their kamma.
>
>
>
|
57,201,932 |
Not using C that often, I came across a possibly simple problem. I have several functions, that need access to a global array-variable `g`. But the actual size of this variable has to be defined in an `init()`-function. The size depends on some other stuff, so `g` has to be declared somehow with a dynamic size. I read about `malloc` and other functions, but I am not sure how to use them properly.
Example:
```
double g[dynamic]; // size is not known yet
int n;
void init()
{
// calculate "n" for array size
n = ...
// declare and initialze g with a size "n"
}
void dostuff()
{
for (int i = 0; i < n; i++)
work(g[i]);
}
```
How should I solve this?
|
2019/07/25
|
[
"https://Stackoverflow.com/questions/57201932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7217855/"
] |
You cannot use an **array**. You must use a **pointer**.
```
double *global_array; // size is not known yet
size_t nglobal_array; // may be helpful to have the size
void init(void)
{
// calculate "nglobal_array" for array size
nglobal_array = 42;
// declare and initialze global_array with a size "nglobal_array"
global_array = malloc(nglobal_array * sizeof *global_array);
if (global_array == NULL) {
fprintf(stderr, "Error allocating resources.\nProgram aborted.\n");
exit(EXIT_FAILURE);
}
}
void dostuff()
{
for (int i = 0; i < nglobal_array; i++)
work(global_array[i]);
}
```
Don't forget to `free(global_array)` when you no longer need it.
Complete usage would then be something like this
```
#include <stdlib.h>
// includes
// declarations & definitions as above
int main(void) {
init();
dostuff();
free(global_array);
}
```
|
132,892 |
In the 1987 *[Robocop](http://www.imdb.com/title/tt0093870/)* movie, Alex Murphy was shot by some gangsters.
When OCP was making Robocop using Alex Murphy's body, **was Alex Murphy still alive, or did OCP use his *dead body* to make Robocop?**
|
2016/06/25
|
[
"https://scifi.stackexchange.com/questions/132892",
"https://scifi.stackexchange.com",
"https://scifi.stackexchange.com/users/64716/"
] |
**Murphy was dead.**
When the doctors are operating on him, the line is
>
> **Surgeon #1 -** *Ok, let's shock him to flatline, then quit.*
>
>
> [They shock him]
>
>
> **Surgeon #2** - *No pulse!*
>
>
> **Surgeon #1** - *I'm calling it* [[medical slang for declaring the time of death](https://ell.stackexchange.com/questions/76601/call-it-what-does-this-term-mean-context-i-cant-im-calling-it-im-calli)].
>
>
>
which tallies very nicely with what we see in the film's official novelisation
>
> A loud voice crashed through the fog. The dreams shattered. “I’ve got a straight line. Crash cart! 10 cc Adrenalin. Stand clear!”
>
>
> He felt cold grease on his chest. A surge of electricity slammed into his muscles. There was the ferret-faced thug.
>
>
> “Hit him again!” someone screamed. A sudden jolt conjured up the face of the Asian hit man. Another jolt. The farmboy. And another. The black man. And another. The high-foreheaded clown who blew his hand to shreds. His killers. He bade farewell to them all. Only blackness filled his life, now. A void.
>
>
> **“That’s it. He’s gone,”** he heard someone say from another planet.
>
>
>
We see later see in the film that he was officially declared dead by the State. He had a funeral and his widow was provided with a pension.
[](https://i.stack.imgur.com/r92r8.jpg)
and this from the film's [original script](http://www.awesomefilm.com/script/robocop-script.pdf)
[](https://i.stack.imgur.com/l0zrZ.png)
---
If you take the later [TV series](https://en.wikipedia.org/wiki/RoboCop:_The_Series) as canon, we actually *see* his body in the DPD morgue
[](https://i.stack.imgur.com/0l77m.jpg)
|
26,644,985 |
I am trying to achieve a strange query. I have a table like this:
table People
```
-----------------------
| id | name | family |
+----+------+--------+
| 1 | Bob | Smith |
+----+------+--------+
| 2 | Joe | Smith |
----------------------
```
I want to return an assoc array like this
```
id : 1
name : bob
family : smith
familySize : 2
```
So something like this
```
"SELECT id, name, family, familySize FROM People"
```
How can I get the familySize in there? Keep in mind my query may have many families and I want them all to be returned.
Thank you.
|
2014/10/30
|
[
"https://Stackoverflow.com/questions/26644985",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3822370/"
] |
The above 2 answers won't work with multiple families.
You can do something like this:
```
SELECT id, name, family, familySize FROM People p1
JOIN (SELECT COUNT(*) as familySize, family FROM People GROUP BY family) p2
USING(family)
```
|
60,085,739 |
I am working on an internal program for work that is essentially built on PHP. My problem is that I have a a header, a side navigation, the main content (to the right of the nav) and a footer. [Rough Layout Picture](https://i.stack.imgur.com/whLdr.png)
My issue is that I have two DIV's within a container, the nav is set to a percentage with a minimum width, and the content section is set to take the remaining space. In total both the nav and content should take about 91% of the screen real estate. [Whats Happening after shrinking the browser a bit](https://i.stack.imgur.com/qhwwU.png)
My CSS looks like this for the fields I think are relevant:
```
.container{
width: 100%;
float: inline-block;
}
.header{
float: left;
text-align: left;
background-color: lightblue;
width: 100%;
vertical-align: middle;
display: block;
border-radius: 15px;
}
.header h1{
font-weight: bold;
font-size: 40px;
text-indent: 50px;
}
.msg_alert{
background-color: green;
color: white;
width: 95%;
padding: 5px;
border-radius: 10px;
}
.err_msg_alert{
background-color: red;
color: white;
width: 95%;
padding: 5px;
border-radius: 10px;
}
.menu{
float: left;
width: 13%;
border: 3px solid grey;
padding: 5px;
background-color: lightgrey;
border-radius: 15px;
margin-top: 20px;
margin-right: 20px;
min-width: 200px;
}
.menu a{
float: left;
color: black;
text-align: left;
padding: 14px;
text-decoration: none;
box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
margin: 3px;
background-color: lightblue;
width: 40%;
min-width: 150px;
border-radius: 15px;
}
.menu a:hover{
background-color: grey;
color: black;
}
.menu ul{
list-style-type: none;
margin: 0;
padding: 0;
}
.menu li{
padding: 8px;
margin-bottom: 7px;
}
.content{
float: left;
width: 78%;
padding: 20px;
margin-top: 20px;
margin-left: 20px;
/*border: 3px solid red;*/
}
.footer{
display: inline-block;
width: 100%;
background-color: lightgrey;
border-radius: 15px;
font-size: 12px;
text-align: center;
margin-top: 5px;
padding-bottom: 10px;
}
```
I'm not sure what I've done wrong. Everything displays properly if the browser is in full screen but when I shrink it down to about 3/4's of the browser size the nav stays where it should be but the contents move below.
I have setup a mobile version which works perfectly but the desktop mode is what I am having issues with.
Thank you for the help in advance.
|
2020/02/05
|
[
"https://Stackoverflow.com/questions/60085739",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12848465/"
] |
REST was never designed for bulk transaction support, it's for representing the state of individual objects. That said, API design is very opinionated and you have to balance REST "pureness" with functionality. If I were designing this, I would go with option 1 and use delete at the "sessions" endpoint since you are removing all of the user sessions and not just a single or subset.
|
5,673,223 |
I can't insert a value using this code:
```
insert into t_category_values (CategoryCode,
CategoryValueCode, CategoryValue) values(2, 1, 1);
```
error msg
```
no primary key
```
|
2011/04/15
|
[
"https://Stackoverflow.com/questions/5673223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/683150/"
] |
Your query is wrong it should be:
```
INSERT INTO `DBA`.`t_category_values`
(CategoryCode, CategoryValueCode, CategoryValue)
VALUES(1, 1, "aaa");
```
See here for more help: [Sql Insert Wiki](http://en.wikipedia.org/wiki/Insert_%28SQL%29)
---
**Edit:**
Your query and error:
>
> insert into t\_category\_values
> (CategoryCode, CategoryValueCode,
> CategoryValue) values(2, 1, 1);
>
>
> no primary key
>
>
>
In insert while specifying to insert in few column instead of all in table you must have to include primary key. That means in your one of CategoryCode, CategoryValueCode, CategoryValue should be primary key or include fourth column that is primary key in table.
|
132,750 |
I want to create a table like
[](https://i.stack.imgur.com/Xe1cb.png)
There are 2 cells in the 4th column which are merged vertically on the right side.
While it is easy to merge them on the left side using `multirow`, I'm at a loss on how to merge on the right side
Here is my source code (using [`IEEEtran.cls`](http://mirrors.ctan.org/macros/latex/contrib/IEEEtran/IEEEtran.cls)):
```
\documentclass[conference]{IEEEtran}
% Add the compsoc option for Computer Society conferences.
% *** GRAPHICS RELATED PACKAGES ***
%
\ifCLASSINFOpdf
\usepackage[pdftex]{graphicx}
% declare the path(s) where your graphic files are
% \graphicspath{{../pdf/}{../jpeg/}}
% and their extensions so you won't have to specify these with
% every instance of \includegraphics
\DeclareGraphicsExtensions{.pdf,.jpeg,.png,.eps}
\else
% or other class option (dvipsone, dvipdf, if not using dvips). graphicx
% will default to the driver specified in the system graphics.cfg if no
% driver is specified.
\usepackage[dvips]{graphicx}
% declare the path(s) where your graphic files are
% \graphicspath{{../eps/}}
% and their extensions so you won't have to specify these with
% every instance of \includegraphics
\DeclareGraphicsExtensions{.eps}
\fi
% correct bad hyphenation here
\hyphenation{op-tical net-works semi-conduc-tor}
\usepackage{lscape}
\usepackage{multirow}
%\usepackage{subfig}
\usepackage{subfigure}
%\usepackage{subcaption}
\usepackage{tikz}
\def\checkmark{\tikz\fill[scale=0.4](0,.35) -- (.25,0) -- (1,.7) -- (.25,.15) -- cycle;}
\documentclass[conference]{IEEEtran}
\ifCLASSINFOpdf
\usepackage[pdftex]{graphicx}
\DeclareGraphicsExtensions{.pdf,.jpeg,.png,.eps}
\else
\usepackage[dvips]{graphicx}
\DeclareGraphicsExtensions{.eps}
\fi
% correct bad hyphenation here
\hyphenation{op-tical net-works semi-conduc-tor}
\usepackage{lscape}
\usepackage{multirow}
\usepackage{subfigure}
\begin{document}
\section{Introduction}
\section{xxx}
\begin{table}[h]
\centering
\begin{tabular}{ |p{0.6cm}|p{1cm}|p{0.6cm}|p{4cm}| }
\hline
{\fontsize{7}{60}\selectfont Source IP} & {\fontsize{7}{60}\selectfont Destination IP} & {\fontsize{7}{60}\selectfont CCN Name} & Example Application Scenarios \\
\hline
$\times$ & xx & xx& Content requester wants to hide its location/IP \\
\hline
dul & $\times$ & lus & \multirow{2}{*}{Content requester wants to hide its location/IP} \\
\cline{1-3}
ddd & $\times$ & lus & \\
\hline
$\times$ & Lucus & lus & Content requester wants to hide its location/IP \\
\hline
$\times$ & Lucus & lus & Content requester wants to hide its location/IP \\
\hline
\end{tabular}
\caption{xxxx}
\label{tab:header}
\end{table}
\begin{thebibliography}{1}
\end{thebibliography}
\end{document}
```
The result is the width of that two cells are not equal.
|
2013/09/11
|
[
"https://tex.stackexchange.com/questions/132750",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/36240/"
] |
@egreg deserves the glory. Here is a MWE:
```
\begin{tabular}{l|l|l|l}
a1 & a2 & a3 & a4\\ \hline
b1 & b2 & b3 & \multirow{2}{*}{bc4}\\ \cline{1-3}
c1 & c2 & c3 & \\ \hline
d1 & d2 & d3 & d4
\end{tabular}
```
|
41,236,858 |
I have created a ionic popup window, instead of the default two buttons at the bottom, I would like to add a button in the body of the popup window. Actually does it really possible to do so? If not, another other method / suggestion?
I have tried to insert some html code in the template but it didn't work.
I would like to add a button like the grey button as shown in the diagram. Thank you for your time for reading my question.
[](https://i.stack.imgur.com/NMowe.png)
|
2016/12/20
|
[
"https://Stackoverflow.com/questions/41236858",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6878655/"
] |
If you have tried everything that comes as an accepted ans according to your links for the ques, then why don't you try debugging your start activity, i mean on which you have put intent to start the respective activity.
While debugging one of my application i found that android soft keyboard has that problem of not going down even after finishing the activity that calls it, it stays on screen for few seconds but this doesn't happen frequently.
So i suggest you to debug your calling activity too just try putting "focusable=false" on the component from which you called the respective activity.
|
64,626 |
I'm trying to follow some of the best practices of the "open science" movement. In my thesis, I've performed all of the analyses in R (a non-proprietary, open-source program for analyzing data), and my datasets are in the non-proprietary CSV format.
I would like to be as transparent as possible, by sharing my datasets and R analysis/code files with my thesis committee, and ultimately with the public once my thesis is finalized and placed in a repository. How can I best do this?
I was thinking about uploading my files to the Open Science Framework (<http://osf.io>) and citing them with a regular HTTPS link. Once my thesis is finalized, I would then "freeze" them on the OSF website (as I understand, this would prevent post-hoc changes), then get a DOI that points to the frozen files and cite that.
Are there any better options?
|
2016/03/05
|
[
"https://academia.stackexchange.com/questions/64626",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/50325/"
] |
First, best compliments for your intent on open and reproducible research!
Your code and datasets ought to bring you better visibility for your research. GitHub is a good alternative to publish your code. If your datasets involve elements of machine learning you may donate it to the UCI Machine Learning Repository.
|
171,023 |
According to the sequence of tenses in the following sentence, which should be used, 'is' or 'was'?
>
> She got a well-paid job as she is/was proficient in both English and Chinese.
>
>
>
|
2018/07/02
|
[
"https://ell.stackexchange.com/questions/171023",
"https://ell.stackexchange.com",
"https://ell.stackexchange.com/users/76987/"
] |
Depends on the context.
If it is recent and the effects are still applied, I'd use *'is.'*
>
> She got the job as she's proficient in both English and Chinese
>
>
>
But, should it be a distant past, I'd use *was* (especially in storytelling).
>
> He got the job as a gym trainer as he *was* very strong and in shape
>
>
>
|
38,700,449 |
I am trying to insert a large xml file with length 43000 into `clob`.
[asktom](https://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:1202548400346932817) remcomanded using bind variables but its links was broken.
so my question how to insert large xml file in a bind variable . this is my procedure
```
CREATE OR REPLACE PROCEDURE sp_insert_xml
(
p_id IN INT,
p_xml IN clob
)
AS
BEGIN
declare x clob;
y number(10);
begin
SELECT FILE into x from PROCESS_D where PROCESS_ID =1;
select dbms_lob.getlength(x) into y from dual;
DBMS_OUTPUT.PUT_LINE(y);
end;
--INSERT INTO TEST_ID VALUES (p_id, p_xml);
END;
```
I want to split the length so I can insert them into a table
|
2016/08/01
|
[
"https://Stackoverflow.com/questions/38700449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2291869/"
] |
This
```
<img ng-src="https://someimageurl/{{ foo.replace('bar','') }} />
```
is not an *angular replace method*, is just the *javascript replace method* being called inside angular interpolation.
In angular2, you can do the same by doing:
```
<img [src]="'https://someimageurl/' + foo.replace('bar','')"/>
```
You can find more information about Template Syntax in [Angular 2 docs](https://angular.io/docs/ts/latest/guide/template-syntax.html).
|