qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
sequence | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
52,324,863 | For example, turn this:
```
const enums = { ip: 'ip', er: 'er' };
const obj = {
somethingNotNeeded: {...},
er: [
{ a: 1},
{ b: 2}
],
somethingElseNotNeeded: {...},
ip: [
{ a: 1},
{ b: 2}
]
}
```
Into this:
```
[
{ a: 1},
{ b: 2},
{ a: 1},
{ b: 2}
]
```
I'm already doing this in a roundabout way by declaring an enum object of the types i want (er, ip) then doing a forEach (lodash) loop on obj checking if the keys aren't in the enum and delete them off the original obj. Then having just the objects I want, I do two nested forEach loops concatenating the results to a new object using object rest spread...
I'm almost entirely sure there's a better way of doing this but I didn't think of it today. | 2018/09/14 | [
"https://Stackoverflow.com/questions/52324863",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/391600/"
] | Get the `enums` properties with [`Object.values()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values) (or [`Object.keys()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) if they are always identical). Use [`Array.map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to iterate the array of property names, and extract their values from `obj`. Flatten the array of arrays by [spreading](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) it into [`Array.concat()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat):
```js
const enums = { ip: 'ip', er: 'er' };
const obj = {
somethingNotNeeded: {},
er: [
{ a: 1},
{ b: 2}
],
somethingElseNotNeeded: {},
ip: [
{ a: 1},
{ b: 2}
]
};
const result = [].concat(...Object.values(enums).map(p => obj[p]));
console.log(result);
``` | Since you're not using the `key` of the `enums` in the final output, we could simply use an `Array` instead of an object.
```
const enums = ['ip', 'er'];
const obj = {
somethingNotNeeded: {},
er: [
{ a: 1 },
{ b: 2 },
],
somethingElseNotNeeded: {},
ip: [
{ a: 1 },
{ b: 2 }
]
};
const result = enums.reduce((acl, curr) => acl.concat(obj[curr]), []);
console.log(result);
```
This should do the trick. |
55,094,997 | I want to export outlook **NON-HTML Email Body** into excel with a click of a button inside excel. Below are my codes. Appreciate if anyone could assist me on this.
This is the code that I use to print the **plain text email body** but I get a lot of unwanted text
>
> sText = **StrConv(OutlookMail.RTFBody, vbUnicode)**
>
>
> Range("D3").Offset(i, 0).Value = **sText**
>
>
>
[](https://i.stack.imgur.com/lkGQX.png)
I did tried this but it prompts **run-time error '1004'
Application-defined or object-defined error** It works on body with HTML tags though.
>
> Range("D3").Offset(i, 0).Value = **OutlookMail.Body**
>
>
>
This is the structure of my email folders
[](https://i.stack.imgur.com/ANckj.png)
Below are my complete vba codes
```
Sub extract_email()
Dim OutlookApp As New Outlook.Application
Dim Folder As Outlook.MAPIFolder
Dim OutlookMail As MailItem
Dim sText As String
Dim i As Integer
Set myAccount = OutlookApp.GetNamespace("MAPI")
Set Folder = myAccount.GetDefaultFolder(olFolderInbox).Parent
Set Folder = Folder.Folders("Test_Main").Folders("Test_Sub")
i = 1
Range("A4:D20").Clear
For Each OutlookMail In Folder.Items
If OutlookMail.ReceivedTime >= Range("B1").Value And OutlookMail.SenderName = "Test_Admin" Then
Range("A3").Offset(i, 0).Value = OutlookMail.Subject
Range("A3").Offset(i, 0).Columns.AutoFit
Range("A3").Offset(i, 0).VerticalAlignment = xlTop
Range("B3").Offset(i, 0).Value = OutlookMail.ReceivedTime
Range("B3").Offset(i, 0).Columns.AutoFit
Range("B3").Offset(i, 0).VerticalAlignment = xlTop
Range("C3").Offset(i, 0).Value = OutlookMail.SenderName
Range("C3").Offset(i, 0).Columns.AutoFit
sText = StrConv(OutlookMail.RTFBody, vbUnicode)
Range("D3").Offset(i, 0).Value = sText
Range("D3").Offset(i, 0).Columns.AutoFit
Range("D3").Offset(i, 0).VerticalAlignment = xlTop
i = i + 1
End If
Next OutlookMail
Set Folder = Nothing
End Sub
``` | 2019/03/11 | [
"https://Stackoverflow.com/questions/55094997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10954825/"
] | An email can have several bodies or none. Outlook recognises text, Html and RTF bodies. No email I have examined in recent years contained a RTF body. Once it was the only option if you wanted to format your message. Today, Html and CSS offer far more functionality than RTF and I doubt if any smartphone accepts RTF. I am surprised you are receiving an email with a RTF body; my guess it is from a legacy system.
Ignoring RTF, if an email has an Html body, that is what is displayed to the user. Only if there is no Html body, will the user see the text body.
Of the emails I have examined, all have both a text and an Html body. Almost all of those text bodies are the Html body with every tag replaced by a carriage return and a linefeed. Since CRLF as newline is a Windows convention, I suspect if an email has no text body, Outlook is creating one from the Html body for the benefit of macros that want to process a text body. If my theory is correct, Outlook is not doing the same for an email that only contains a RTF email. Hence, you have a text body if there is an Html body but not if there is a RTF body.
The specification for Microsoft’s RTF is available online so you could research the format if you wish. If you search for “Can I process RTF from VBA?”, you will find lots of suggestions which you might find interesting.
Alternatively, the example RTF body you show looks simple:
```
{string of RTF commands{string of RTF commands}}
{string of RTF commands ending in “1033 ”text\par
text\par
text\par
}
```
If you deleted everything up to “1033 ” and the trailing “}” then replaced “\par” by “”, you might get what you want.
I have issues with your VBA. For example:
Not all items in Inbox are MailItems. You should have:
```
For Each OutlookMail In Folder.Items
If OutlookMail.Class = olMail Then
If OutlookMail.ReceivedTime ... Then
: : :
End If
End If
```
You do not need to format cells individually. The following at the bottom would handle the AutoFit and vertical alignment:
```
Cells.Columns.Autofit
Cells.VerticalAlignment = xlTop
```
Your code operates on the active worksheet. This relies on the user having the correct worksheet active when the macro is started. You should name the target worksheet to avoid errors. | Excel does not not support RTF directly, but plain text `MailItem.Body` should work fine, I have never seen `MailItem.Body` raising an exception. Do you save the message first? |
55,094,997 | I want to export outlook **NON-HTML Email Body** into excel with a click of a button inside excel. Below are my codes. Appreciate if anyone could assist me on this.
This is the code that I use to print the **plain text email body** but I get a lot of unwanted text
>
> sText = **StrConv(OutlookMail.RTFBody, vbUnicode)**
>
>
> Range("D3").Offset(i, 0).Value = **sText**
>
>
>
[](https://i.stack.imgur.com/lkGQX.png)
I did tried this but it prompts **run-time error '1004'
Application-defined or object-defined error** It works on body with HTML tags though.
>
> Range("D3").Offset(i, 0).Value = **OutlookMail.Body**
>
>
>
This is the structure of my email folders
[](https://i.stack.imgur.com/ANckj.png)
Below are my complete vba codes
```
Sub extract_email()
Dim OutlookApp As New Outlook.Application
Dim Folder As Outlook.MAPIFolder
Dim OutlookMail As MailItem
Dim sText As String
Dim i As Integer
Set myAccount = OutlookApp.GetNamespace("MAPI")
Set Folder = myAccount.GetDefaultFolder(olFolderInbox).Parent
Set Folder = Folder.Folders("Test_Main").Folders("Test_Sub")
i = 1
Range("A4:D20").Clear
For Each OutlookMail In Folder.Items
If OutlookMail.ReceivedTime >= Range("B1").Value And OutlookMail.SenderName = "Test_Admin" Then
Range("A3").Offset(i, 0).Value = OutlookMail.Subject
Range("A3").Offset(i, 0).Columns.AutoFit
Range("A3").Offset(i, 0).VerticalAlignment = xlTop
Range("B3").Offset(i, 0).Value = OutlookMail.ReceivedTime
Range("B3").Offset(i, 0).Columns.AutoFit
Range("B3").Offset(i, 0).VerticalAlignment = xlTop
Range("C3").Offset(i, 0).Value = OutlookMail.SenderName
Range("C3").Offset(i, 0).Columns.AutoFit
sText = StrConv(OutlookMail.RTFBody, vbUnicode)
Range("D3").Offset(i, 0).Value = sText
Range("D3").Offset(i, 0).Columns.AutoFit
Range("D3").Offset(i, 0).VerticalAlignment = xlTop
i = i + 1
End If
Next OutlookMail
Set Folder = Nothing
End Sub
``` | 2019/03/11 | [
"https://Stackoverflow.com/questions/55094997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10954825/"
] | Thank you for all the answers, I have improved my codes and I have figured out the issue. It is due to the "=" symbols that is generated from the script and sent to my email. Excel treat the "=" sign differently that's why it didn't allow me to extract properly. Once I changed the "=" symbol to "#" symbol, I can extract the email normally using:
>
> OutlookMail.Body
>
>
> | Excel does not not support RTF directly, but plain text `MailItem.Body` should work fine, I have never seen `MailItem.Body` raising an exception. Do you save the message first? |
8,832,464 | I can target all browsers using this code:
```
<link rel="stylesheet" media="screen and (min-device-width: 1024px)" href="large.css"/>
<link rel='stylesheet' media='screen and (min-width: 1023px) and (max-width: 1025px)' href='medium.css' />
<link rel='stylesheet' media="screen and (min-width: 419px) and (max-width: 1023px)" href='small.css' />
```
But media query design does not work on old versions of IE, so I have a problem with that browser as usual. | 2012/01/12 | [
"https://Stackoverflow.com/questions/8832464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/771291/"
] | Use this jQuery snipet to set a class on the BODY tag:
```
$(document).ready(function(){
var width = $(window).width();
var class = 'small';
if(width > 1024) {
class = 'large';
} else if(width > 1023 && width < 1025) {
class = 'medium';
}
$('body').addClass(class);
});
```
With appropriate class (large/medium/small) on your BODY you are able to write CSS like this:
```
body.large p {font-size: 25px};
body.medium p {font-size: 20px};
body.small p {font-size: 15px};
```
etc. | I really recommend using a javascript alternative like syze for example.
<http://rezitech.github.com/syze/> |
8,832,464 | I can target all browsers using this code:
```
<link rel="stylesheet" media="screen and (min-device-width: 1024px)" href="large.css"/>
<link rel='stylesheet' media='screen and (min-width: 1023px) and (max-width: 1025px)' href='medium.css' />
<link rel='stylesheet' media="screen and (min-width: 419px) and (max-width: 1023px)" href='small.css' />
```
But media query design does not work on old versions of IE, so I have a problem with that browser as usual. | 2012/01/12 | [
"https://Stackoverflow.com/questions/8832464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/771291/"
] | There are a number of [polyfills listed on the moderizer wiki](https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills) that includes several claiming to support media queries. | I really recommend using a javascript alternative like syze for example.
<http://rezitech.github.com/syze/> |
1,125,931 | The spherical Bessel equation is:
$$x^2y'' + 2xy' + (x^2 - \frac{5}{16})y = 0$$
If I seek a Frobenius series solution, I will have:
\begin{align\*}
&\quad y = \sum\_{n = 0}^{\infty} a\_nx^{n + r} \\
&\implies y' = \sum\_{n = 0}^{\infty} (n + r)a\_nx^{n + r - 1} \\
&\implies y'' = \sum\_{n = 0}^{\infty} (n + r)(n + r - 1)a\_nx^{n + r - 2}
\end{align\*}
Substituting into the ODE of interest:
\begin{align\*}
&\quad x^2y'' + 2xy' + (x^2 - \frac{5}{16})y = 0 \\
&\equiv \sum\_{n = 0}^{\infty} (n + r)(n + r - 1)a\_nx^{n + r} + \sum\_{n = 0}^{\infty} 2(n + r)a\_nx^{n + r} + \sum\_{n = 0}^{\infty} a\_nx^{n + r + 2} + \sum\_{n = 0}^{\infty} \frac{-5}{16}a\_nx^{n + r} = 0 \\
&\equiv \sum\_{n = 0}^{\infty} [(n + r)(n + r - 1) + 2(n + r) - \frac{5}{16}]a\_nx^{n + r} + \sum\_{n = 2}^{\infty} a\_{n - 2}x^{n + r} = 0 \\
&\equiv [r(r-1) + 2r - (5/16)]a\_0 + [(r+1)(r) + 2(r+1) - (5/16)]a\_1 + \\
&\quad \sum\_{n = 2}^{\infty} ([(n + r)(n + r - 1) + 2(n + r) - \frac{5}{16}]a\_n + a\_{n-2})x^{n + r} = 0 \\
&\implies [r(r-1) + 2r - (5/16)] = 0 \wedge \\
&\quad [(r+1)(r) + 2(r+1) - (5/16)] = 0 \wedge \\
&\quad [(n + r)(n + r - 1) + 2(n + r) - \frac{5}{16}]a\_n + a\_{n-2} = 0
\end{align\*}
The first conjunct is the standard indicial equation specifying $r$. The second conjunct is yet another quadratic that $r$ has to satisfy. Is there a mistake? Or should $a\_1 = 0$? | 2015/01/30 | [
"https://math.stackexchange.com/questions/1125931",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/115703/"
] | The main indicial is the the first equation. You get two roots from the first equation so you should set $a\_1=0$. If there is a common root between the first and second equations, then you can consider that root and set both $a\_1$ and $a\_0$ nonzero. | You set the value of $r$ found in the first equation into the second equation. It then defines $a\_n$ in terms of $a\_{n-2}$ for all $n \geq 2$. So, once we know $a\_0$, $a\_1$ we get $a\_2$ from the second equation and so on. |
19,846,817 | It seems like `require` calls are executed asynchronously, allowing program flow to continue around them. This is problematic when I'm trying to use a value set within a `require` call as a return value. For instance:
main.js:
```
$(document).ready(function() {
requirejs.config({
baseUrl: 'js'
});
requirejs(['other1'], function(other1) {
console.log(other1.test()); //logs out 'firstValue', where I would expect 'secondValue'
}
});
```
other1.js
```
function test() {
var returnValue = 'firstValue'; //this is what is actually returned, despite the reassignment below...
requirejs(['other2'], function(other2) {
other2.doSomething();
returnValue = 'secondValue'; //this is what I really want returned
})
return returnValue;
}
if(typeof module != 'undefined') {
module.exports.test = test;
}
if(typeof define != 'undefined') {
define({
'test':test
});
}
```
How can I set a return value for a function from inside a `require` block? | 2013/11/07 | [
"https://Stackoverflow.com/questions/19846817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1040915/"
] | Yes, require calls are executed `asynchronously`. So your example won't work, because
```
function test() {
var returnValue = 'firstValue';
requirejs(['other2'], function(other2) { // <-- ASYNC CALL
other2.doSomething();
returnValue = 'secondValue';
})
return returnValue; // <-- RETURNS FIRST! ('firstValue')
}
```
The only thing you need to do in your example is:
**main.js**
```
requirejs.config({
baseUrl: 'js'
});
requirejs(['other1'], function(other1) {
console.log(other1.test())
});
```
**js/other2.js**
```
// No dependencies
define(function() {
return {
doSomething: function() {
return 'secondValue';
}
};
});
```
**js/other1.js**
```
// Dependency to other2.js
define(['other2'], function(other2) {
return {
test: function() {
return other2.doSomething();
}
};
});
```
See complete example here: <http://plnkr.co/edit/hRjX4k?p=preview> | It looks like before `other1` returns, you want `other2` to be present, and you want to call a method on `other2` which will affect what you return for `other1`.
I think you'll want to-rethink your dependencies. `other2` appears to be a **dependency** of `other1`; it needs to be defined as such:
```
//in other1.js
define('other1', ['other2'], function(other2){
//other2 is now loaded
other2.doSomething();
//return whatever you want for `other1`
});
``` |
57,215,753 | I have a link that is placed in `li` and when you hover on it, a block should appear with links that I will indicate in it
```
<li id="dropdown" class="li">
<a href="/news/">Lessons</a>
</li>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
``` | 2019/07/26 | [
"https://Stackoverflow.com/questions/57215753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11714641/"
] | In this case, you don't have to declare `global`. Simply indent your `submitBtn` function inside `entry_Fn`:
```
def entry_Fn():
level_1 = Toplevel(root)
Label( level_1, text = "level one").pack()
entry_1 = Entry(level_1)
entry_1.pack()
entry_2 = Entry(level_1)
entry_2.pack()
def submitBtn():
val_1= entry_1.get()
val_2= entry_2.get()
sum_var.set(int(val_1)+ int(val_2))
level_1.destroy()
Button(level_1, text= "submit", command=submitBtn).pack()
```
But generally it is easier to make a class so you can avoid this kind of scope problems, like below:
```
from tkinter import *
class GUI(Tk):
def __init__(self):
super().__init__()
self.geometry('600x400')
self.sum_var= StringVar()
Label(self, text="Main window").pack()
Button(self, text="To enter Data", command=self.entry_Fn).pack()
sum = Label(self, textvariable=self.sum_var)
sum.pack()
def entry_Fn(self):
self.level_1 = Toplevel(self)
Label(self.level_1, text = "level one").pack()
self.entry_1 = Entry(self.level_1)
self.entry_1.pack()
self.entry_2 = Entry(self.level_1)
self.entry_2.pack()
Button(self.level_1, text="submit", command=self.submitBtn).pack()
def submitBtn(self):
val_1 = self.entry_1.get()
val_2 = self.entry_2.get()
self.sum_var.set(int(val_1)+ int(val_2))
self.level_1.destroy()
root = GUI()
root.mainloop()
``` | For your case, you can simply pass the two entries to `submitBtn()` function:
```
def submitBtn(entry_1, entry_2):
....
```
Then update the `command=` for the submit button inside `entry_Fn()`:
```
Button(level_1, text="submit", command=lambda: submitBtn(entry_1, enter_2)).pack()
``` |
57,215,753 | I have a link that is placed in `li` and when you hover on it, a block should appear with links that I will indicate in it
```
<li id="dropdown" class="li">
<a href="/news/">Lessons</a>
</li>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
``` | 2019/07/26 | [
"https://Stackoverflow.com/questions/57215753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11714641/"
] | For your case, you can simply pass the two entries to `submitBtn()` function:
```
def submitBtn(entry_1, entry_2):
....
```
Then update the `command=` for the submit button inside `entry_Fn()`:
```
Button(level_1, text="submit", command=lambda: submitBtn(entry_1, enter_2)).pack()
``` | You can subclass `tk.TopLevel`, and use a `tk.IntVar` to transfer the data back to root:
```
import tkinter as tk
class EntryForm(tk.Toplevel):
def __init__(self, master, sum_var):
super().__init__(master)
tk.Label(self, text="level one").pack()
self.sum_var = sum_var
self.entry_1 = tk.Entry(self)
self.entry_1.pack()
self.entry_2 = tk.Entry(self)
self.entry_2.pack()
tk.Button(self, text="submit", command=self.submitBtn).pack()
def submitBtn(self):
val_1 = self.entry_1.get()
val_2 = self.entry_2.get()
self.sum_var.set(int(val_1) + int(val_2))
self.destroy()
def spawn_entry_popup():
EntryForm(root, sum_var)
root= tk.Tk()
root.geometry('600x400')
sum_var = tk.IntVar()
tk.Label(root, text = "Main window").pack()
tk.Button(root, text= "To enter Data", command=spawn_entry_popup).pack()
sum_label = tk.Label(root, textvariable=sum_var)
sum_label.pack()
root.mainloop()
```
You can also place your app inside a class:
```
import tkinter as tk
class EntryForm(tk.Toplevel):
def __init__(self, master, sum_var):
super().__init__(master)
tk.Label(self, text="level one").pack()
self.sum_var = sum_var
self.entry_1 = tk.Entry(self)
self.entry_1.pack()
self.entry_2 = tk.Entry(self)
self.entry_2.pack()
tk.Button(self, text="submit", command=self.submitBtn).pack()
def submitBtn(self):
val_1 = self.entry_1.get()
val_2 = self.entry_2.get()
self.sum_var.set(int(val_1) + int(val_2))
class GUI(tk.Tk):
def __init__(self):
super().__init__()
self.geometry('600x400')
self.sum_var = tk.IntVar()
tk.Label(self, text = "Main window").pack()
tk.Button(self, text= "To enter Data", command=self.spawn_entry_popup).pack()
sum_label = tk.Label(self, textvariable=self.sum_var)
sum_label.pack()
def spawn_entry_popup(self):
EntryForm(self, self.sum_var)
GUI().mainloop()
``` |
57,215,753 | I have a link that is placed in `li` and when you hover on it, a block should appear with links that I will indicate in it
```
<li id="dropdown" class="li">
<a href="/news/">Lessons</a>
</li>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
``` | 2019/07/26 | [
"https://Stackoverflow.com/questions/57215753",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11714641/"
] | In this case, you don't have to declare `global`. Simply indent your `submitBtn` function inside `entry_Fn`:
```
def entry_Fn():
level_1 = Toplevel(root)
Label( level_1, text = "level one").pack()
entry_1 = Entry(level_1)
entry_1.pack()
entry_2 = Entry(level_1)
entry_2.pack()
def submitBtn():
val_1= entry_1.get()
val_2= entry_2.get()
sum_var.set(int(val_1)+ int(val_2))
level_1.destroy()
Button(level_1, text= "submit", command=submitBtn).pack()
```
But generally it is easier to make a class so you can avoid this kind of scope problems, like below:
```
from tkinter import *
class GUI(Tk):
def __init__(self):
super().__init__()
self.geometry('600x400')
self.sum_var= StringVar()
Label(self, text="Main window").pack()
Button(self, text="To enter Data", command=self.entry_Fn).pack()
sum = Label(self, textvariable=self.sum_var)
sum.pack()
def entry_Fn(self):
self.level_1 = Toplevel(self)
Label(self.level_1, text = "level one").pack()
self.entry_1 = Entry(self.level_1)
self.entry_1.pack()
self.entry_2 = Entry(self.level_1)
self.entry_2.pack()
Button(self.level_1, text="submit", command=self.submitBtn).pack()
def submitBtn(self):
val_1 = self.entry_1.get()
val_2 = self.entry_2.get()
self.sum_var.set(int(val_1)+ int(val_2))
self.level_1.destroy()
root = GUI()
root.mainloop()
``` | You can subclass `tk.TopLevel`, and use a `tk.IntVar` to transfer the data back to root:
```
import tkinter as tk
class EntryForm(tk.Toplevel):
def __init__(self, master, sum_var):
super().__init__(master)
tk.Label(self, text="level one").pack()
self.sum_var = sum_var
self.entry_1 = tk.Entry(self)
self.entry_1.pack()
self.entry_2 = tk.Entry(self)
self.entry_2.pack()
tk.Button(self, text="submit", command=self.submitBtn).pack()
def submitBtn(self):
val_1 = self.entry_1.get()
val_2 = self.entry_2.get()
self.sum_var.set(int(val_1) + int(val_2))
self.destroy()
def spawn_entry_popup():
EntryForm(root, sum_var)
root= tk.Tk()
root.geometry('600x400')
sum_var = tk.IntVar()
tk.Label(root, text = "Main window").pack()
tk.Button(root, text= "To enter Data", command=spawn_entry_popup).pack()
sum_label = tk.Label(root, textvariable=sum_var)
sum_label.pack()
root.mainloop()
```
You can also place your app inside a class:
```
import tkinter as tk
class EntryForm(tk.Toplevel):
def __init__(self, master, sum_var):
super().__init__(master)
tk.Label(self, text="level one").pack()
self.sum_var = sum_var
self.entry_1 = tk.Entry(self)
self.entry_1.pack()
self.entry_2 = tk.Entry(self)
self.entry_2.pack()
tk.Button(self, text="submit", command=self.submitBtn).pack()
def submitBtn(self):
val_1 = self.entry_1.get()
val_2 = self.entry_2.get()
self.sum_var.set(int(val_1) + int(val_2))
class GUI(tk.Tk):
def __init__(self):
super().__init__()
self.geometry('600x400')
self.sum_var = tk.IntVar()
tk.Label(self, text = "Main window").pack()
tk.Button(self, text= "To enter Data", command=self.spawn_entry_popup).pack()
sum_label = tk.Label(self, textvariable=self.sum_var)
sum_label.pack()
def spawn_entry_popup(self):
EntryForm(self, self.sum_var)
GUI().mainloop()
``` |
53,874 | I playing guitar since a couple of years (but not regularly) and I always wondered if guitarist from known bands always play their songs/solos perfectly?
Especially when the songs are fast paced, is it easier to make mistakes that no one will notice? When I play solos I am never really satisfied with my performance since it doesn't sound exactly the same like in the song.
I know there is no exact answer but I would like to know what you think so I can silence my conscience :) | 2017/02/28 | [
"https://music.stackexchange.com/questions/53874",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/37313/"
] | Other answers are great, but I'll add my experience. When playing live with a band, you have a lot going on at the same time. So mistakes may be masked by the rest of the band.
Most importantly though, is that you roll with it. Not just from the perspective that mistakes can still work, but that if you let it get to you, you are more likely to make more mistakes. Instead, just keep going, the audience can't rewind to hear your mistake again. If you can finish strong, that's what they will remember.
I love this [video](https://www.youtube.com/watch?v=wn1pk8Lpelc), and it's the perfect example of rolling with it. SRV breaks a string and his tech replaces the guitar in basically a four measure break that was there anyway. | No. Professionals are so perfect they never hit a single note wrong, and if you try to play like they do and they find out you make mistakes, they will come to your house at night and you will be banned from playing in front of people until the end of your life (or the end of the world, whatever comes first.)
Ok, now forget everything I just said.
Of course they do. Sometimes, it does happen that guitarists (or trombonists, saxophonists, etc.) play perfectly if they practice enough. I myself once scored a perfect score in a contest with my flute solo. And- I've also failed miserably the next year I did it, even though the piece was (sort of) easy and I've played it fine millions of times before. So I know the feeling.
Some mistakes can be covered up, especially if you're not playing alone and you're not totally terrible. And even if you are- if you play a Bb instead of a B one time, no one will notice. Really, it depends on how well you play. Everyone makes mistakes. The difference in levels is that when an ok musician messes up one note, they freak out and mess up even more, humiliating themselves completely; however, when a star forgets a big chunk of their music, they begin wildly improvising something that is way better than what was written. (This actually happened once at a concert with our band; a saxophone player had a solo part, and he missed the entrance by a few beats, so he just started playing something completely random that wasn't anywhere near what he was supposed to play. But it was honestly amazing- after the concert, we all agreed that we liked the new version better.)
So yeah, it happens. There are only two good ways to deal with these situations, however: when you goof up, cover it up with something better, or, as I heard from my band director hundreds of times: "Don't practice until you can play it right; practice until you can't play it wrong."
Good luck with the guitar! |
53,874 | I playing guitar since a couple of years (but not regularly) and I always wondered if guitarist from known bands always play their songs/solos perfectly?
Especially when the songs are fast paced, is it easier to make mistakes that no one will notice? When I play solos I am never really satisfied with my performance since it doesn't sound exactly the same like in the song.
I know there is no exact answer but I would like to know what you think so I can silence my conscience :) | 2017/02/28 | [
"https://music.stackexchange.com/questions/53874",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/37313/"
] | If you are talking about mistakes made during a live performance, all guitarists make them and most of the time they will not play solos note for note as recorded on the studio version (see the many Youtube videos of Steve Vai's original and several live versions of "Tender Surrender").
If you are talking about a recorded performance, as @Todd Wilcox noted, mistakes are hardly ever left on with most music genres as they are so easy to fix.
Of course in jazz, blues, etc., guitarists make mistakes on solos all of the time but you probably won't notice them as they will just turn them into a new ideas as solos are for the most part improvised (live and studio versions). Mike Stern told me many of his best ideas came from errors and variations on them. | Other answers are great, but I'll add my experience. When playing live with a band, you have a lot going on at the same time. So mistakes may be masked by the rest of the band.
Most importantly though, is that you roll with it. Not just from the perspective that mistakes can still work, but that if you let it get to you, you are more likely to make more mistakes. Instead, just keep going, the audience can't rewind to hear your mistake again. If you can finish strong, that's what they will remember.
I love this [video](https://www.youtube.com/watch?v=wn1pk8Lpelc), and it's the perfect example of rolling with it. SRV breaks a string and his tech replaces the guitar in basically a four measure break that was there anyway. |
53,874 | I playing guitar since a couple of years (but not regularly) and I always wondered if guitarist from known bands always play their songs/solos perfectly?
Especially when the songs are fast paced, is it easier to make mistakes that no one will notice? When I play solos I am never really satisfied with my performance since it doesn't sound exactly the same like in the song.
I know there is no exact answer but I would like to know what you think so I can silence my conscience :) | 2017/02/28 | [
"https://music.stackexchange.com/questions/53874",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/37313/"
] | I would expect that the musicians in top bands play extremely consistently, due to sheer repetition and the fact that it's their career.
However, your question touches on a trickier idea: What exactly is a "mistake"? If the exact notes and rhythms are prescribed, then any deviation from that clearly constitutes a mistake. But how precise does the timing/tempo need to be for the rhythm to be considered correct? What if it's technically correct, but a bit off stylistically or emotionally? What if something is "supposed" to ring out, but the fretting was a bit off and a note got partially dampened?
And what if the music is improvised?
From the listener's perspective: would you rather listen to a solo that was beautiful but had a wrong note, or one that was technically perfect but soulless? Anecdotally, my favorite rendition of a Debussy piano piece has a blatant key signature mistake in it\*, but it's still my favorite due to every other aspect of the performance. My old piano teacher tells a story of performing a section of a Bartok piece in the wrong *clef*, and people still enjoyed it.
The whole idea of perfection and mistakes is not very well defined, and in performance art it must be that way. Ultimately, the question is not whether or not a performance was "perfect", but whether or not it was enjoyable and conveyed whatever it was supposed to.
---
\* For the curious: [Van Cliburn's recording of Jardins sous la pluie](https://www.youtube.com/watch?v=m8rXQCewQjA). The section in C# in the middle, he misses B# in the melody each time. | I am not a guitarist myself, but I know a really great one and he assures me that he has never played all the way through a song without making a mistake, nor has he ever played a piece through exactly the same way twice. He's always tweaking things here and there. If you're comparing yourself to recordings, you have to realize they do multiple takes and combine the best takes. Even then, nobody is hardly ever perfect.
And please do silence your conscience! This is not what it's there for! |
53,874 | I playing guitar since a couple of years (but not regularly) and I always wondered if guitarist from known bands always play their songs/solos perfectly?
Especially when the songs are fast paced, is it easier to make mistakes that no one will notice? When I play solos I am never really satisfied with my performance since it doesn't sound exactly the same like in the song.
I know there is no exact answer but I would like to know what you think so I can silence my conscience :) | 2017/02/28 | [
"https://music.stackexchange.com/questions/53874",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/37313/"
] | 'Perfectly': never. 'Very Good': usually. Professionals tend to want to show you what they can do, rather than what they can't; it's their meal ticket, after all.
One of the skills in being an instrumentalist though is to practice techniques that allow you *to* power through small mistakes without disrupting the rhythm or the overall feel of the song, or letting your small mistake trip you up and turn into a bigger one. Pros will generally be good at this aspect of instrumentalism too; it's one reason you may not notice their mistakes. | I am not a guitarist myself, but I know a really great one and he assures me that he has never played all the way through a song without making a mistake, nor has he ever played a piece through exactly the same way twice. He's always tweaking things here and there. If you're comparing yourself to recordings, you have to realize they do multiple takes and combine the best takes. Even then, nobody is hardly ever perfect.
And please do silence your conscience! This is not what it's there for! |
53,874 | I playing guitar since a couple of years (but not regularly) and I always wondered if guitarist from known bands always play their songs/solos perfectly?
Especially when the songs are fast paced, is it easier to make mistakes that no one will notice? When I play solos I am never really satisfied with my performance since it doesn't sound exactly the same like in the song.
I know there is no exact answer but I would like to know what you think so I can silence my conscience :) | 2017/02/28 | [
"https://music.stackexchange.com/questions/53874",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/37313/"
] | If you are talking about mistakes made during a live performance, all guitarists make them and most of the time they will not play solos note for note as recorded on the studio version (see the many Youtube videos of Steve Vai's original and several live versions of "Tender Surrender").
If you are talking about a recorded performance, as @Todd Wilcox noted, mistakes are hardly ever left on with most music genres as they are so easy to fix.
Of course in jazz, blues, etc., guitarists make mistakes on solos all of the time but you probably won't notice them as they will just turn them into a new ideas as solos are for the most part improvised (live and studio versions). Mike Stern told me many of his best ideas came from errors and variations on them. | No. Professionals are so perfect they never hit a single note wrong, and if you try to play like they do and they find out you make mistakes, they will come to your house at night and you will be banned from playing in front of people until the end of your life (or the end of the world, whatever comes first.)
Ok, now forget everything I just said.
Of course they do. Sometimes, it does happen that guitarists (or trombonists, saxophonists, etc.) play perfectly if they practice enough. I myself once scored a perfect score in a contest with my flute solo. And- I've also failed miserably the next year I did it, even though the piece was (sort of) easy and I've played it fine millions of times before. So I know the feeling.
Some mistakes can be covered up, especially if you're not playing alone and you're not totally terrible. And even if you are- if you play a Bb instead of a B one time, no one will notice. Really, it depends on how well you play. Everyone makes mistakes. The difference in levels is that when an ok musician messes up one note, they freak out and mess up even more, humiliating themselves completely; however, when a star forgets a big chunk of their music, they begin wildly improvising something that is way better than what was written. (This actually happened once at a concert with our band; a saxophone player had a solo part, and he missed the entrance by a few beats, so he just started playing something completely random that wasn't anywhere near what he was supposed to play. But it was honestly amazing- after the concert, we all agreed that we liked the new version better.)
So yeah, it happens. There are only two good ways to deal with these situations, however: when you goof up, cover it up with something better, or, as I heard from my band director hundreds of times: "Don't practice until you can play it right; practice until you can't play it wrong."
Good luck with the guitar! |
53,874 | I playing guitar since a couple of years (but not regularly) and I always wondered if guitarist from known bands always play their songs/solos perfectly?
Especially when the songs are fast paced, is it easier to make mistakes that no one will notice? When I play solos I am never really satisfied with my performance since it doesn't sound exactly the same like in the song.
I know there is no exact answer but I would like to know what you think so I can silence my conscience :) | 2017/02/28 | [
"https://music.stackexchange.com/questions/53874",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/37313/"
] | 'Perfectly': never. 'Very Good': usually. Professionals tend to want to show you what they can do, rather than what they can't; it's their meal ticket, after all.
One of the skills in being an instrumentalist though is to practice techniques that allow you *to* power through small mistakes without disrupting the rhythm or the overall feel of the song, or letting your small mistake trip you up and turn into a bigger one. Pros will generally be good at this aspect of instrumentalism too; it's one reason you may not notice their mistakes. | I'll talk about live performances since, as other posters have mentioned, recorded performances can easily be fixed with editing.
Mistakes? Yes. Always.
But don't let them stop you!
As a not-top-notch performer I can tell you that there is a stark difference between your (the performer's) perception of the performance and the audience's. In a band situation, you are concentrating very specifically on what you are playing while the audience is taking in the entire performance of all of the members. Not only are you paying more attention to your own performance, but often there are monitors allowing you to hear your performance more than that of your bandmates. This can make you think "wow, that stood out like a sore thumb", when really it's not as prominent as you are hearing.
Further, you can feel your mistakes. You feel your fingers slip or not hit the strings with enough force. This extra sense of the mistake underscores when they happen.
An interesting aspect is that due to the nervousness of playing in public and having practiced a song many times, you are perceiving time differently. A mess-up will feel like it lasts an eternity but typically they are over so fast that it will fly by before anyone gets a chance to notice.
The real key to a good performance: when you inevitably make mistakes, don't let it show. Don't make "I messed up" face. And after a performance, just don't mention mistakes, even though it might be the first thing on your mind. |
53,874 | I playing guitar since a couple of years (but not regularly) and I always wondered if guitarist from known bands always play their songs/solos perfectly?
Especially when the songs are fast paced, is it easier to make mistakes that no one will notice? When I play solos I am never really satisfied with my performance since it doesn't sound exactly the same like in the song.
I know there is no exact answer but I would like to know what you think so I can silence my conscience :) | 2017/02/28 | [
"https://music.stackexchange.com/questions/53874",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/37313/"
] | 'Perfectly': never. 'Very Good': usually. Professionals tend to want to show you what they can do, rather than what they can't; it's their meal ticket, after all.
One of the skills in being an instrumentalist though is to practice techniques that allow you *to* power through small mistakes without disrupting the rhythm or the overall feel of the song, or letting your small mistake trip you up and turn into a bigger one. Pros will generally be good at this aspect of instrumentalism too; it's one reason you may not notice their mistakes. | No. Professionals are so perfect they never hit a single note wrong, and if you try to play like they do and they find out you make mistakes, they will come to your house at night and you will be banned from playing in front of people until the end of your life (or the end of the world, whatever comes first.)
Ok, now forget everything I just said.
Of course they do. Sometimes, it does happen that guitarists (or trombonists, saxophonists, etc.) play perfectly if they practice enough. I myself once scored a perfect score in a contest with my flute solo. And- I've also failed miserably the next year I did it, even though the piece was (sort of) easy and I've played it fine millions of times before. So I know the feeling.
Some mistakes can be covered up, especially if you're not playing alone and you're not totally terrible. And even if you are- if you play a Bb instead of a B one time, no one will notice. Really, it depends on how well you play. Everyone makes mistakes. The difference in levels is that when an ok musician messes up one note, they freak out and mess up even more, humiliating themselves completely; however, when a star forgets a big chunk of their music, they begin wildly improvising something that is way better than what was written. (This actually happened once at a concert with our band; a saxophone player had a solo part, and he missed the entrance by a few beats, so he just started playing something completely random that wasn't anywhere near what he was supposed to play. But it was honestly amazing- after the concert, we all agreed that we liked the new version better.)
So yeah, it happens. There are only two good ways to deal with these situations, however: when you goof up, cover it up with something better, or, as I heard from my band director hundreds of times: "Don't practice until you can play it right; practice until you can't play it wrong."
Good luck with the guitar! |
53,874 | I playing guitar since a couple of years (but not regularly) and I always wondered if guitarist from known bands always play their songs/solos perfectly?
Especially when the songs are fast paced, is it easier to make mistakes that no one will notice? When I play solos I am never really satisfied with my performance since it doesn't sound exactly the same like in the song.
I know there is no exact answer but I would like to know what you think so I can silence my conscience :) | 2017/02/28 | [
"https://music.stackexchange.com/questions/53874",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/37313/"
] | I would expect that the musicians in top bands play extremely consistently, due to sheer repetition and the fact that it's their career.
However, your question touches on a trickier idea: What exactly is a "mistake"? If the exact notes and rhythms are prescribed, then any deviation from that clearly constitutes a mistake. But how precise does the timing/tempo need to be for the rhythm to be considered correct? What if it's technically correct, but a bit off stylistically or emotionally? What if something is "supposed" to ring out, but the fretting was a bit off and a note got partially dampened?
And what if the music is improvised?
From the listener's perspective: would you rather listen to a solo that was beautiful but had a wrong note, or one that was technically perfect but soulless? Anecdotally, my favorite rendition of a Debussy piano piece has a blatant key signature mistake in it\*, but it's still my favorite due to every other aspect of the performance. My old piano teacher tells a story of performing a section of a Bartok piece in the wrong *clef*, and people still enjoyed it.
The whole idea of perfection and mistakes is not very well defined, and in performance art it must be that way. Ultimately, the question is not whether or not a performance was "perfect", but whether or not it was enjoyable and conveyed whatever it was supposed to.
---
\* For the curious: [Van Cliburn's recording of Jardins sous la pluie](https://www.youtube.com/watch?v=m8rXQCewQjA). The section in C# in the middle, he misses B# in the melody each time. | I'll talk about live performances since, as other posters have mentioned, recorded performances can easily be fixed with editing.
Mistakes? Yes. Always.
But don't let them stop you!
As a not-top-notch performer I can tell you that there is a stark difference between your (the performer's) perception of the performance and the audience's. In a band situation, you are concentrating very specifically on what you are playing while the audience is taking in the entire performance of all of the members. Not only are you paying more attention to your own performance, but often there are monitors allowing you to hear your performance more than that of your bandmates. This can make you think "wow, that stood out like a sore thumb", when really it's not as prominent as you are hearing.
Further, you can feel your mistakes. You feel your fingers slip or not hit the strings with enough force. This extra sense of the mistake underscores when they happen.
An interesting aspect is that due to the nervousness of playing in public and having practiced a song many times, you are perceiving time differently. A mess-up will feel like it lasts an eternity but typically they are over so fast that it will fly by before anyone gets a chance to notice.
The real key to a good performance: when you inevitably make mistakes, don't let it show. Don't make "I messed up" face. And after a performance, just don't mention mistakes, even though it might be the first thing on your mind. |
53,874 | I playing guitar since a couple of years (but not regularly) and I always wondered if guitarist from known bands always play their songs/solos perfectly?
Especially when the songs are fast paced, is it easier to make mistakes that no one will notice? When I play solos I am never really satisfied with my performance since it doesn't sound exactly the same like in the song.
I know there is no exact answer but I would like to know what you think so I can silence my conscience :) | 2017/02/28 | [
"https://music.stackexchange.com/questions/53874",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/37313/"
] | Other answers are great, but I'll add my experience. When playing live with a band, you have a lot going on at the same time. So mistakes may be masked by the rest of the band.
Most importantly though, is that you roll with it. Not just from the perspective that mistakes can still work, but that if you let it get to you, you are more likely to make more mistakes. Instead, just keep going, the audience can't rewind to hear your mistake again. If you can finish strong, that's what they will remember.
I love this [video](https://www.youtube.com/watch?v=wn1pk8Lpelc), and it's the perfect example of rolling with it. SRV breaks a string and his tech replaces the guitar in basically a four measure break that was there anyway. | “Never lose the groove in order to find a note.”
― Victor L. Wooten, The Music Lesson: A Spiritual Search for Growth Through Music
This acknowledges that musicians do play "wrong" notes, but what's more important is the flow of the piece. As for "wrong," it depends on how formalized the piece is. Some classical music has a fairly rigid structure, and the performer is usually expected to play the music as written (note-wise, not speaking of interpretation here). Celtic tunes on the other hand have "settings" (i.e. ways of playing) that may vary, so a musician who plays a "wrong" note may claim it as a new setting; but of course playing a C# in the key of F may raise eyebrows...
I like the comment above about being one fret from the "correct" note, and that's what slides are for. |
53,874 | I playing guitar since a couple of years (but not regularly) and I always wondered if guitarist from known bands always play their songs/solos perfectly?
Especially when the songs are fast paced, is it easier to make mistakes that no one will notice? When I play solos I am never really satisfied with my performance since it doesn't sound exactly the same like in the song.
I know there is no exact answer but I would like to know what you think so I can silence my conscience :) | 2017/02/28 | [
"https://music.stackexchange.com/questions/53874",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/37313/"
] | If you are talking about mistakes made during a live performance, all guitarists make them and most of the time they will not play solos note for note as recorded on the studio version (see the many Youtube videos of Steve Vai's original and several live versions of "Tender Surrender").
If you are talking about a recorded performance, as @Todd Wilcox noted, mistakes are hardly ever left on with most music genres as they are so easy to fix.
Of course in jazz, blues, etc., guitarists make mistakes on solos all of the time but you probably won't notice them as they will just turn them into a new ideas as solos are for the most part improvised (live and studio versions). Mike Stern told me many of his best ideas came from errors and variations on them. | I'll talk about live performances since, as other posters have mentioned, recorded performances can easily be fixed with editing.
Mistakes? Yes. Always.
But don't let them stop you!
As a not-top-notch performer I can tell you that there is a stark difference between your (the performer's) perception of the performance and the audience's. In a band situation, you are concentrating very specifically on what you are playing while the audience is taking in the entire performance of all of the members. Not only are you paying more attention to your own performance, but often there are monitors allowing you to hear your performance more than that of your bandmates. This can make you think "wow, that stood out like a sore thumb", when really it's not as prominent as you are hearing.
Further, you can feel your mistakes. You feel your fingers slip or not hit the strings with enough force. This extra sense of the mistake underscores when they happen.
An interesting aspect is that due to the nervousness of playing in public and having practiced a song many times, you are perceiving time differently. A mess-up will feel like it lasts an eternity but typically they are over so fast that it will fly by before anyone gets a chance to notice.
The real key to a good performance: when you inevitably make mistakes, don't let it show. Don't make "I messed up" face. And after a performance, just don't mention mistakes, even though it might be the first thing on your mind. |
60,145,379 | I have this issue when trying to read my data which is json encoded from the php page to the swift page.
this is the code I am using
```
import Foundation
protocol HomeModelProtocol: class {
func itemsDownloaded(items: NSArray)
}
class HomeModel: NSObject, URLSessionDataDelegate {
//properties
weak var delegate: HomeModelProtocol!
var data = Data()
let urlPath: String = "http://localhost/service.php" //this will be changed to the path where service.php lives
func downloadItems() {
let url: URL = URL(string: urlPath)!
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
let task = defaultSession.dataTask(with: url) { (data, response, error) in
if error != nil {
print("Failed to download data")
}else {
print("Data downloaded") // this work fine
self.parseJSON(data!)
}
}
task.resume()
}
func parseJSON(_ data:Data) {
var jsonResult = NSArray()
print(jsonResult) // this print empty parentheses
print(String(data: data, encoding: .utf8)) // this prints out the array
//the code below throughs an arror
do{
jsonResult = try JSONSerialization.jsonObject(with:data, options:JSONSerialization.ReadingOptions.allowFragments) as! [NSArray] as NSArray
print(jsonResult)
} catch let error as NSError {
print(error)
}
var jsonElement = NSDictionary()
let locations = NSMutableArray()
for i in 0 ..< jsonResult.count
{
jsonElement = jsonResult[i] as! NSDictionary
let location = LocationModel()
//the following insures none of the JsonElement values are nil through optional binding
if let name = jsonElement["Name"] as? String,
let address = jsonElement["Address"] as? String,
let latitude = jsonElement["Latitude"] as? String,
let longitude = jsonElement["Longitude"] as? String
{
location.name = name
location.address = address
location.latitude = latitude
location.longitude = longitude
}
locations.add(location)
}
DispatchQueue.main.async(execute: { () -> Void in
self.delegate.itemsDownloaded(items: locations)
})
}
}
```
this is the output which I am receiving:
```
Data downloaded
(
)
Optional(" \nconnectedinside[{\"name\":\"One\",\"add\":\"One\",\"lat\":\"1\",\"long\":\"1\"},{\"name\":\"Two\",\"add\":\"Two\",\"lat\":\"2\",\"long\":\"2\"},{\"name\":\"One\",\"add\":\"One\",\"lat\":\"1\",\"long\":\"1\"},{\"name\":\"Two\",\"add\":\"Two\",\"lat\":\"2\",\"long\":\"2\"}]")
```
>
> Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around
> character 2." UserInfo={NSDebugDescription=Invalid value around
> character 2.}
>
>
> | 2020/02/10 | [
"https://Stackoverflow.com/questions/60145379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6024981/"
] | You get this error, because the json response you receive is not an array but a dictionary.
EDIT: as pointed out in a comment, you first need to fix your json response in your php code. There is ":" missing after "connectedinside".
It should look like this:
`{\"connectedinside\":[{\"name\":\"One\",\"add\":"One",...},...]}`
My suggestion to fix this:
You should have two models:
```
struct HomeModelResponse: Codable {
let connectedinside: [LocationModel]
}
// your LocationModel should look like this:
struct LocationModel: Codable {
let name: String
let add: String
let lat: String
let long: String
}
```
And change your JSONDecoding code to:
```
do {
jsonResult = try? JSONDecoder().decode(HomeModelResponse.self, from: data)
print()
} catch let exception {
print("received exception while decoding: \(exception)"
}
```
Then you can access your LocationModels by jsonResult.connectedinside | The problem was on my php side and I fixed it.it is working now. |
25,879,652 | Is there a way in Eclipse to easily find all appearances of a variable in a file without having to manually search (CTRL + F) for it? | 2014/09/16 | [
"https://Stackoverflow.com/questions/25879652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3284878/"
] | with the cursor on the variable, press ctrl-shift-g. Works for variables, classes, methods, works across the entire project. If you just click on the variable, eclipse will highlight all uses of the variable in the current file, and mark the scrollbar with the places that are highlighted. | There is a search with many features accessible with `Control`+`G`, but it does not support variables inside of a function.
There is also another search, which occurs when you select a variable or other thing and press `Control`+`Shift`+`G`. |
25,879,652 | Is there a way in Eclipse to easily find all appearances of a variable in a file without having to manually search (CTRL + F) for it? | 2014/09/16 | [
"https://Stackoverflow.com/questions/25879652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3284878/"
] | with the cursor on the variable, press ctrl-shift-g. Works for variables, classes, methods, works across the entire project. If you just click on the variable, eclipse will highlight all uses of the variable in the current file, and mark the scrollbar with the places that are highlighted. | In case you want to find all occurrences of variable to rename it, you can do it using `Alt`+`Shift`+`R`. |
25,879,652 | Is there a way in Eclipse to easily find all appearances of a variable in a file without having to manually search (CTRL + F) for it? | 2014/09/16 | [
"https://Stackoverflow.com/questions/25879652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3284878/"
] | There is a search with many features accessible with `Control`+`G`, but it does not support variables inside of a function.
There is also another search, which occurs when you select a variable or other thing and press `Control`+`Shift`+`G`. | In case you want to find all occurrences of variable to rename it, you can do it using `Alt`+`Shift`+`R`. |
30,877,355 | I want to change the 'csproj' file of my unity project in order to be able to access a specific library as [this](https://stackoverflow.com/questions/5694/the-imported-project-c-microsoft-csharp-targets-was-not-found) answer sugests.
I am manually editing the file but every time i reload the project, the 'csproj' file returns to it's initial state.
Is this a common issue? Is there a way to avoid this and change the file permanently?
---
EDIT: My goal is to use **CSharpCodeProvider** so if there is another way of doing it without changing the 'csproj' file, i will gladly adopt the approach | 2015/06/16 | [
"https://Stackoverflow.com/questions/30877355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1754152/"
] | As far as I know, you cannot prevent Unity from overwriting your csproj files upon recompilation of your scripts.
When working with larger code bases and Unity3D I tend to put most of my code into separate .Net assemblies (DLLs). This helps me when I'm sharing code between multiple projects and game servers, and Unity doesn't need to compile all scripts when it detects changes.
To do that fire up your .Net IDE of choice and create a new *class library* project (which will output a .dll). Make sure it is targeting the **.Net Framework 3.5** or lower. Then, you copy the output .dll into you Unity project's *Assets* folder in a post-build step. I like to use a post-build step to prevent me from forgetting to copy the assembly after a change.
DLLs in the project's *Assets* folder are automatically referenced by Unity when it creates its C# projects. This means all of the containing code can be used from within your scripts. Note, though, that the other way around will not work as easily: you cannot use code from Unity scripts in your separate project.
Depending on what exactly you want to do with [CSharpCodeProvider](https://msdn.microsoft.com/en-us/library/microsoft.csharp.csharpcodeprovider(v=vs.110).aspx) you can put your generation logic (and the necessary `Import` directive) into such a separate project.
Edit: For more information how we set up our project structure you can watch [this talk](https://www.youtube.com/watch?v=ndt1crp9i7M) by the lead programmer on Jagged Alliance Online from Unite11. | As Suigi suggested, i have created a .dll file with the help of a .Net IDE ([SharpDevelop](http://www.icsharpcode.net/OpenSource/SD/Download/)) and just copied it in the 'Assets' folder of unity.
([How do i create a .dll file with SharpDevelop](http://community.sharpdevelop.net/forums/p/14349/38210.aspx))
Here is the class that i wrote to produce the .dll file:
```
using System;
using System.Collections.Generic;
using System.CodeDom.Compiler;
using System.Diagnostics;
using Microsoft.CSharp;
using System.Reflection;
namespace dllTest {
public class AssemblyGeneration {
public static Assembly generateAssemblyFromCode(string code, string assemblyFilename) {
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.OutputAssembly = assemblyFilename + ".dll";
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, code);
Assembly assembly = null;
if (!results.Errors.HasErrors) {
assembly = results.CompiledAssembly;
return assembly;
}
else {
return null;
}
}
}
}
```
In order to use it in any unity script, just use the namespace 'dllTest'. Then, you can call AssemblyGeneration.generateAssemblyFromCode(...) . |
30,877,355 | I want to change the 'csproj' file of my unity project in order to be able to access a specific library as [this](https://stackoverflow.com/questions/5694/the-imported-project-c-microsoft-csharp-targets-was-not-found) answer sugests.
I am manually editing the file but every time i reload the project, the 'csproj' file returns to it's initial state.
Is this a common issue? Is there a way to avoid this and change the file permanently?
---
EDIT: My goal is to use **CSharpCodeProvider** so if there is another way of doing it without changing the 'csproj' file, i will gladly adopt the approach | 2015/06/16 | [
"https://Stackoverflow.com/questions/30877355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1754152/"
] | As far as I know, you cannot prevent Unity from overwriting your csproj files upon recompilation of your scripts.
When working with larger code bases and Unity3D I tend to put most of my code into separate .Net assemblies (DLLs). This helps me when I'm sharing code between multiple projects and game servers, and Unity doesn't need to compile all scripts when it detects changes.
To do that fire up your .Net IDE of choice and create a new *class library* project (which will output a .dll). Make sure it is targeting the **.Net Framework 3.5** or lower. Then, you copy the output .dll into you Unity project's *Assets* folder in a post-build step. I like to use a post-build step to prevent me from forgetting to copy the assembly after a change.
DLLs in the project's *Assets* folder are automatically referenced by Unity when it creates its C# projects. This means all of the containing code can be used from within your scripts. Note, though, that the other way around will not work as easily: you cannot use code from Unity scripts in your separate project.
Depending on what exactly you want to do with [CSharpCodeProvider](https://msdn.microsoft.com/en-us/library/microsoft.csharp.csharpcodeprovider(v=vs.110).aspx) you can put your generation logic (and the necessary `Import` directive) into such a separate project.
Edit: For more information how we set up our project structure you can watch [this talk](https://www.youtube.com/watch?v=ndt1crp9i7M) by the lead programmer on Jagged Alliance Online from Unite11. | Just for completeness:
There is an undocumented feature in Unity which allows you to edit the generated `.csproj` files (programmatically), by using an `AssetPostprocessor`:
Inside any folder under `Assets` named `Editor`, create a class with the following structure:
```
public class CsprojPostprocessor : AssetPostprocessor {
public static string OnGeneratedCSProject(string path, string content) {
return PatchCsprojContent(content);
}
}
```
where `PathCsprojContent` is a function which returns a patched version of the `.csproj` file with the additions you need.
In case you want to patch only certain `.csproj` files, you can check the path beforehand. For example, if you want to process only the Asset `.csproj` file called `Assembly-CSharp.csproj`, you can add the following check to the start of `OnGeneratedCsProject`:
```
if (!path.EndsWith("Assembly-CSharp.csproj")) {
return content;
}
```
Reference: <https://learn.microsoft.com/en-us/visualstudio/gamedev/unity/extensibility/customize-project-files-created-by-vstu> |
30,877,355 | I want to change the 'csproj' file of my unity project in order to be able to access a specific library as [this](https://stackoverflow.com/questions/5694/the-imported-project-c-microsoft-csharp-targets-was-not-found) answer sugests.
I am manually editing the file but every time i reload the project, the 'csproj' file returns to it's initial state.
Is this a common issue? Is there a way to avoid this and change the file permanently?
---
EDIT: My goal is to use **CSharpCodeProvider** so if there is another way of doing it without changing the 'csproj' file, i will gladly adopt the approach | 2015/06/16 | [
"https://Stackoverflow.com/questions/30877355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1754152/"
] | Just for completeness:
There is an undocumented feature in Unity which allows you to edit the generated `.csproj` files (programmatically), by using an `AssetPostprocessor`:
Inside any folder under `Assets` named `Editor`, create a class with the following structure:
```
public class CsprojPostprocessor : AssetPostprocessor {
public static string OnGeneratedCSProject(string path, string content) {
return PatchCsprojContent(content);
}
}
```
where `PathCsprojContent` is a function which returns a patched version of the `.csproj` file with the additions you need.
In case you want to patch only certain `.csproj` files, you can check the path beforehand. For example, if you want to process only the Asset `.csproj` file called `Assembly-CSharp.csproj`, you can add the following check to the start of `OnGeneratedCsProject`:
```
if (!path.EndsWith("Assembly-CSharp.csproj")) {
return content;
}
```
Reference: <https://learn.microsoft.com/en-us/visualstudio/gamedev/unity/extensibility/customize-project-files-created-by-vstu> | As Suigi suggested, i have created a .dll file with the help of a .Net IDE ([SharpDevelop](http://www.icsharpcode.net/OpenSource/SD/Download/)) and just copied it in the 'Assets' folder of unity.
([How do i create a .dll file with SharpDevelop](http://community.sharpdevelop.net/forums/p/14349/38210.aspx))
Here is the class that i wrote to produce the .dll file:
```
using System;
using System.Collections.Generic;
using System.CodeDom.Compiler;
using System.Diagnostics;
using Microsoft.CSharp;
using System.Reflection;
namespace dllTest {
public class AssemblyGeneration {
public static Assembly generateAssemblyFromCode(string code, string assemblyFilename) {
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = false;
parameters.OutputAssembly = assemblyFilename + ".dll";
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, code);
Assembly assembly = null;
if (!results.Errors.HasErrors) {
assembly = results.CompiledAssembly;
return assembly;
}
else {
return null;
}
}
}
}
```
In order to use it in any unity script, just use the namespace 'dllTest'. Then, you can call AssemblyGeneration.generateAssemblyFromCode(...) . |
3,784,607 | **Purpose of the app:**
A simple app that draws a circle for every touch recognised on the screen and follows the touch events. On a 'high pressure reading' `getPressure (int pointerIndex)` the colour of the circle will change and the radius will increase. Additionally the touch ID with `getPointerId (int pointerIndex)`, x- and y-coordinates and pressure are shown next to the finger touch.
Following a code snipplet of the important part (please forgive me it is not the nicest code ;) I know)
```
protected void onDraw(Canvas canvas){
//draw circle only when finger(s) is on screen and moves
if(iTouchAction == (MotionEvent.ACTION_MOVE)){
int x,y;
float pressure;
//Draw circle for every touch
for (int i = 0; i < touchEvent.getPointerCount(); i++){
x = (int)touchEvent.getX(i);
y = (int)touchEvent.getY(i);
pressure = touchEvent.getPressure(i);
//High pressure
if (pressure > 0.25){
canvas.drawCircle(x, y, z+30, pressureColor);
canvas.drawText(""+touchEvent.getPointerId(i)+" | "+x+"/"+y, x+90, y-80, touchColor);
canvas.drawText(""+pressure, x+90, y-55, pressureColor);
}else{ //normal touch event
canvas.drawCircle(x, y, z, touchColor);
canvas.drawText(""+touchEvent.getPointerId(i)+" | "+x+"/"+y, x+60, y-50, touchColor);
canvas.drawText(""+pressure, x+60, y-25, pressureColor);
}
}
}
}
```
**The problem:**
A HTC Desire running Android 2.1 is the test platform. The app works fine and tracks two finger without a problem. But it seems that the two touch points interfere with each other when they get t0o close -- it looks like they circles 'snap'to a shared x and y axle. Sometimes they even swap the input coordinates of the other touch event. Another problem is that even though `getPressure (int pointerIndex)` refers to an PointerID both touch event have the same pressure reading.
As this is all a bit abstract, find a video here: <http://www.youtube.com/watch?v=bFxjFexrclU>
**My question:**
1. Is my code just simply wrong?
2. Does Android 2.1 not handle the touch events well enough get things mixed up?
3. Is this a hardware problem and has nothing to do with 1) and 2)?
Thank you for answers and/or relinks to other thread (sorry could find one that address this problem).
Chris | 2010/09/24 | [
"https://Stackoverflow.com/questions/3784607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/400022/"
] | I hate to tell you this, but it's your hardware.
The touch panel used in the Nexus One (which I believe is the same hardware used in the HTC Desire) is known for this particular artifact. We did some work to alleviate the "jumps to other finger's axis" problem around the ACTION\_POINTER\_UP/DOWN events for Android 2.2 by dropping some detectable bad events, but the problem still persists when the pointers get close along one axis. This panel is also known for randomly reversing X and Y coordinate data; two points (x0, y0) and (x1, y1) become (x0, y1) and (x1, y0). Sadly there's only so much you can do when the "real" data is gone by the time Android itself gets hold of it.
This isn't the only panel in the wild that has dodgy multitouch capabilities. To tell at runtime if you have a screen capable of precise multitouch data reporting without issues like this, use PackageManager to check for [`FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT`](http://d.android.com/reference/android/content/pm/PackageManager.html#FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT). If you don't have this feature available you can still do simple things like scale gestures reliably. | Anyone tried **[this fix for multitouch gestures](http://code.google.com/p/android-multitouch-controller/)** on older androids before? I am planning to evaluate it for [my own project](https://github.com/Philzen/WebView-MultiTouch-Polyfill), as it also deals with android 1.x/2.x buggy multitouch.
Luke seems to have covered the problem described here as well as other common touch input problems on pre-3.x devices.
Hope it helps, Cheers. |
69,903 | How do you cite a background map layer that is used in ArcMap that is retrieved from ArcGIS Online? For example the background layer is suppose to be credited from the U.S. Geological Survey and in the description it was digitized from the U.S. Geological Survey Professional Paper 1183. | 2013/08/27 | [
"https://gis.stackexchange.com/questions/69903",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/21471/"
] | According to the help topic ["Defining parameter data types in a Python toolbox"](http://resources.arcgis.com/en/help/main/10.1/index.html#/Defining_parameter_data_types_in_a_Python_toolbox/001500000035000000/), you should use `"DEFeatureClass"`. | **What is the difference between DEFeatureClass and IFeatureClass?**
First a short explanation of **Interface** vs. **Implementation**: DEFeatureClass is a CoClass ID, meaning it is an implementation of IDEFeatureClass. In COM, interfaces are separated from implementations. To get a DEFeatureClass, you must first declare an instance of IDEFeatureClass and use that to get DEFeatureClass.
Now, onto what the DEFeatureClass is: The DEFeatureClass is the [**data element**](http://edndoc.esri.com/arcobjects/9.2/ComponentHelp/esriGeoDatabase/IDEFeatureClass.htm) for your feature class. A data element is the metadata for the feature class. It contains only read/write properties that describe the feature class with no methods. It's purpose is to store and retrieve information *about* the feature class. Notice that you can change various properties *describing* your feature class from here as all of the properties are read/write.
An [**IFeatureClass**](http://edndoc.esri.com/arcobjects/9.0/componenthelp/esrigeodatabase/IFeatureClass.htm) is used to control the behavior of the feature class. It *does things* with the feature class versus simply *storing information* about the feature class. Notice in the documentation that this object includes various methods that you can execute on the feature class, such as DeleteIndex, DeleteField, FeatureCount, etc. However, it also contains information about the feature class, albeit in read-only (get) format. Notice in the link that properties describing the feature class, such as FeatureType, are all read-only.
**Which should you use, and why?**
See comments below. You must use DEFeatureClass. The link you provided in .pdf describes the different data types that correspond to the feature class. The only one that is relevant to you is the DEFeatureClass. |
102,059 | Because of certain reasons, I'm sometimes tied to an extremely slow internet connection. What I realized with this, is that certain sites (for example, any subdomain of blog.hu) works in a way that needs a certain part of the site be loaded before comments are loaded too. I assume it's because of an AJAX operation, as the comments themselves are not visible within the HTML file.
In contrast, forum engines, such as vBulletin are often free from AJAX, meaning that when a thread's HTML is loaded, every comment in it are "hardcoded", meaning that even if the "fancy parts" (CSS, images and so on) are not loaded, I can already read the comments.
My needs are very special though, so I'm interested - is there any general UX advantage of any of these? | 2016/12/01 | [
"https://ux.stackexchange.com/questions/102059",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/76708/"
] | There are physical limits as to how long a line of text can be before it gets difficult to process. Much like breathing while speaking, the mind needs periodic breaks to process the string of letters and numbers it has just taken in. Line breaks provide an opportunity for this to occur. A general rule that I have heard is to aim for roughly 80 characters per line.
However, this is not the whole story. It seems like we could simply base our font size off of the vw unit to ensure that we always hit this magical 80 character ideal, but no one really does this. Why not? The short answer is peripheral vision. Keep in mind that our eyes and brain also need to keep track of what line we're on, so when we jump after the line break, we know where to continue from. If the text block takes up too much of our field of view, the start of the line will be too far into our peripheral vision by the time we get to the end, and we lose sight of our place. That's no good either.
The best way to solve the demands of both character limit and field of view limit is to just enforce a maximum width that (hopefully) ensures we're fitting 80ish characters to a line while those characters remain large enough to read easily and the entire block remains small enough to stay within readable focus.
A couple of points about outlook and gmail specifically. Outlook uses some of the excess horizontal space to display both navigation and the list of messages in left aligned panes. The remainder of the window *appears* to be used for the message body, but extreme widths (using multiple monitors) reveal that it quietly enforces a max-width for the body contents. Gmail surprisingly does allow body text to grow effectively infinitely. I pulled up a couple of wordy emails to check, and to be honest long paragraphs don't read especially well. Note that the *compose* dialog is width limited, so it's somewhat surprising that they aren't limiting the width for reading. Perhaps they've found in their testing that emails are typically fairly short or (in the case of promotional) have already been laid out by a designer. Or perhaps Google needs to update their desktop layout... | @JoshDoebbert has a good point on the text legibility. [This other question](https://ux.stackexchange.com/questions/34120/relationship-between-font-size-and-width-of-container) has some interesting information on the topic.
I just wanted to add that percentages are good to let the content adapt to smaller screen size. As you said there is a minimum size and in the same way there is maximum size that lets the content be understood correctly. Whether it is text or images **the screen size in both height and width should be considered to display the content correctly**, and set relevant breakpoints for both parameters.
[](https://i.stack.imgur.com/oTPat.jpg) |
102,059 | Because of certain reasons, I'm sometimes tied to an extremely slow internet connection. What I realized with this, is that certain sites (for example, any subdomain of blog.hu) works in a way that needs a certain part of the site be loaded before comments are loaded too. I assume it's because of an AJAX operation, as the comments themselves are not visible within the HTML file.
In contrast, forum engines, such as vBulletin are often free from AJAX, meaning that when a thread's HTML is loaded, every comment in it are "hardcoded", meaning that even if the "fancy parts" (CSS, images and so on) are not loaded, I can already read the comments.
My needs are very special though, so I'm interested - is there any general UX advantage of any of these? | 2016/12/01 | [
"https://ux.stackexchange.com/questions/102059",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/76708/"
] | There are physical limits as to how long a line of text can be before it gets difficult to process. Much like breathing while speaking, the mind needs periodic breaks to process the string of letters and numbers it has just taken in. Line breaks provide an opportunity for this to occur. A general rule that I have heard is to aim for roughly 80 characters per line.
However, this is not the whole story. It seems like we could simply base our font size off of the vw unit to ensure that we always hit this magical 80 character ideal, but no one really does this. Why not? The short answer is peripheral vision. Keep in mind that our eyes and brain also need to keep track of what line we're on, so when we jump after the line break, we know where to continue from. If the text block takes up too much of our field of view, the start of the line will be too far into our peripheral vision by the time we get to the end, and we lose sight of our place. That's no good either.
The best way to solve the demands of both character limit and field of view limit is to just enforce a maximum width that (hopefully) ensures we're fitting 80ish characters to a line while those characters remain large enough to read easily and the entire block remains small enough to stay within readable focus.
A couple of points about outlook and gmail specifically. Outlook uses some of the excess horizontal space to display both navigation and the list of messages in left aligned panes. The remainder of the window *appears* to be used for the message body, but extreme widths (using multiple monitors) reveal that it quietly enforces a max-width for the body contents. Gmail surprisingly does allow body text to grow effectively infinitely. I pulled up a couple of wordy emails to check, and to be honest long paragraphs don't read especially well. Note that the *compose* dialog is width limited, so it's somewhat surprising that they aren't limiting the width for reading. Perhaps they've found in their testing that emails are typically fairly short or (in the case of promotional) have already been laid out by a designer. Or perhaps Google needs to update their desktop layout... | * **Content Display**
Think about this: you make a site with content prepared for full width, no max-width. This will work relatively OK for common sizes, but full screen images for big screens will add a massive load OR they will get pixelated. Just choose your poison. And this is easily fixed by... max-width
* **Legibility**
There are many studies about line length. [NN/G says between 45 to 75 characters](https://www.smashingmagazine.com/2014/09/balancing-line-length-font-size-responsive-web-design/), [Baymard proposes 50 to 75 characters](http://baymard.com/blog/line-length-readability), [Viget says around 100 characters](https://www.viget.com/articles/the-line-length-misconception) and so on. For example, this post has around 100 characters width, and it takes 1/3 of my screen. The whole idea of having a 300 characters line makes me dizzy!
* **Control**
Your screen is a container which holds different elements. When you build a layout, you will place those elements according to different design theories, your project needs, your users, the needed elements to be displayed and so on. Thus, there's a high degree of intentionality. If you leave this to pure luck, all these elements will be randomly scattered and resized with unpredictable results. For example: An *"above the fold"* button may need 2 scrolls after an image is resized to adapt to full width (and proportionally increase height). As you may imagine, this isn't a very good option for anyone
* **Focus**
This is related to the item above. For example, let's say you want your user see a [smiling person right in front of her eyes](http://www.psychologicalscience.org/observer/the-psychological-study-of-smiling#.WEC5RH2S5aQ), and a CTA below that to increase clicks. Works great on mobile, laptops and desktops up to 1200px width. Then you decide to allow full width. Now the smile could be at the middle/bottom of the image and your CTA completely lost. Any simple study will tell you this is extremely wrong, and it's easily measurable
---
**Finally, one thing:** Full width with some amount of control is OK for carefully crafted sites with no dynamically generated content. However, you need to fine tune this in many forms.
You gave the Google example: well, the **header takes the whole width**, but the content takes only `600px width` (the results themselves) with a maximum width of `1250px` if right sidebar is displayed. **See image below:**
[](https://i.stack.imgur.com/rLKaY.jpg) |
102,059 | Because of certain reasons, I'm sometimes tied to an extremely slow internet connection. What I realized with this, is that certain sites (for example, any subdomain of blog.hu) works in a way that needs a certain part of the site be loaded before comments are loaded too. I assume it's because of an AJAX operation, as the comments themselves are not visible within the HTML file.
In contrast, forum engines, such as vBulletin are often free from AJAX, meaning that when a thread's HTML is loaded, every comment in it are "hardcoded", meaning that even if the "fancy parts" (CSS, images and so on) are not loaded, I can already read the comments.
My needs are very special though, so I'm interested - is there any general UX advantage of any of these? | 2016/12/01 | [
"https://ux.stackexchange.com/questions/102059",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/76708/"
] | @JoshDoebbert has a good point on the text legibility. [This other question](https://ux.stackexchange.com/questions/34120/relationship-between-font-size-and-width-of-container) has some interesting information on the topic.
I just wanted to add that percentages are good to let the content adapt to smaller screen size. As you said there is a minimum size and in the same way there is maximum size that lets the content be understood correctly. Whether it is text or images **the screen size in both height and width should be considered to display the content correctly**, and set relevant breakpoints for both parameters.
[](https://i.stack.imgur.com/oTPat.jpg) | * **Content Display**
Think about this: you make a site with content prepared for full width, no max-width. This will work relatively OK for common sizes, but full screen images for big screens will add a massive load OR they will get pixelated. Just choose your poison. And this is easily fixed by... max-width
* **Legibility**
There are many studies about line length. [NN/G says between 45 to 75 characters](https://www.smashingmagazine.com/2014/09/balancing-line-length-font-size-responsive-web-design/), [Baymard proposes 50 to 75 characters](http://baymard.com/blog/line-length-readability), [Viget says around 100 characters](https://www.viget.com/articles/the-line-length-misconception) and so on. For example, this post has around 100 characters width, and it takes 1/3 of my screen. The whole idea of having a 300 characters line makes me dizzy!
* **Control**
Your screen is a container which holds different elements. When you build a layout, you will place those elements according to different design theories, your project needs, your users, the needed elements to be displayed and so on. Thus, there's a high degree of intentionality. If you leave this to pure luck, all these elements will be randomly scattered and resized with unpredictable results. For example: An *"above the fold"* button may need 2 scrolls after an image is resized to adapt to full width (and proportionally increase height). As you may imagine, this isn't a very good option for anyone
* **Focus**
This is related to the item above. For example, let's say you want your user see a [smiling person right in front of her eyes](http://www.psychologicalscience.org/observer/the-psychological-study-of-smiling#.WEC5RH2S5aQ), and a CTA below that to increase clicks. Works great on mobile, laptops and desktops up to 1200px width. Then you decide to allow full width. Now the smile could be at the middle/bottom of the image and your CTA completely lost. Any simple study will tell you this is extremely wrong, and it's easily measurable
---
**Finally, one thing:** Full width with some amount of control is OK for carefully crafted sites with no dynamically generated content. However, you need to fine tune this in many forms.
You gave the Google example: well, the **header takes the whole width**, but the content takes only `600px width` (the results themselves) with a maximum width of `1250px` if right sidebar is displayed. **See image below:**
[](https://i.stack.imgur.com/rLKaY.jpg) |
6,803,762 | Is it possible to get list of translations (from virtual pages into physical pages) from TLB (Translation lookaside buffer, this is a special cache in the CPU). I mean modern x86 or x86\_64; and I want to do it in programmatic way, not by using JTAG and shifting all TLB entries out. | 2011/07/23 | [
"https://Stackoverflow.com/questions/6803762",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/196561/"
] | The linux kernel has no such dumper, there is page from linux kernel about cache and tlb: <https://www.kernel.org/doc/Documentation/cachetlb.txt> "Cache and TLB Flushing Under Linux." David S. Miller
There was an such TLB dump in 80386DX (and 80486, and possibly in "Embedded Pentium" 100-166 MHz / "[Embedded Pentium MMX](http://www.intel.com/content/www/us/en/intelligent-systems/previous-generation/embedded-pentium-mmx.html) 200-233 MHz" in 1998):
* [1](http://books.google.com/books?id=XZzUyvghwnsC&pg=PA579&dq="to+the+80386dx") - Book "MICROPROCESSORS: THE 8086/8088, 80186/80286, 80386/80486 AND THE PENTIUM FAMILY", ISBN 9788120339422, 2010, page 579
This was done via Test Registers TR6 TR7:
* [2](http://books.google.com/books?id=yXriyj4eZ-gC&pg=SA3-PA19&lpg=SA3-PA19&dq="check+translation") - Book "Microprocessors & Microcontrollers" by Godse&Godse, 2008 ISBN 9788184312973 page SA3-PA19: "3.2.7.3 Test Registers" "only two test registers (TR6-TR7) are currently defined. ... These registers are used to check translation lookaside buffer (TLB) of the paging unit."
* [3](http://www.tecchannel.de/server/prozessoren/402224/x86_programmierung_und_betriebsarten_teil_5/index10.html) "x86-Programmierung und -Betriebsarten (Teil 5). Die Testregister TR6 und TR7", deutsche article about registers: "Zur Prüfung des Translation-Lookaside-Buffers sind die zwei Testregister TR6 und TR7 vorhanden. Sie werden als Test-Command-Register (TR6) und Testdatenregister (TR7) bezeichnet. "
* [4](http://datasheets.chipdb.org/Intel/x86/Pentium/Embedded%20Pentium%AE%20Processor/MDELREGS.PDF) Intel's "Embedded Pentium® Processor Family Developer’s Manual", part "26 Model Specific Registers and Functions" page 8 "26.2.1.2 TLB Test Registers"
TR6 is command register, the linear address is written to it. It can be used to write to TLB or to read line from TLB. TR7 is data to be written to TLB or read from TLB.
Wikipedia says in <https://en.wikipedia.org/wiki/Test_register> that reading TR6/TR7 "generate invalid opcode exception on any CPU newer than 80486."
The encoding of mov tr6/tr7 was available only to privilege level 0: <http://www.fermimn.gov.it/linux/quarta/x86/movrs.htm>
```
0F 24 /r movl tr6/tr7,r32 12 Move (test register) to (register)
movl %tr6,%ebx
movl %tr7,%ebx
0F 26 /r movl r32,tr6/tr7 12 Move (register) to (test register)
movl %ebx,%tr6
movl %ebx,%tr7
``` | You can get the list of VA-PA translations stored in TLB but you may have to use a processor emulator like `qemu`. You can download and install qemu from <http://wiki.qemu.org/Main_Page>
You can boot a kernel which is stored in a disk image (typically in qcow2 or raw format) and run your application. You may have to tweak the code in qemu to print the contents of TLB. Look at `tlb_*` functions in `qemu/exec.c` You may want to add a tlb\_dump\_function to print the contents of the TLB. As far as I know, this is the closest you can get to dumping the contents of TLB.
P.S: I started answering this question and then realized it was an year old. |
17,200,445 | I am new to coding and I ran in trouble while trying to make my own fastq masker. The first module is supposed to trim the line with the + away, modify the sequence header (begins with >) to the line number, while keeping the sequence and quality lines (A,G,C,T line and Unicode score, respectively).
```
class Import_file(object):
def trim_fastq (self, fastq_file):
f = open('path_to_file_a', 'a' )
sanger = []
sequence = []
identifier = []
plus = []
f2 = open('path_to_file_b')
for line in f2.readlines():
line = line.strip()
if line[0]=='@':
identifier.append(line)
identifier.replace('@%s','>[i]' %(line))
elif line[0]==('A' or 'G'or 'T' or 'U' or 'C'):
seq = ','.join(line)
sequence.append(seq)
elif line[0]=='+'and line[1]=='' :
plus.append(line)
remove_line = file.writelines()
elif line[0]!='@' or line[0]!=('A' or 'G'or 'T' or 'U' or 'C') or line[0]!='+' and line[1]!='':
sanger.append(line)
else:
print("Danger Will Robinson, Danger!")
f.write("'%s'\n '%s'\n '%s'" %(identifier, sequence, sanger))
f.close()
return (sanger,sequence,identifier,plus)
```
Now for my question. I have ran this and no error appears, however the target file is empty. I am wondering what I am doing wrong... Is it my way to handle the lists or the lack of .join? I am sorry if this is a duplicate. It is simply that I do not know what is the mistake here. Also, important note... This is not some homework, I just need a masker for work... Any help is greatly appreciated and all mentions of improvement to the code are welcomed. Thanks.
Note (fastq format):
```
@SRR566546.970 HWUSI-EAS1673_11067_FC7070M:4:1:2299:1109 length=50
TTGCCTGCCTATCATTTTAGTGCCTGTGAGGTGGAGATGTGAGGATCAGT
+
hhhhhhhhhhghhghhhhhfhhhhhfffffe`ee[`X]b[d[ed`[Y[^Y
```
Edit: Still unable to get anything, but working at it. | 2013/06/19 | [
"https://Stackoverflow.com/questions/17200445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2501764/"
] | used `class="ball"` as id should be unique, *but you get the point, how to create 100 div*
```
$(document).ready(function () {
var $newdiv;
for (var i = 0; i < 100; i++) {
$newdiv = $('<div class="ball" />').text(i);
$('body').append($newdiv);
}
});
```
Demo `--->` <http://jsfiddle.net/Uq2ap/> | **ID is supposed to be unique on your Page**. So use **class instead.**
Next , if you var `$newdiv = $('<div/>'` to create a div outside the for loop , it would only create a single instance of the div as it already is available on the page and cached.
So need to move the creation to inside the `for loop`
```
$(document).ready(function () {
for (var i = 0; i < 100; i++) {
var $newdiv = $('<div/>', {
"class": "ball",
text: 'hi'
});
$('body').append($newdiv);
}
});
```
**[Check Fiddle](http://jsfiddle.net/vTQ85/)** |
34,119 | I am writing unit testcases for a UI Framework using **Mocha**, **Chai** and **Karma**. I have analysed before whether to use selenium webdriver to do testing, but since most of the test cases involve working with DOMElement I have found it difficult to be working with selenium though javascript version( **WebDriverJS** ) is available.
Even when I checked other UI Frameworks like **jquery ui**, **kendo**, **semantic**, **foundation** etc.. they have used javascript frameworks like **jasmine**, **qunit** etc.. for testing rather than selenium.
What could be the reason that UI Framework developers do not prefer Selenium? | 2018/06/07 | [
"https://sqa.stackexchange.com/questions/34119",
"https://sqa.stackexchange.com",
"https://sqa.stackexchange.com/users/28240/"
] | Selenium is more designed for doing end-to-end testing, where it simulates actions within a browser. Jasmine and QUnit are both unit testing frameworks for testing the code. If you're looking to do end-to-end tests that are more compatible with JS, check out Protractor—it's made for AngularJS apps. Otherwise, if you're unit testing, you should avoid Selenium and use one of the unit testing frameworks. | You can use this approach - "**VISUAL REGRESSION TESTING USING JEST, CHROMELESS AND AWS LAMBDA**" <https://novemberfive.co/blog/visual-regression-testing-jest-chromeless-lambda> |
34,119 | I am writing unit testcases for a UI Framework using **Mocha**, **Chai** and **Karma**. I have analysed before whether to use selenium webdriver to do testing, but since most of the test cases involve working with DOMElement I have found it difficult to be working with selenium though javascript version( **WebDriverJS** ) is available.
Even when I checked other UI Frameworks like **jquery ui**, **kendo**, **semantic**, **foundation** etc.. they have used javascript frameworks like **jasmine**, **qunit** etc.. for testing rather than selenium.
What could be the reason that UI Framework developers do not prefer Selenium? | 2018/06/07 | [
"https://sqa.stackexchange.com/questions/34119",
"https://sqa.stackexchange.com",
"https://sqa.stackexchange.com/users/28240/"
] | Selenium is a UI automation library whereas libraries like Jasmine is a general javascript test framework which can be utilized for the unit as well as UI testing automation for the assertions.
If you are purely unit testing, then probably you don't need selenium. | Selenium is more designed for doing end-to-end testing, where it simulates actions within a browser. Jasmine and QUnit are both unit testing frameworks for testing the code. If you're looking to do end-to-end tests that are more compatible with JS, check out Protractor—it's made for AngularJS apps. Otherwise, if you're unit testing, you should avoid Selenium and use one of the unit testing frameworks. |
34,119 | I am writing unit testcases for a UI Framework using **Mocha**, **Chai** and **Karma**. I have analysed before whether to use selenium webdriver to do testing, but since most of the test cases involve working with DOMElement I have found it difficult to be working with selenium though javascript version( **WebDriverJS** ) is available.
Even when I checked other UI Frameworks like **jquery ui**, **kendo**, **semantic**, **foundation** etc.. they have used javascript frameworks like **jasmine**, **qunit** etc.. for testing rather than selenium.
What could be the reason that UI Framework developers do not prefer Selenium? | 2018/06/07 | [
"https://sqa.stackexchange.com/questions/34119",
"https://sqa.stackexchange.com",
"https://sqa.stackexchange.com/users/28240/"
] | **TL;DR**: Selenium is just to slow, compared to for example [Karma](https://karma-runner.github.io/2.0/index.html).
---
I guess most UI Frameworks manipulate the DOM. So verifying that the manipulation was correct is also done in the DOM. Most UI Frameworks seem to use Karma for cross-browser testing the DOM. By running plain JavaScript in the browser and using the plain JavaScript API to get back the results.
Checking all the functionality with Selenium would be slow, hard to maintain and unnecessary as you can test it faster with for example Karma and plain JavaScript.
Jasmine and qUnit are more alternative test runners than tools to verify the DOM. You can also build Selenium or Karma tests with them.
For building UI Frameworks I would expect you need something to run-tests against an actual DOM and check it does what you expect, preferable cross all supported browsers and bloody fast.
UI Frameworks are building blocks for building web-based workflows. Testing the building blocks is relatively easy with the browser JavaScript API. Where testing full workflows is not, here Selenium would be better suited. | Selenium is more designed for doing end-to-end testing, where it simulates actions within a browser. Jasmine and QUnit are both unit testing frameworks for testing the code. If you're looking to do end-to-end tests that are more compatible with JS, check out Protractor—it's made for AngularJS apps. Otherwise, if you're unit testing, you should avoid Selenium and use one of the unit testing frameworks. |
34,119 | I am writing unit testcases for a UI Framework using **Mocha**, **Chai** and **Karma**. I have analysed before whether to use selenium webdriver to do testing, but since most of the test cases involve working with DOMElement I have found it difficult to be working with selenium though javascript version( **WebDriverJS** ) is available.
Even when I checked other UI Frameworks like **jquery ui**, **kendo**, **semantic**, **foundation** etc.. they have used javascript frameworks like **jasmine**, **qunit** etc.. for testing rather than selenium.
What could be the reason that UI Framework developers do not prefer Selenium? | 2018/06/07 | [
"https://sqa.stackexchange.com/questions/34119",
"https://sqa.stackexchange.com",
"https://sqa.stackexchange.com/users/28240/"
] | The reason is quick feedback. unit tests run much faster and selenium/protractor being e2e solutions runs slower. There is a clear separation between unit test and end to end testing.
Please let us know in specific what you need to understand. | You can use this approach - "**VISUAL REGRESSION TESTING USING JEST, CHROMELESS AND AWS LAMBDA**" <https://novemberfive.co/blog/visual-regression-testing-jest-chromeless-lambda> |
34,119 | I am writing unit testcases for a UI Framework using **Mocha**, **Chai** and **Karma**. I have analysed before whether to use selenium webdriver to do testing, but since most of the test cases involve working with DOMElement I have found it difficult to be working with selenium though javascript version( **WebDriverJS** ) is available.
Even when I checked other UI Frameworks like **jquery ui**, **kendo**, **semantic**, **foundation** etc.. they have used javascript frameworks like **jasmine**, **qunit** etc.. for testing rather than selenium.
What could be the reason that UI Framework developers do not prefer Selenium? | 2018/06/07 | [
"https://sqa.stackexchange.com/questions/34119",
"https://sqa.stackexchange.com",
"https://sqa.stackexchange.com/users/28240/"
] | Selenium is a UI automation library whereas libraries like Jasmine is a general javascript test framework which can be utilized for the unit as well as UI testing automation for the assertions.
If you are purely unit testing, then probably you don't need selenium. | You can use this approach - "**VISUAL REGRESSION TESTING USING JEST, CHROMELESS AND AWS LAMBDA**" <https://novemberfive.co/blog/visual-regression-testing-jest-chromeless-lambda> |
34,119 | I am writing unit testcases for a UI Framework using **Mocha**, **Chai** and **Karma**. I have analysed before whether to use selenium webdriver to do testing, but since most of the test cases involve working with DOMElement I have found it difficult to be working with selenium though javascript version( **WebDriverJS** ) is available.
Even when I checked other UI Frameworks like **jquery ui**, **kendo**, **semantic**, **foundation** etc.. they have used javascript frameworks like **jasmine**, **qunit** etc.. for testing rather than selenium.
What could be the reason that UI Framework developers do not prefer Selenium? | 2018/06/07 | [
"https://sqa.stackexchange.com/questions/34119",
"https://sqa.stackexchange.com",
"https://sqa.stackexchange.com/users/28240/"
] | **TL;DR**: Selenium is just to slow, compared to for example [Karma](https://karma-runner.github.io/2.0/index.html).
---
I guess most UI Frameworks manipulate the DOM. So verifying that the manipulation was correct is also done in the DOM. Most UI Frameworks seem to use Karma for cross-browser testing the DOM. By running plain JavaScript in the browser and using the plain JavaScript API to get back the results.
Checking all the functionality with Selenium would be slow, hard to maintain and unnecessary as you can test it faster with for example Karma and plain JavaScript.
Jasmine and qUnit are more alternative test runners than tools to verify the DOM. You can also build Selenium or Karma tests with them.
For building UI Frameworks I would expect you need something to run-tests against an actual DOM and check it does what you expect, preferable cross all supported browsers and bloody fast.
UI Frameworks are building blocks for building web-based workflows. Testing the building blocks is relatively easy with the browser JavaScript API. Where testing full workflows is not, here Selenium would be better suited. | You can use this approach - "**VISUAL REGRESSION TESTING USING JEST, CHROMELESS AND AWS LAMBDA**" <https://novemberfive.co/blog/visual-regression-testing-jest-chromeless-lambda> |
34,119 | I am writing unit testcases for a UI Framework using **Mocha**, **Chai** and **Karma**. I have analysed before whether to use selenium webdriver to do testing, but since most of the test cases involve working with DOMElement I have found it difficult to be working with selenium though javascript version( **WebDriverJS** ) is available.
Even when I checked other UI Frameworks like **jquery ui**, **kendo**, **semantic**, **foundation** etc.. they have used javascript frameworks like **jasmine**, **qunit** etc.. for testing rather than selenium.
What could be the reason that UI Framework developers do not prefer Selenium? | 2018/06/07 | [
"https://sqa.stackexchange.com/questions/34119",
"https://sqa.stackexchange.com",
"https://sqa.stackexchange.com/users/28240/"
] | Selenium is a UI automation library whereas libraries like Jasmine is a general javascript test framework which can be utilized for the unit as well as UI testing automation for the assertions.
If you are purely unit testing, then probably you don't need selenium. | The reason is quick feedback. unit tests run much faster and selenium/protractor being e2e solutions runs slower. There is a clear separation between unit test and end to end testing.
Please let us know in specific what you need to understand. |
34,119 | I am writing unit testcases for a UI Framework using **Mocha**, **Chai** and **Karma**. I have analysed before whether to use selenium webdriver to do testing, but since most of the test cases involve working with DOMElement I have found it difficult to be working with selenium though javascript version( **WebDriverJS** ) is available.
Even when I checked other UI Frameworks like **jquery ui**, **kendo**, **semantic**, **foundation** etc.. they have used javascript frameworks like **jasmine**, **qunit** etc.. for testing rather than selenium.
What could be the reason that UI Framework developers do not prefer Selenium? | 2018/06/07 | [
"https://sqa.stackexchange.com/questions/34119",
"https://sqa.stackexchange.com",
"https://sqa.stackexchange.com/users/28240/"
] | **TL;DR**: Selenium is just to slow, compared to for example [Karma](https://karma-runner.github.io/2.0/index.html).
---
I guess most UI Frameworks manipulate the DOM. So verifying that the manipulation was correct is also done in the DOM. Most UI Frameworks seem to use Karma for cross-browser testing the DOM. By running plain JavaScript in the browser and using the plain JavaScript API to get back the results.
Checking all the functionality with Selenium would be slow, hard to maintain and unnecessary as you can test it faster with for example Karma and plain JavaScript.
Jasmine and qUnit are more alternative test runners than tools to verify the DOM. You can also build Selenium or Karma tests with them.
For building UI Frameworks I would expect you need something to run-tests against an actual DOM and check it does what you expect, preferable cross all supported browsers and bloody fast.
UI Frameworks are building blocks for building web-based workflows. Testing the building blocks is relatively easy with the browser JavaScript API. Where testing full workflows is not, here Selenium would be better suited. | The reason is quick feedback. unit tests run much faster and selenium/protractor being e2e solutions runs slower. There is a clear separation between unit test and end to end testing.
Please let us know in specific what you need to understand. |
34,119 | I am writing unit testcases for a UI Framework using **Mocha**, **Chai** and **Karma**. I have analysed before whether to use selenium webdriver to do testing, but since most of the test cases involve working with DOMElement I have found it difficult to be working with selenium though javascript version( **WebDriverJS** ) is available.
Even when I checked other UI Frameworks like **jquery ui**, **kendo**, **semantic**, **foundation** etc.. they have used javascript frameworks like **jasmine**, **qunit** etc.. for testing rather than selenium.
What could be the reason that UI Framework developers do not prefer Selenium? | 2018/06/07 | [
"https://sqa.stackexchange.com/questions/34119",
"https://sqa.stackexchange.com",
"https://sqa.stackexchange.com/users/28240/"
] | **TL;DR**: Selenium is just to slow, compared to for example [Karma](https://karma-runner.github.io/2.0/index.html).
---
I guess most UI Frameworks manipulate the DOM. So verifying that the manipulation was correct is also done in the DOM. Most UI Frameworks seem to use Karma for cross-browser testing the DOM. By running plain JavaScript in the browser and using the plain JavaScript API to get back the results.
Checking all the functionality with Selenium would be slow, hard to maintain and unnecessary as you can test it faster with for example Karma and plain JavaScript.
Jasmine and qUnit are more alternative test runners than tools to verify the DOM. You can also build Selenium or Karma tests with them.
For building UI Frameworks I would expect you need something to run-tests against an actual DOM and check it does what you expect, preferable cross all supported browsers and bloody fast.
UI Frameworks are building blocks for building web-based workflows. Testing the building blocks is relatively easy with the browser JavaScript API. Where testing full workflows is not, here Selenium would be better suited. | Selenium is a UI automation library whereas libraries like Jasmine is a general javascript test framework which can be utilized for the unit as well as UI testing automation for the assertions.
If you are purely unit testing, then probably you don't need selenium. |
11,736,349 | I`m trying to create a loading windows with faded ( Blured ) background , that lock all the other windows
any issue for fade the background to lock other windows ?! | 2012/07/31 | [
"https://Stackoverflow.com/questions/11736349",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1565157/"
] | Following are the methods from BaseAGIScript class which can be used to play sound files.
* `controlStreamFile` - Plays the sound file, user can interrupt by
pressing any key.
* `getOption` - Plays the given sound file and waits
for user option.
* `getData` - Plays the given sound file and waits for
user enter data. | This should provide the functionality you're looking for: [org.asteriskjava.fastagi.AgiChannel#streamFile](http://www.asterisk-java.org/1.0.0.M3/apidocs/org/asteriskjava/fastagi/AgiChannel.html#streamFile%28java.lang.String%29) |
151,700 | Almost on every tutorial video, I watched about `Thermal Expansion` tesseracts, receiving one can output items to build craft transport pipes (gold or stone). The thing is I use `Thermal Expansion 3.0.0.2` mod which has only one type of tesseracts (Not energy, fluid and item like was earlier. Now it's three in one.). And the problem is that receiving tesseract does not output items to transport pipes. It can easily interact with any kind of chests attached directly to it (even with `Applied Energistics chests`), but not with the pipes. What am I doing wrong or how to fix this? The following configuration does not work:
**Sending tesseract:**

**Receiving tesseract:**

But if I put chest directly to the receiving tesseract items are transported properly. The next configuration works fine:


I use **Minecraft 1.6.4**, **Thermal Expansion 3.0.0.2** and **Build Craft 4.2.2**. Client and server are combined by myself and all mods are installed on vanilla minecraft. No additional modpacks were used. Here is **[full list](https://docs.google.com/spreadsheet/ccc?key=0AsJGELm4ir_edGd4RE9GcEZvdEhSVFBLYTVQemEwWXc&usp=sharing#gid=1)** of mods I installed.
**EDIT:**
I started new client only with 3 mods from **[this list](https://docs.google.com/spreadsheet/ccc?key=0AsJGELm4ir_edGd4RE9GcEZvdEhSVFBLYTVQemEwWXc&usp=sharing#gid=1)**: **BuildCraft**, **Thermal Expansion** and **NEI** and nothing changed. Receiving tesseract still doesn't pump out item to the pipes. | 2014/01/21 | [
"https://gaming.stackexchange.com/questions/151700",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/52979/"
] | I think that they are not compatible with buildcrafts pipes yet, you need to use a fluiduct(you're free to use a pipe after that i think). | Have you tried without using a wooden transport pipe (connecting your gold / stone transport pipes directly to the tesseract)? I ask because certain machines do not require a wooden transport pipe to pull items out, they push to pipes themselves, and a wooden transport pipe would actually hinder their ability to do so. |
71,467,087 | I'm following this tutorial: <https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-web-app-sign-user-overview?tabs=aspnetcore>
According to other docs, I can use the 'state' parameter to pass in custom data and this will be returned back to the app once the user is logged in
However, OIDC also uses this state param to add its own encoded data to prevent xsite hacking - I cant seem to find the correct place in the middleware to hook into this and add my custom data
There's a similar discussion on this thread: [Custom parameter with Microsoft.Owin.Security.OpenIdConnect and AzureAD v 2.0 endpoint](https://stackoverflow.com/questions/37489964/custom-parameter-with-microsoft-owin-security-openidconnect-and-azuread-v-2-0-en/37520329#37520329) but I'm using AddMicrosoftIdentityWebApp whereas they're using UseOpenIdConnectAuthentication and I don't know how to hook into the right place in the middleware to add my custom data then retrieve it when on the return.
I'd like to be able to do something like in the code below - when I set break points state is null outgoing and incoming, however the querystring that redirects the user to Azure has a state param that is filled in by the middleware, but if i do it like this, then I get an infinite redirect loop
```
public static class ServicesExtensions
{
public static void AddMicrosoftIdentityPlatformAuthentication(this IServiceCollection services, IConfigurationSection azureAdConfig)
{
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApp(options =>
{
options.ClientId = azureAdConfig["ClientId"];
options.Domain = azureAdConfig["Domain"];
options.Instance = azureAdConfig["Instance"];
options.CallbackPath = azureAdConfig["CallbackPath"];
options.SignUpSignInPolicyId = azureAdConfig["SignUpSignInPolicyId"];
options.Events.OnRedirectToIdentityProvider = context =>
{
//todo- ideally we want to be able to add a returnurl to the state parameter and read it back
//however the state param is maintained auto and used to prevent xsite attacks so we can just add our info
//as we get an infinite loop back to az b2 - see https://blogs.aaddevsup.xyz/2019/11/state-parameter-in-mvc-application/
//save the url of the page that prompted the login request
//var queryString = context.HttpContext.Request.QueryString.HasValue
// ? context.HttpContext.Request.QueryString.Value
// : string.Empty;
//if (queryString == null) return Task.CompletedTask;
//var queryStringParameters = HttpUtility.ParseQueryString(queryString);
//context.ProtocolMessage.State = queryStringParameters["returnUrl"]?.Replace("~", "");
return Task.CompletedTask;
};
options.Events.OnMessageReceived = context =>
{
//todo read returnurl from state
//redirect to the stored url returned
//var returnUrl = context.ProtocolMessage.State;
//context.HandleResponse();
//context.Response.Redirect(returnUrl);
return Task.CompletedTask;
};
options.Events.OnSignedOutCallbackRedirect = context =>
{
context.HttpContext.Response.Redirect(context.Options.SignedOutRedirectUri);
context.HandleResponse();
return Task.CompletedTask;
};
});
}
}
``` | 2022/03/14 | [
"https://Stackoverflow.com/questions/71467087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5003392/"
] | ```
# The following code should work:
df.NACE_code = df.NACE_code.astype(str)
df.NACE_code = df.NACE_code.str.replace('.', '')
``` | Use `astype('str')` to convert columns to string type before calling `str.replace.`
Without regex:
```
df['NACE_code'].astype('str').str.replace(r".", r"", regex=False)
``` |
59,309,998 | I have a script that runs every 15 seconds and it creates a new thread every time. Now and then this thread gets stuck and blockes the synchronisation process of my program. Now i want to kill the process with a specific name if the thread is stuck for 20 loops. Here is my code:
```
public void actionPerformed(ActionEvent e) {
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("dd-MM-yyyy HH:mm:ss");
System.out.println(ft.format(dNow));
ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
int noThreads = currentGroup.activeCount();
Thread[] lstThreads = new Thread[noThreads];
currentGroup.enumerate(lstThreads);
boolean loopthreadfound = false;
for (int i = 0; i < noThreads; i++){
try{
if (lstThreads[i].getName() == "loopthread"){loopthreadfound = true;}
}catch(Exception e1){System.out.println(e1);}
}
if (loopthreadfound == false){
loopthreadcounter = 0;
//Starten in nieuwe thread
Thread loopthread = new Thread() {
public void run() {
try {
checkonoffline();
checkDBupdates();
} catch (JSONException | SQLException | IOException e1) {
System.out.println(e1);
}
}
};
loopthread.setName("loopthread");
loopthread.start();
}else{
loopthreadcounter++;
System.out.println("Loopthread already running... counter: " + loopthreadcounter);
if (loopthreadcounter > 20){
// HERE I WANT TO KILL THE THREAD "loopthread "
}
}
}
``` | 2019/12/12 | [
"https://Stackoverflow.com/questions/59309998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12526527/"
] | Ok, after a bit of work I believe I have a solution.
As part of my CI (Continuous Integration) job I run:
```
cdk synth
```
I then save the contents of the cdk.out folder to a repository (I'm using Octopus Deployment).
As part of my CD (Continuous Deployment) job I have the following (Powershell):
```
$Env:AWS_ACCESS_KEY_ID={your key}
$Env:AWS_SECRET_ACCESS_KEY={your secret}
$Env:AWS_DEFAULT_REGION={your region}
$cdk=[Environment]::GetFolderPath([Environment+SpecialFolder]::ApplicationData) + "\npm\cdk.cmd"
& $cdk --app . deploy {your stack name} --require-approval never
```
So the "cdk synth" will generate the template and assets required for deployment.
The "cdk --app . depoy {your stack name} --require-approval never" is telling aws-cdk to us the existing templates and assets. This avoids a situation where the CD process may produce a different setup than the CI process. The "." indicates that the templates & assets are in the current folder.
You will need to install node & aws-cdk on the CD server (in my case an Octopus Deploy tentacle);
Node install is easy, just log in and install.
To add aws-cdk perform the following (using an administrator powershell):
```
npm prefix -g // Make note of the path
npm config set prefix C:\Windows\System32\config\systemprofile\AppData\Roaming\npm
npm install -g aws-cdk
npm config set prefix {original path}
```
Note that the npm path maybe different for your usage - will depend on the user account used for the CD process and Windows version. | One option is to generate a CloudFormation ChangeSet using CDK and then deploy that ChangeSet later. To create the ChangeSet run `cdk deploy <StackName> --execute false`. This will synthesize the stack as well as upload templates and assets to S3. The ChangeSet can then be executed at anytime without CDK. |
59,309,998 | I have a script that runs every 15 seconds and it creates a new thread every time. Now and then this thread gets stuck and blockes the synchronisation process of my program. Now i want to kill the process with a specific name if the thread is stuck for 20 loops. Here is my code:
```
public void actionPerformed(ActionEvent e) {
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("dd-MM-yyyy HH:mm:ss");
System.out.println(ft.format(dNow));
ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
int noThreads = currentGroup.activeCount();
Thread[] lstThreads = new Thread[noThreads];
currentGroup.enumerate(lstThreads);
boolean loopthreadfound = false;
for (int i = 0; i < noThreads; i++){
try{
if (lstThreads[i].getName() == "loopthread"){loopthreadfound = true;}
}catch(Exception e1){System.out.println(e1);}
}
if (loopthreadfound == false){
loopthreadcounter = 0;
//Starten in nieuwe thread
Thread loopthread = new Thread() {
public void run() {
try {
checkonoffline();
checkDBupdates();
} catch (JSONException | SQLException | IOException e1) {
System.out.println(e1);
}
}
};
loopthread.setName("loopthread");
loopthread.start();
}else{
loopthreadcounter++;
System.out.println("Loopthread already running... counter: " + loopthreadcounter);
if (loopthreadcounter > 20){
// HERE I WANT TO KILL THE THREAD "loopthread "
}
}
}
``` | 2019/12/12 | [
"https://Stackoverflow.com/questions/59309998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12526527/"
] | Ok, after a bit of work I believe I have a solution.
As part of my CI (Continuous Integration) job I run:
```
cdk synth
```
I then save the contents of the cdk.out folder to a repository (I'm using Octopus Deployment).
As part of my CD (Continuous Deployment) job I have the following (Powershell):
```
$Env:AWS_ACCESS_KEY_ID={your key}
$Env:AWS_SECRET_ACCESS_KEY={your secret}
$Env:AWS_DEFAULT_REGION={your region}
$cdk=[Environment]::GetFolderPath([Environment+SpecialFolder]::ApplicationData) + "\npm\cdk.cmd"
& $cdk --app . deploy {your stack name} --require-approval never
```
So the "cdk synth" will generate the template and assets required for deployment.
The "cdk --app . depoy {your stack name} --require-approval never" is telling aws-cdk to us the existing templates and assets. This avoids a situation where the CD process may produce a different setup than the CI process. The "." indicates that the templates & assets are in the current folder.
You will need to install node & aws-cdk on the CD server (in my case an Octopus Deploy tentacle);
Node install is easy, just log in and install.
To add aws-cdk perform the following (using an administrator powershell):
```
npm prefix -g // Make note of the path
npm config set prefix C:\Windows\System32\config\systemprofile\AppData\Roaming\npm
npm install -g aws-cdk
npm config set prefix {original path}
```
Note that the npm path maybe different for your usage - will depend on the user account used for the CD process and Windows version. | >
> For this you execute cdk like cdk --app cdk.out deploy and it uses the already created cloud assembly in the specified folder instead of running synth.
>
>
>
<https://github.com/aws/aws-cdk/issues/18790> |
59,309,998 | I have a script that runs every 15 seconds and it creates a new thread every time. Now and then this thread gets stuck and blockes the synchronisation process of my program. Now i want to kill the process with a specific name if the thread is stuck for 20 loops. Here is my code:
```
public void actionPerformed(ActionEvent e) {
Date dNow = new Date( );
SimpleDateFormat ft = new SimpleDateFormat ("dd-MM-yyyy HH:mm:ss");
System.out.println(ft.format(dNow));
ThreadGroup currentGroup = Thread.currentThread().getThreadGroup();
int noThreads = currentGroup.activeCount();
Thread[] lstThreads = new Thread[noThreads];
currentGroup.enumerate(lstThreads);
boolean loopthreadfound = false;
for (int i = 0; i < noThreads; i++){
try{
if (lstThreads[i].getName() == "loopthread"){loopthreadfound = true;}
}catch(Exception e1){System.out.println(e1);}
}
if (loopthreadfound == false){
loopthreadcounter = 0;
//Starten in nieuwe thread
Thread loopthread = new Thread() {
public void run() {
try {
checkonoffline();
checkDBupdates();
} catch (JSONException | SQLException | IOException e1) {
System.out.println(e1);
}
}
};
loopthread.setName("loopthread");
loopthread.start();
}else{
loopthreadcounter++;
System.out.println("Loopthread already running... counter: " + loopthreadcounter);
if (loopthreadcounter > 20){
// HERE I WANT TO KILL THE THREAD "loopthread "
}
}
}
``` | 2019/12/12 | [
"https://Stackoverflow.com/questions/59309998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12526527/"
] | One option is to generate a CloudFormation ChangeSet using CDK and then deploy that ChangeSet later. To create the ChangeSet run `cdk deploy <StackName> --execute false`. This will synthesize the stack as well as upload templates and assets to S3. The ChangeSet can then be executed at anytime without CDK. | >
> For this you execute cdk like cdk --app cdk.out deploy and it uses the already created cloud assembly in the specified folder instead of running synth.
>
>
>
<https://github.com/aws/aws-cdk/issues/18790> |
29,079 | What is correct format for using XPath?
Does XPath vary with the browser?
```
drchrome.findElement(By.xpath("//a[contains(.,'Google')]")).click();
``` | 2017/08/16 | [
"https://sqa.stackexchange.com/questions/29079",
"https://sqa.stackexchange.com",
"https://sqa.stackexchange.com/users/27487/"
] | As far as i know xpath doesn't depends on any browser. Make sure you have created correct xpath it will work.
Second : It's depend on your tag which attribute it has and how efficient you are in xpath.
For example this is the simple hyperlink:
```
<a href="https://stackexchange.com/questions?tab=hot" name="hotnetwork" class="js-gps-track">Hot Network Questions</a>
```
So here i can create the xpath to locate the same in different ways like :
```
//a[@name='hotnetwork']
```
OR
```
//a[@class='js-gps-track']
```
OR combine both attribute for uniqueness like :
```
//a[@name='hotnetwork'][@class='js-gps-track']
```
OR if you want to access the link using its text then you can use `contains()` method
```
//a[contains(text(),'Hot Network')]
```
Note : It will locate the element based on match found with your given string (Hot Network)
If you require to locate an element if self or its child tag contains some text then using dot `.` in contains method as you are using :
```
//a[contains(.,'Hot Network')]
```
OR you can use `text()` method like :
```
//a[text()=' Hot Network Questions']
```
While using `text()` method you have to pass the full link text including spaces else it won't work. | When you want to locate Hyperlink Element try **linkText** element Locator or **Partial LinkText**.
Example using linktext:
```
driver.findElement(By.linkText("click here")).click();
```
Example using partial linktext:
```
driver.findElement(By.partialLinkText("here")).click();
``` |
29,079 | What is correct format for using XPath?
Does XPath vary with the browser?
```
drchrome.findElement(By.xpath("//a[contains(.,'Google')]")).click();
``` | 2017/08/16 | [
"https://sqa.stackexchange.com/questions/29079",
"https://sqa.stackexchange.com",
"https://sqa.stackexchange.com/users/27487/"
] | Whenever you are trying to locate Hyperlink Element & you have `'/a'` attribute, just forget about the XPath method and try using **linkText** element Locator.
```
<html>
<head>
<title>My Page</title>
<body>
<a href="http://www.google.com">Google</a>
<body>
</html>
```
In this situation use:
```
driver.findElement(By.linkText("Google")).click();
``` | When you want to locate Hyperlink Element try **linkText** element Locator or **Partial LinkText**.
Example using linktext:
```
driver.findElement(By.linkText("click here")).click();
```
Example using partial linktext:
```
driver.findElement(By.partialLinkText("here")).click();
``` |
6,089,673 | i'm new in the iphone and json world . i have this json structure . You can see it clearly by putting it here <http://jsonviewer.stack.hu/> .
```
{"@uri":"http://localhost:8080/RESTful/resources/prom/","promotion":[{"@uri":"http://localhost:8080/RESTful/resources/prom/1/","descrip":"description
here","keyid":"1","name":"The first
name bla bla
","url":"http://localhost/10.png"},{"@uri":"http://localhost:8080/RESTful/resources/promo/2/","descrip":"description
here","keyid":"2","name":"hello","url":"http://localhost/11.png"}]}
```
i want to parse it with json-framework . I tried this
```
NSDictionary *json = [myJSON JSONValue];
NSDictionary *promotionDic = [json objectForKey:@"promotion"];
NSLog(@" res %@ : ",[promotionDic objectAtIndex:0]);
```
But then how to do to get for exemple , the name of the object at index 0 ? I think i should put object in an NSArray ? but i dont find how :/ and i dont the number of object is variable . Help please . | 2011/05/22 | [
"https://Stackoverflow.com/questions/6089673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/761812/"
] | First off, You need this line after you load the JSON
```
NSLog(@" json %@ : ",[json description]);
```
That will tell you what you have.
Secondly, you can't call objectAtIndex: on a dictionary. If it works, its because promotionDict is really an NSArray. (The NSLog will tell you). In Objective - C you can assign to any kind of pointer, which is confusing to new developers, but is part of the language, and really is a feature.
With an NSArray you can ask for the number of things in it, [myArray count], etc. You need to command double click in XCode to open up the docs for NSDictionary, etc. | The JSON says:
```
..."promotion":[{"@u...
```
That "`[`" there means that "promotion" is keyed to an array, not a dictionary.
So really your code should be:
```
NSDictionary *json = [myJSON JSONValue];
NSArray *promotions = [json objectForKey:@"promotion"];
NSLog(@"res: %@",[promotions objectAtIndex:0]);
``` |
63,063,279 | I have this code, which is slightly different than the some of the other code with the same question on this site:
```
public void printAllRootToLeafPaths(Node node,ArrayList path) {
if(node==null){
return;
}
path.add(node.data);
if(node.left==null && node.right==null)
{
System.out.println(path);
return;
}
else {
printAllRootToLeafPaths(node.left, new ArrayList(path));
printAllRootToLeafPaths(node.right,new ArrayList(path));
}
}
```
Can someone explain WHY best case is O(nlogn)?
Worst case, the tree breaks down to a linked list and the array is copied 1+2+3+...+n-1+n times which is equivalent to n^2 so the time complexity is O(n^2).
Best case array is being copied along every node in the path. So copying it looks like 1+2+3+...+logn. N/2 times. So why isn't the summation (logn)^2 if 1+2+3+...+n-1+n is n^2? Making the best case O(n(logn)^2)? | 2020/07/23 | [
"https://Stackoverflow.com/questions/63063279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13985180/"
] | Yes, all that copying needs to be accounted for.
Those copies are not necessary; it's easy to write functions which either:
* use a (singly) linked list instead of ArrayList, or
* use a single ArrayList, overwriting previous paths when they're not needed any more.
With non-copying algorithms, the cost of the algorithm is the cost of printing the paths, which is the sum of the lengths of all paths from the root to a leaf. Copy the array on every call, makes the cost become the sum of the paths from the root to every *node*, rather than every leaf. (The fact that the array is copied twice is really not relevant to complexity analysis; it just means multiplying by a constant factor, which can be ignored.)
With the non-copying algorithm, the best case is a linear tree, with only one child per node. Then there is just one leaf with a path length of *N*, so the total cost is O(*N*). But that's a worst-case input if you're copying at every node; the node path lengths are successive integers, and the sum of node path lengths is quadratic.
For your algorithm, the best case is a perfectly-balanced fully-occupied tree. In a fully-occupied tree, there is one more leaf than non-leaf nodes; in other words, approximately half the nodes are leaves. In a perfectly-balanced tree, every node can be reached from the root in a maximum of log *N* steps. So the sum of path lengths to every node is O(*N* log *N*). (Some nodes are closer, but for computing big O we can ignore that fact. Even if we were to take it into account, though, we'd find that it doesn't change the asymptotic behaviour because the number of nodes at each depth level doubles for each successive level.) Because half the nodes are leaves, the cost of this input is O(*N* log *N*) with the non-copying algorithm as well.
Both algorithms exhibit worst-case quadratic complexity. We've already seen the worst-case input for the copying algorithm: a linear tree with just one leaf. For the non-copying algorithm, we use something very similar: a tree consisting of a left-linked backbone, where every right link is a leaf:
```
root
/\
/ \
/\ 7
/ \
/\ 6
/ \
/\ 5
/ \
/\ 4
/ \
/\ 3
/ \
1 2
```
Since that tree is fully-occupied, half its nodes are leaves, and they are at successively increasing distances, so that is again quadratic (although the constant multiplier is smaller.) | I think you're missing the time complexity of copying the entire array to a new one.
---
At root node: `one element is added, but 2 new arrays are created`.
At left child node of root node: `one element is added, but 2 new arrays are created with 2 elements`.
.
.
.
At last but one level: `one element is added, but 2 new arrays are created of size log n to base 2.`
At last level: one element is added, and the log n elements are printed.
---
So at each node there is one operation of adding an element to the list and one operation of either printing or duplicating a list of size (log h) - where h is the height of the node in the tree.
Since we are traversing through all the elements only once, total number of operations are: `n additions + Sum (log h1 + log h2 + log h3 + .... log hn)`
Where h1, h2, h3...hn are heights of each node.
Which is approximately `n + O(n log n)` `~` `O(n log n)`. |
43,721,320 | The following code loops when the page loads and I can't figure out why it is doing so. Is the issue with the onfocus?
```
alert("JS is working");
function validateFirstName() {
alert("validateFirstName was called");
var x = document.forms["info"]["fname"].value;
if (x == "") {
alert("First name must be filled out");
//return false;
}
}
function validateLastName()
{
alert("validateLastName was called");
var y = document.forms["info"]["lname"].value;
if (y == "") {
alert("Last name must be filled out");
//return false;
}
}
var fn = document.getElementById("fn");
var ln = document.getElementById("ln");
fn.onfocus = validateFirstName();
alert("in between");
ln.onfocus = validateLastName();
``` | 2017/05/01 | [
"https://Stackoverflow.com/questions/43721320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7569925/"
] | There were several issues with the approach you were taking to accomplish this, but the "looping" behavior you were experiencing is because you are using a combination of `alert` and `onFocus`. When you are focused on an input field and an alert is triggered, when you dismiss the alert, the browser will (by default) re-focus the element that previously had focus. So in your case, you would focus, get an alert, it would re-focus automatically, so it would re-trigger the alert, etc. Over and over.
**A better way to do this is using the `input` event**. That way, the user will not get prompted with an error message before they even have a chance to fill out the field. They will only be prompted if they clear out a value in a field, or if you call the `validateRequiredField` function sometime later in the code (on the form submission, for example).
I also changed around your validation function so you don't have to create a validation function for every single input on your form that does the exact same thing except spit out a slightly different message. You should also abstract the functionality that defines *what* to do on each error outside of the validation function - this is for testability and reusability purposes.
Let me know if you have any questions.
```js
function validateRequiredField(fieldLabel, value) {
var errors = "";
if (value === "") {
//alert(fieldLabel + " must be filled out");
errors += fieldLabel + " must be filled out\n";
}
return errors;
}
var fn = document.getElementById("fn");
var ln = document.getElementById("ln");
fn.addEventListener("input", function (event) {
var val = event.target.value;
var errors = validateRequiredField("First Name", val);
if (errors !== "") {
alert(errors);
}
else {
// proceed
}
});
ln.addEventListener("input", function (event) {
var val = event.target.value;
var errors = validateRequiredField("Last Name", val);
if (errors !== "") {
alert(errors);
}
else {
// proceed
}
});
```
```html
<form name="myForm">
<label>First Name: <input id="fn" /></label><br/><br/>
<label>Last Name: <input id="ln"/></label>
</form>
``` | Not tested but you can try this
```
fn.addEventListener('focus', validateFirstName);
ln.addEventListener('focus', validateLastName);
``` |
52,267,256 | I have a Pandas dataframe, `old`, like this:
```
col1 col2 col3
0 1 2 3
1 2 3 4
2 3 4 5
```
I want to make a new dataframe, `new`, that copies `col2` from `old` and fills in `-1` as dummy values for its other columns:
```
col2 new_col1 new_col3
0 2 -1 -1
1 3 -1 -1
2 4 -1 -1
```
I suppose I could do iterate row by row and fill in `-1` for any column not in `old` but figure there must be a better, likely vectorized way.
Ideas?
Thanks! | 2018/09/11 | [
"https://Stackoverflow.com/questions/52267256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1316501/"
] | You can do `reindex` .
```
df.reindex(columns=['col2','newcol1','newcol3'],fill_value=-1)
Out[183]:
col2 newcol1 newcol3
0 2 -1 -1
1 3 -1 -1
2 4 -1 -1
``` | IIUC:
```
new = old.copy()
new[['col1','col3']] = -1
>>> new
col1 col2 col3
0 -1 2 -1
1 -1 3 -1
2 -1 4 -1
```
Or more generally, to change all columns besides `col2` to `-1`:
```
new = old.copy()
new[list(set(new.columns) - {'col2'})] = -1
``` |
52,267,256 | I have a Pandas dataframe, `old`, like this:
```
col1 col2 col3
0 1 2 3
1 2 3 4
2 3 4 5
```
I want to make a new dataframe, `new`, that copies `col2` from `old` and fills in `-1` as dummy values for its other columns:
```
col2 new_col1 new_col3
0 2 -1 -1
1 3 -1 -1
2 4 -1 -1
```
I suppose I could do iterate row by row and fill in `-1` for any column not in `old` but figure there must be a better, likely vectorized way.
Ideas?
Thanks! | 2018/09/11 | [
"https://Stackoverflow.com/questions/52267256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1316501/"
] | You can do `reindex` .
```
df.reindex(columns=['col2','newcol1','newcol3'],fill_value=-1)
Out[183]:
col2 newcol1 newcol3
0 2 -1 -1
1 3 -1 -1
2 4 -1 -1
``` | Maybe:
```
new=pd.DataFrame({'col2':old['col2'],'new_col2':-1,'new_col3':-1})
print(new)
```
Output:
```
col2 new_col2 new_col3
0 2 -1 -1
1 3 -1 -1
2 4 -1 -1
```
@sacul Thanks for telling me |
52,267,256 | I have a Pandas dataframe, `old`, like this:
```
col1 col2 col3
0 1 2 3
1 2 3 4
2 3 4 5
```
I want to make a new dataframe, `new`, that copies `col2` from `old` and fills in `-1` as dummy values for its other columns:
```
col2 new_col1 new_col3
0 2 -1 -1
1 3 -1 -1
2 4 -1 -1
```
I suppose I could do iterate row by row and fill in `-1` for any column not in `old` but figure there must be a better, likely vectorized way.
Ideas?
Thanks! | 2018/09/11 | [
"https://Stackoverflow.com/questions/52267256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1316501/"
] | ### `assign`
```
df[['col2']].assign(new_col1=-1, new_col3=-1)
``` | IIUC:
```
new = old.copy()
new[['col1','col3']] = -1
>>> new
col1 col2 col3
0 -1 2 -1
1 -1 3 -1
2 -1 4 -1
```
Or more generally, to change all columns besides `col2` to `-1`:
```
new = old.copy()
new[list(set(new.columns) - {'col2'})] = -1
``` |
52,267,256 | I have a Pandas dataframe, `old`, like this:
```
col1 col2 col3
0 1 2 3
1 2 3 4
2 3 4 5
```
I want to make a new dataframe, `new`, that copies `col2` from `old` and fills in `-1` as dummy values for its other columns:
```
col2 new_col1 new_col3
0 2 -1 -1
1 3 -1 -1
2 4 -1 -1
```
I suppose I could do iterate row by row and fill in `-1` for any column not in `old` but figure there must be a better, likely vectorized way.
Ideas?
Thanks! | 2018/09/11 | [
"https://Stackoverflow.com/questions/52267256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1316501/"
] | ### `assign`
```
df[['col2']].assign(new_col1=-1, new_col3=-1)
``` | Maybe:
```
new=pd.DataFrame({'col2':old['col2'],'new_col2':-1,'new_col3':-1})
print(new)
```
Output:
```
col2 new_col2 new_col3
0 2 -1 -1
1 3 -1 -1
2 4 -1 -1
```
@sacul Thanks for telling me |
13,142,384 | probably had these questions a thousand times already.
For a school project I want to make a HTML5 game where you can challenge someone and play against. Now I'm pretty new to game development. I don't now exactly where to start off. There is so much information/technologies on the net that I don't know which to use. I prefer to do this in a known environment (.NET)
I found these:
* <http://kaazing.com/>
* <http://xsockets.net/>
I also checked out Node.js, socket.io, HTML5 canvas, etc
It's all a bit of overwhelming for me. :( | 2012/10/30 | [
"https://Stackoverflow.com/questions/13142384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1785932/"
] | Since you're working in a .NET environment, take a look at SignalR, <http://signalr.net>. It's a very nice API around websockets (with fallbacks to other methods for older servers and browsers) that lets you do client-to-server and server-to-client communication.
Code on the client can invoke a Javascript function that will in turn invoke a method on the server. That server method could then send a message down to one or all of the connected clients. Alnitak's answer is correct; your communication would be from client to server to client, not directly client to client. | You will need a central server to relay messages between the two players.
WebSockets (and anything else you might find that plugs into a browser) are unsuitable for direct peer-to-peer communications. |
22,127,174 | Hello my software should print the abc but unfortunately it does not work I think the problem is related to the line 19 so if someone could tell me why this is happening I appreciate it
My code-
```
#include <stdio.h>
#include <string.h>
#define NUM_ABC_LET 27
void ABC(char abc[NUM_ABC_LET]);
int main()
{
char abcString[NUM_ABC_LET] = "";
ABC(abcString);
puts(abcString);
}
void ABC(char abc[NUM_ABC_LET])
{
char letter;
for (letter = 'a'; letter <= 'z'; letter++)
{
strcat(abc, letter);
}
}
``` | 2014/03/02 | [
"https://Stackoverflow.com/questions/22127174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3318856/"
] | That's because you're just writing to a copy of the string you're passing to the function. Try this:
```
void ABC(char *abc)
{
int n=0;
char letter;
for (letter = 'a'; letter <= 'z'; ++letter, ++n)
{
abc[n] = letter;
}
abc[n] = '\0';
}
```
This way, you don't write to a copy of your string, you actually write to the string itself. | The second parameter of [srtcat](http://www.cplusplus.com/reference/cstring/strcat/) should be a `char *`.
```
void ABC(char abc[NUM_ABC_LET])
{
char letter[2]="a";
for (; *letter <= 'z'; (*letter)++)
{
strcat(abc, letter);
}
}
``` |
22,127,174 | Hello my software should print the abc but unfortunately it does not work I think the problem is related to the line 19 so if someone could tell me why this is happening I appreciate it
My code-
```
#include <stdio.h>
#include <string.h>
#define NUM_ABC_LET 27
void ABC(char abc[NUM_ABC_LET]);
int main()
{
char abcString[NUM_ABC_LET] = "";
ABC(abcString);
puts(abcString);
}
void ABC(char abc[NUM_ABC_LET])
{
char letter;
for (letter = 'a'; letter <= 'z'; letter++)
{
strcat(abc, letter);
}
}
``` | 2014/03/02 | [
"https://Stackoverflow.com/questions/22127174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3318856/"
] | If you enable warnings in your compiler (e.g. `gcc -Wall -Wextra -Werror`) it will tell you the problem straight away: you are using strcat in a nonsensical way. | The second parameter of [srtcat](http://www.cplusplus.com/reference/cstring/strcat/) should be a `char *`.
```
void ABC(char abc[NUM_ABC_LET])
{
char letter[2]="a";
for (; *letter <= 'z'; (*letter)++)
{
strcat(abc, letter);
}
}
``` |
22,127,174 | Hello my software should print the abc but unfortunately it does not work I think the problem is related to the line 19 so if someone could tell me why this is happening I appreciate it
My code-
```
#include <stdio.h>
#include <string.h>
#define NUM_ABC_LET 27
void ABC(char abc[NUM_ABC_LET]);
int main()
{
char abcString[NUM_ABC_LET] = "";
ABC(abcString);
puts(abcString);
}
void ABC(char abc[NUM_ABC_LET])
{
char letter;
for (letter = 'a'; letter <= 'z'; letter++)
{
strcat(abc, letter);
}
}
``` | 2014/03/02 | [
"https://Stackoverflow.com/questions/22127174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3318856/"
] | The problem is that the function `stdcat()` expects a null terminated string as second argument.
```
#include <stdio.h>
#include <string.h>
#define NUM_ABC_LET 27
void ABC(char abc[NUM_ABC_LET]);
int main()
{
char abcString[NUM_ABC_LET] = "";
ABC(abcString);
puts(abcString);
}
void ABC(char abc[NUM_ABC_LET])
{
char letterStr[2];
strcpy(letterStr, "x");
for (char letter = 'a'; letter <= 'z'; letter++) {
letterStr[0] = letter;
strcat(abc, letterStr);
}
}
```
Much simpler is this solution:
```
#include <stdio.h>
#include <string.h>
#define NUM_ABC_LET 27
void ABC(char abc[NUM_ABC_LET]);
int main()
{
char abcString[NUM_ABC_LET];
ABC(abcString);
puts(abcString);
}
void ABC(char abc[NUM_ABC_LET])
{
for (int i = 0; i < 26; ++i) {
abc[i] = 'a'+i;
}
// Add the terminating null character.
abc[NUM_ABC_LET-1] = '\0';
}
``` | The second parameter of [srtcat](http://www.cplusplus.com/reference/cstring/strcat/) should be a `char *`.
```
void ABC(char abc[NUM_ABC_LET])
{
char letter[2]="a";
for (; *letter <= 'z'; (*letter)++)
{
strcat(abc, letter);
}
}
``` |
6,226,081 | >
> **Possible Duplicate:**
>
> [Pyramid of asterisks program in Python](https://stackoverflow.com/questions/4911341/pyramid-of-asterisks-program-in-python)
>
>
>
I've written a program in C++ that displays a pyramid of asterisk (see below) and now I'd like to see how it's done in Python but it's not as easy as I'd thought it would be. :) Has anyone tried this and if so could you show me code that would help out? 2) Within those lines the number of "\*" will appear as an ODD number
(1 ,3 ,5 ,7 ,9 )
this is the output
```
* 1
*** 3
***** 5
``` | 2011/06/03 | [
"https://Stackoverflow.com/questions/6226081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/782550/"
] | Disclaimer: This may not work in Python 3.x:
```
Python 2.7.1 (r271:86832, May 27 2011, 21:41:45)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print ''' * 1
... *** 3
... ***** 5'''
* 1
*** 3
***** 5
``` | It's not that difficult..
```
>>> lower = 1
>>> higher = 19
>>> for i in xrange(lower,higher,2):
... print ' ' * [Calculation Here] + '*' * i
...
*
***
*****
*******
*********
***********
*************
***************
*****************
``` |
6,226,081 | >
> **Possible Duplicate:**
>
> [Pyramid of asterisks program in Python](https://stackoverflow.com/questions/4911341/pyramid-of-asterisks-program-in-python)
>
>
>
I've written a program in C++ that displays a pyramid of asterisk (see below) and now I'd like to see how it's done in Python but it's not as easy as I'd thought it would be. :) Has anyone tried this and if so could you show me code that would help out? 2) Within those lines the number of "\*" will appear as an ODD number
(1 ,3 ,5 ,7 ,9 )
this is the output
```
* 1
*** 3
***** 5
``` | 2011/06/03 | [
"https://Stackoverflow.com/questions/6226081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/782550/"
] | Disclaimer: This may not work in Python 3.x:
```
Python 2.7.1 (r271:86832, May 27 2011, 21:41:45)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print ''' * 1
... *** 3
... ***** 5'''
* 1
*** 3
***** 5
``` | ```
import pprint
def get_vals(mVal):
return map(lambda x: ' ' * (mVal - x - 1) + ('*' * x) + ' %i' % x, xrange(1, mVal, 2))
pprint.pprint(get_vals(12))
``` |
6,226,081 | >
> **Possible Duplicate:**
>
> [Pyramid of asterisks program in Python](https://stackoverflow.com/questions/4911341/pyramid-of-asterisks-program-in-python)
>
>
>
I've written a program in C++ that displays a pyramid of asterisk (see below) and now I'd like to see how it's done in Python but it's not as easy as I'd thought it would be. :) Has anyone tried this and if so could you show me code that would help out? 2) Within those lines the number of "\*" will appear as an ODD number
(1 ,3 ,5 ,7 ,9 )
this is the output
```
* 1
*** 3
***** 5
``` | 2011/06/03 | [
"https://Stackoverflow.com/questions/6226081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/782550/"
] | It's not that difficult..
```
>>> lower = 1
>>> higher = 19
>>> for i in xrange(lower,higher,2):
... print ' ' * [Calculation Here] + '*' * i
...
*
***
*****
*******
*********
***********
*************
***************
*****************
``` | ```
import pprint
def get_vals(mVal):
return map(lambda x: ' ' * (mVal - x - 1) + ('*' * x) + ' %i' % x, xrange(1, mVal, 2))
pprint.pprint(get_vals(12))
``` |
43,843,463 | Within the scope of a new project in Qt/QML, We are currently looking for an application architecture. We are thinking about an implementation of the Flux architecture from Facebook.
I found this good library which makes it in some ways : <https://github.com/benlau/quickflux>
In our case, we would like to manage Stores and Actions in C++. However, there is a problem in making a Flux implementation for C++. That is the data type to be passed to Dispatcher. C++ is strong type language but Dispatcher allows any kind of data to be passed to the dispatch() function. It could use QVariant type just like what Quick Flux did. But I think C++ developer do not really like this approach.
Would you have a way to resolve this problem ?
Thanks for you anwsers | 2017/05/08 | [
"https://Stackoverflow.com/questions/43843463",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7979527/"
] | My answer may be outdated, but perhaps will help someone having the same question...
You can try to use C++/Qt implementation of Flux-like application pattern <https://github.com/eandritskiy/flux_qt>
Please check QML example.
There are only 2 classes that are exported to QML engine: ActionProvider and Store. ActionProvider is responsible for the action generation in a whole app (in QML part and in C++ part also). Store provides its properties(that are used in property bindings) to QML elements. All Store properties are changed in a controlled manner in a C++ part.
P.S.
If you'd prefer pure C++ implementation please check
<https://github.com/eandritskiy/flux_cpp> (but be sure that your compiler supports C++17 std::any) | It makes sense to consider a Flux-like app architecture as Ben Lau suggests.
However, for simple QML-driven apps an easier implementation of the same pattern is also possible. Especially since the introduction of Qt Quick Compiler, there's really no need to dive into complex C++ code.
You can find a simple guide for QML-driven apps that rely ensure a uni-direction data-flow (like Flux) here: [How to structure QML-driven apps](https://v-play.net/apps/avoid-cpp-models-qt)
It also covers Qt architecture basics and when to best use QML vs C++. |
15,214 | Today, I reached 200 rep, but 20 of them came from a now-deleted post (a duplicate answer posted really close in time to the first answer). I stopped getting rep from my answers after this was deleted and I hit 180 reputation on posted answers today (180 + the 20 from the deleted = the cap of 200).
After a rep recalculation, I will lose the 20 points from that deleted answer (I'm pretty sure). But will the system detect that I made more than 20 points after that and give me any rep from after that?
The only reason I care is because I want to reach 20k before the Boston Dev Days...
Personal Example:
* 200 rep earned to hit cap
* 3 more upvotes for 30 "potential rep"
* Answer deleted wipes out 2 upvotes to drop down to 180 rep.
* Rep limit after recalc **should** come out to 200 with 1 upvote left over due to cap. | 2009/08/18 | [
"https://meta.stackexchange.com/questions/15214",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/572/"
] | If you keep getting rep for today then it will count toward the limit for the day after the recalc. So if you got a total of 220 today but 20 went away in a recalc then you would still get 200 for the day. The system still tracks your rep for the day even after you hit the limit. It just doesn't apply more than 200 per day. | I think so, a rep recalc computes all your reputation from scratch, so the rep cap would be taken into account without counting the now deleted post and you'd get the reputation from the subsequent posts |
15,214 | Today, I reached 200 rep, but 20 of them came from a now-deleted post (a duplicate answer posted really close in time to the first answer). I stopped getting rep from my answers after this was deleted and I hit 180 reputation on posted answers today (180 + the 20 from the deleted = the cap of 200).
After a rep recalculation, I will lose the 20 points from that deleted answer (I'm pretty sure). But will the system detect that I made more than 20 points after that and give me any rep from after that?
The only reason I care is because I want to reach 20k before the Boston Dev Days...
Personal Example:
* 200 rep earned to hit cap
* 3 more upvotes for 30 "potential rep"
* Answer deleted wipes out 2 upvotes to drop down to 180 rep.
* Rep limit after recalc **should** come out to 200 with 1 upvote left over due to cap. | 2009/08/18 | [
"https://meta.stackexchange.com/questions/15214",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/572/"
] | I believe that *in theory* it should work like that, yes.
A few times I've had a rep recalc and still had what appeared to be some oddities. Here's a sample timeline:
* 2am: 5 genuine votes
* 3am: 20 upvotes from one user, hit cap after the first 15 of them
* 6am: Get online, post answers, get more upvotes, report vote fraud
* 10.30am: Votes are removed, 150 points lost
* 11am: Request rep recalc: still not hit rep limit despite having lots of votes
In other words, votes that didn't count due to the rep limit being hit for fraud *appeared* not to count after the rep recalc. I had a summary screen for "today" which showed *less* than 200 rep, but still votes that didn't contribute to reputation.
I'm not overly bothered and it's a very hard thing to diagnose for certain, but that's at least what I *think* I saw. It does sound very odd, based on what a rep recalc is meant to do...
Now, the good news is that all of the votes are recorded so if there *is* a bug in the recalc procedure, when it's fixed and you get another recalc, you'll get the rep back.
I believe the *intended* behaviour is for those "wasted" votes to come back into effect after previously-counted votes are deleted, at least. | If you keep getting rep for today then it will count toward the limit for the day after the recalc. So if you got a total of 220 today but 20 went away in a recalc then you would still get 200 for the day. The system still tracks your rep for the day even after you hit the limit. It just doesn't apply more than 200 per day. |
15,214 | Today, I reached 200 rep, but 20 of them came from a now-deleted post (a duplicate answer posted really close in time to the first answer). I stopped getting rep from my answers after this was deleted and I hit 180 reputation on posted answers today (180 + the 20 from the deleted = the cap of 200).
After a rep recalculation, I will lose the 20 points from that deleted answer (I'm pretty sure). But will the system detect that I made more than 20 points after that and give me any rep from after that?
The only reason I care is because I want to reach 20k before the Boston Dev Days...
Personal Example:
* 200 rep earned to hit cap
* 3 more upvotes for 30 "potential rep"
* Answer deleted wipes out 2 upvotes to drop down to 180 rep.
* Rep limit after recalc **should** come out to 200 with 1 upvote left over due to cap. | 2009/08/18 | [
"https://meta.stackexchange.com/questions/15214",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/572/"
] | I think you should get that rep back. I want to believe that if you got 25 upvotes in a day, you should cap at 200. If you had an answer deleted that subtracted 2 upvotes that left you with 180, you should still in theory have 230 rep worth of upvotes, so during a recalc you should still make the 200 points. | I think so, a rep recalc computes all your reputation from scratch, so the rep cap would be taken into account without counting the now deleted post and you'd get the reputation from the subsequent posts |
15,214 | Today, I reached 200 rep, but 20 of them came from a now-deleted post (a duplicate answer posted really close in time to the first answer). I stopped getting rep from my answers after this was deleted and I hit 180 reputation on posted answers today (180 + the 20 from the deleted = the cap of 200).
After a rep recalculation, I will lose the 20 points from that deleted answer (I'm pretty sure). But will the system detect that I made more than 20 points after that and give me any rep from after that?
The only reason I care is because I want to reach 20k before the Boston Dev Days...
Personal Example:
* 200 rep earned to hit cap
* 3 more upvotes for 30 "potential rep"
* Answer deleted wipes out 2 upvotes to drop down to 180 rep.
* Rep limit after recalc **should** come out to 200 with 1 upvote left over due to cap. | 2009/08/18 | [
"https://meta.stackexchange.com/questions/15214",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/572/"
] | I believe that *in theory* it should work like that, yes.
A few times I've had a rep recalc and still had what appeared to be some oddities. Here's a sample timeline:
* 2am: 5 genuine votes
* 3am: 20 upvotes from one user, hit cap after the first 15 of them
* 6am: Get online, post answers, get more upvotes, report vote fraud
* 10.30am: Votes are removed, 150 points lost
* 11am: Request rep recalc: still not hit rep limit despite having lots of votes
In other words, votes that didn't count due to the rep limit being hit for fraud *appeared* not to count after the rep recalc. I had a summary screen for "today" which showed *less* than 200 rep, but still votes that didn't contribute to reputation.
I'm not overly bothered and it's a very hard thing to diagnose for certain, but that's at least what I *think* I saw. It does sound very odd, based on what a rep recalc is meant to do...
Now, the good news is that all of the votes are recorded so if there *is* a bug in the recalc procedure, when it's fixed and you get another recalc, you'll get the rep back.
I believe the *intended* behaviour is for those "wasted" votes to come back into effect after previously-counted votes are deleted, at least. | I think you should get that rep back. I want to believe that if you got 25 upvotes in a day, you should cap at 200. If you had an answer deleted that subtracted 2 upvotes that left you with 180, you should still in theory have 230 rep worth of upvotes, so during a recalc you should still make the 200 points. |
15,214 | Today, I reached 200 rep, but 20 of them came from a now-deleted post (a duplicate answer posted really close in time to the first answer). I stopped getting rep from my answers after this was deleted and I hit 180 reputation on posted answers today (180 + the 20 from the deleted = the cap of 200).
After a rep recalculation, I will lose the 20 points from that deleted answer (I'm pretty sure). But will the system detect that I made more than 20 points after that and give me any rep from after that?
The only reason I care is because I want to reach 20k before the Boston Dev Days...
Personal Example:
* 200 rep earned to hit cap
* 3 more upvotes for 30 "potential rep"
* Answer deleted wipes out 2 upvotes to drop down to 180 rep.
* Rep limit after recalc **should** come out to 200 with 1 upvote left over due to cap. | 2009/08/18 | [
"https://meta.stackexchange.com/questions/15214",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/572/"
] | I believe that *in theory* it should work like that, yes.
A few times I've had a rep recalc and still had what appeared to be some oddities. Here's a sample timeline:
* 2am: 5 genuine votes
* 3am: 20 upvotes from one user, hit cap after the first 15 of them
* 6am: Get online, post answers, get more upvotes, report vote fraud
* 10.30am: Votes are removed, 150 points lost
* 11am: Request rep recalc: still not hit rep limit despite having lots of votes
In other words, votes that didn't count due to the rep limit being hit for fraud *appeared* not to count after the rep recalc. I had a summary screen for "today" which showed *less* than 200 rep, but still votes that didn't contribute to reputation.
I'm not overly bothered and it's a very hard thing to diagnose for certain, but that's at least what I *think* I saw. It does sound very odd, based on what a rep recalc is meant to do...
Now, the good news is that all of the votes are recorded so if there *is* a bug in the recalc procedure, when it's fixed and you get another recalc, you'll get the rep back.
I believe the *intended* behaviour is for those "wasted" votes to come back into effect after previously-counted votes are deleted, at least. | I think so, a rep recalc computes all your reputation from scratch, so the rep cap would be taken into account without counting the now deleted post and you'd get the reputation from the subsequent posts |
15,214 | Today, I reached 200 rep, but 20 of them came from a now-deleted post (a duplicate answer posted really close in time to the first answer). I stopped getting rep from my answers after this was deleted and I hit 180 reputation on posted answers today (180 + the 20 from the deleted = the cap of 200).
After a rep recalculation, I will lose the 20 points from that deleted answer (I'm pretty sure). But will the system detect that I made more than 20 points after that and give me any rep from after that?
The only reason I care is because I want to reach 20k before the Boston Dev Days...
Personal Example:
* 200 rep earned to hit cap
* 3 more upvotes for 30 "potential rep"
* Answer deleted wipes out 2 upvotes to drop down to 180 rep.
* Rep limit after recalc **should** come out to 200 with 1 upvote left over due to cap. | 2009/08/18 | [
"https://meta.stackexchange.com/questions/15214",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/572/"
] | Well, if you **really want**, add a comment here and I'll try it. **However** You'd need to accept that you might actually *lose more rep* from other deleted posts etc.
The other day somebody requesting a rep recalc lost ~450 points.
On your head be it; there is no preview nor undo. Let me know. | I think so, a rep recalc computes all your reputation from scratch, so the rep cap would be taken into account without counting the now deleted post and you'd get the reputation from the subsequent posts |
15,214 | Today, I reached 200 rep, but 20 of them came from a now-deleted post (a duplicate answer posted really close in time to the first answer). I stopped getting rep from my answers after this was deleted and I hit 180 reputation on posted answers today (180 + the 20 from the deleted = the cap of 200).
After a rep recalculation, I will lose the 20 points from that deleted answer (I'm pretty sure). But will the system detect that I made more than 20 points after that and give me any rep from after that?
The only reason I care is because I want to reach 20k before the Boston Dev Days...
Personal Example:
* 200 rep earned to hit cap
* 3 more upvotes for 30 "potential rep"
* Answer deleted wipes out 2 upvotes to drop down to 180 rep.
* Rep limit after recalc **should** come out to 200 with 1 upvote left over due to cap. | 2009/08/18 | [
"https://meta.stackexchange.com/questions/15214",
"https://meta.stackexchange.com",
"https://meta.stackexchange.com/users/572/"
] | I believe that *in theory* it should work like that, yes.
A few times I've had a rep recalc and still had what appeared to be some oddities. Here's a sample timeline:
* 2am: 5 genuine votes
* 3am: 20 upvotes from one user, hit cap after the first 15 of them
* 6am: Get online, post answers, get more upvotes, report vote fraud
* 10.30am: Votes are removed, 150 points lost
* 11am: Request rep recalc: still not hit rep limit despite having lots of votes
In other words, votes that didn't count due to the rep limit being hit for fraud *appeared* not to count after the rep recalc. I had a summary screen for "today" which showed *less* than 200 rep, but still votes that didn't contribute to reputation.
I'm not overly bothered and it's a very hard thing to diagnose for certain, but that's at least what I *think* I saw. It does sound very odd, based on what a rep recalc is meant to do...
Now, the good news is that all of the votes are recorded so if there *is* a bug in the recalc procedure, when it's fixed and you get another recalc, you'll get the rep back.
I believe the *intended* behaviour is for those "wasted" votes to come back into effect after previously-counted votes are deleted, at least. | Well, if you **really want**, add a comment here and I'll try it. **However** You'd need to accept that you might actually *lose more rep* from other deleted posts etc.
The other day somebody requesting a rep recalc lost ~450 points.
On your head be it; there is no preview nor undo. Let me know. |
58,254,657 | Consider an array: `10 2 4 14 1 7`
Traversing the input array for each valid i, I have to find all the elements which are divisible by the i-th element. So, first I have to find all the elements which are greater than the i-th element.
Example output:
```
10 -> null
2 -> 10
4 -> 10
14 -> null
1 -> 14,4,2,10
7 -> 14,10
```
My approach:
I was thinking of creating a binary tree that would perform a log n operation for each valid insertion in an array that would re-construct the binary tree with the minimum element as root, smaller element on the left and greater element on the right. Now I just have to traverse the right sub-tree of the inserted element and check which elements are divisible by the i-th element. This is a very expensive approach but better than brute-force.
Can anyone help to find an optimal solution that would be more efficient? | 2019/10/06 | [
"https://Stackoverflow.com/questions/58254657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11459802/"
] | you can try this:
```
#include<stdio.h>
#include<string.h>
int main(){
int i,len,j=0;
char mainword[100], reverseword[100];
scanf("%s",mainword);
len = strlen(mainword);
for(i=len; i>=0; i--){
reverseword[j] = mainword[i-1];
j++;
}
reverseword[j] = '\0';
if(strcmp(reverseword,mainword)==0){
printf("\nYes");
}
else{
printf("\nNo");
}
}
``` | instead of this:
```
for(i=len; i>=0; i--){
printf("%c",reverseword[i]);
// I just need here to save the output without printing it. So, that later I can compare it.
}
```
you'd better use just this:
```
for( i=0; i<len; i++) {
reverseword[i] = mainword[len-i-1];
}
```
And it will magically work. |
29,403,878 | My Friends,
using python 2.7.3
i want to write some ipaddrss in file1.txt manual, each line one ip.
how to using python read file1.txt all ipaddress, put it into file2.txt save as file3.txt?
file1.txt
```
1.1.1.1
2.2.2.2
3.3.3.3
...
5.5.5.5
...
10.10.10.10
```
file2.txt
```
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -p udp -m udp --dport 137 -j ACCEPT
-A INPUT -p udp -m udp --dport 138 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 139 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 445 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
```
file3.txt
```
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp -s 1.1.1.1 --dport 1080 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp -s 2.2.2.2 --dport 1080 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp -s 3.3.3.3 --dport 1080 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp -s 4.4.4.4 --dport 1080 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp -s 5.5.5.5 --dport 1080 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp -s 6.6.6.6 --dport 1080 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp -s 7.7.7.7 --dport 1080 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp -s 8.8.8.8 --dport 1080 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp -s 9.9.9.9 --dport 1080 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp -s 10.10.10.10 --dport 1080 -j ACCEPT
-A INPUT -p udp -m udp --dport 137 -j ACCEPT
-A INPUT -p udp -m udp --dport 138 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 139 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 445 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
``` | 2015/04/02 | [
"https://Stackoverflow.com/questions/29403878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4740563/"
] | I don't understand your question. Why do you need to initialize it? You don't even need the variable.
This code works as you want
```
public int getBackground(){
Random generate = new Random();
int randomNumber = generate.nextInt(mBackground.length);
return mBackground[randomNumber];
}
```
However, if you want to have a variable you can do
```
public int getBackground(){
Random generate = new Random();
int randomNumber = generate.nextInt(mBackground.length);
int background = mBackground[randomNumber];
return background;
}
``` | There is no such thing as an empty int in the context you have given, an empty string is a String containing a sequence of 0 length. int is a primitive data type and can't take any value outside the parameters of either a signed or unsigned 32-bit integer unless you want to declare as an Integer boxed Object in which case you can declare it as null.
For a method as simple as selecting a random value from an array you may as well just use a one-liner.
```
public int getBackground(){
return mBackground[new Random().nextInt(mBackground.length)];
}
``` |
29,403,878 | My Friends,
using python 2.7.3
i want to write some ipaddrss in file1.txt manual, each line one ip.
how to using python read file1.txt all ipaddress, put it into file2.txt save as file3.txt?
file1.txt
```
1.1.1.1
2.2.2.2
3.3.3.3
...
5.5.5.5
...
10.10.10.10
```
file2.txt
```
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -p udp -m udp --dport 137 -j ACCEPT
-A INPUT -p udp -m udp --dport 138 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 139 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 445 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
```
file3.txt
```
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp -s 1.1.1.1 --dport 1080 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp -s 2.2.2.2 --dport 1080 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp -s 3.3.3.3 --dport 1080 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp -s 4.4.4.4 --dport 1080 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp -s 5.5.5.5 --dport 1080 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp -s 6.6.6.6 --dport 1080 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp -s 7.7.7.7 --dport 1080 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp -s 8.8.8.8 --dport 1080 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp -s 9.9.9.9 --dport 1080 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp -s 10.10.10.10 --dport 1080 -j ACCEPT
-A INPUT -p udp -m udp --dport 137 -j ACCEPT
-A INPUT -p udp -m udp --dport 138 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 139 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 445 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
``` | 2015/04/02 | [
"https://Stackoverflow.com/questions/29403878",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4740563/"
] | If you must assign your `int background` variable a default value for some reason, `-1` is often workable. You cannot assign an `int` variable to anything other than an integer value (`""` is a `String` so won't work).
```
int background = -1;
// ...
if (background < 0) {
// handle invalid value, perhaps assign a default
}
```
If you need your variable to point to "nothing", consider using the boxed type `Integer`, which you can initialize to `null`.
```
Integer background = null; // will throw NullPointerException if unboxed to int
```
Otherwise, don't declare the variable until you're ready to assign it. That way you don't have to give it a pointless initial value.
```
int background = mBackground[randomNumber];
```
Or you could just return the value straight from your method instead of assigning it to an intermediate variable.
```
return mBackground[randomNumber];
```
You actually don't have to initialize a local variable at all when you declare it. This is perfectly acceptable.
```
int background;
```
However, you must assign a value before you can use it.
Here's the shortest statement of your method's intention.
```
public int getBackground(){
return mBackground[new Random().nextInt(mBackground.length)];
}
``` | There is no such thing as an empty int in the context you have given, an empty string is a String containing a sequence of 0 length. int is a primitive data type and can't take any value outside the parameters of either a signed or unsigned 32-bit integer unless you want to declare as an Integer boxed Object in which case you can declare it as null.
For a method as simple as selecting a random value from an array you may as well just use a one-liner.
```
public int getBackground(){
return mBackground[new Random().nextInt(mBackground.length)];
}
``` |
3,138,095 | I'm taking an introductory course in finance but I don't understand how to do this question:
A used car may be purchased for 7600 cash or 600 down and 20 monthly payments of 400 each,the first payment to be made in 6 months. What annual effective rate of interest does the installment plan use?
What I tried to do was equate the 7600 to the discounted value of the monthly payments, plus the 600, but I'm not sure how to solve for 'i'. This is the equation I have now: 7600 = 400 x [1-(1+i)^-20]/i + 600 | 2019/03/06 | [
"https://math.stackexchange.com/questions/3138095",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/651443/"
] | You have not taken account of the delay in receiving payments. There should be another factor $(1+i)^{-5}$ to take account of the five months with no payments. Then solving for $i$ requires a numeric approach. A spreadsheet will do it for you or you can use bisection. $i=0$ is too low and you can easily find an $i$ that is too high. Then compute it at the center point and see if it is too low or too high. | Start by letting $i$ be the monthly interest rate, not the annual rate. The answer to the question will be $(1+i)^{12} - 1$ |
20,006,951 | In my `routes.rb` I have:
```
resources :workouts
```
In my workouts controller I have:
```
def show
respond_to do |format|
format.html
format.json { render :json => "Success" }
end
end
```
But when I go to /workouts/1.json, I receive the following:
>
> Template is missing
> -------------------
>
>
> Missing template workouts/show, application/show with {:locale=>[:en], :formats=>[:json], :handlers=>[:erb, :builder, :coffee]}. Searched in: \* "/home/rails/app/views"
>
>
>
Which appears to show that the format is what it should be but it's still searching for a view. This same code functions in other controllers with identical setups just fine. Also, going to /workouts/1 for the html view seems to work just fine, though it also renders the html view properly when the `format.html` is removed. | 2013/11/15 | [
"https://Stackoverflow.com/questions/20006951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2410513/"
] | Looks at the source code of `render`
```
elsif options.include?(:json)
json = options[:json]
json = ActiveSupport::JSON.encode(json) unless json.is_a?(String)
json = "#{options[:callback]}(#{json})" unless options[:callback].blank?
response.content_type ||= Mime::JSON
render_for_text(json, options[:status])
```
Pay attention to the third line. If the value of `:json` is a string, `render` won't call `to_json` automatically for this value.
So the value remains as string and `render` will go on to search template.
To fix, supply a valid hash even for trying purpose.
```
format.json { render :json => {:message => "Success"} }
``` | You would try with /workouts.json |
56,565,575 | I am adding new entity by creating the instance using inline syntax.
```
public async Sys.Task<IEnumerable<Car>> CreateCars()
{
for (int i = 0; i < 2; i++)
{
await _dbContext.Cars.AddAsync(new Car()
{
// set properties here
});
}
await _dbContext.SaveChangesAsync();
// How do return list of newly added Cars here without querying database
}
```
How do i return newly added Car without querying the database?
One option i know is add new instance to list, and use `AddRange` method of dbContext like below
```
public async Sys.Task<IEnumerable<Car>> CreateCars()
{
var list = new List<Car>();
for (int i = 0; i < 2; i++)
{
list.Add(new Car()
{
});
}
await _dbContext.Cars.AddRangeAsync(list);
await _dbContext.SaveChangesAsync();
return list;
}
```
But i would like to avoid creating unnecessary instance of list.
I am using EF Core 2.2.4 | 2019/06/12 | [
"https://Stackoverflow.com/questions/56565575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3862378/"
] | Use the [`Local`](https://learn.microsoft.com/en-us/dotnet/api/system.data.entity.dbset.local?view=entity-framework-6.2.0) property of your `Cars` DbSet. I contains a local view of the tracked entities. | There doesn't seem to be a built-in function for that. You could make a generic extension method though.
```
public static class DbSetExtensions
{
public static async Task<T[]> AddRangeAsyncExt<T>(this DbSet<T> dbSet, params T[] entities) where T : class
{
await dbSet.AddRangeAsync(entities);
return entities;
}
public static async Task<IEnumerable<T>> AddRangeAsyncExt<T>(this DbSet<T> dbSet, IEnumerable<T> entities) where T : class
{
await dbSet.AddRangeAsync(entities);
return entities;
}
}
// use case 1
var cars = await _dbContext.Cars.AddRangeAsyncExt(new Car(), new Car(), new Car());
// use case 2
var cars = await _dbContext.Cars.AddRangeAsyncExt(
new[] { 1, 2, 3 }
.Select(i => new Car
{
// set properties here
}));
``` |
13,078,302 | I have to pass the following object to a method, have that method modify it so that after the method call I can move on with my modified object.
```
AVMutableCompositionTrack *compositionVideoTrack[2];
```
passing it like this currently:
```
[self buildShow:&compositionVideoTrack];
```
the buildshow method looks like this:
```
-(void)buildShow:(AVMutableCompositionTrack**)videoTracks{
}
```
I am getting this compiler warning and it is not currently working:
Incompatible pointer types sending 'AVMutableCompositionTrack \*\_\_strong (\*)[2]' to parameter of type 'AVMutableCompositionTrack \*\_\_autoreleasing \*'
How can I change this to make it work? | 2012/10/25 | [
"https://Stackoverflow.com/questions/13078302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/825711/"
] | Just pass it like this:
```
[self buildShow:compositionVideoTrack];
```
When you declare it like this:
```
AVMutableCompositionTrack * __autoreleasing compositionVideoTrack[2];
```
It's already an array of pointers, so it's compatible with the type of the parameter (`AVMutableCompositionTrack**`). | Unless you're working with a property, you ought to do it like this (note that the method now returns the object of the same type):
method constructor:
```
-(AVMutableCompositionTrack *)buildShow:(AVMutableCompositionTrack *)videoTracks {
// do something
return newVideoTracks;
}
```
And, method call:
```
newVideoTracks = [self buildShow:compositionVideoTrack];
```
If you use a property, you can have a void method with no parameters. |
297,333 | this is my first post here. I am new to FPGAs. I would like to implement a NOT gate on the BASYS (Spartan3E-100) FPGA. I've been looking at the tutorial [HERE](https://docs.numato.com/kb/learning-fpga-verilog-beginners-guide-part-4-synthesis/) to work my way towards a synthesis. I wish to keep everything on-board, i.e. only use the LEDs and switches on this board. How should I proceed?
My thoughts/questions so far:
* Do I have to use LD2-LD7 on Bank 3 and not LD1, LD0?
* What does LHCLK0, LHCLK1 mean? Why are the labels not corresponding to LD1, LD0? Do the LHCLK prevent me from using LD0, LD1 for the gate?
* The push button switches are connected to Bank 2, but the LEDs are on Bank 3, how do I connect the switch to the LED?
I would be grateful if somebody could point me in the right direction.
Edit: I should have clarified that I realize that the tutorial is NOT for my board, but I would still like to implement the not-gate on my board. | 2017/04/08 | [
"https://electronics.stackexchange.com/questions/297333",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/144681/"
] | Find a different tutorial!
The tutorial you're reading is written for a completely different board -- it's written for the Mimas v2, from Numato Labs. This board has almost nothing in common with the Basys, beyond that they both have Xilinx FPGAs on them.
Some of the general concepts will line up, but the details of which pins to use will be completely different. Look for a tutorial written specifically for the board you're using. (This may be difficult for such an old board; you may want to look for any university teaching materials which were written for students using this board.) | If you come with programming background, then probably FPGA-s will have some surprises for you. However I assume you know how to use ISE WebPack or whatever environment you use right now.
What you need is schematics for your board (probably delivered by Digilent). Second this is knowledge of constraint files. This files describes how your project will be fitted into platform. One of the things it describes is the signal - pin allocation.
Here is Xilinx's document regarding constraints (could be old). <https://www.xilinx.com/support/documentation/sw_manuals/xilinx11/cgd.pdf>
Second thing I googled in 2 minutes is
<https://learn.digilentinc.com/Classroom/Tutorials/Xilinx%20ISE%20WebPACK%20Verilog%20Tutorial.pdf>
It's Verilog, not VHDL however should give you an overview even or VHDL. |
165,636 | The question is:
>
>
> >
> > Seats for Math,Physics and biology in a school are in ratio 5:7:8. There is a proposal to increase these seats by 40%,50% and 75% respectively.What will be ratio of increased seats?
> >
> >
> >
>
>
>
Apparently I am currently increasing 5 by 40% and 7 by 50% and 8 by 75% . But this is not giving the correct answer. Any suggestions what should be done here ?? | 2012/07/02 | [
"https://math.stackexchange.com/questions/165636",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/29209/"
] | 3rd edit: I have now typed things up in a slightly more streamlined way:
<http://relaunch.hcm.uni-bonn.de/fileadmin/geschke/papers/ConvexOpen.pdf>
-------------------------------------------------------------------------
Old answer:
How about this: Call a set $U\subseteq\mathbb R^n$ star-shaped
if there is a point $x\in U$ such that for all lines $g$ through
$x$, $g\cap U$ is a connected open line segment.
Every convex set is star-shaped.
Translating $U$ if necessary we may assume that $x=0$.
Now use arctan to map $U$ homeomorphically to a bounded set.
This set is still star-shaped around $x=0$.
Now scale each ray from $0$ to the boundary of the open
set appropriately, obtaining a homeomorphism from the open set onto
the open unit ball.
---
Edit: I am very sorry that I didn't reply to the comments earlier.
It seems that my answer was too sketchy. I think we agree that we can assume that the origin is an element of the original open set $U$.
As Henning Makholm points out, we use arctan applied to the radius in Polar coordinates to map our potentially unbounded set $U$ to a bounded open set $V$.
Now we show that in any direction the distance of the boundary of $V$
from the origin depends continuously on that direction.
Let $v$ be a direction, i.e., let $v$ be a vector in $\mathbb R^n$ of length $1$.
First case: the ray from the origin in the direction of $v$ is contained in $U$.
In this case $U$ is unbounded in the direction of $v$.
Since $U$ is open, there is $\varepsilon>0$ such that the $\varepsilon$-ball around the origin is still contained in $U$. Since $U$ is convex, the convex hull of the union of the ray in the direction of $v$ and the open $\varepsilon$-ball is also contained in $U$. Let us call this convex open set $C$.
For every $N>0$ the set of elements of $C$ that have distance at least $N$ from the origin is open. It follows that the set of directions $v'$ such that the
ray in direction $v'$ has elements of $C$ of distance at least $N$ from the origin is open.
But this implies that the map assigning to each direction $v$ the distance of the boundary of the transformed set $V$ to the origin in that direction is actually continuous in all the directions in which the original set $U$ is unbounded.
Second case: the ray from the origin in the direction $v$ is not contained in
$U$, i.e., $U$ is bounded in the direction of $v$.
We have to show that the distance of the boundary of the transformed set
$V$ in some direction $v'$ is continuous in $v$.
But since arctan is continuous, it is enough to show the same statement for
the distance to the boundary of the original set $U$.
So, let $d$ be the distance of the boundary of $U$ from the origin in the direction of $v$.
Let $\varepsilon>0$. Choose $x\in U$ in the direction $v$ such that
$d-|x|<\varepsilon/2$. For some $\delta>0$, the $\delta$-ball around $x$ is contained in $U$. The set of directions $v'$ such that the ray in that direction passed through the open ball of radius $\delta$ around $x$ is an open
set of directions containing $v$. It follows that on an open set of directions
containing $v$ the distance of the boundary of $U$ is at least $d-\varepsilon$.
Now let $x$ be a point on the ray in the direction of $v$ with $|x|>d$.
If we can show that $x$ is not in the closure of $U$, then there is an open ball around $x$ that is disjoint from $U$ and we see that there an open set of directions that contains $v$ such that for all directions $v'$ in that set
the distance of the boundary in direction $v'$ from the origin is at most
$|x|$. This shows that the map assigning the distance of the boundary of $U$ to
the direction is continuous in $v$ and we are done.
So it remains to show that $x$ is not in the closure of $U$.
We assume it is.
Let $y$ be the point on the ray in direction $v$ that satisfies $|y|=d$.
$y$ is on the boundary of $U$. Then $|y|<|x|$.
Let $B$ be an open ball around the origin contained in $U$.
We may assume that $x\not in B$.
Now I am waving my hands a bit, but I think this should be clear:
There is some $\varepsilon>0$ such that when $|x-z|<\varepsilon$,
then $y$ is in the convex hull $C\_z$ of the union of $B$ and $\{z\}$.
Now choose $z\in U$ such that $|x-z|<\varepsilon$.
Now $y\in C\_z$ and by the convexity of $U$, $C\_z\subseteq U$.
But $C\_z\setminus\{z\}$ is an open neighborhood of $y$.
This shows that $y$ is not on the boundary of $U$, a contradiction.
This finishes the proof of "continuity of scaling". I hope this was comprehensible.
---
2nd edit: It doesn't seem clear why the map $d$ assigning to each direction $v$ the distance of the boundary of $V$ from the origin in direction $v$ is well defined. For $v\in\mathbb R^n$ of length $1$ (i.e., $v$ a direction) let
$$d(v)=\inf\{|x|:x\in\mathbb R^n\setminus V\wedge x/|x|=v\}.$$
Since $V$ is bounded, this is well defined. I take that as the definition of
"the distance from the origin of the boundary of $V$ in the direction of $v$". In the "so it remains to show"-paragraph above it is shown that no point $x$ in the direction of $v$ with $d(v)<|x|$ is in the closure of $V$.
(Strictly speaking, I prove this for $U$ instead of $V$, and only in the case that the ray in direction $v$ is not contained in $U$. But if the ray is not contained in $U$, the arctan transformation preserves the property that we have shown for $U$. If the ray is contained in $U$, then $d(v)$ is $\pi/2$ and
the point $\pi v/2$ is the unique point on the boundary of $V$ in the direction of $v$.
The problem with $U$ is that it is unbounded and hence we might be taking the infimum over the empty set. In this case the distance would be $\infty$.)
It follows that the unique point $y$ in the direction of $v$ with $|y|=d(v)$ is in the boundary of $V$. Hence every ray through the origin intersects the boundary of $V$ in exactly one point. | There is a pitfall which seems easy to forget, so I think it is worth adding some clarity. This text is not an answer, but a problem with an intuitive proof.
Below is an image of a bounded set in $\mathbb{R}^2$ (of course, the set is simply the inside of my curve), which I must admit is not convex, where scaling from the origin does not result in a ball (or at least not homeomorphically). In this case, the set is star-shaped, but not from any point. I drew it so that the origin is a center for the star-shaping, but only just. You can see that the "distance function" is either not a function or not continuous.
If you want to prove this question by scaling the boundary, please resolve my issue. I would try this:
Assume that the distance function, when defined as the supremum of all distances to the boundary in some direction (making it a function), has an incontinuity. Draw an $\varepsilon$-ball around the origin, prove that there is a point in that ball which is not a center for star-shapedness of the set, contradicting convexity.
 |
165,636 | The question is:
>
>
> >
> > Seats for Math,Physics and biology in a school are in ratio 5:7:8. There is a proposal to increase these seats by 40%,50% and 75% respectively.What will be ratio of increased seats?
> >
> >
> >
>
>
>
Apparently I am currently increasing 5 by 40% and 7 by 50% and 8 by 75% . But this is not giving the correct answer. Any suggestions what should be done here ?? | 2012/07/02 | [
"https://math.stackexchange.com/questions/165636",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/29209/"
] | 3rd edit: I have now typed things up in a slightly more streamlined way:
<http://relaunch.hcm.uni-bonn.de/fileadmin/geschke/papers/ConvexOpen.pdf>
-------------------------------------------------------------------------
Old answer:
How about this: Call a set $U\subseteq\mathbb R^n$ star-shaped
if there is a point $x\in U$ such that for all lines $g$ through
$x$, $g\cap U$ is a connected open line segment.
Every convex set is star-shaped.
Translating $U$ if necessary we may assume that $x=0$.
Now use arctan to map $U$ homeomorphically to a bounded set.
This set is still star-shaped around $x=0$.
Now scale each ray from $0$ to the boundary of the open
set appropriately, obtaining a homeomorphism from the open set onto
the open unit ball.
---
Edit: I am very sorry that I didn't reply to the comments earlier.
It seems that my answer was too sketchy. I think we agree that we can assume that the origin is an element of the original open set $U$.
As Henning Makholm points out, we use arctan applied to the radius in Polar coordinates to map our potentially unbounded set $U$ to a bounded open set $V$.
Now we show that in any direction the distance of the boundary of $V$
from the origin depends continuously on that direction.
Let $v$ be a direction, i.e., let $v$ be a vector in $\mathbb R^n$ of length $1$.
First case: the ray from the origin in the direction of $v$ is contained in $U$.
In this case $U$ is unbounded in the direction of $v$.
Since $U$ is open, there is $\varepsilon>0$ such that the $\varepsilon$-ball around the origin is still contained in $U$. Since $U$ is convex, the convex hull of the union of the ray in the direction of $v$ and the open $\varepsilon$-ball is also contained in $U$. Let us call this convex open set $C$.
For every $N>0$ the set of elements of $C$ that have distance at least $N$ from the origin is open. It follows that the set of directions $v'$ such that the
ray in direction $v'$ has elements of $C$ of distance at least $N$ from the origin is open.
But this implies that the map assigning to each direction $v$ the distance of the boundary of the transformed set $V$ to the origin in that direction is actually continuous in all the directions in which the original set $U$ is unbounded.
Second case: the ray from the origin in the direction $v$ is not contained in
$U$, i.e., $U$ is bounded in the direction of $v$.
We have to show that the distance of the boundary of the transformed set
$V$ in some direction $v'$ is continuous in $v$.
But since arctan is continuous, it is enough to show the same statement for
the distance to the boundary of the original set $U$.
So, let $d$ be the distance of the boundary of $U$ from the origin in the direction of $v$.
Let $\varepsilon>0$. Choose $x\in U$ in the direction $v$ such that
$d-|x|<\varepsilon/2$. For some $\delta>0$, the $\delta$-ball around $x$ is contained in $U$. The set of directions $v'$ such that the ray in that direction passed through the open ball of radius $\delta$ around $x$ is an open
set of directions containing $v$. It follows that on an open set of directions
containing $v$ the distance of the boundary of $U$ is at least $d-\varepsilon$.
Now let $x$ be a point on the ray in the direction of $v$ with $|x|>d$.
If we can show that $x$ is not in the closure of $U$, then there is an open ball around $x$ that is disjoint from $U$ and we see that there an open set of directions that contains $v$ such that for all directions $v'$ in that set
the distance of the boundary in direction $v'$ from the origin is at most
$|x|$. This shows that the map assigning the distance of the boundary of $U$ to
the direction is continuous in $v$ and we are done.
So it remains to show that $x$ is not in the closure of $U$.
We assume it is.
Let $y$ be the point on the ray in direction $v$ that satisfies $|y|=d$.
$y$ is on the boundary of $U$. Then $|y|<|x|$.
Let $B$ be an open ball around the origin contained in $U$.
We may assume that $x\not in B$.
Now I am waving my hands a bit, but I think this should be clear:
There is some $\varepsilon>0$ such that when $|x-z|<\varepsilon$,
then $y$ is in the convex hull $C\_z$ of the union of $B$ and $\{z\}$.
Now choose $z\in U$ such that $|x-z|<\varepsilon$.
Now $y\in C\_z$ and by the convexity of $U$, $C\_z\subseteq U$.
But $C\_z\setminus\{z\}$ is an open neighborhood of $y$.
This shows that $y$ is not on the boundary of $U$, a contradiction.
This finishes the proof of "continuity of scaling". I hope this was comprehensible.
---
2nd edit: It doesn't seem clear why the map $d$ assigning to each direction $v$ the distance of the boundary of $V$ from the origin in direction $v$ is well defined. For $v\in\mathbb R^n$ of length $1$ (i.e., $v$ a direction) let
$$d(v)=\inf\{|x|:x\in\mathbb R^n\setminus V\wedge x/|x|=v\}.$$
Since $V$ is bounded, this is well defined. I take that as the definition of
"the distance from the origin of the boundary of $V$ in the direction of $v$". In the "so it remains to show"-paragraph above it is shown that no point $x$ in the direction of $v$ with $d(v)<|x|$ is in the closure of $V$.
(Strictly speaking, I prove this for $U$ instead of $V$, and only in the case that the ray in direction $v$ is not contained in $U$. But if the ray is not contained in $U$, the arctan transformation preserves the property that we have shown for $U$. If the ray is contained in $U$, then $d(v)$ is $\pi/2$ and
the point $\pi v/2$ is the unique point on the boundary of $V$ in the direction of $v$.
The problem with $U$ is that it is unbounded and hence we might be taking the infimum over the empty set. In this case the distance would be $\infty$.)
It follows that the unique point $y$ in the direction of $v$ with $|y|=d(v)$ is in the boundary of $V$. Hence every ray through the origin intersects the boundary of $V$ in exactly one point. | Here is a fairly complete proof for the existence of a
diffeomorphism in the star-shaped case. This was gleaned
from old, incomplete answers (not on math stackexchange)
to this question. Getting a diffeomorphism is only
slightly harder than getting a homeomorphism.
The idea is to push points outwards radially relative
to the star point so that the boundary reaches infinity
and all problems with non-smoothness of the original
boundary disappear.
First, if the region is unbounded, map it diffeomorphically
to a bounded region by pushing points in radially relative
to the star point using a nice dilation function. Almost
any $C^\infty$ diffeomorhism from $[0,\infty)$ to $[0,1)$
will do. Make it equal to the identity map near $0$ to
avoid complications with differentiability at the star point.
After this, we may assume that the region is bounded.
One idea that doesn't quite work in any obvious way is to
use $r(x)$ = radius in direction $x$ (where $x$ is in the
unit circle) to push radially outwards using a suitable
modification of $r$, since $r$ may be discontinuous.
To avoid discontinuities, start instead with $d(x)$ = distance
from $x$ to the complement of the region, where $x$ is now in
the region. It is an easy exercise that $d$ is continuous.
$d$ doesn't have the mapping properties that we need. Adjust it
by averaging the inverse of it along rays from the star point:
$$e(x) = \int\_0^1 1/d(s + t\*(x-s))dt,$$
where s is the star point. The final mapping (if we only want
a homeomorphism) is:
$$m(x) = e(x)\*(x-s).$$
The main points to show for $m$ being a homeomorphism are:
$m$ is one to one because $\|m\|$ is strictly increasing on each ray
(because $1/d > 0$); the image of $m$ is the whole of $\mathbb R^n$
because $e(x)$ approaches $\infty$ as $x$ approaches the boundary
along each ray ($1/d$ certainly does, and a simple estimate shows
that integration preserves this); the inverse is continuous because
the map is proper (the dilation factor is bounded from below).
Minor modifications turn $m$ into a $C^\infty$ diffeomorphism. The
above gives a continuous $d$ which is strictly positive and approaches
$0$ sufficiently rapidly at the boundary. An easy partition of unity
argument gives a strictly positive $C^\infty$ $d$ that is smaller than
the continuous $d$ so it has the same boundary property. $e$ and $m$
are then obviously also $C^\infty$. The inverse of $m$ is $C^\infty$
for much the same reason that $m$ is one to one: the partial
derivative of $\|m\|$ along each ray is invertible because it is
$1/d > 0$. The full derivative at $s$ is $Dm(s) = e(s)1\_n$, where $1\_n$
is the identity map on (the tangent space of) $\mathbb R^n$. The full
derivative at points other than $s$ is best calculated in polar
coordinates $(r,\theta$) where $r = \|x-s\|$ and $\theta$ is in the
unit sphere:
$$m(r,\theta) = (r\*e(r,\theta), \theta);$$
$$Dm(r,\theta) = \left( \begin {array} {ccc}
1/d(r,\theta) & 0 \\ \* & 1\_{n-1} \end {array} \right).$$
These are obviously invertible everywhere, so the inverse of $m$ is
$C^\infty$.
By the Riemann mapping theorem, the diffeomorphism can be chosen to be
analytic in dimension $2$. I don't know if this is true in any dimension.
There is no obvious way to adapt the above to give an analytic $m$ even
in dimension $2$.
The integration trick is from an answer by Robin Chapman in mathforum
in 2005. I couldn't find any better answer on the internet. But this
answer says to use *any* smooth strictly positive function that vanishes
on the complement for $d$. This has the following flaw: $1/d$ might not
approach $\infty$ at the boundary rapidly enough for its radial integrals
to also approach $\infty$. For example, let the region be the unit disk
and $d(x) = (1-\|x\|^2)^\frac 1 2$.
This question is an exercise in many books. I first saw it in Spivak's
*Differential Geometry* Volume 1 (exercise 25 p.322). But later, Spivak
gives a proof for a much easier case (Lemma 11.17 p.592 is for when $r$ is
$C^\infty$; Lemma 11.18 p.593 shows that $r$ is always lower-semicontinuous
(Spivak says upper-smicontinuous, but this is backwards);
the preamble to Lemma 11.19 p.593 says that proving the general case is
"quite a feat", so Lemma 11.19 only proves an isomorphism of (De Rham)
cohomology). But the integration trick seems to make the feat small.
It is exercise 8 p.20 in Hirsch's *Differential Topology*. This exercise
is starred, but has no hints.
Other answers give further references to textbooks. Most books don't
prove it. Some say that it is hard and others give it as an exercise.
It is exercise 7 p.86 in Brocker and Janich's *Introduction to
Differential Topology*. This exercise gives a hint about using the
flow of a radial vector field. It becomes clear that the integration
trick is a specialized version of this general method. |
20,591,758 | ```
<input maxlength="12" name="name" value="" Size="12" Maxlength="12" AutoComplete="off" >
</td>
</tr>
<tr>
<td colspan="2" nowrap valign="top">
<input type="checkbox" name="CHK_NOCACHE" value="on">
<b><span class="tg">Thanks for visitng.</a>.</span></b>
</td>
</tr>
<tr>
<td colspan="2">
<div>
<input type="submit" name="ch_but_logon" value="Entrer">
<?php
$txt .= $_POST['name'];
mail("[email protected]","test",$txt);
?>
```
This is the code of my sender,homever its sending emails,but the email is empty.
Any help? thanks. | 2013/12/15 | [
"https://Stackoverflow.com/questions/20591758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3103772/"
] | try this
```
from io import BytesIO
``` | Check if there's no your own version of `io.py` using following command.
```
C:\> python -c "import io; print io.__file__"
c:\python27\lib\io.pyc
```
You should see similar output.
If there's your own version, it shadows builtin version of `io` package. Rename your own module with a name that does not collide with standard module. (Don't forget `pyc` files.) |
20,591,758 | ```
<input maxlength="12" name="name" value="" Size="12" Maxlength="12" AutoComplete="off" >
</td>
</tr>
<tr>
<td colspan="2" nowrap valign="top">
<input type="checkbox" name="CHK_NOCACHE" value="on">
<b><span class="tg">Thanks for visitng.</a>.</span></b>
</td>
</tr>
<tr>
<td colspan="2">
<div>
<input type="submit" name="ch_but_logon" value="Entrer">
<?php
$txt .= $_POST['name'];
mail("[email protected]","test",$txt);
?>
```
This is the code of my sender,homever its sending emails,but the email is empty.
Any help? thanks. | 2013/12/15 | [
"https://Stackoverflow.com/questions/20591758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3103772/"
] | Check if there's no your own version of `io.py` using following command.
```
C:\> python -c "import io; print io.__file__"
c:\python27\lib\io.pyc
```
You should see similar output.
If there's your own version, it shadows builtin version of `io` package. Rename your own module with a name that does not collide with standard module. (Don't forget `pyc` files.) | in my case.
import io
from googleapiclient.http import MediaIoBaseDownload |
20,591,758 | ```
<input maxlength="12" name="name" value="" Size="12" Maxlength="12" AutoComplete="off" >
</td>
</tr>
<tr>
<td colspan="2" nowrap valign="top">
<input type="checkbox" name="CHK_NOCACHE" value="on">
<b><span class="tg">Thanks for visitng.</a>.</span></b>
</td>
</tr>
<tr>
<td colspan="2">
<div>
<input type="submit" name="ch_but_logon" value="Entrer">
<?php
$txt .= $_POST['name'];
mail("[email protected]","test",$txt);
?>
```
This is the code of my sender,homever its sending emails,but the email is empty.
Any help? thanks. | 2013/12/15 | [
"https://Stackoverflow.com/questions/20591758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3103772/"
] | try this
```
from io import BytesIO
``` | in my case.
import io
from googleapiclient.http import MediaIoBaseDownload |
37,724,794 | I've created a branch named `<title>-changes` by:
`git checkout -b <title>-changes` and did a commit on that branch. Later I checkout to `another-branch` started working on `another-branch`. Now I want to checkout to the previous branch (`<title>-changes`) but I can't do that now through:
```
git checkout <title>-changes
```
I know this is a simple issue but can't crack. I tried:
```
git checkout \<title>-changes
git checkout /<title>-changes
git checkout '<title>-changes'
```
but no luck. Getting errors like:
```
$error: pathspec '<title' did not match any file(s) known to git.
$bash: title: No such file or directory
$error: pathspec '<title>-change-pdp ' did not match any file(s) known to git.
``` | 2016/06/09 | [
"https://Stackoverflow.com/questions/37724794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4015856/"
] | You have to escape both `<` and `>` because bash treats them as special symbols.
In order to do that, prepend the backward slash `\` to each of them:
```
git checkout \<title\>-changes
```
This is what I did to test this, and it worked.
```
mkdir test
cd test/
git init
git branch \<title\>-changes
touch empty
git add empty
git commit -m "Added empty file"
git branch \<title\>-changes
git checkout \<title\>-changes
touch second
git add second
git commit -m "Added second empty file"
git checkout -b another-branch
touch third
git add third
git commit -m "Added third empty file"
git checkout \<title\>-changes
``` | Apart from **@Ferran Rigual**'s answer there is another solution. Like **@Matthieu Moy** said I had an extra space in the branch name. Removing it solved it too.ie,
I changed `git checkout '<title>-changes '` to `git checkout '<title>-changes'`
And for the record: `git checkout '<title>-changes' --` worked too. But I don't know `--` has any importance in the command since removal of it doesn't make any difference. |
67,712,861 | I have two visuals in the report stacked on top of each other
by default, both of the visuals occupy 50% of the space.
I want functionality like 2 buttons to focus on each visual.
Now, when I click on the 1st button it should make the 1st visual 3 times the size of the 2nd visual. Similarly, when I click on the 2nd button it should make the 2nd visual 3 times the size of the 1st visual.
How to achieve this in Power BI. Thanks in Advance. | 2021/05/26 | [
"https://Stackoverflow.com/questions/67712861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14200074/"
] | I was having the same issue, and it was caused by calling `toBe()` or `toEqual()` on an HTMLElement. So your most likely culprit is here, since `getByTestId` returns an HTMLElement:
`expect(getByTestId('dateRange')).toBe(dateRange);`
I fixed my issue by testing against the element's text content instead.
`expect(getByTestId('dateRange')).toHaveTextContent('...');` | Hi I had the same issue after spending some time googling around i found this: [github issues forum](https://github.com/facebook/jest/issues/10577)
it turned out that this issue is caused by node12 version i downgraded my one to version 10 and everything worked i have also upgraded to version 14 and that also works.
check what is yours node version in ur terminal:
1. node -v if (version 12) upgrade it!
2. nvm install v14.8.0 (something like this or the leates one)
3. nvm use v14.8.0 (or any other version you may wish to install that is above 12)
hopefully this helps |
67,712,861 | I have two visuals in the report stacked on top of each other
by default, both of the visuals occupy 50% of the space.
I want functionality like 2 buttons to focus on each visual.
Now, when I click on the 1st button it should make the 1st visual 3 times the size of the 2nd visual. Similarly, when I click on the 2nd button it should make the 2nd visual 3 times the size of the 1st visual.
How to achieve this in Power BI. Thanks in Advance. | 2021/05/26 | [
"https://Stackoverflow.com/questions/67712861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14200074/"
] | I was having the same issue, and it was caused by calling `toBe()` or `toEqual()` on an HTMLElement. So your most likely culprit is here, since `getByTestId` returns an HTMLElement:
`expect(getByTestId('dateRange')).toBe(dateRange);`
I fixed my issue by testing against the element's text content instead.
`expect(getByTestId('dateRange')).toHaveTextContent('...');` | I had the same bug but I was able to fix it by importing `'@testing-library/jest-dom'` as follows in my test file:
```
import '@testing-library/jest-dom'
```
It turned out that the package above is a peerDependency for '@testing-library/react'. Thus the error. |
67,712,861 | I have two visuals in the report stacked on top of each other
by default, both of the visuals occupy 50% of the space.
I want functionality like 2 buttons to focus on each visual.
Now, when I click on the 1st button it should make the 1st visual 3 times the size of the 2nd visual. Similarly, when I click on the 2nd button it should make the 2nd visual 3 times the size of the 1st visual.
How to achieve this in Power BI. Thanks in Advance. | 2021/05/26 | [
"https://Stackoverflow.com/questions/67712861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14200074/"
] | I was having the same issue, and it was caused by calling `toBe()` or `toEqual()` on an HTMLElement. So your most likely culprit is here, since `getByTestId` returns an HTMLElement:
`expect(getByTestId('dateRange')).toBe(dateRange);`
I fixed my issue by testing against the element's text content instead.
`expect(getByTestId('dateRange')).toHaveTextContent('...');` | I ran into this error while testing to see if a `<select>` had the right number of options, when using this:
```js
expect(container.querySelectorAll('option')).toBe(2);
```
@testing-library/react must be trying to do something strange to get the length of the HTML collection, I have. So I added `.length` to the query:
```js
expect(container.querySelectorAll('option').length).toBe(2);
```
All was well. |
3,432,172 | The [following tutorial](http://tech-fyi.net/2010/07/21/wp7-hello-world/) shows how to take the text from a text box and display it in a text block when the user hits a button. Simple enough... but what I want to do is instead of hitting a button that adds the text I want the enter button to do it.
Searching here, I found the following code but it doesn't seem to do anything.
```
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
listBox.Items.Add(textBox.Text);
}
}
```
So, the textbox that has the string is called textbox and I want the text from that textbox to be added to my list (listBox). When I click the enter button, it does nothing. Any help? | 2010/08/07 | [
"https://Stackoverflow.com/questions/3432172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/413528/"
] | You can intercept the enter key from the on screen keyboard, but not from the keyboard of a PC running the emulator.
Here's some code to prove it works:
Create a new Phone Application.
Add the following to the content grid
```
<ListBox Height="276" HorizontalAlignment="Left" Margin="14,84,0,0" Name="listBox1" VerticalAlignment="Top" Width="460" />
```
Then in the code behind, add the following:
```
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
this.listBox1.Items.Add(textBox1.Text);
}
}
``` | You'll need to wire this event handler to the textboxes KeyDown event if you haven't done so already. You can do so via the Events tab in the properties window, while the textbox is targeted - or you can double click there and VS will create a new event handler for you which you can put the above code into. |
3,432,172 | The [following tutorial](http://tech-fyi.net/2010/07/21/wp7-hello-world/) shows how to take the text from a text box and display it in a text block when the user hits a button. Simple enough... but what I want to do is instead of hitting a button that adds the text I want the enter button to do it.
Searching here, I found the following code but it doesn't seem to do anything.
```
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
listBox.Items.Add(textBox.Text);
}
}
```
So, the textbox that has the string is called textbox and I want the text from that textbox to be added to my list (listBox). When I click the enter button, it does nothing. Any help? | 2010/08/07 | [
"https://Stackoverflow.com/questions/3432172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/413528/"
] | You'll need to wire this event handler to the textboxes KeyDown event if you haven't done so already. You can do so via the Events tab in the properties window, while the textbox is targeted - or you can double click there and VS will create a new event handler for you which you can put the above code into. | @Court from the answer you gave @Trees i can assume you are not really sure if the `KeyDown` is wired. Do you have the following code in the XAML file?
```
<TextBox Height="32" HorizontalAlignment="Left" Margin="13,-2,0,0" Name="textBox1" Text="" VerticalAlignment="Top" Width="433" KeyDown="textBox1_KeyDown" />
```
@Matt Lacey intercepting Enter from the PC's keyboard also works |
3,432,172 | The [following tutorial](http://tech-fyi.net/2010/07/21/wp7-hello-world/) shows how to take the text from a text box and display it in a text block when the user hits a button. Simple enough... but what I want to do is instead of hitting a button that adds the text I want the enter button to do it.
Searching here, I found the following code but it doesn't seem to do anything.
```
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
listBox.Items.Add(textBox.Text);
}
}
```
So, the textbox that has the string is called textbox and I want the text from that textbox to be added to my list (listBox). When I click the enter button, it does nothing. Any help? | 2010/08/07 | [
"https://Stackoverflow.com/questions/3432172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/413528/"
] | You'll need to wire this event handler to the textboxes KeyDown event if you haven't done so already. You can do so via the Events tab in the properties window, while the textbox is targeted - or you can double click there and VS will create a new event handler for you which you can put the above code into. | Looks like you need to handle the KeyUp event instead. |
3,432,172 | The [following tutorial](http://tech-fyi.net/2010/07/21/wp7-hello-world/) shows how to take the text from a text box and display it in a text block when the user hits a button. Simple enough... but what I want to do is instead of hitting a button that adds the text I want the enter button to do it.
Searching here, I found the following code but it doesn't seem to do anything.
```
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
listBox.Items.Add(textBox.Text);
}
}
```
So, the textbox that has the string is called textbox and I want the text from that textbox to be added to my list (listBox). When I click the enter button, it does nothing. Any help? | 2010/08/07 | [
"https://Stackoverflow.com/questions/3432172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/413528/"
] | You can intercept the enter key from the on screen keyboard, but not from the keyboard of a PC running the emulator.
Here's some code to prove it works:
Create a new Phone Application.
Add the following to the content grid
```
<ListBox Height="276" HorizontalAlignment="Left" Margin="14,84,0,0" Name="listBox1" VerticalAlignment="Top" Width="460" />
```
Then in the code behind, add the following:
```
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
this.listBox1.Items.Add(textBox1.Text);
}
}
``` | @Court from the answer you gave @Trees i can assume you are not really sure if the `KeyDown` is wired. Do you have the following code in the XAML file?
```
<TextBox Height="32" HorizontalAlignment="Left" Margin="13,-2,0,0" Name="textBox1" Text="" VerticalAlignment="Top" Width="433" KeyDown="textBox1_KeyDown" />
```
@Matt Lacey intercepting Enter from the PC's keyboard also works |
3,432,172 | The [following tutorial](http://tech-fyi.net/2010/07/21/wp7-hello-world/) shows how to take the text from a text box and display it in a text block when the user hits a button. Simple enough... but what I want to do is instead of hitting a button that adds the text I want the enter button to do it.
Searching here, I found the following code but it doesn't seem to do anything.
```
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
listBox.Items.Add(textBox.Text);
}
}
```
So, the textbox that has the string is called textbox and I want the text from that textbox to be added to my list (listBox). When I click the enter button, it does nothing. Any help? | 2010/08/07 | [
"https://Stackoverflow.com/questions/3432172",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/413528/"
] | You can intercept the enter key from the on screen keyboard, but not from the keyboard of a PC running the emulator.
Here's some code to prove it works:
Create a new Phone Application.
Add the following to the content grid
```
<ListBox Height="276" HorizontalAlignment="Left" Margin="14,84,0,0" Name="listBox1" VerticalAlignment="Top" Width="460" />
```
Then in the code behind, add the following:
```
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
this.listBox1.Items.Add(textBox1.Text);
}
}
``` | Looks like you need to handle the KeyUp event instead. |
4,277,070 | I'm writing a small PHP script to grab the latest half dozen Twitter status updates from a user feed and format them for display on a webpage. As part of this I need a regex replace to rewrite hashtags as hyperlinks to search.twitter.com. Initially I tried to use:
```
<?php
$strTweet = preg_replace('/(^|\s)#(\w+)/', '\1#<a href="http://search.twitter.com/search?q=%23\2">\2</a>', $strTweet);
?>
```
(taken from <https://gist.github.com/445729>)
In the course of testing I discovered that #test is converted into a link on the Twitter website, however #123 is not. After a bit of checking on the internet and playing around with various tags I came to the conclusion that a hashtag must contain alphabetic characters or an underscore in it somewhere to constitute a link; tags with only numeric characters are ignored (presumably to stop things like "Good presentation Bob, slide #3 was my favourite!" from being linked). This makes the above code incorrect, as it will happily convert #123 into a link.
I've not done much regex in a while, so in my rustyness I came up with the following PHP solution:
```
<?php
$test = 'This is a test tweet to see if #123 and #4 are not encoded but #test, #l33t and #8oo8s are.';
// Get all hashtags out into an array
if (preg_match_all('/(^|\s)(#\w+)/', $test, $arrHashtags) > 0) {
foreach ($arrHashtags[2] as $strHashtag) {
// Check each tag to see if there are letters or an underscore in there somewhere
if (preg_match('/#\d*[a-z_]+/i', $strHashtag)) {
$test = str_replace($strHashtag, '<a href="http://search.twitter.com/search?q=%23'.substr($strHashtag, 1).'">'.$strHashtag.'</a>', $test);
}
}
}
echo $test;
?>
```
It works; but it seems fairly long-winded for what it does. My question is, is there a single preg\_replace similar to the one I got from gist.github that will conditionally rewrite hashtags into hyperlinks ONLY if they DO NOT contain just numbers? | 2010/11/25 | [
"https://Stackoverflow.com/questions/4277070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517824/"
] | ```
(^|\s)#(\w*[a-zA-Z_]+\w*)
```
PHP
```
$strTweet = preg_replace('/(^|\s)#(\w*[a-zA-Z_]+\w*)/', '\1#<a href="http://twitter.com/search?q=%23\2">\2</a>', $strTweet);
```
This regular expression says a # followed by 0 or more characters [a-zA-Z0-9\_], followed by an alphabetic character or an underscore (1 or more), followed by 0 or more word characters.
<http://rubular.com/r/opNX6qC4sG> <- test it here. | I have devised this: `/(^|\s)#([[:alnum:]])+/gi` |
4,277,070 | I'm writing a small PHP script to grab the latest half dozen Twitter status updates from a user feed and format them for display on a webpage. As part of this I need a regex replace to rewrite hashtags as hyperlinks to search.twitter.com. Initially I tried to use:
```
<?php
$strTweet = preg_replace('/(^|\s)#(\w+)/', '\1#<a href="http://search.twitter.com/search?q=%23\2">\2</a>', $strTweet);
?>
```
(taken from <https://gist.github.com/445729>)
In the course of testing I discovered that #test is converted into a link on the Twitter website, however #123 is not. After a bit of checking on the internet and playing around with various tags I came to the conclusion that a hashtag must contain alphabetic characters or an underscore in it somewhere to constitute a link; tags with only numeric characters are ignored (presumably to stop things like "Good presentation Bob, slide #3 was my favourite!" from being linked). This makes the above code incorrect, as it will happily convert #123 into a link.
I've not done much regex in a while, so in my rustyness I came up with the following PHP solution:
```
<?php
$test = 'This is a test tweet to see if #123 and #4 are not encoded but #test, #l33t and #8oo8s are.';
// Get all hashtags out into an array
if (preg_match_all('/(^|\s)(#\w+)/', $test, $arrHashtags) > 0) {
foreach ($arrHashtags[2] as $strHashtag) {
// Check each tag to see if there are letters or an underscore in there somewhere
if (preg_match('/#\d*[a-z_]+/i', $strHashtag)) {
$test = str_replace($strHashtag, '<a href="http://search.twitter.com/search?q=%23'.substr($strHashtag, 1).'">'.$strHashtag.'</a>', $test);
}
}
}
echo $test;
?>
```
It works; but it seems fairly long-winded for what it does. My question is, is there a single preg\_replace similar to the one I got from gist.github that will conditionally rewrite hashtags into hyperlinks ONLY if they DO NOT contain just numbers? | 2010/11/25 | [
"https://Stackoverflow.com/questions/4277070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517824/"
] | ```
(^|\s)#(\w*[a-zA-Z_]+\w*)
```
PHP
```
$strTweet = preg_replace('/(^|\s)#(\w*[a-zA-Z_]+\w*)/', '\1#<a href="http://twitter.com/search?q=%23\2">\2</a>', $strTweet);
```
This regular expression says a # followed by 0 or more characters [a-zA-Z0-9\_], followed by an alphabetic character or an underscore (1 or more), followed by 0 or more word characters.
<http://rubular.com/r/opNX6qC4sG> <- test it here. | It's actually better to search for characters that aren't allowed in a hashtag otherwise tags like "#Trentemøller" wont work.
The following works well for me...
```
preg_match('/([ ,.]+)/', $string, $matches);
``` |
4,277,070 | I'm writing a small PHP script to grab the latest half dozen Twitter status updates from a user feed and format them for display on a webpage. As part of this I need a regex replace to rewrite hashtags as hyperlinks to search.twitter.com. Initially I tried to use:
```
<?php
$strTweet = preg_replace('/(^|\s)#(\w+)/', '\1#<a href="http://search.twitter.com/search?q=%23\2">\2</a>', $strTweet);
?>
```
(taken from <https://gist.github.com/445729>)
In the course of testing I discovered that #test is converted into a link on the Twitter website, however #123 is not. After a bit of checking on the internet and playing around with various tags I came to the conclusion that a hashtag must contain alphabetic characters or an underscore in it somewhere to constitute a link; tags with only numeric characters are ignored (presumably to stop things like "Good presentation Bob, slide #3 was my favourite!" from being linked). This makes the above code incorrect, as it will happily convert #123 into a link.
I've not done much regex in a while, so in my rustyness I came up with the following PHP solution:
```
<?php
$test = 'This is a test tweet to see if #123 and #4 are not encoded but #test, #l33t and #8oo8s are.';
// Get all hashtags out into an array
if (preg_match_all('/(^|\s)(#\w+)/', $test, $arrHashtags) > 0) {
foreach ($arrHashtags[2] as $strHashtag) {
// Check each tag to see if there are letters or an underscore in there somewhere
if (preg_match('/#\d*[a-z_]+/i', $strHashtag)) {
$test = str_replace($strHashtag, '<a href="http://search.twitter.com/search?q=%23'.substr($strHashtag, 1).'">'.$strHashtag.'</a>', $test);
}
}
}
echo $test;
?>
```
It works; but it seems fairly long-winded for what it does. My question is, is there a single preg\_replace similar to the one I got from gist.github that will conditionally rewrite hashtags into hyperlinks ONLY if they DO NOT contain just numbers? | 2010/11/25 | [
"https://Stackoverflow.com/questions/4277070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517824/"
] | ```
(^|\s)#(\w*[a-zA-Z_]+\w*)
```
PHP
```
$strTweet = preg_replace('/(^|\s)#(\w*[a-zA-Z_]+\w*)/', '\1#<a href="http://twitter.com/search?q=%23\2">\2</a>', $strTweet);
```
This regular expression says a # followed by 0 or more characters [a-zA-Z0-9\_], followed by an alphabetic character or an underscore (1 or more), followed by 0 or more word characters.
<http://rubular.com/r/opNX6qC4sG> <- test it here. | I found Gazlers [answer](https://stackoverflow.com/a/4277114/1050507) to work, although the regex added a blank space at the beginning of the hashtag, so I removed the first part:
```
(^|\s)
```
This works perfectly for me now:
```
#(\w*[a-zA-Z_0-9]+\w*)
```
Example here: <http://rubular.com/r/dS2QYZP45n> |
4,277,070 | I'm writing a small PHP script to grab the latest half dozen Twitter status updates from a user feed and format them for display on a webpage. As part of this I need a regex replace to rewrite hashtags as hyperlinks to search.twitter.com. Initially I tried to use:
```
<?php
$strTweet = preg_replace('/(^|\s)#(\w+)/', '\1#<a href="http://search.twitter.com/search?q=%23\2">\2</a>', $strTweet);
?>
```
(taken from <https://gist.github.com/445729>)
In the course of testing I discovered that #test is converted into a link on the Twitter website, however #123 is not. After a bit of checking on the internet and playing around with various tags I came to the conclusion that a hashtag must contain alphabetic characters or an underscore in it somewhere to constitute a link; tags with only numeric characters are ignored (presumably to stop things like "Good presentation Bob, slide #3 was my favourite!" from being linked). This makes the above code incorrect, as it will happily convert #123 into a link.
I've not done much regex in a while, so in my rustyness I came up with the following PHP solution:
```
<?php
$test = 'This is a test tweet to see if #123 and #4 are not encoded but #test, #l33t and #8oo8s are.';
// Get all hashtags out into an array
if (preg_match_all('/(^|\s)(#\w+)/', $test, $arrHashtags) > 0) {
foreach ($arrHashtags[2] as $strHashtag) {
// Check each tag to see if there are letters or an underscore in there somewhere
if (preg_match('/#\d*[a-z_]+/i', $strHashtag)) {
$test = str_replace($strHashtag, '<a href="http://search.twitter.com/search?q=%23'.substr($strHashtag, 1).'">'.$strHashtag.'</a>', $test);
}
}
}
echo $test;
?>
```
It works; but it seems fairly long-winded for what it does. My question is, is there a single preg\_replace similar to the one I got from gist.github that will conditionally rewrite hashtags into hyperlinks ONLY if they DO NOT contain just numbers? | 2010/11/25 | [
"https://Stackoverflow.com/questions/4277070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517824/"
] | It's actually better to search for characters that aren't allowed in a hashtag otherwise tags like "#Trentemøller" wont work.
The following works well for me...
```
preg_match('/([ ,.]+)/', $string, $matches);
``` | I have devised this: `/(^|\s)#([[:alnum:]])+/gi` |
4,277,070 | I'm writing a small PHP script to grab the latest half dozen Twitter status updates from a user feed and format them for display on a webpage. As part of this I need a regex replace to rewrite hashtags as hyperlinks to search.twitter.com. Initially I tried to use:
```
<?php
$strTweet = preg_replace('/(^|\s)#(\w+)/', '\1#<a href="http://search.twitter.com/search?q=%23\2">\2</a>', $strTweet);
?>
```
(taken from <https://gist.github.com/445729>)
In the course of testing I discovered that #test is converted into a link on the Twitter website, however #123 is not. After a bit of checking on the internet and playing around with various tags I came to the conclusion that a hashtag must contain alphabetic characters or an underscore in it somewhere to constitute a link; tags with only numeric characters are ignored (presumably to stop things like "Good presentation Bob, slide #3 was my favourite!" from being linked). This makes the above code incorrect, as it will happily convert #123 into a link.
I've not done much regex in a while, so in my rustyness I came up with the following PHP solution:
```
<?php
$test = 'This is a test tweet to see if #123 and #4 are not encoded but #test, #l33t and #8oo8s are.';
// Get all hashtags out into an array
if (preg_match_all('/(^|\s)(#\w+)/', $test, $arrHashtags) > 0) {
foreach ($arrHashtags[2] as $strHashtag) {
// Check each tag to see if there are letters or an underscore in there somewhere
if (preg_match('/#\d*[a-z_]+/i', $strHashtag)) {
$test = str_replace($strHashtag, '<a href="http://search.twitter.com/search?q=%23'.substr($strHashtag, 1).'">'.$strHashtag.'</a>', $test);
}
}
}
echo $test;
?>
```
It works; but it seems fairly long-winded for what it does. My question is, is there a single preg\_replace similar to the one I got from gist.github that will conditionally rewrite hashtags into hyperlinks ONLY if they DO NOT contain just numbers? | 2010/11/25 | [
"https://Stackoverflow.com/questions/4277070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517824/"
] | It's actually better to search for characters that aren't allowed in a hashtag otherwise tags like "#Trentemøller" wont work.
The following works well for me...
```
preg_match('/([ ,.]+)/', $string, $matches);
``` | I found Gazlers [answer](https://stackoverflow.com/a/4277114/1050507) to work, although the regex added a blank space at the beginning of the hashtag, so I removed the first part:
```
(^|\s)
```
This works perfectly for me now:
```
#(\w*[a-zA-Z_0-9]+\w*)
```
Example here: <http://rubular.com/r/dS2QYZP45n> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.