qid int64 10 74.7M | question stringlengths 15 26.2k | date stringlengths 10 10 | metadata list | response_j stringlengths 27 28.1k | response_k stringlengths 23 26.8k |
|---|---|---|---|---|---|
31,860 | To force myself and collaborators to only use AMS-Math commands, I load this package in the preamble:
```
\usepackage[all,warning]{onlyamsmath}
```
However, when this is combined with `TikZ`, I get into trouble when using TikZ's calc library, as this involves using `$` for computations. How can I resolve this conflict?
MWE: Try uncommenting `onlyamsmath`
```
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{tikz}
\usetikzlibrary{positioning,calc}
\usepackage[all,warning]{onlyamsmath}
\begin{document}
\begin{tikzpicture}
\node (node1) [] {Box 2 text};
\node (node2) [right=of node1] {Box 3 text};
\draw[->] (node2.north) -- ++(0,0.5) -| ($ (node1.east) + (0.25,0) $);
\end{tikzpicture}
\end{document}
``` | 2011/10/17 | [
"https://tex.stackexchange.com/questions/31860",
"https://tex.stackexchange.com",
"https://tex.stackexchange.com/users/1183/"
] | You could adjust the catcode of the `$` within the `tikzpicture` environment as follows:
```
\documentclass{article}
\usepackage[all,warning]{onlyamsmath}
\usepackage{tikz}
\usetikzlibrary{calc}
\makeatletter
\let\@@tikzpicture\tikzpicture
\def\tikzpicture{\catcode`\$=3 \@@tikzpicture}
\makeatother
\begin{document}
\begin{tikzpicture}
\draw [red,ultra thick] (0,0) -- ($(2,0)+(2,2)$);
\end{tikzpicture}
\end{document}
```
I have tested this solution (as well as @egreg's) with your MWE and both solutions seem to work fine. | The `$$` protection from `onlyamsmath` makes lots of problems, not only with `tikz` (see e.g. this [question](https://tex.stackexchange.com/questions/59984/use-mathematical-equation-in-caption-with-onlyamsmath)).
To disable this incompatible feature, but not the other protections from `onlyamsmath`, add to your preamble *after* loading `onlyamsmath`.
```
\AtBeginDocument{\catcode`\$=3}
``` |
504,358 | Hello and thank you for any help.
I have a Lenovo Yoga 11s and I wanted to try out using Ubuntu on it. I have used Linux a little bit in the past, but I would still consider myself a complete novice at it.
I went through the process of making the bootable USB drive and also made a separate partition for me to install Ubuntu on. Somehow I must have selected an option that wiped the whole drive and installed Ubuntu instead of just on the partition I had made. (I installed 14.04 if that helps)
So once that happened, I tried using the Lenovo recovery button, called "OneKey", on my computer but that just takes me to the "GRUB" menu that has Ubuntu options. I have checked the hard drive and it appears that there are no longer any Windows partitions present.
The hard drive partitions that I see on GParted are:
* sda1, fat32, /boot/efi, size: 512MiB, used: 4.36MiB
* sda2, ext4, size: 114.86GiB, used: 10.82GiB
* sda3, linux-swap, size:3.88Gib, used: 4.00 KiB
I don't really have any crucial data that was on there, but I just want to have a working copy of Windows available for use since that is what I am most comfortable with.
I tried calling Lenovo support but they said that I would have to buy a recovery disc, which costs $70.
Please let me know if there is any other information that I could give you to further assist me.
Thank you! | 2014/07/29 | [
"https://askubuntu.com/questions/504358",
"https://askubuntu.com",
"https://askubuntu.com/users/310436/"
] | Credit to kraxor's comment on the original question:
You should try reinstalling `iptables` by executing the following command:
```
sudo apt-get --reinstall install iptables
``` | Use following command:
```
sudo apt-get update
sudo apt-get install iptables-persistent
```
and it will install the `iptables-persistent` package for you. |
44,210,656 | I would like to install the modules 'mutagen' and 'gTTS' for my code, but I want to have it so it will install the modules on every computer that doesn't have them, but it won't try to install them if they're already installed. I currently have:
```
def install(package):
pip.main(['install', package])
install('mutagen')
install('gTTS')
from gtts import gTTS
from mutagen.mp3 import MP3
```
However, if you already have the modules, this will just add unnecessary clutter to the start of the program whenever you open it. | 2017/05/26 | [
"https://Stackoverflow.com/questions/44210656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7781906/"
] | you can use simple try/except:
```py
try:
import mutagen
print("module 'mutagen' is installed")
except ModuleNotFoundError:
print("module 'mutagen' is not installed")
# or
install("mutagen") # the install function from the question
``` | If you would like to preview if a specific package (or some) are installed or not maybe you can use the idle in python.
Specifically :
1. Open IDLE
2. Browse to File > Open Module > Some Module
3. IDLE will either display the module or will prompt an error message.
Above is tested with python 3.9.0 |
4,603,859 | I have this Dispose method I want to change. (Yeah I should check every object for null, I know)
```
protected override void Dispose(bool disposing)
{
if( disposing )
{
if( monthLineBrush != null)
monthLineBrush.Dispose();
monthHeaderLineBrush.Dispose();
shadowBrush.Dispose();
monthHeaderLineBrushDark.Dispose();
monthFontBrush.Dispose();
weekendBgBrush.Dispose();
whiteBrush.Dispose();
dayFontBrush.Dispose();
chartBrush.Dispose();
chartWarningBrush.Dispose();
barBrush.Dispose();
monthLinePen.Dispose();
monthHeaderLinePen.Dispose();
monthHeaderLinePenDark.Dispose();
warningLinePen.Dispose();
monthFont.Dispose();
yearFont.Dispose();
weekLinePen.Dispose();
dayLinePen.Dispose();
tooltip.Dispose();
toolTipLabel.Dispose();
}
base.Dispose(disposing);
}
```
VS uses a System.ComponentModel.IContainer object named components , and only disposes this components object. Yet I can't find any code where the different objects are added to the components objedct ??
```
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
```
How does this work ? | 2011/01/05 | [
"https://Stackoverflow.com/questions/4603859",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/171953/"
] | **The code to add each object that is created to the `components` container is automatically generated and added to the `*.Designer.cs` file associated with each form by the designer.**
For example, the `Form1.Designer.cs` file might look something like this in a brand new, empty project once you've added a `ToolTip` control to the form:
```
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.SuspendLayout();
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 264);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
```
There are two relevant lines of code in that whole mess, the two that appear at the very top:
```
this.components = new System.ComponentModel.Container();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
```
The first line creates a [`System.ComponentModel.Container`](http://msdn.microsoft.com/en-us/library/system.componentmodel.container.aspx) object called `components`, to which all of the components that implement `IDisposable` will be added when they are created.
The second line creates a `ToolTip` object (in response to one being drug to the form's surface during design time), and uses a [constructor overload](http://msdn.microsoft.com/en-US/library/5d6h5z2z.aspx) that accepts a parameter of type `IContainer`.
Extending this same song and dance to the other components that are added to your form allows them all to be disposed at one go with the [`Dispose` method](http://msdn.microsoft.com/en-us/library/7b22tcd4.aspx) provided by the `components` container. | For who cares, I just added a "DisposeIfNotNull" method. Writing my own IContainer seems overkill, since I'll then too will have to manually add the objects to the container ...
```
protected override void Dispose(bool disposing)
{
if( disposing )
{
DisposeIfNotNull(monthLineBrush);
DisposeIfNotNull(monthLineBrush);
DisposeIfNotNull(monthHeaderLineBrush);
DisposeIfNotNull(shadowBrush);
DisposeIfNotNull(monthHeaderLineBrushDark);
DisposeIfNotNull(monthFontBrush);
DisposeIfNotNull(weekendBgBrush);
DisposeIfNotNull(whiteBrush);
DisposeIfNotNull(dayFontBrush);
DisposeIfNotNull(chartBrush);
DisposeIfNotNull(chartWarningBrush);
DisposeIfNotNull(barBrush);
DisposeIfNotNull(monthLinePen);
DisposeIfNotNull(monthHeaderLinePen);
DisposeIfNotNull(monthHeaderLinePenDark);
DisposeIfNotNull(warningLinePen);
DisposeIfNotNull(monthFont);
DisposeIfNotNull(yearFont);
DisposeIfNotNull(weekLinePen);
DisposeIfNotNull(dayLinePen);
DisposeIfNotNull(tooltip);
DisposeIfNotNull(toolTipLabel);
}
base.Dispose(disposing);
}
private void DisposeIfNotNull(IDisposable objToDispose)
{
if (objToDispose != null)
objToDispose.Dispose();
}
``` |
2,445,874 | I am getting an error in an ajax call from jQuery.
Here is my jQuery function:
```
function DeleteItem(RecordId, UId, XmlName, ItemType, UserProfileId) {
var obj = {
RecordId: RecordId,
UserId: UId,
UserProfileId: UserProfileId,
ItemType: ItemType,
FileName: XmlName
};
var json = Sys.Serialization.JavaScriptSerializer.serialize(obj);
$.ajax({
type: "POST",
url: "EditUserProfile.aspx/DeleteRecord",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function(msg) {
if (msg.d != null) {
RefreshData(ItemType, msg.d);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("error occured during deleting");
}
});
}
```
and this is my `WebMethod`:
```cs
[WebMethod]
public static string DeleteRecord(Int64 RecordId, Int64 UserId, Int64 UserProfileId, string ItemType, string FileName) {
try {
string FilePath = HttpContext.Current.Server.MapPath(FileName);
XDocument xmldoc = XDocument.Load(FilePath);
XElement Xelm = xmldoc.Element("UserProfile");
XElement parentElement = Xelm.XPathSelectElement(ItemType + "/Fields");
(from BO in parentElement.Descendants("Record")
where BO.Element("Id").Attribute("value").Value == RecordId.ToString()
select BO).Remove();
XDocument xdoc = XDocument.Parse(Xelm.ToString(), LoadOptions.PreserveWhitespace);
xdoc.Save(FilePath);
UserInfoHandler obj = new UserInfoHandler();
return obj.GetHTML(UserId, UserProfileId, FileName, ItemType, RecordId, Xelm).ToString();
} catch (Exception ex) {
HandleException.LogError(ex, "EditUserProfile.aspx", "DeleteRecord");
}
return "success";
}
```
Can anybody please tell me what's wrong in my code?
I am getting this error:
```
{
"Message":"Invalid JSON primitive: RecordId.",
"StackTrace":"
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)
at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)
at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)
at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)
at System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)
at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)
at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)",
"ExceptionType":"System.ArgumentException"
}
``` | 2010/03/15 | [
"https://Stackoverflow.com/questions/2445874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/207817/"
] | Using
```
data : JSON.stringify(obj)
```
in the above situation would have worked I believe.
Note: You should add json2.js library all browsers don't support that JSON object (IE7-)
[Difference between json.js and json2.js](https://stackoverflow.com/questions/552135/difference-between-json-js-and-json2-js) | If manually formatting JSON, there is a very handy validator here: [jsonlint.com](http://jsonlint.com/)
Use double quotes instead of single quotes:
### Invalid:
```
{
'project': 'a2ab6ef4-1a8c-40cd-b561-2112b6baffd6',
'franchise': '110bcca5-cc74-416a-9e2a-f90a8c5f63a0'
}
```
### Valid:
```
{
"project": "a2ab6ef4-1a8c-40cd-b561-2112b6baffd6",
"franchise": "18e899f6-dd71-41b7-8c45-5dc0919679ef"
}
``` |
29,395,873 | I have an assignment and I cannot figure out this part.
The assignment requires that I create two separate functions and call them in the main. So my question is what is the syntax for calling a pointer to an array and how do I call that function in the main program? For example,
```
int function_1(int x, *array);
```
How would I call `function_1`? Or am I completely lost here?
I should add that anytime I try and call the function with the array, I get this error:
`[Warning] assignment makes pointer from integer without a cast [enabled by default]` | 2015/04/01 | [
"https://Stackoverflow.com/questions/29395873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4598281/"
] | ```
int function(int x, char *array)
{
//do some work
return 0;
}
```
And in main
```
int main()
{
char arr[5] = {'a', 'b', 'c', 'd'};
int x = 5;
function(x, &arr[0]);
return 0;
}
``` | Interestingly enough, arrays are already pointers in C. So if you want to pass an array as a pointer to your function, you just simply pass the array you declared! I gave a little example below, although, I don't know what your code is supposed to do. I passed `function_1(...)` the number 12, and then the array pointer.
```
int function_1(int x, *array)
{
...
}
int main()
{
//declare a ten element integer array
int arr[10];
//calls the function, passing in 12 for the integer, and a pointer to the array.
function_1(12, arr);
...
return 0;
}
```
I hope this clears it up a little. The method of using the square brackets with arrays `[]` is actually something you can do with all pointers in C.You don't really need to consider that part too much yet, but just remember that arrays are already pointers, so you don't need to do anything else to pass them as pointers. In fact, you could rewrite your function to just use an array as an argument, like this, rather than using a `*` for pointers:
```
int function_1(int x, int array[])
{
...
}
``` |
402,246 | When in shell (bash) - I want to have Ctrl-Backspace binded to "delete word backward". Is it possible?
**Edit**:
I'm using `konsole` - terminal at KDE. | 2012/03/17 | [
"https://superuser.com/questions/402246",
"https://superuser.com",
"https://superuser.com/users/84963/"
] | I found this thread via google, but the answer wasn't what I wanted to hear.
So I played around:
On my terminal, normal backspace sends `^H`, while ctrl+backspace sends `^?`.
So it should simple be a case of rebinding `^?` to delete a word, which by default is available via Ctrl+W.
### First (unsuccessful try):
```
$ bind -P | grep 'C-w'
unix-word-rubout can be found on "\C-w".
```
So therefore this should work:
```
$ bind '"\C-?":unix-word-rubout'
```
However it does not... anyone able to explain?
### Second (successful) try:
```
$ bind '"\C-?":"^W"'
```
Where the `^W` is a literal/raw `^W` (press ctrl+V then ctrl+W to make it appear). | There are some good answers here, but I solved it in Konsole with Settings->Edit Current Profile->Keyboard->Edit, then adding a mapping from `Backspace+Control` to `\x17`. (I found the ASCII code for Ctrl-w using `showkey --ascii`.) |
6,001,464 | I have a three different folders (css, js, images)placed where the system, application, user\_guide folders live.. Now I am trying to include those files in my header\_view.php like below:
```
<link rel="stylesheet" href="<?php echo base_url()?>/css/styles.css" type="text/css" media="screen">
<link rel="stylesheet" href="<?php echo base_url()?>/css/layout.css" type="text/css" media="screen">
```
Then in my view file I am including the header file like this
```
$this->load->view('header_view');
```
None of the css styles are showing..
Can someone please help me with this? thanks alot... | 2011/05/14 | [
"https://Stackoverflow.com/questions/6001464",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/684972/"
] | In ios UITableView you can only have one column/cell. If you want more propertyes, in a same cell you need to create a custom table view cell by subcalssing UITableViewCell. In interface builder you can customize the layout. TUTORIAL: <http://adeem.me/blog/2009/05/30/iphone-sdk-tutorial-part-6-creating-custom-uitableviewcell-using-interface-builder-uitableview/>
Concrete example for your problem:
the .h file:
```
#import <UIKit/UIKit.h>
@interface MyCell : UITableViewCell {
UIButton * column1;
UIButton * column2;
UILabel* column1_label1;
UILabel* column1_label2;
UILabel* column2_label1;
UILabel* column2_label2;
}
@property (nonatomic,retain) UIButton * column1;
@property (nonatomic,retain) UIButton * column2;
@property (nonatomic,retain) UILabel* column1_label1;
@property (nonatomic,retain) UILabel* column1_label2;
@property (nonatomic,retain) UILabel* column2_label1;
@property (nonatomic,retain) UILabel* column2_label2;
@end
```
the .m file:
```
#import "MyCell.h"
@implementation MyCell
@synthesize column1,column1_label1,column1_label2,column2,column2_label1,column2_label2;
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
column1 = [UIButton buttonWithType: UIButtonTypeCustom];
column1.tag = 1;
column1.autoresizingMask = 292;
column1.backgroundColor = [UIColor redColor];
column1.frame = CGRectMake(0, 0, self.contentView.bounds.size.width/2, self.contentView.bounds.size.height);
column1_label1 = [[UILabel alloc] initWithFrame: CGRectMake(column1.bounds.size.width*1/5,
0,
column1.bounds.size.width*4/5,
column1.bounds.size.height/2)];
column1_label1.backgroundColor = [UIColor redColor];
[column1 addSubview:column1_label1];
column1_label2 = [[UILabel alloc] initWithFrame: CGRectMake(column1.bounds.size.width*1/5,
column1.bounds.size.height/2,
column1.bounds.size.width*4/5,
column1.bounds.size.height/2)];
column1_label2.backgroundColor = [UIColor greenColor];
[column1 addSubview:column1_label2];
[self.contentView addSubview: column1];
column2 = [UIButton buttonWithType: UIButtonTypeCustom];
column2.tag = 2;
column2.autoresizingMask = 292;
column2.backgroundColor = [UIColor greenColor];
column2.frame = CGRectMake(self.contentView.bounds.size.width/2, 0, self.contentView.bounds.size.width/2, self.contentView.bounds.size.height);
column2_label1 = [[UILabel alloc] initWithFrame: CGRectMake(column2.bounds.size.width*1/5,
0,
column2.bounds.size.width*4/5,
column2.bounds.size.height/2)];
column2_label1.backgroundColor = [UIColor redColor];
[column2 addSubview:column2_label1];
column2_label2 = [[UILabel alloc] initWithFrame: CGRectMake(column2.bounds.size.width*1/5,
column2.bounds.size.height/2,
column2.bounds.size.width*4/5,
column2.bounds.size.height/2)];
column2_label2.backgroundColor = [UIColor greenColor];
[column2 addSubview:column2_label2];
[self.contentView addSubview: column2];
}
return self;
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
[super setSelected:selected animated:animated];
// Configure the view for the selected state
}
- (void)dealloc
{
[super dealloc];
}
@end
```
the usage in UITableViewController:
```
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return 40;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
MyCell * mycell2 = ((MyCell*)cell);
if (cell == nil) {
cell = [[[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
[mycell2.column1 addTarget:self action:@selector(column1Selected:) forControlEvents:UIControlEventTouchUpInside];
[mycell2.column2 addTarget:self action:@selector(column1Selected:) forControlEvents:UIControlEventTouchUpInside];
}
// Configure the cell...
mycell2.column1_label1.text = @"column1_label1";
mycell2.column1_label2.text = @"column1_label2";
mycell2.column1.tag = indexPath.row*2;
mycell2.column2_label1.text = @"column2_label1";
mycell2.column2_label2.text = @"column2_label2";
mycell2.column2.tag = indexPath.row*2 +1;
return cell;
}
- (void) column1Selected: (id) sender
{
UIAlertView *alert = [[ UIAlertView alloc]
initWithTitle: @" Alert"
message: [NSString stringWithFormat: @"button %d",((UIButton *) sender).tag]
delegate: nil
cancelButtonTitle: @" OK"
otherButtonTitles: nil];
[alert show] ;
[alert release];
}
``` | In iOS6 you can use the [UICollectionView](http://developer.apple.com/library/ios/#documentation/uikit/reference/UICollectionView_class/Reference/Reference.html).
If you need iOS5 support [AQGridView](https://github.com/AlanQuatermain/AQGridView) is a grid control that will give you what you are after. |
48,794,897 | In MySQL, it is fairly easy to find the number of records that exist within some time interval.
```
SELECT COUNT(*) FROM records WHERE create_date > '2018-01-01 01:15:00' AND create_date < '2018-01-01 02:15:00'
```
But I want to do the opposite, sort of. Rather than providing a time interval and getting a count of records, I want to provide a count of records and check if a X minute time interval exists where more than Y many records were created. Getting the exact time interval is not essential, only if one exists or not. At a higher level, I am attempting to identify if there was any X minute "surge" when more than Y records where created during the course of a day.
For example, in the past 24 hours was there any 1 hour interval where a "surge" of more than 50 new records occurred?
I have already ruled out dividing the 24 hours into blocks of 1 hour intervals and checking each block. This does not work because the "surge" could span two sequential 1 hour blocks, such as 25 records at the end of the 01:00:00 block and 25 records at the beginning of the 02:00:00 block. | 2018/02/14 | [
"https://Stackoverflow.com/questions/48794897",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/446738/"
] | The kotlinx.coroutines library actually makes use of multiplatform projects since it supports both the JVM and JS compilation targets.
You can find the common module [here](https://github.com/Kotlin/kotlinx.coroutines/tree/master/kotlinx-coroutines-core/common), and the specific `expect` declarations for the functions you've mentioned [here](https://github.com/Kotlin/kotlinx.coroutines/blob/master/kotlinx-coroutines-core/common/src/Builders.common.kt). | While the source code in the other answer helped, I found [this page](https://kotlinlang.org/docs/multiplatform-connect-to-apis.html) (linked off of the page @jim-andreas mentioned in the comments above) was much more helpful.
Specifically, this passage:
>
> If you're developing a multiplatform application that needs to access platform-specific APIs that implement the required functionality (for example, generating a UUID), use the Kotlin mechanism of *expected* and *actual declarations*.
>
>
> With this mechanism, a common source set defines an *expected
> declaration*, and platform source sets must provide the *actual
> declaration* that corresponds to the expected declaration. This works
> for most Kotlin declarations, such as functions, classes, interfaces,
> enumerations, properties, and annotations.
>
>
> [](https://i.stack.imgur.com/9kRFR.png)
>
>
> The compiler ensures that every declaration marked with the `expect` keyword in the common module has the corresponding declarations marked with the `actual` keyword in all platform modules. The IDE provides tools that help you create the missing actual declarations.
>
>
>
Again, for more information, you can visit [this page](https://kotlinlang.org/docs/multiplatform-connect-to-apis.html). |
5,176 | Some of my larger annealer embeddings (~200 qubits) don't anneal down to the ground state while some of them do very easily.
Are there established guidelines for designing annealer embeddings to ensure that ground state configurations can be easily found? If so, where can this information be found?
If not, is addressing this issue more a matter of properly setting annealer parameters/annealing schedule. What are some good papers with information on this? | 2019/01/11 | [
"https://quantumcomputing.stackexchange.com/questions/5176",
"https://quantumcomputing.stackexchange.com",
"https://quantumcomputing.stackexchange.com/users/4943/"
] | A necessary and sufficient condition is that, given an $n\times n$ matrix $M$, you can construct a $2n\times 2n$ unitary matrix $U$ provided the singular values of $M$ are all upper bounded by 1.
Sufficiency
===========
To see this, express the singular value decomposition of $M$ as
$$
M=RDV
$$
where $D$ is diagonal and $R$, $V$ are unitary. Now define
$$
U=\left(\begin{array}{cc}
M & R\sqrt{\mathbb{I}-D^2}V \\
R\sqrt{\mathbb{I}-D^2}V & -M
\end{array}\right),
$$
which we can only do if the singular values are no larger than 1. Let's verify that it's unitary
\begin{align\*}
UU^\dagger&=\left(\begin{array}{cc}
RDV & R\sqrt{\mathbb{I}-D^2}V \\
R\sqrt{\mathbb{I}-D^2}V & -RDV
\end{array}\right)\left(\begin{array}{cc}
V^\dagger DR^\dagger & V^\dagger\sqrt{\mathbb{I}-D^2}R^\dagger \\
V^\dagger\sqrt{\mathbb{I}-D^2}R^\dagger & -V^\dagger DR^\dagger
\end{array}\right) \\
&=\left(\begin{array}{cc}
RD^2R^\dagger+R(\mathbb{I}-D^2)R^\dagger & 0 \\
0 & RD^2R^\dagger+R(\mathbb{I}-D^2)R^\dagger
\end{array}\right) \\
&=\mathbb{I}.
\end{align\*}
Necessity
=========
Imagine I have a matrix $M$ with a singular value $\lambda>1$ and corresponding normalised vector $|\lambda\rangle$. Assume I construct a unitary
$$
U=\left(\begin{array}{cc} M & A \\ B & C \end{array}\right).
$$
Let's act $U$ on the state $\left(\begin{array}{c} |\lambda\rangle \\ 0 \end{array}\right)$. We get
$$
U\left(\begin{array}{c} |\lambda\rangle \\ 0 \end{array}\right)=\left(\begin{array}{c} M|\lambda\rangle \\ B|\lambda\rangle \end{array}\right).
$$
This output state must have a norm that is at least the norm of $M|\lambda\rangle$, i.e. $\lambda>1$. But if $U$ is a unitary, the norm must be 1. So it must be impossible to perform such a construction if there exists a singular value $\lambda>1$. | Here's a solution that follows a slightly different idea, but provides the precise number of rows that need to be added to get a unitary matrix.
Let $M$ be an arbitrary $n\times m$ matrix. As a first observation, note that the task of adding rows/columns can be reduced to that of adding rows to get $m$ orthonormal columns. Indeed, once this is done, we get an isometry, which one can then trivially make into a unitary by simply building an orthonormal basis from the orthonormal columns in the usual way (Gram-Schmidt etc).
We thus want to figure out when it is possible to add rows to $M$ to obtain orthonormal columns, and when it is possible, exactly how many rows need to be added.
Call $S$ the block of rows added to $M$. If we are adding $s$ rows, then $S$ is an $s\times m$ matrix. Note that the full ($M$ with $S$ added) matrix is an isometry ***iff***
$$M^\dagger M + S^\dagger S = I\_{m\times m}
\Longleftrightarrow S^\dagger S = I\_{m\times m}-M^\dagger M.$$
Now, thinking in terms of SVDs, observe how this means that this is possible ***iff*** the singular values of $M$ are all in the range $[0,1]$.
Furthermore, we can now also say that the singular values of $S$, call these $s\_k$, must be $s\_k=\sqrt{1-m\_k^2}$, with $m\_k$ the singular values of $M$.
In summary, we found that $S$ must be a matrix whose singular values are $\sqrt{1-m\_k^2}$. More precisely, multiplicity needs to be also matched here: *e.g.* if $M$ has a two-fold degenerate singular value $0.5$, then $S$ needs to have a two-fold degenerate singular value $\sqrt{1-0.5^2}$.
This is telling us that $S$ needs to have rank equal to that of $I-M^\dagger M$, or in other words, $S$ needs to have a number of rows equal to the number of nonzero singular values of $M$. This is both necessary and sufficient, and once verified, building $S$ can be done taking as right singular vectors those of $M$ with nonzero singular values, and as left singular vectors an arbitrary orthonormal set in the relevant space.
As an easy sanity check, try taking an arbitrary set of orthonormal columns in whatever (sufficiently large) dimension you like. Observe how removing $k$ rows from the corresponding matrix, $I-M^\dagger M$ has precisely $k$ vanishing eigenvalues, implying that precisely $k$ rows need to be added to $M$ to get back an isometry. |
29,625,693 | I am accessing my database using model by using following code.
```
$persons = WysPerson::where('family_id', $id)->get();
```
I checked `$persons`is empty or not by using following code.
```
if($persons){
var_dump($persons);
}
```
Actually `$persons` is empty. But I am getting result for `var_dump` as
`object(Illuminate\Database\Eloquent\Collection)#417 (1) { ["items":protected]=> array(0) { } }`
How will I check `$persons` is empty? Can anyone help? | 2015/04/14 | [
"https://Stackoverflow.com/questions/29625693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3659972/"
] | try this.
```
is_null($var)?abort('empty'):abort('filled')
``` | You can use isEmpty() method.
At the same time you can check it by simply with count() method before once you fetch the data.
```
$count = WysPerson::where('family_id', $id)->count();
if($count==0){
return redirect()->back()->withErrors('Empty Data');
}
$persons = WysPerson::where('family_id', $id)->get();
``` |
59,242,176 | I have 3 tables
```
Product(id, sku, product_name)
product_sales_forecast_3(id,product_id)
product_sales_forecast_detail_3(id,product_sales_forecast,forecast,year)
```
`forecast` field in table `product_sales_forecast_detail_3` is a JSON,
it looks like:
>
> `{"25":{"qty":0},"26":{"qty":0},"27":{"qty":0},"28":{"qty":0},"29":{"qty":0},"30":{"qty":1},"31":{"qty":0},"32":{"qty":0},"33":{"qty":1},"34":{"qty":1},"35":{"qty":0},"36":{"qty":0},"37":{"qty":0},"38":{"qty":0},"39":{"qty":0},"40":{"qty":0},"41":{"qty":0},"42":{"qty":0},"43":{"qty":0},"47":{"qty":0},"48":{"qty":0},"49":{"qty":0},"50":{"qty":0},"51":{"qty":0},"52":{"qty":0}}`
>
>
>
In laravel controller I wrote:
```
$DataForecasts=DB::table('product_sales_forecast_3')
->join('product_sales_forecast_detail_3','product_sales_forecast_3.id',
"=",'product_sales_forecast_detail_3.product_sales_forecast_id')
->join('products','products.id','=','product_sales_forecast_3.product_id')
->select('product_sales_forecast_detail_3.forecast')
->where([
['product_sales_forecast_3.channel','=', $AVCWHStoreID],
['products.product_sku','=', $sku],
['product_sales_forecast_detail_3.year','=', 2019]
])->get();
$objs = json_decode($DataForecasts);
foreach($objs as $obj)
{
dd($obj);
}
```
The result is:
>
> `{#1457 ▼ +"forecast":
> "{"1":{"qty":145},"2":{"qty":0},"3":{"qty":0},"4":{"qty":0},"5":{"qty":0},"6":{"qty":0},"7":{"qty":58},"8":{"qty":69},"9":{"qty":74},"10":{"qty":97},"11":{"qty":69},"12":{"qty":69},"13":{"qty":74},"14":{"qty":95},"15":{"qty":94},"16":{"qty":93},"17":{"qty":87},"18":{"qty":85},"19":{"qty":79},"20":{"qty":80},"21":{"qty":77},"22":{"qty":64},"23":{"qty":68},"24":{"qty":63},"25":{"qty":63},"26":{"qty":60},"27":{"qty":70},"28":{"qty":83},"29":{"qty":99},"30":{"qty":86},"31":{"qty":29},"32":{"qty":68},"33":{"qty":68},"34":{"qty":62},"35":{"qty":63},"36":{"qty":66},"37":{"qty":66},"38":{"qty":65},"39":{"qty":55},"40":{"qty":39},"41":{"qty":63},"42":{"qty":52},"43":{"qty":52},"44":{"qty":47},"45":{"qty":64},"46":{"qty":74},"47":{"qty":80},"48":{"qty":105},"49":{"qty":102},"50":{"qty":106},"51":{"qty":88},"52":{"qty":68}}
> ◀"`}
>
>
>
I try to access a value but I don't know how to access the values. | 2019/12/09 | [
"https://Stackoverflow.com/questions/59242176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8577943/"
] | **Try this ...**
```
<?php
$objs = '{
"forecast":
{
"1":{"qty":145}
,"2":{"qty":0}
,"3":{"qty":0}
,"4":{"qty":0}
,"5":{"qty":0}
,"6":{"qty":0}
,"7":{"qty":58}
,"8":{"qty":69}
,"9":{"qty":74}
,"10":{"qty":97}
,"11":{"qty":69}
,"12":{"qty":69}
,"13":{"qty":74}
,"14":{"qty":95}
,"15":{"qty":94}
,"16":{"qty":93}
,"17":{"qty":87}
,"18":{"qty":85}
,"19":{"qty":79}
,"20":{"qty":80}
,"21":{"qty":77}
,"22":{"qty":64}
,"23":{"qty":68}
,"24":{"qty":63}
,"25":{"qty":63}
,"26":{"qty":60}
,"27":{"qty":70}
,"28":{"qty":83}
,"29":{"qty":99}
,"30":{"qty":86}
,"31":{"qty":29}
,"32":{"qty":68}
,"33":{"qty":68}
,"34":{"qty":62}
,"35":{"qty":63}
,"36":{"qty":66}
,"37":{"qty":66}
,"38":{"qty":65}
,"39":{"qty":55}
,"40":{"qty":39}
,"41":{"qty":63}
,"42":{"qty":52}
,"43":{"qty":52}
,"44":{"qty":47}
,"45":{"qty":64}
,"46":{"qty":74}
,"47":{"qty":80}
,"48":{"qty":105}
,"49":{"qty":102}
,"50":{"qty":106}
,"51":{"qty":88}
,"52":{"qty":68}
}
}';
$objs = json_decode($objs);
foreach($objs->forecast as $key=>$val)
{
//var_dump($key); // $key will be week
//var_dump ($val->qty); // qty here
}
```
**If array , change foreach loop like following code ..**
```
foreach($objs['forecast'] as $key=>$val)
{
// var_dump($key); // $key will be week
// var_dump ($val['qty']); qty here
}
``` | **Change in your controller like ...**
```
$DataForecasts=DB::table('product_sales_forecast_3')
->join('product_sales_forecast_detail_3','product_sales_forecast_3.id',
"=",'product_sales_forecast_detail_3.product_sales_forecast_id')
->join('products','products.id','=','product_sales_forecast_3.product_id')
->select('product_sales_forecast_detail_3.forecast')
->where([
['product_sales_forecast_3.channel','=', $AVCWHStoreID],
['products.product_sku','=', $sku],
['product_sales_forecast_detail_3.year','=', 2019]
])->get()->toArray();
$objs = json_decode($DataForecasts['forecast'],true);
foreach($objs as $key=>$val)
{
var_dump($key) // week here
var_dump($val['qty'])
}
``` |
21,703,547 | I've a little problem.
I use modrewrite to load language-content dynamically into webpage...
example:
www.mydomain.xyz/en (the english version)
www.mydomain.xyz/fr (the french version)
...
My .htaccess:
```
RewriteRule ^en$ index.html?lang=en
```
But:
*www.mydomain.xyz/en?foo=bar*
and
```
<?php
if(isset($_GET["foo"])) {
echo "Yeah! There is some stuff!";
}
?>
```
doesn't work... the GET-Parameter is ignored. What I have to do?
* it works, with *www.meinedomain.xyz/en.html?foo=bar* but I don't want to display any Extensions. | 2014/02/11 | [
"https://Stackoverflow.com/questions/21703547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1736442/"
] | Use `QSA` flag:
```
RewriteRule ^en$ index.html?lang=en [L,QSA]
```
To make this work for en and fr use this:
```
RewriteRule ^(en|fr)/?$ index.html?lang=$1 [L,QSA]
```
* `QSA` (Query String Append) flag preserves existing query parameters while adding a new one. | You need the `[QSA]` instruction right after your rewrite rule
<http://httpd.apache.org/docs/current/mod/mod_rewrite.html>
QSA is "query string append" and preserves query strings on rewrite
I'd also recomment using (/|$) instead of just $, or calling `yourdomain.com/ensomefile.php` would also result in rewriting
```
RewriteRule ^en(/|$) index.html?lang=en [QSA]
``` |
27,746,819 | I am trying to install and run a CakePHP 3.0 project on a shared host.
However, CakePHP 3.0 requires `php-intl` extension, but the hosting provider has denied me to install/enable `intl` extension on the shared hosting.
How can I run CakePHP 3.0 without `intl` extension ?
Is there anyway to disable it in CakePHP? Or is there any alternative that I can use ?
I am into a big trouble. Please help... | 2015/01/02 | [
"https://Stackoverflow.com/questions/27746819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2143117/"
] | In both XAMPP and WAMP, mcrypt and mbstring extensions are working by default.
In XAMPP, intl extension is included but you have to uncomment extension=php\_intl.dll in php.ini and restart the server through the XAMPP Control Panel.
In WAMP, the intl extension is “activated” by default but not working. To make it work you have to go to php folder (by default) C:\wamp\bin\php\php{version}, copy all the files that looks like icu\*.dll and paste them into the apache bin directory C:\wamp\bin\apache\apache{version}\bin. Then restart all services and it should be OK.
<http://book.cakephp.org/3.0/en/installation.html#requirements> | Just open php.ini file and look around below this line:
**[ExtensionList]**
You must see this line: **extension=php\_intl.dll**. if not, please add it :) |
5,893,392 | In short, when the property value changing, I have to update some logic in my code, for example:
```
- (void)setProp:(NSString *)theProp
{
if (prop != theProp){
[prop release];
prop = [theProp copy];
[self myLogic];
}
}
```
or:
```
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if ([keyPath isEqualToString:@"prop"]){
[self myLogic];
}
}
```
Which is the best way, and WHY?
EDIT: I prefect the second way, because I don't know what the compiler will generate `@synthesize` directive for me, I choose to believe the compiler is more smarter than my owe setter implementation, hence I will not break something. | 2011/05/05 | [
"https://Stackoverflow.com/questions/5893392",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/395213/"
] | Tough call, IMHO both options suck.
The first one forces you to write your own setter, which is a lot of boilerplate code. (Not to mention that you have to remember to also fire KVO notifications with `willChangeValueForKey:` and `didChangeValueForKey:` if you want KVO for the property in question to work.)
The second option is also quite heavy-weight and your implementation is not enough. What if your superclass also has some KVO in place? You’d have to call `super` somewhere in the handler. If not, are you sure your superclass won’t change? (More about KVO in a [related question](https://stackoverflow.com/questions/5866502).)
Sometimes you can sidestep the issue using other methods like bindings (if you’re on a Mac) or plain notifications (you can post a notification that a model changed and all interested parties should refresh).
If you have many recalculations like this and can’t find any better way around, I would try to write a superclass with better observing support, with interface like this:
```
[self addTriggerForKeyPath:@"foo" action:^{
NSLog(@"Foo changed.");
}];
```
This will take more work, but it will keep your classes cleanly separated and you can solve all KVO-related problems on one place. If there are not enough recalculated properties to make this worthwile, I usually go with the first solution (custom setter). | In your case the best option is to add the logic inside the setter. Your setter implementation is correct if your property declaration is something like
@property (nonatomic, copy) YCYourClass \*prop;
KVO is used normally when checking for changes on external objects properties.
NSNotifications are better suited to inform of events. |
1,578,070 | I'm making this tiny utility program (Windows Forms) and it would need to save a bit of data to the disk. In DB terms it would be about one table, no more than about couple thousand rows, each row being less then 1KB in size.
What would you use?
**Added:** Forgot to say - it would be really neat if the whole program would be just one .EXE file (plus the data file, of course). Thus I'd prefer something that is built in .NET. | 2009/10/16 | [
"https://Stackoverflow.com/questions/1578070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41360/"
] | You can create an array of your class, mark it [Serializable] and just use the built-in serialize/deserialize methods for persistence. | [Berkeley DB](http://en.wikipedia.org/wiki/Berkeley_DB) is also a good choice for embedded database. And there is a [library](http://sourceforge.net/projects/libdb-dotnet/) that provides a .NET 2.0 interface for it. |
2,726,195 | I have the equation: $$z^4 + 8z^3 + 16z^2 + 9 = 0$$
I need to find all the complex solutions and I've got no clue how to approach it. I've tried factoring but nothing came out of it. I'm still very new to the world of complex numbers so I'll appreciate any help. | 2018/04/07 | [
"https://math.stackexchange.com/questions/2726195",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/549828/"
] | If you substitute $$x=z+2$$ the equation turns into $$x^4-8x^2+25=0$$ which can be solved by a further substitution $y=x^2$ | $$z^2(z+4)^2 =9i^2$$
so $$z^2+4z-3i=0\;\;\;\;{\rm or}\;\;\;\;z^2+4z+3i=0$$
You have a discriminant $D = 2(3+i)^2$ in the first case and $D = 2(3-i)^2$ in the second case. |
18,407,860 | I recently typed out this java program to accept ten areas and their pin-codes and then search to find a particular area and print out it's pin-code.
Here's the code from the program :
```
import java.util.Scanner;
public class Sal {
public static void main (String args []){
Scanner s=new Scanner(System.in);
System.out.println("Enter 10 areas and their pincodes");
String area[]=new String [10];
int pincode[]=new int [10];
String search;
int chk=0;
int p=0;
for (int i=0;i<=9;i++){
area[i]=s.nextLine();
pincode[i]=s.nextInt();
}
System.out.println("Enter Search");
search=s.nextLine();
for (int j=0;j<=9;j++){
if(search==area[j]){
chk=1;
j=p;
break;
}
}
if(chk==1){
System.out.println("Search Found "+"Pincode : "+pincode[p] );
} else {
System.out.println("Search not Found");
}
}
}
```
And after entering two areas I get this ERROR:
```
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at Sal.main(Sal.java:14)
```
Can someone please tell me what I'm doing wrong! :/
Any help is appreciated. | 2013/08/23 | [
"https://Stackoverflow.com/questions/18407860",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2711784/"
] | From the docs for [`Scanner#nextInt()`](http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28%29):
>
> InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
>
>
>
So, it sounds like your `Scanner` is trying to read in an `int` but getting something that it can't turn into an `int` (either what it read is not a number or the number is too large).
You call the relevant function here:
```
for (int i=0;i<=9;i++){
area[i]=s.nextLine();
pincode[i]=s.nextInt(); // <-- the culprit
}
```
My guess is that at some point, your call to `.nextLine()` swallows up an entire line, and the next line starts with an "area". I can't do more without knowing how you expect the input to be formatted. | The input can not be parsed as an integer.
Maybe you have a comma at the end of line.
btw:
>
> if(search==area[j])
>
>
>
is bad practice to check string equality. use search.equals(area[j]) with null-check. |
47,094 | I am using the Earth-Sun distance to teach kids the usefulness of trigonometry. [This site](http://www.eso.org/public/outreach/eduoff/aol/market/collaboration/solpar/) is helpful.
But one of the more engaged asked what the most accurate measurement is. After some research, I found that elapsed time measurements of reflected radar returns seems to be the way we do it now. By measuring the distance to another planet this way and combining the parallax method, we can calculate accurate distance to the sun. But is this THE most accurate way to measure the AU? What is the error margin? If the AU were changing by .0000001 percent annually, could we detect it? | 2021/10/17 | [
"https://astronomy.stackexchange.com/questions/47094",
"https://astronomy.stackexchange.com",
"https://astronomy.stackexchange.com/users/33853/"
] | As mentioned in a comment, the AU is no longer measured, it is defined, as 149 597 870 700 metres, or exactly the distance that light travels in a vacuum in $499 \frac{9823}{2053373}$seconds.
But I suppose your question is about the accuracy of the measurement of the distance between the Earth and Sun.
As noted in the linked question, the measured value of the Earth's Semimajor axis is 149,597,887,500 m, A measured difference on the order of 0.00001% from the defined AU. This is found by radar measurements of the planets, combined with a form of Kepler's third law, that relates the distances to the planets to their orbital periods. (Kepler's third law isn't actually precise enough for this, you need a Newtonian n-body model of the solar system) The basic idea is that if you know the relative positions of the Earth and Venus you can model their orbits, and this allows you to calculate the size of their orbits, and hence the Astronomical Unit (in the old definition) | As Wikipedia says, the [Astronomical unit](https://en.wikipedia.org/wiki/Astronomical_unit) is "*roughly* the distance from Earth to the Sun".
>
> The astronomical unit was originally conceived as the average of Earth's aphelion and perihelion; however, since 2012 it has been defined as exactly $149\,597\,870\,700$ m.
>
>
>
From the [JPL Solar System Dynamics](https://ssd.jpl.nasa.gov/faq.html#b05) site:
>
> The average Sun-Earth distance is not an exact quantity because the orbit of the Earth about the Sun is not exactly elliptical due to changing perturbations by other planets and because general relativity slightly modifies the elliptical solutions obtained from Newton's theory of gravity.
>
>
>
The astronomical unit (AU) is a convenient unit for approximating orbits around the Sun. According to Kepler's 3rd law, the orbital period $T$ of a planet in an orbit with semi-major axis $a$ is given by
$$T^2=a^3$$
where $T$ is in years, and $a$ is in AU. However, that equation neglects the mass of the planet. That's fine for a rough approximation, since the Sun is far more massive than any planet (even the Sun / Jupiter mass ratio is over 1000). Such a system, which treats the mass of the orbiting body as negligible, is called a one-body system.
Fortunately, Newton discovered that a [two-body gravitational system](https://en.wikipedia.org/wiki/Two-body_problem) could be "reduced" to a pair of one-body systems, where we treat one of the bodies as being fixed at the focus of the orbit. The Newtonian version of the previous equation for a two-body system is
$$a^3=\frac{G(m\_1+m\_2)}{4\pi^2}T^2$$
where $m\_1$ and $m\_2$ are the masses of the two bodies, and $G$ is the [universal gravitational constant](https://en.wikipedia.org/wiki/Gravitational_constant).
Using Newtonian mechanics, astronomers were able to calculate the *relative* distances and masses of bodies in the Solar System. The AU was a convenient way to express those relative distances. Although they were certainly curious to know the true size of the AU, they didn't *need* to know it in order to predict the positions of bodies on the celestial sphere.
It was realised that by making *very* careful parallax observations that the length of the AU could be estimated. The [transit of Venus](https://en.wikipedia.org/wiki/Transit_of_Venus) is an ideal phenomenon for this because the amount of parallax is relatively large, if you make several simultaneous measurements from widely-separated points on the Earth. Of course, this requires that you can accurately calculate the distance between your observation posts, and can determine the timings of the transit with sufficient precision.
---
The AU is a convenient "measuring rod" for the Solar System. Although we say it's the mean distance from the Earth to the Sun, that does *not* imply that it's the time-averaged distance, even in an idealised two-body model of the Sun & Earth.
From Wikipedia [Semi-major and semi-minor axes](https://en.wikipedia.org/wiki/Semi-major_and_semi-minor_axes):
>
> It is often said that the semi-major axis is the "average" distance between the primary focus of the ellipse and the orbiting body. This is not quite accurate, because it depends on what the average is taken over.
>
>
> * averaging the distance over the [eccentric anomaly](https://en.wikipedia.org/wiki/Eccentric_anomaly) indeed results in the semi-major axis.
> * averaging over the [true anomaly](https://en.wikipedia.org/wiki/True_anomaly) (the true orbital angle, measured at the focus) results in the semi-minor axis, $b=a{\sqrt {1-e^{2}}}$
> * averaging over the [mean anomaly](https://en.wikipedia.org/wiki/Mean_anomaly) (the fraction of the orbital period that has elapsed since pericentre, expressed as an angle) gives the time-average, $a\left(1+{\frac {e^{2}}{2}}\right)$.
>
>
>
In the above equations, $e$ is the [eccentricity](https://en.wikipedia.org/wiki/Orbital_eccentricity) of the ellipse. For Earth's orbit, $e\approx 0.0167$, so all of those averages are roughly equal.
Of course, the Earth's true motion relative to the Sun is *far* more complicated than a simple two-body system. Firstly, the Moon's mass is relatively large: the Moon / Earth mass ratio is $\approx 0.0123$, and the mean distance from the centre of the Earth to the Earth-Moon [barycentre](https://en.wikipedia.org/wiki/Barycenter) is $\approx 4\,670$ km. So with just those three bodies, we no longer have a simple mean Sun-Earth distance.
And then we need to include perturbations from the other Solar System bodies. FWIW, the analytical [theory of the Moon's motion](https://en.wikipedia.org/wiki/Lunar_theory) is quite complex: "The number of terms needed to express the Moon's position with the accuracy sought at the beginning of the twentieth century was over 1400".
The best modern ephemeris calculations do not use perturbed Newtonian ellipses. Instead, they integrate the equations of motion of the major masses in the Solar System. The [Jet Propulsion Laboratory Development Ephemeris](https://en.wikipedia.org/wiki/Jet_Propulsion_Laboratory_Development_Ephemeris) takes into account the 343 most massive asteroids in its calculations. You can freely access their data, spanning from 9999 BC to 9999 AD, via the [Horizons](https://ssd.jpl.nasa.gov/horizons/) system.
---
Here's a plot of the Sun-Earth distance, generated using Horizons, for the period 2020-Apr-3 to 2022-Apr-3. The mean (time-averaged) distance over that period is $\approx 149\,619\,270$ km.
[](https://i.stack.imgur.com/NY2A1.png)
If you want to generate your own plots, here's a [live link to my Sage / Python script](https://sagecell.sagemath.org/?z=eJx1V_9z2sYS_52_4qqkD8kBWdh15oWOpsWOPHVqDAM0b1LCaM7oADmSTk86YYjH_3t39yQh7JQZELe33_ezeyfDMNhEqCwUW8EynqwFC7jibJXJmP0hs_C7THK2khnjTPFsLRS7l8G-xeDDkwC-TN7nItuGyZotRaJERvQ0koqFym4R5_-yUCmRsPs9Gw_Z2QSZz5yznu18sHsfWoZhtFphnMpMsUx04Pv_QuQqb5EXqyJZKimjnJUsUVb4S77ciFaryCLmMmOjVJr3T0_zPLAf0shOeM7ttdye8jQ83ZRR-KswEjZQwNg9z4W_jAMUBuPDwZ-e743_8IZAaH_xpu3WbHB56_mzL2MPSZ-9q9loAuTRXzP_r7ub2RSpfw67H9utiXftj28Hd8ToXd3ejGc3V5o8_TKdaZ2fzhzHabdQj381mkyQdje684jk3w4uvduppmnKR-92NvBnFelq-tm_Hk2Gg1nt4Ojyk_9xMBs0pchpJLxv66T-XufKjPkuD78LN0yUeW5ZrUCs2Eqo5cbHgpu6uJ2yhh2WA0HhQ6b4K1KrT6XUSVuh9p_evp2OrltPVTKfW1ej4XBw9xE9eNIKn8F3727mUcBPWjnQprPBZObPbobk7RMZI_Jo3KTKlIje2J_e_F0RBRLBtge2KUh0CyAD2xVw7FTmygRwdAjN7lMbEBxz1e6zthI71X7uMERDDjthkha4YbYhhHYHA7SeLVIak0o7FzxbbszMMH_Lra9vv0LUnmmf0F9v5BkEWBv1arFwBZJhzu5kInTS8JNmmHnjbsQIaN7kZmpYL3aP9ei4VJElpIpoUZiIXEdKnHaeRqEiqqmlSjtfE8N-kGFi0t78ot97v7CsVkNnbK8zWaRmz5r3-gvASojF4UtF0Ig5yOoaukbvwwejgoZr_P4LLkEVlc01ENrda3HfdX4xNGKI1ut-4knX6RkaP65xwQISg5IIovQcqI9UuTvLCmj7ZZFtRfVfRhJMZUKLEHLfd9hjGKiN2wON23XJyQsl_SJFpe41j3JRAhWqkMAMMtEAg_lF2q1X9ZiKSCwV4zBWBM8Vg0QzuWJHUsbLemjM0aB0XzeRncM8TU2ryli9LrVQ2g5MmLDmStSrGk5k6V8RJZlINyIWGXDo4S2LJPjptdcNp_HxGjvl5jzXW2a707bm_W5vQScADOCEWBbE_IaImXysyP0KxfLR-vUoU2_YGHd05Ow_FDL7VEQhR8l9DiQCRRPA1zD7-4CdE1Q9dxbz_tniCOEz2WesZgAnNQexKB8mgL8VeDrMF1Vs1DnlEn0PO5X7Iikgf8BhorIGSt4wb6ewKdiSRyIJeEaK6n2g4ho7Uj7C2MF2av1A-hBsB3p4vVFdFcZ41OGRWz66WVPzQ9BhPuxAi2To9iqSXJm5dSgFWFzU7HXEcMKl4KhpogKSthoeAZhC9nPdgsx1mXOIFj97GvBlXCUOYEIsjpk6LAbVwAjsJZPRbSCuzviRO8G7-N1-ftZfVC4FUCHMeAWTyyKMAnYpvoei7D2NCZVuwVYIzWTWgWpjCmbIHr5bBxgSmIgm8OotLX8oOdYaFqYWsTSRZwIh79SggEMPottigkHTITeBAjbFumDxQNthKyl2ys4PNPQm2MMGuHQCLKiMnkewQFCUcaIL9R75885l5t5h79geviZoBLPB3gI7ZxbqQotnzZpSqMd1RDxCOjD3GDIoQldIKyiESWNiMETT2pECC2txXEWdxaqM2NsvzRwy_KogZTKr8g4F9kAIYyBZCnYv1KOAW6HaCLxUhlWtI4mSVZmx9R2tXm3Cox3s-XIrRs2uzt4pBAKcXdTUnBgr49i-y55QrG-fr57Zt9iwKjenNKbQrXXG0w2cOmpDy_hIHicnSYxBFS4w0ZHsEBulcxOWi0V1otFvRx_jah8J1-gbFTDWWRjQhjufFxAYwbEop6vIQYcR8weZGYtKgu9E7kf8XkQgYxxmDExF41vMgLHJ4tMp2rN7F3j7WdMKf6wyCEAdXilMSpNx5P8L98srteKRz2GaJTGcc64RiZWqkhjqI_QASVKfwoVE5SZEB6P6EF5dUfCXvLo4slcfgy9QTirvqYf8lKuNqaH6Qras6WcRyWWo9vRmomlHLun5lJ30HD1h6-n5QwfPa72DIGicXfs4TADycNcGSIxtXOKhjv_4rroB7GlsAgv0Nj27JIed7djORT2J0AWcxhUAXkSua8WMk3McFDEwUwzYyCuoDflp5DGPIqPTaNnyZnUf8eU3KPJWZCpcHhdSX1uMRowPBVyNeJ7iVQlOqVDSzo6i3UEInZeR7-rIdzryH2RDz1-tFAbeTqdiR6k4PU6NRijcxJWvBXzywnTs_0LWSh2n-np4QCBcEhs5s3O-FWa7eh20Ybd9mGUBXvbh8uZDe6cR3_sxT_gazhurkXWXbVQcmQFenWEwhEt4qYRrik-atYEOe4KXizZpb6YdZNQ-hUE6KhS8cNzEoHy6XVvIaINd07IDsZSBMKuzMd_IR3Ns_QPlH4F4&lang=sage&interacts=eJxNjkEOgkAMRe_SNSQjuJBZ6TkIi0EqEkaGdDqYSLi7LRrjru-1-b_1CpEdI9gV2FGPDBbKqoIMrjgxkuA5pklY7ki3hSlMfpkpN-Vuw_yRxb9ElQdzFOgk_it2DBzBMiWUikQL_iD4oHWtT6gZwws14yTzc-j4ro-pX3qwN-cjbhm0IYwPR6Mk1s3WvAGMKT37). There are some instructions on using the script in this [Space Exploration answer](https://space.stackexchange.com/a/55061/38535). |
2,018,480 | I'm looking for a function to dump variables and objects, with human readable explanations of their data types. For instance, in php `var_dump` does this.
```
$foo = array();
$foo[] = 1;
$foo['moo'] = 2;
var_dump($foo);
```
Yields:
```
array(2) {
[0]=>
int(1)
["moo"]=>
int(2)
}
``` | 2010/01/07 | [
"https://Stackoverflow.com/questions/2018480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/245292/"
] | Check out the `dump` command:
```
> x <- c(8,6,7,5,3,0,9)
> dump("x", "")
x <-
c(8, 6, 7, 5, 3, 0, 9)
``` | I think you want 'str' which tells you the structure of an r object. |
80,638 | Any feedback is welcome. I'm new to puzzling in general so please let me know how long it took you to come up with your answer and what your thoughts were. I have tough skin.
**Hint**
>
> There's two parts here, If you're struggling then solve it bit by bit.
>
>
>
**Hint 2**
>
> There should be 10 symbols at the top, three are missing. The section to the right is not independent from the others.
>
>
>
[](https://i.stack.imgur.com/Ms2FR.png) | 2019/03/13 | [
"https://puzzling.stackexchange.com/questions/80638",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/9810/"
] | I don't get it yet, but this is my first attempt on this puzzle.
>
> Code is based on Webdings and Wingdings. Therefore, the top part is saying:
>
>
>
>
> SQR [CRACK/MISSING?] PU [SPACE][SPACE] 7A
>
>
>
Door 1
>
> R (C/P/O?)
>
>
>
Door 2
>
> LR
>
>
>
Door 3
>
> QR
>
>
>
Door 4
>
> I believe the hint is saying something about squares? So I'm trying to see if it's R or some other value
>
>
> | Not a full answer but an initial thought.
I hope that the answer includes
>
> Magic Eye
>
>
>
Because then you could
>
> Make the 4 doors into 5 to match the 10 symbols up top with the pattern involving superposition of door symbols on top of each other.
>
>
> |
59,625,685 | For a class project, my groupmates and I are to code a tic tac toe program. So far, this is what we have. All of us have 0 experience in python and this is our first time actually coding in python.
```
import random
import colorama
from colorama import Fore, Style
print(Fore.LIGHTWHITE_EX + "Tic Tac Toe - Below is the key to the board.")
Style.RESET_ALL
player_1_pick = ""
player_2_pick = ""
if (player_1_pick == "" or player_2_pick == ""):
if (player_1_pick == ""):
player_1_pick = "Player 1"
if (player_2_pick == ""):
player_2_pick = "Player 2"
else:
pass
board = ["_"] * 9
print(Fore.LIGHTBLUE_EX + "0|1|2\n3|4|5\n6|7|8\n")
def print_board():
for i in range(0, 3):
for j in range(0, 3):
if (board[i*3 + j] == 'X'):
print(Fore.RED + board[i*3 + j], end = '')
elif (board[i*3 + j] == 'O'):
print(Fore.BLUE + board[i*3 + j], end = '')
else:
print(board[i*3 + j], end = '')
print(Style.RESET_ALL, end = '')
if j != 2:
print('|', end = '')
print()
print_board()
while True:
x = input('Player 1, pick a number from 0-8: ') #
x = int(x)
board[x] = 'X'
print_board()
o = input('Player 2, pick a number from 0-8:')
o = int(o)
board[o] = 'O'
print_board()
answer = raw_input("Would you like to play it again?")
if answer == 'yes':
restart_game()
else:
close_game()
WAYS_T0_WIN = ((0,1,2)(3,4,5)(6,7,8)(0,3,6)(1,4,7)(2,5,8)(0,4,8)(2,4,6))
```
We're stuck on how to have the program detect when someone has won the game and then have it print "You won!" and also having the program detect when it's a tie and print "It's a tie!". We've looked all over the internet for a solution but none of them work and we can't understand the instructions. No use asking the teacher because they don't know python or how to code. | 2020/01/07 | [
"https://Stackoverflow.com/questions/59625685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12262043/"
] | I have changed your code in such a way that first of all "save players choices" and in second "check if a player won and break the loop":
```
import random
import colorama
from colorama import Fore, Style
print(Fore.LIGHTWHITE_EX + "Tic Tac Toe - Below is the key to the board.")
Style.RESET_ALL
player_1_pick = ""
player_2_pick = ""
if (player_1_pick == "" or player_2_pick == ""):
if (player_1_pick == ""):
player_1_pick = "Player 1"
if (player_2_pick == ""):
player_2_pick = "Player 2"
else:
pass
board = ["_"] * 9
print(Fore.LIGHTBLUE_EX + "0|1|2\n3|4|5\n6|7|8\n")
def print_board():
for i in range(0, 3):
for j in range(0, 3):
if (board[i*3 + j] == 'X'):
print(Fore.RED + board[i*3 + j], end = '')
elif (board[i*3 + j] == 'O'):
print(Fore.BLUE + board[i*3 + j], end = '')
else:
print(board[i*3 + j], end = '')
print(Style.RESET_ALL, end = '')
if j != 2:
print('|', end = '')
print()
def won(choices):
WAYS_T0_WIN = [(0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6)]
for tpl in WAYS_T0_WIN:
if all(e in choices for e in tpl):
return True
return False
print_board()
turn = True
first_player_choices = []
second_player_choices = []
while True:
if turn:
x = input('Player 1, pick a number from 0-8: ') #
x = int(x)
if board[x] == '_':
board[x] = 'X'
first_player_choices.append(x)
turn = not turn
print_board()
if won(first_player_choices):
print('Player 1 won!')
break
else:
print('Already taken! Again:')
continue
else:
o = input('Player 2, pick a number from 0-8: ') #
o = int(o)
if board[o] == '_':
board[o] = 'O'
second_player_choices.append(o)
turn = not turn
print_board()
if won(second_player_choices):
print('Player 2 won!')
break
else:
print('Already taken! Again:')
continue
# answer = input("Would you like to play it again?")
# if answer == 'yes':
# restart_game()
# else:
# close_game()
```
I also added a condition to check if players choice is already taken! By the way, you can do it way much better. :)
**EDIT:** there was a little problem with spaces in my answer here and I solve it in edit. Now you can directly copy it in a py file and run it! | Firstly, you need a condition which doesn't allow the same space to be allocated twice, when test running I could type space 3 as much as I wanted for example without it stopping me. You need some sort of check for this.
Secondly, for the actual win system, you made it easy because you already have the co-ordinates for all of the winning games, I recommend something along the lines of:
```
def checkwin(team):
for i in WAYS_TO_WIN:
checked = False
while not checked:
k = 0
for j in i:
if board[j] == team:
k+=1
if k == 3:
return True
checked = True
```
This way is checks if any of the co-ordinates have all 3 of any set. You might have to adjust this code, but this looks like a solution.
Note: I'm still a beginner at coding and I stumbled upon your thread, this is an idea not necessarily a working solution |
11,873,265 | Would anyone know why my submit button wouldn't call javascript to verify if certain fields are populated in the form?
To have better idea I have provided a link to the website: <http://www.flyingcowproduction.com/pls> and click on the button "reservation" from the top menu.
Form:
```
<form method="post" action="process.php">
<div class="grid_6">
<div class="element">
<label>Name*</label>
<input type="text" name="name" class="text" style="width:427px;" />
</div>
</div>
<div class="clear"></div>
<div class="grid_3">
<div class="element">
<label>Email*</label>
<input type="text" name="email" class="text" style="width:200px;" />
</div>
</div>
<div class="grid_3">
<div class="element">
<label>Phone</label>
<input type="text" name="phone" class="text" style="width:200px;" />
</div>
</div>
<div class="clear"></div>
<div class="grid_3">
<div class="element">
<label>Address*</label>
<input type="text" name="address" class="text" style="width:200px;" />
</div>
</div>
<div class="grid_2">
<div class="element">
<label>City*</label>
<input type="text" name="city" class="text" style="width:119px;" />
</div>
</div>
<div class="grid_1">
<div class="element">
<label>Zip*</label>
<input type="text" name="zipcode" class="text" style="width:55px;" />
</div>
</div>
<div class="clear"></div>
<div class="grid_6">
<div class="element">
<label>Where do you want to go?*</label>
<input type="text" name="service" class="text" style="width:427px;" />
</div>
</div>
<div class="clear"></div>
<div class="grid_3">
<div class="element">
<label>Date and time of service*</label>
<input type="text" name="datetime" class="text" style="width:200px;" />
</div>
</div>
<div class="grid_2">
<div class="element">
<label>Passengers (max)</label>
<input type="text" name="passingers" class="text" style="width:75px;" />
</div>
</div>
<div class="grid_1">
</div>
<div class="clear"></div>
<div class="grid_6">
<div class="element">
<label>Comment</label>
<textarea name="comment" class="text textarea" style="width:427px;" rows="4" /></textarea>
</div>
</div>
<div class="clear"></div>
<div class="grid_6">
<div class="element">
<input type="submit" id="submit" value="MAKE RESERVATION" />
<p> </p>
</div>
</div>
</form>
<script type="text/javascript">
```
$(document).ready(function() {
```
//if submit button is clicked
$('#submit').click(function () {
//Get the data from all the fields
var name = $('input[name=name]');
var email = $('input[name=email]');
var phone = $('input[name=phone]');
var address = $('input[name=address]');
var city = $('input[name=city]');
var zipcode = $('input[name=zipcode]');
var service = $('input[name=service]');
var datetime = $('input[name=datetime]');
var passingers = $('input[name=passingers]');
var comment = $('textarea[name=comment]');
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (email.val()=='') {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
if (address.val()=='') {
address.addClass('hightlight');
return false;
} else address.removeClass('hightlight');
if (city.val()=='') {
city.addClass('hightlight');
return false;
} else city.removeClass('hightlight');
if (zipcode.val()=='') {
zipcode.addClass('hightlight');
return false;
} else zipcode.removeClass('hightlight');
if (service.val()=='') {
service.addClass('hightlight');
return false;
} else service.removeClass('hightlight');
if (datetime.val()=='') {
datetime.addClass('hightlight');
return false;
} else datetime.removeClass('hightlight');
//organize the data properly
var data = 'name=' + name.val() + '&email=' + email.val() + '&phone=' + phone.val() + '&address=' + address.val() + '&city=' + city.val() + '&zipcode=' + zipcode.val() + '&service=' + service.val() + '&datetime=' + datetime.val() + '&passingers=' + passingers.val() + '&comment=' + encodeURIComponent(comment.val());
//disabled all the text fields
$('.text').attr('disabled','true');
//show the loading sign
$('.loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "process.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
//if process.php returned 0/false (send mail failed)
} else alert('Sorry, unexpected error. Please try again later.');
}
});
//cancel the submit button default behaviours
return false;
});
```
});
many many thanks in advance | 2012/08/08 | [
"https://Stackoverflow.com/questions/11873265",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1399599/"
] | Your function is fine and is getting called if one uses your provided html above. But the site you gave link of shows this
```
<input type="submit" value="MAKE RESERVATION" id="FormId">
```
see that id="FormId" it should be "submit"
Ok now please try this
1) Make sure you backup things
2) Remove the validation function that we just added to index.html
3) Replace the last script block (which starts from line 358) on index.html with the following
```
<script type="text/javascript">
$(document).ready(function () {
// Added by Prayas (Start)
function menuItemClick(section) {
content1 = "loader.html " + section;
toTheSky();
$("#singleContentContainer").delay(400).fadeIn();
$('#singleContentInside').load(content1);
if(section=="#reservations")
{
$('#submit').click(function(e) {
e.preventDefault();
//Get the data from all the fields
var name = $('input[name=name]');
var email = $('input[name=email]');
var phone = $('input[name=phone]');
var address = $('input[name=address]');
var city = $('input[name=city]');
var zipcode = $('input[name=zipcode]');
var service = $('input[name=service]');
var datetime = $('input[name=datetime]');
var passingers = $('input[name=passingers]');
var comment = $('textarea[name=comment]');
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (email.val()=='') {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
if (address.val()=='') {
address.addClass('hightlight');
return false;
} else address.removeClass('hightlight');
if (city.val()=='') {
city.addClass('hightlight');
return false;
} else city.removeClass('hightlight');
if (zipcode.val()=='') {
zipcode.addClass('hightlight');
return false;
} else zipcode.removeClass('hightlight');
if (service.val()=='') {
service.addClass('hightlight');
return false;
} else service.removeClass('hightlight');
if (datetime.val()=='') {
datetime.addClass('hightlight');
return false;
} else datetime.removeClass('hightlight');
//organize the data properly
var data = 'name=' + name.val() + '&email=' + email.val() + '&phone=' + phone.val() + '&address=' + address.val() + '&city=' + city.val() + '&zipcode=' + zipcode.val() + '&service=' + service.val() + '&datetime=' + datetime.val() + '&passingers=' + passingers.val() + '&comment=' + encodeURIComponent(comment.val());
//disabled all the text fields
$('.text').attr('disabled','true');
//show the loading sign
$('.loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "process.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
//if process.php returned 0/false (send mail failed)
} else alert('Sorry, unexpected error. Please try again later.');
}
});
//cancel the submit button default behaviours
return false;
});
}
}
$("#services1").click(function() {
menuItemClick("#services")
});
$("#services2").click(function() {
menuItemClick("#services")
});
$("#rates1").click(function() {
menuItemClick("#rates")
});
$("#rates2").click(function() {
menuItemClick("#rates")
});
$("#reservations1").click(function() {
menuItemClick("#reservations")
});
$("#reservations2").click(function() {
menuItemClick("#reservations")
});
$("#fleet1").click(function() {
menuItemClick("#fleets")
});
$("#fleet2").click(function() {
menuItemClick("#fleets")
});
$("#closeContainer").click(function() {
downToEarth();
$("#singleContentContainer").fadeOut();
});
// Added by Prayas (End)
});
</script>
```
EDIT 2
1) Remove the Script block at the bottom that we just added.
2) Copy the whole reservations div from loader.html into a new file named reservations.html.
3) Place the original validation function in this div back on its position in "reservations.html".
4) Place this script block at the end of your index.html
```
<script type="text/javascript">
$(document).ready(function () {
// Added by Prayas (Start)
function menuItemClick(section) {
if(section=="#reservations")
{
content1 = "reservations.html;
}
else
{
content1 = "loader.html " + section;
toTheSky();
$("#singleContentContainer").delay(400).fadeIn();
$('#singleContentInside').load(content1);
}
$("#services1").click(function() {
menuItemClick("#services")
});
$("#services2").click(function() {
menuItemClick("#services")
});
$("#rates1").click(function() {
menuItemClick("#rates")
});
$("#rates2").click(function() {
menuItemClick("#rates")
});
$("#reservations1").click(function() {
menuItemClick("#reservations")
});
$("#reservations2").click(function() {
menuItemClick("#reservations")
});
$("#fleet1").click(function() {
menuItemClick("#fleets")
});
$("#fleet2").click(function() {
menuItemClick("#fleets")
});
$("#closeContainer").click(function() {
downToEarth();
$("#singleContentContainer").fadeOut();
});
// Added by Prayas (End)
});
</script>
``` | In your click event handler you'll probably want to prevent the default action of the click which is submitting the form before your code runs.
```
$('#submit').click(function(e) {
e.preventDefault();
...
});
```
However, I'd do what Laurent said and bind on the form submit instead. |
11,172,827 | I have a UITableView with static cells and I am trying to change the height of the cell when it meets a condition. The conditions are being met but the cell heights won't change.
The code I am using is
```
[self.tableView setRowHeight:10];
```
And
```
self.tableView rowHeight = 10;
```
Neither of these will change the row height of the cells
Is there another way to change them? | 2012/06/23 | [
"https://Stackoverflow.com/questions/11172827",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1282180/"
] | you can use this for all row of tableview
```
override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 100
}
``` | You Can create the dynamic cell with Text height then you can set the static and dynamic cell both in on table view
Here is link to dynamic cell with text
[How to change cell height dynamically in UITableView static cell](https://stackoverflow.com/questions/25420980/how-to-change-cell-height-dynamically-in-uitableview-static-cell) |
4,008,598 | I want to connect to a mongodb database using excel macros, does anybody knows how to acomplish this task? | 2010/10/24 | [
"https://Stackoverflow.com/questions/4008598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/270494/"
] | My own solution was to let Python glue them together using pymongo and win32com. It's then fairly straightforward to run whatever you want. In my case I have the Python loop simply continuously "listen" to certain Excel cells, call what it needs from Mongo, then put it back into Excel. It's flexible and many things can be done this way. Here is the full code base, but you will have to change the calls to Mongodb to match your own database. In here you will also see certain ways you can change colours and things of Excel cells from within Python. Oh I should mention that it's peppered with ansi escape sequences so you might want to run Python from [ansicon](http://adoxa.hostmyway.net/ansicon/) or [ConEmu](http://conemu.codeplex.com/).
```
import win32com.client as win32
import time # will need this for time parsing
from optparse import OptionParser
import pdb # debugger, when necessary
import string # for string parsing and the alphabet
from pymongo import MongoClient
import inspect
from datetime import datetime, timedelta, tzinfo
from dateutil import tz
from bson.son import SON
import msvcrt # for getch
import os
import sys # for stdout.write
from collections import OrderedDict
def parseCmdLine():
parser = OptionParser(description="Retrieve realtime data.")
parser.add_option("--f",
dest="file",
help="filename",
default="bbcapture.xls")
parser.add_option("--mongohost",
dest="mongohost",
default="192.168.1.30")
parser.add_option("--mongoport",
dest="mongoport",
type="int",
default=27017)
(options, args) = parser.parse_args()
return(options)
options = parseCmdLine() # parse the commandline
client = MongoClient(options.mongohost, options.mongoport) # link to mongo
db = client.bb # the database
bbsecs = db.bbsecs # now all the collections
bbdaily = db.bbdaily
bbticks = db.bbticks
linkstatusperiod = False # for the moving period in the top left excel cell showing we're linked
def ansi(colour = "white", bright = False, back = "black"):
# ansi colour sequences
brit = {True: "\033[1m",
False: "\033[0m"}
colo = {"black": "\033[30m",
"red": "\033[31m",
"green": "\033[32m",
"yellow": "\033[33m",
"blue": "\033[34m",
"magenta": "\033[35m",
"cyan": "\033[36m",
"white": "\033[37m"}
bakk = {"black": "\033[40m",
"red": "\033[41m",
"green": "\033[42m",
"yellow": "\033[43m",
"blue": "\033[44m",
"magenta": "\033[45m",
"cyan": "\033[46m",
"white": "\033[47m"}
sys.stdout.write(brit[bright])
sys.stdout.write(colo[colour])
sys.stdout.write(bakk[back])
def mdaily(ticker = "USDEUR Curncy", field = "LAST_PRICE", sortdirection = 1, numget = 1000000):
ansi("cyan", False)
print "\nGetting", ticker, "field", field, "from Mongo...",
lister = OrderedDict()
#for post in bbdaily.find({"ticker": ticker, "fieldname": field}).limit(numget).sort("time", sortdirection):
for post in bbdaily.find({"$query": {"ticker": ticker, "fieldname": field}, "$orderby": {"time": -1}}).limit(numget):
lister[str(post["time"])] = post["fieldvalue"]
ansi("cyan", True)
print "got", len(lister), "values",
ansi()
return lister
def mtick(tickers, sortdirection = 1, numget = 1000000):
if len(tickers) == 0:
return []
else:
ansi("green", False)
print "\n Getting minutes for for", tickers,
tickerdic = OrderedDict()
for eachticker in tickers:
eachdic = dict()
print numget
for post in bbticks.find({"ticker": eachticker}).limit(numget):
eachdic[post["time"]] = [post["open"], post["high"], post["low"], post["close"]]
ansi("green")
tickerdic[eachticker] = eachdic
print "got", len(eachdic), "for ticker", eachticker,
ansi("green", True)
print "got", len(tickerdic), "tickers",
dates = [set(tickerdic[x].keys()) for x in tickerdic] # get all the dates
dates = set.intersection(*dates) # get the unique ones
dates = [x for x in dates] # convert to list
if sortdirection == -1:
dates = sorted(dates, reverse = True)
else:
dates = sorted(dates, reverse = False)
retlist = [[[x, tickerdic[y][x][0], tickerdic[y][x][1], tickerdic[y][x][2], tickerdic[y][x][3]] for x in dates] for y in tickerdic.keys()]
ansi()
return retlist
def getsecs():
seclist = []
for post in bbsecs.find():
seclist.append(post["ticker"])
return(seclist)
def offsetString(startrow, startcol, endrow, endcol):
startrowstr = str(startrow)
endrowstr = str(endrow)
if(startcol > 26):
startcolstr = string.uppercase[startcol / 26 - 1] + string.uppercase[startcol % 26 - 1]
else:
startcolstr = string.uppercase[startcol - 1]
if(endcol > 26):
endcolstr = string.uppercase[endcol / 26 - 1] + string.uppercase[endcol % 26 - 1]
else:
endcolstr = string.uppercase[endcol - 1]
return(startcolstr + startrowstr + ":" + endcolstr + endrowstr)
def main():
excel = win32.gencache.EnsureDispatch("Excel.Application")
excel.Visible = 1
try: # try to link to the file
ansi("red", False)
print "Linking to", options.file
wb = excel.Workbooks(options.file)
ws = wb.Worksheets("MongoData")
ansi()
except: # not open then try to load it
try:
ansi("red", False)
print "Not open.... trying to open in current directory", os.getcwd()
ansi()
wb = excel.Workbooks.Open(os.getcwd() + "\\" + options.file)
ws = wb.Worksheets("MongoData")
ansi()
except: # can't load then ask to create it
ansi("red", True)
print options.file, "not found here. Create? (y/n) ",
ansi("yellow", True)
response = msvcrt.getch()
print response
ansi()
if response.upper() == "Y":
wb = excel.Workbooks.Add()
ws = excel.Worksheets.Add()
ws.Name = "MongoData"
wb.SaveAs(os.getcwd() + "\\" + options.file)
else: # don't wanna create it then exit
print "bye."
return
# see if ticks sheet works otherwise add it
try:
wst = wb.Worksheets("MongoTicks")
except:
wst = excel.Worksheets.Add()
wst.Name = "MongoTicks"
wst.Cells(3, 2).Value = 1
# see if securities list sheet works otherwise add it
try:
wall = wb.Worksheets("AllSecurities")
wall.Cells(1, 1).Value = "List of all securities"
wall.Range("A1:A1").Interior.ColorIndex = 8
wall.Range("A:A").ColumnWidth = 22
except:
wall = excel.Worksheets.Add()
wall.Name = "AllSecurities"
wall.Cells(1, 1).Value = "List of all securities"
wall.Range("A1:A1").Interior.ColorIndex = 8
wall.Range("A:A").ColumnWidth = 22
ansi("green", True)
print "talking to", options.file,
ansi("green", False)
print "... press any key when this console has the focus, to end communication"
ansi()
def linkstatusupdate():
global linkstatusperiod
if linkstatusperiod:
ws.Cells(1, 1).Value = "Talking to Python|"
wst.Cells(1, 1).Value = "Talking to Python!"
linkstatusperiod = False
else:
ws.Cells(1, 1).Value = "Talking to Python|"
wst.Cells(1, 1).Value = "Talking to Python!"
linkstatusperiod = True
ws.Cells(1, 2).Value = datetime.now()
# daily worksheet header formatting
ws.Cells(1, 1).Value = "Excel linked to Python"
ws.Cells(1, 3).Value = "Sort direction:"
ws.Cells(1, 4).Value = 1
ws.Cells(1, 5).Value = "Fetch max:"
ws.Cells(2, 1).Value = "Enter tickers:"
ws.Cells(3, 1).Value = "Start data:"
ws.Cells(4, 1).Value = "End data:"
ws.Range("A:A").ColumnWidth = 22
ws.Range("B:B").ColumnWidth = 20
ws.Range("A2:GS2").Interior.ColorIndex = 19 # beige 200 columns
ws.Range("A3:GS4").Interior.ColorIndex = 15 # grey
ws.Range("A2").Interior.ColorIndex = 3 # red
ws.Range("A3:A4").Interior.ColorIndex = 16 # dark grey
# minute worksheet header formatting
wst.Cells(1, 1).Value = "Excel linked to Python"
wst.Cells(2, 1).Value = "Enter tickers:"
#wst.Cells(3, 1).Value = "Enter periodicity:"
wst.Cells(1, 3).Value = "Sort direction:"
wst.Cells(1, 4).Value = 1
wst.Cells(1, 5).Value = "Fetch max:"
wst.Range("A:A").ColumnWidth = 22
wst.Range("B:B").ColumnWidth = 20
wst.Range("A2:GS3").Interior.ColorIndex = 19 # beige 200 columns
wst.Range("A4:GS5").Interior.ColorIndex = 15 # grey
wst.Range("A2:A3").Interior.ColorIndex = 4 # red
wst.Range("6:100000").Clear()
linkstatusperiod = False
oldsecd = []
oldseci = []
oldnumget = oldsortdir = toldnumget = toldsortdir = 0
while not msvcrt.kbhit():
try:
print "...", wb.Name,
securities = ws.Range("B2:GS2").Value[0]
sortdir = ws.Cells(1, 4).Value
if sortdir == None:
sortdir = 1
sortdir = int(sortdir)
numget = ws.Cells(1, 6).Value
if numget == None:
numget = 1000000
numget = int(numget)
securities = [x for x in securities if x is not None]
if not ((oldsecd == securities) and (oldnumget == numget) and (oldsortdir == sortdir)): # clear content of cells
ws.Range("5:1000000").Clear()
ws.Range("B3:GS4").Clear()
ws.Range("B3:GS4").Interior.ColorIndex = 15 # grey
oldsecd = securities
oldnumget = numget
oldsortdir = sortdir
currentcol = 0
for sec in securities:
linkstatusupdate()
secdata = mdaily(sec, "LAST_PRICE", sortdir, numget)
currentrow = 0
vallist = []
datelist = []
if sortdir == -1:
sortedkeys = sorted(secdata, reverse = True)
else:
sortedkeys = sorted(secdata, reverse = False)
for eachkey in sortedkeys:
datelist.append(eachkey)
vallist.append(secdata[eachkey])
#now stick them in Excel
ws.Range(offsetString(5 + currentrow, 2 + currentcol, 5 + currentrow + len(vallist) - 1, 2 + currentcol)).Value = \
tuple([(x, ) for x in vallist])
if currentcol == 0:
ws.Range(offsetString(5 + currentrow, 1, 5 + currentrow + len(vallist) - 1, 1)).Value = \
tuple([(x, ) for x in datelist])
if len(sortedkeys) > 0:
ws.Cells(3, 2 + currentcol).Value = sortedkeys[len(sortedkeys) - 1].split()[0] # start data date
ws.Cells(4, 2 + currentcol).Value = sortedkeys[0].split()[0] # end data date
currentcol += 1
# now do the tick data
securitiest = wst.Range("B2:GS2").Value[0]
securitiest = [x for x in securitiest if x is not None]
tsortdir = wst.Cells(1, 4).Value
if tsortdir == None:
tsortdir = 1
tsortdir = int(tsortdir)
tnumget = wst.Cells(1, 6).Value
if tnumget == None:
tnumget = 1000000
tnumget = int(tnumget)
if not ((oldseci == securitiest) and (toldnumget == tnumget) and (toldsortdir == tsortdir)): # clear the contents of the cells
wst.Range("6:1000000").Clear()
wst.Range("B4:GS5").Clear()
wst.Range("B4:GS5").Interior.ColorIndex = 15 # grey
oldseci = securitiest
toldnumget = tnumget
toldsortdir = tsortdir
secdata = mtick(securitiest, tsortdir, tnumget)
currentsec = 0
for x in secdata:
sender = [tuple(y[1:5]) for y in x]
wst.Range(offsetString(6, 2 + currentsec * 4, 6 + len(x) - 1, 5 + currentsec * 4)).Value = sender
if currentsec == 0: # then put the dates in
dates = [tuple([y[0], ]) for y in x]
wst.Range(offsetString(6, 1, 6 + len(x) - 1, 1)).Value = dates
wst.Range(offsetString(5, 2 + currentsec * 4, 5, 5 + currentsec * 4)).Value = ["open", "high", "low", "close"]
currentsec += 1
for x in range(0, len(securitiest)):
wst.Cells(4, 2 + x * 4).Value = securitiest[x]
linkstatusupdate()
allsecs = tuple([(yy, ) for yy in getsecs()])
wall.Range(offsetString(2, 1, len(allsecs) + 1, 1)).Value = allsecs
except:
print "\nExcel busy",
time.sleep(1)
endchar = msvcrt.getch() # capture the last character so it doesn't go to console
print "\nbye."
if __name__ == "__main__":
main()
``` | They say there is a 3rd party Mongodb COM driver around:
<http://na-s.jp/MongoCOM/index.en.html>
After installing and referencing it, you can run queries like
```
Dim oConn
Dim oCursor,o
Set oConn = oMng.NewScopedDBConnection( cHostAndPort )
Set oCursor = oConn.Query( "ec.member", oMng.FJ("{ ""age"": 37 }")
Do While oCursor.More
Set o = oCursor.Next
MsgBox "mname: " & o("mname")
MsgBox "dept: " & o("dept")
MsgBox "age: " & o("age")
Loop
```
This is for those who thinks that de-normalizing of MongoDb structures and translating them into SQL-queryable form on the fly each time you need some chunk of data is an overkill ;-) |
44,749,992 | I am using Socket.io to create a simple application. To test if the client side and the server side are working correctly I use `socket.emit` to send message to the server and `socket.on` to write the message on the server console.
Now, I have been able to connect the client side to the server side by writing something on the console when the client is connected. But my issue is when I tried to send (`socket.emit`) data to the server, the `socket.on` method is not triggered. It doesn't give any errors as well.
Below is snippet of my codes
**Client Side --index.html**
```
<!DOCTYPE html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
<script socket.io.js"></script>
<script src="socket.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
$(function () {
var socket = io();
$('form').submit(function(){
socket.emit('message', $('#m').val());
$('#m').val('');
return false;
});
});
</script>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
```
**socket.io.js**
```
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.io=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
module.exports = _dereq_('./lib/');
},{"./lib/":2}],2:[function(_dereq_,module,exports){
/**
* Module dependencies.
*/
var url = _dereq_('./url');
var parser = _dereq_('socket.io-parser');
var Manager = _dereq_('./manager');
var debug = _dereq_('debug')('socket.io-client');
/**
* Module exports.
*/
module.exports = exports = lookup;
/**
* Managers cache.
*/
var cache = exports.managers = {};
/**
* Looks up an existing `Manager` for multiplexing.
* If the user summons:
*
* `io('http://localhost/a');`
* `io('http://localhost/b');`
*
* We reuse the existing instance based on same scheme/port/host,
* and we initialize sockets for each namespace.
*
* @api public
*/
function lookup(uri, opts) {
if (typeof uri == 'object') {
opts = uri;
uri = undefined;
}
opts = opts || {};
var parsed = url(uri);
var source = parsed.source;
var id = parsed.id;
var path = parsed.path;
var sameNamespace = (cache[id] && cache[id].nsps[path] &&
path == cache[id].nsps[path].nsp);
var newConnection = opts.forceNew || opts['force new connection'] ||
false === opts.multiplex || sameNamespace;
var io;
if (newConnection) {
debug('ignoring socket cache for %s', source);
io = Manager(source, opts);
} else {
if (!cache[id]) {
debug('new io instance for %s', source);
cache[id] = Manager(source, opts);
}
io = cache[id];
}
return io.socket(parsed.path);
}
/**
* Protocol version.
*
* @api public
*/
exports.protocol = parser.protocol;
/**
* `connect`.
*
* @param {String} uri
* @api public
*/
exports.connect = lookup;
/**
* Expose constructors for standalone build.
*
* @api public
*/
exports.Manager = _dereq_('./manager');
exports.Socket = _dereq_('./socket');
},{"./manager":3,"./socket":5,"./url":6,"debug":10,"socket.io-parser":44}],3:[function(_dereq_,module,exports){
/**
* Module dependencies.
*/
var url = _dereq_('./url');
var eio = _dereq_('engine.io-client');
var Socket = _dereq_('./socket');
var Emitter = _dereq_('component-emitter');
var parser = _dereq_('socket.io-parser');
var on = _dereq_('./on');
var bind = _dereq_('component-bind');
var object = _dereq_('object-component');
var debug = _dereq_('debug')('socket.io-client:manager');
var indexOf = _dereq_('indexof');
var Backoff = _dereq_('backo2');
/**
* Module exports
*/
module.exports = Manager;
/**
* `Manager` constructor.
*
* @param {String} engine instance or engine uri/opts
* @param {Object} options
* @api public
*/
function Manager(uri, opts){
if (!(this instanceof Manager)) return new Manager(uri, opts);
if (uri && ('object' == typeof uri)) {
opts = uri;
uri = undefined;
}
opts = opts || {};
opts.path = opts.path || '/socket.io';
this.nsps = {};
this.subs = [];
this.opts = opts;
this.reconnection(opts.reconnection !== false);
this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
this.reconnectionDelay(opts.reconnectionDelay || 1000);
this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
this.randomizationFactor(opts.randomizationFactor || 0.5);
this.backoff = new Backoff({
min: this.reconnectionDelay(),
max: this.reconnectionDelayMax(),
jitter: this.randomizationFactor()
});
this.timeout(null == opts.timeout ? 20000 : opts.timeout);
this.readyState = 'closed';
this.uri = uri;
this.connected = [];
this.encoding = false;
this.packetBuffer = [];
this.encoder = new parser.Encoder();
this.decoder = new parser.Decoder();
this.autoConnect = opts.autoConnect !== false;
if (this.autoConnect) this.open();
}
/**
* Propagate given event to sockets and emit on `this`
*
* @api private
*/
Manager.prototype.emitAll = function() {
this.emit.apply(this, arguments);
for (var nsp in this.nsps) {
this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
}
};
/**
* Update `socket.id` of all sockets
*
* @api private
*/
Manager.prototype.updateSocketIds = function(){
for (var nsp in this.nsps) {
this.nsps[nsp].id = this.engine.id;
}
};
/**
* Mix in `Emitter`.
*/
Emitter(Manager.prototype);
/**
* Sets the `reconnection` config.
*
* @param {Boolean} true/false if it should automatically reconnect
* @return {Manager} self or value
* @api public
*/
Manager.prototype.reconnection = function(v){
if (!arguments.length) return this._reconnection;
this._reconnection = !!v;
return this;
};
/**
* Sets the reconnection attempts config.
*
* @param {Number} max reconnection attempts before giving up
* @return {Manager} self or value
* @api public
*/
Manager.prototype.reconnectionAttempts = function(v){
if (!arguments.length) return this._reconnectionAttempts;
this._reconnectionAttempts = v;
return this;
};
/**
* Sets the delay between reconnections.
*
* @param {Number} delay
* @return {Manager} self or value
* @api public
*/
Manager.prototype.reconnectionDelay = function(v){
if (!arguments.length) return this._reconnectionDelay;
this._reconnectionDelay = v;
this.backoff && this.backoff.setMin(v);
return this;
};
Manager.prototype.randomizationFactor = function(v){
if (!arguments.length) return this._randomizationFactor;
this._randomizationFactor = v;
this.backoff && this.backoff.setJitter(v);
return this;
};
/**
* Sets the maximum delay between reconnections.
*
* @param {Number} delay
* @return {Manager} self or value
* @api public
*/
Manager.prototype.reconnectionDelayMax = function(v){
if (!arguments.length) return this._reconnectionDelayMax;
this._reconnectionDelayMax = v;
this.backoff && this.backoff.setMax(v);
return this;
};
/**
* Sets the connection timeout. `false` to disable
*
* @return {Manager} self or value
* @api public
*/
Manager.prototype.timeout = function(v){
if (!arguments.length) return this._timeout;
this._timeout = v;
return this;
};
/**
* Starts trying to reconnect if reconnection is enabled and we have not
* started reconnecting yet
*
* @api private
*/
Manager.prototype.maybeReconnectOnOpen = function() {
// Only try to reconnect if it's the first time we're connecting
if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
// keeps reconnection from firing twice for the same reconnection loop
this.reconnect();
}
};
/**
* Sets the current transport `socket`.
*
* @param {Function} optional, callback
* @return {Manager} self
* @api public
*/
Manager.prototype.open =
Manager.prototype.connect = function(fn){
debug('readyState %s', this.readyState);
if (~this.readyState.indexOf('open')) return this;
debug('opening %s', this.uri);
this.engine = eio(this.uri, this.opts);
var socket = this.engine;
var self = this;
this.readyState = 'opening';
this.skipReconnect = false;
// emit `open`
var openSub = on(socket, 'open', function() {
self.onopen();
fn && fn();
});
// emit `connect_error`
var errorSub = on(socket, 'error', function(data){
debug('connect_error');
self.cleanup();
self.readyState = 'closed';
self.emitAll('connect_error', data);
if (fn) {
var err = new Error('Connection error');
err.data = data;
fn(err);
} else {
// Only do this if there is no fn to handle the error
self.maybeReconnectOnOpen();
}
});
// emit `connect_timeout`
if (false !== this._timeout) {
var timeout = this._timeout;
debug('connect attempt will timeout after %d', timeout);
// set timer
var timer = setTimeout(function(){
debug('connect attempt timed out after %d', timeout);
openSub.destroy();
socket.close();
socket.emit('error', 'timeout');
self.emitAll('connect_timeout', timeout);
}, timeout);
this.subs.push({
destroy: function(){
clearTimeout(timer);
}
});
}
this.subs.push(openSub);
this.subs.push(errorSub);
return this;
};
/**
* Called upon transport open.
*
* @api private
*/
Manager.prototype.onopen = function(){
debug('open');
// clear old subs
this.cleanup();
// mark as open
this.readyState = 'open';
this.emit('open');
// add new subs
var socket = this.engine;
this.subs.push(on(socket, 'data', bind(this, 'ondata')));
this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
this.subs.push(on(socket, 'error', bind(this, 'onerror')));
this.subs.push(on(socket, 'close', bind(this, 'onclose')));
};
/**
* Called with data.
*
* @api private
*/
Manager.prototype.ondata = function(data){
this.decoder.add(data);
};
/**
* Called when parser fully decodes a packet.
*
* @api private
*/
Manager.prototype.ondecoded = function(packet) {
this.emit('packet', packet);
};
/**
* Called upon socket error.
*
* @api private
*/
Manager.prototype.onerror = function(err){
debug('error', err);
this.emitAll('error', err);
};
/**
* Creates a new socket for the given `nsp`.
*
* @return {Socket}
* @api public
*/
Manager.prototype.socket = function(nsp){
var socket = this.nsps[nsp];
if (!socket) {
socket = new Socket(this, nsp);
this.nsps[nsp] = socket;
var self = this;
socket.on('connect', function(){
socket.id = self.engine.id;
if (!~indexOf(self.connected, socket)) {
self.connected.push(socket);
}
});
}
return socket;
};
/**
* Called upon a socket close.
*
* @param {Socket} socket
*/
Manager.prototype.destroy = function(socket){
var index = indexOf(this.connected, socket);
if (~index) this.connected.splice(index, 1);
if (this.connected.length) return;
this.close();
};
/**
* Writes a packet.
*
* @param {Object} packet
* @api private
*/
Manager.prototype.packet = function(packet){
debug('writing packet %j', packet);
var self = this;
if (!self.encoding) {
// encode, then write to engine with result
self.encoding = true;
this.encoder.encode(packet, function(encodedPackets) {
for (var i = 0; i < encodedPackets.length; i++) {
self.engine.write(encodedPackets[i]);
}
self.encoding = false;
self.processPacketQueue();
});
} else { // add packet to the queue
self.packetBuffer.push(packet);
}
};
.....
```
**Socket.js**
```
app.factory('socket', function(socketFactory){
var socket = io.connect('http://0.0.0.0:3001');
mySocket = socketFactory({
ioSocket: socket
});
return socket;
});
```
**Server Side**
```
var express = require('express'),
app = express(),
cors = require('cors'),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
mongoose = require('mongoose'),
users = {};
var path = require('path');
var gcm = require('node-gcm');
var fs = require('fs');
var url = require('url');
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', "http://"+req.headers.host+':3001');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
next();
}
);
io.sockets.on('connection', function(socket){
console.log('New User Connected to this server'); // This prints the content as soon as a client connects to the server.
socket.on('message', function(msg){
console.log('message: ' + msg); //This doesn't work and as well doesn't print any error message on the server console
});
});
```
I cant seem to figure what is actually wrong, maybe I am not doing something right.
Extra information
```
node.js v4.2.6
express 4.15.3
socket.io 1.7.3
``` | 2017/06/25 | [
"https://Stackoverflow.com/questions/44749992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2595059/"
] | You can use an intermediate variable to hold the value of one.
```
var a = 1
var b = 2
var c = a
a = b
b = c
```
You can use a method shown in this link [here](https://stackoverflow.com/a/16201730/4216035) but in my opinion is not very readable. | ```
let foo = {
example: '2',
anotherExample: '1'
};
let anotherFoo = 'orange';
```
First, use a dummy variable to store the original value of one variable:
```
const dummy = anotherFoo;
```
Then, overwrite that variable with the original value of the second variable:
```
anotherFoo = Object.assign({}, foo);
```
Finally, overwrite the second variable with the original value of the first variable, which happens to be stored in the dummy variable:
```
foo = dummy;
``` |
5,437,806 | >
> **Possible Duplicate:**
>
> [Simulating a BlueScreen](https://stackoverflow.com/questions/667581/simulating-a-bluescreen)
>
>
>
Hello SO,
I'm trying to induce a BSOD somehow inline in my C code. My main background is Java but have been fortunate to have been tutored by some coworkers and am helping out with a simple C utility.
There's two sections:
1) write to a hard drive (I finished this, wasn't too bad)
2) Force a blue screen immediately after sending the last SCSI write command
You can probably tell the intent of the program easily now.
I've tried two things so far:
1) Externally calling pskill.exe (windows utility) to manually crash csrss.exe which forces a blue screen every time since csrss.exe is a required service of windows. This doesn't work because it's not fast enough. The call to the external utility takes too long so we need inline code to compile with the write to disk section in order to crash the computer fast enough.
2) Use the windows.h API to call TerminateProcess: <http://msdn.microsoft.com/en-us/library/ms686714%28v=vs.85%29.aspx>
The problem is this function cannot end system related tasks so it can't close csrss.exe
This has left me short on options. I need a clever way to kill csrss.exe in our own native code without an external call or a clever way to force a blue screen in internal code OR I need a very simple driver I can load and call which will blue screen the machine immediately. Could be as short as 1 line calling KeBugCheck <http://msdn.microsoft.com/en-us/library/ff551948.aspx>
Thanks for your time and input. | 2011/03/25 | [
"https://Stackoverflow.com/questions/5437806",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/584947/"
] | Your best bet is to write a trivial driver that calls [`KeBugCheck()`](http://msdn.microsoft.com/en-us/library/ff551948.aspx) as you yourself suggest. You can take the most simple example from the [Windows Driver Kit](http://msdn.microsoft.com/en-us/windows/hardware/gg487428.aspx) and cut it down to the barebones. | I recomment [Not My Fault](http://download.sysinternals.com/Files/Notmyfault.zip) from sysinternals. |
1,758,363 | When creating a query with EF, Normally we will create an anonymous type in order to limit the number of columns returned.
But anonymous type cannot be returned or used as a parameter to a method call, which means all work related to that anonymous object should be done inside a single method. This is really bad.
And certainly, we don't want to create explicit types just to represent a subset of an existing entity.
In my point of view, we still wanna play with the existing entity (like Person), but in different scenarios, we just care about certain properties. So I believe the best way is to partially populate an entity. But it seems Linq 2 EF does not support it.
Any suggestions?
Thanks | 2009/11/18 | [
"https://Stackoverflow.com/questions/1758363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/214024/"
] | ```
And certainly, we don't want to create explicit types just to represent a subset of an existing entity.
```
I don't think there is a way to work around it. If you domain model has small set of properties than the EF generated types, then just use LINQ to project the EF model to your domain model. It's actually not that bad, because you are not relying on ET model directly, and it's easier to do TDD. | You can return an anonymous type as `System.Object`, else you have to "create explicit types to represent a subset of an existing entity". What I would do is create a public interface with a subset of the properties of the entity type, and then make the entity type and the subset type both implement it. The subset type can be internal so your application code only sees the entity type and the interface. |
1,104,660 | In Carl Sagan's novel *Contact*, the main character (Ellie Arroway) is told by an alien that certain megastructures in the universe were created by an unknown advanced intelligence that left messages embedded inside transcendental numbers. To check this, Arroway writes a program that computes the digits of $\pi$ in several bases, and eventually finds that the base 11 representation of $\pi$ contains a sequence of ones and zeros that, when properly aligned on a page, produce a circular pattern. She takes this as an indication that there is a higher intelligence that imbues meaning in the universe and yaddayaddayadda.
I always thought that Sagan was pulling a fast one on us. Given that transcendental numbers (or, for that matter, irrational numbers) are infinite, non-repeating sequences of digits, they contain any possible sequence of numbers, including the one Arroway found. It's hard for me to infer anything philosophical/spiritual from the fact that you can find this sequence if you look hard enough (to make a somewhat facile comparison, if I look hard enough in my sock drawer, I will find both socks of any given pair, but you can't take this as evidence for a higher intelligence in the universe). But then, Sagan did know one or two things about math, so maybe I'm missing something here. Are there any circumstances in which finding a particular sequence in a certain position of $\pi$ would make mathematicians go "wow!"? | 2015/01/14 | [
"https://math.stackexchange.com/questions/1104660",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/203950/"
] | Let us assume that pi is a normal number (a reasonable, yet unproven conjecture). Then yes, any combination, specifically the one envisioned by Sagan, is buried somewhere deep inside pi. In this sense there is nothing surprising. However, the surprise would be to find it much sooner than expected. That is the main meaning of Sagan's idea: Not that Ellie found it, but that she found it so early that it would be statistically so improbable, that it would be nearly impossible to occur naturally. | I think the point is that it's would be a highly unusual finding based on the part of Pi we've seen until now. I don't know how big the pattern was but it was the product of two prime number indicating a structure - lets just say it was 121 numbers long (11x11).
That would mean there was a sequence of 121 number that was mostly 0 with some 1s. The question is, how often does such a thing happen - not how often could it happen with an infinite number of numbers - but how often has it happened in the 10^20 numbers they know in the movie.
If it happens all the time.. Most of the number in Pi are 0 or 1 and this time it happened to make a circle - you could say - it's just chance.
But if it's unusual to have a sequence that is only 0s and 1s and on top of that the first/only time we found it formed a picture of a circle - then you should realize this isn't an accident.
To claim that, "but there are still an infinite numbers to look at so probably this happens all the time" is not being intellectually honest. |
61,814,929 | I want to migrate my JSF Application from ManagedBean to CDI Beans.
First of all I have done a simple test to see if CDI are working, but they don't.
Here my example, using Wildfly 10 and myfaces 2.2
beans.xml in .\WEB-INF
```
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
bean-discovery-mode="all">
</beans>
```
xhtml page:
```
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>
test
</title>
</h:head>
<h:body>
<h:outputText value="#{CDITest.hello}"/>
<h:outputText value="test"/>
</h:body>
</html>
```
The backing Bean
```
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import java.io.Serializable;
@Named("CDITest")
@SessionScoped
public class CDITest implements Serializable{
public String getHello(){
return "Hello";
}
}
```
The output
>
> test
>
>
>
No error message (!) and no call to CDITest.getHello() method. What I'm missing? | 2020/05/15 | [
"https://Stackoverflow.com/questions/61814929",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834035/"
] | The problem is more general.
In JSF 2.3, JSF picks up CDI via BeanManager#getELResolver. In pre JSF 2.3, the container or the CDI impl has to marry JSF and CDI. | I think you need to Declare a @FacesConfig annotated class to activate CDI in JSF 2.3
```
import javax.enterprise.context.ApplicationScoped;
import javax.faces.annotation.FacesConfig;
@FacesConfig
@ApplicationScoped
public class ConfigurationBean {
}
``` |
46,270,606 | I'm trying to calculate the cosine similarity between all the values.
The time for 1000\*20000 calculations cost me more than 10 mins.
Code:
```
from gensim import matutils
# array_A contains 1,000 TF-IDF values
# array_B contains 20,000 TF-IDF values
for x in array_A:
for y in array_B:
matutils.cossim(x,y)
```
It's necessary to using gensim package to get the tf-idf value and similarity calculation.
Can someone please give me some advice and guidance to speed up time? | 2017/09/18 | [
"https://Stackoverflow.com/questions/46270606",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8000414/"
] | *O*(*m*√*n*) seems a bit strange to me, but you can get *O*(*m* log *n*) — which is asymptotically even better — by adapting a balanced binary search tree structure (such as a red–black tree) instead of using a literal list.
Specifically, you need a normal binary tree structure, *plus*:
* the nodes have a "subtree-size" property.
+ this will let you calculate the relative position (= list index) of a node in *O*(log *n*) time if you're starting from the root and navigating to it.
* instead of keeping nodes in order by their actual values (0 through *n*−1), each node will have an "identifier". Each time we move a node to the beginning of the list, we set its identifier to be a smaller number than we've used previously for any node (so 0, then −1, then −2, etc.). So we keep the nodes in order by this "identifier".
+ this will let you navigate to a node from the root of the tree given only its identifier.
+ this, plus the preceding, will let you calculate the relative position of a node, given its "identifier", in *O*(log *n*) time.
* a mapping from values to current node "identifiers". (Since your values conveniently range from 0 to n−1, this can just be an array of integers.)
+ this, plus the preceding, will let you calculate the relative position of a node, given only its value, in *O*(log *n*) time.
+ in fact, we don't even need to include the values inside the binary tree structure; the nodes *only* need the identifiers.
* logic to rebalance parent nodes, by "rotating" them as with a red–black tree, when they get too skewed. This can be done in *O*(log *n*) time, and it's essential, since you're going to be continually removing nodes from various parts of the tree and moving them to the leftmost leaf, so the tree will rapidly become very unbalanced if that's not corrected.
You can initialize the tree in *O*(*n*) time, and add or remove a node in *O*(log *n*) time.
Unfortunately, this approach involves a lot of bookkeeping to keep all the sizes updated and to keep everything balanced. That won't affect the algorithmic complexity, but will make for a messy implementation. Maybe someone else can think of something simpler? (Or alternatively, maybe someone else can think of something less "custom", where more of the bookkeeping is handled by an off-the-shelf `java.util.TreeMap` or `std::map` or whatnot?) | Imagine an indexed doubly-linked list. The index is an array `INDICES` of pointers, pointing at nodes numbered 0, √n, 2√n, ..., (n-1)√n. Each node also stores its own index number `IDX` (first √n nodes always store 0, next √n nodes store 1, ...; the indices get updated with each operation so that to keep this invariant).
There is also an array `NODES` of pointers pointing to the nodes. The array never changes.
Now finding an index of an arbitrary node and moving it to the front of the list is an O(√n) operation.
To identify and move node number 5:
1. `NODES[5]` is a pointer to the node that has the number 5.
2. Determine its current position in the list: count from `INDICES[NODES[5]->IDX]` until you find the number 5. This is O(√n).
3. Remove the node from the list and insert it to the front. This is O(1).
4. Update the `INDICES` array and the `IDX` fields of affected nodes. There are O(√n) items in `INDICES` to modify (make them to point to the previous element, `INDICES[i] = INDICES[i]->PREV`), and also O(√n) nodes that need their `IDX` field updated (`INDICES[i]->IDX = INDICES[i]->IDX + 1`). |
6,788,340 | I have a `Map<String, String>` that I'd like to display to a user but I don't want them to be able to select the field to modify it's value. I've been using a form with textfields and setting setting a property to disable them. This is not ideal as their aesthetics change. Am I doing it the correct way and simply need to apply some css or is their a better way of doing this? | 2011/07/22 | [
"https://Stackoverflow.com/questions/6788340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/374265/"
] | You could make a form 'label' which is un-modifiable but looks like the rest of the form. Might need a few tweaks but this should get you started:
```
Ext.form.LabelField = function(config){
Ext.form.LabelField.superclass.constructor.call(this, config);
};
Ext.extend(Ext.form.LabelField, Ext.form.Field, {
isField: true,
value: '',
renderSelectors: {fieldEl: '.x-form-labelfield'},
renderTpl: [
'<tpl if="label">',
'<div class="x-form-label"><span>{label}</span></div>',
'</tpl>',
'<div class="x-form-label x-form-labelfield" style="width:70%; text-align:right"><span>{value}</span></div>',
],
setValue:function(val) {
this.value = val;
if(this.rendered){
this.fieldEl.update('<span>' + val + '</span>');
}
return this;
},
});
Ext.reg('labelfield', Ext.form.LabelField);
``` | I have had the same need and wanted the field to function similar to the ExtJS displayfield. I have done this in Sencha Touch by creating the field, disabling it, then adding back the normal field class. The editor is removed using the disable : true, but the field isn't grayed out and still is easy to read.
```
{
xtype: 'textfield',
disabled: true,
disabledCls: 'x-field',
label: 'Label',
name: 'name'
}
```
This could become a simple override if I had enough of these fields and took the time to override the other field types I needed. |
243,670 | I looted a cybernetic pain inhibitor and cybernetic limb actuator off of Kellogg's body and they are worth quite a bit of caps. I can't tell, however, if they're useful for anything else... like, are they something you can give to Valentine, for instance? Or are they just sellable junk pieces? | 2015/11/16 | [
"https://gaming.stackexchange.com/questions/243670",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/69426/"
] | Pretty sure the post indicating you can have the implants installed by the Institute is a hoax.
I have completed the institute endgame (and non-radiant side quests) and talked to every named NPC in every division (nobody was killed or exiled), none of them mentions the implants when they are in my inventory and no doctors have this as an option in any sub menus. | The two cybernetic items not used for the next quest are miscellaneous items and you can sell them if you want. |
221,069 | I would like to remove an existing cable from the breaker panel, that feeds a single home run outlet, and wire it to a consumer UPS that I will locate near the panel, through a junction box.
**Questions**:
1. To join the power cord from the UPS to the junction box can I put a NEMA 5-15 inlet on the box and use a consumer power cord?
2. Instead of a NEMA inlet **(a)** could I do it with an IEC C14 inlet? **(b)** could I just insert a consumer power cord into the box with strain relief and splice wires inside the box? This would all be on the surface near the breaker panel, nothing inside walls but also no conduits.
3. As a further optional step, if the junction box additionally is fed raw power and I add a switch to bypass the UPS, can I just switch the hot or must the neutrals be switched too? The grounds? I assume the UPS input and output grounds are bonded but I don't know about the neutrals. The inlet hot would never be connected to the raw power hot, but is there still any unacceptable danger in this arrangement?
[](https://i.stack.imgur.com/l8HJL.jpg)
[This question](https://diy.stackexchange.com/questions/166657/getting-ups-power-from-one-room-to-another) is instructive but the answers focus on the practicality of running new cable from room to room. My situation is to use existing, to-code, wiring from the basement to the room, and adds the idea of switching to raw power. | 2021/03/30 | [
"https://diy.stackexchange.com/questions/221069",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/65210/"
] | Yes.
You can run an isolated electrical line, using normal in-wall wiring methods, from a single inlet to outlets.
The inlet will need to be in the NEMA family. A C13 inlet won't cut it for at least 2 reasons off the top of my head: first it lacks the necessary ampacity, and second it is voltage-agnostic, and the inlet needs to be keyed to reject a power source of the wrong voltage.
As far as having a built-in switch, same rules apply as for a generator. You must have exactly one neutral-ground bond in the entire system. Not zero, not two. ("two" is its own special kind of 'bad'). If the power source bonds neutral and ground, then you must switch neutral. If it does not, then you must not.
The best bet is to switch neutral, but not bond neutral around the switch - have the isolated circuit draw neutral only from the switch. These types of switches are expensive, so I'd just do cord-and-plug myself.
You would never have a reason to switch safety ground. | You could install one of these upstream of the outlet: <https://ezgeneratorswitch.com>
I am not affiliated with them in any way. |
38,027,402 | I'm going through some tutorials on how smart pointers work in **C++**, but I'm stuck on the first one I tried: the *unique pointer*. I'm following guidelines from [wikipedia](https://en.wikipedia.org/wiki/Smart_pointer), [cppreference](http://en.cppreference.com/w/cpp/memory/unique_ptr) and [cplusplus](http://www.cplusplus.com/reference/memory/unique_ptr/). I've also looked at [this answer](https://stackoverflow.com/questions/16894400/how-to-declare-stdunique-ptr-and-what-is-the-use-of-it) already. A unique pointer is supposed to be the only pointer that has ownership over a certain memory cell/block if I understood this correctly. This means that only the unique pointer (should) point to that cell and no other pointer. From wikipedia they use the following code as an example:
```
std::unique_ptr<int> p1(new int(5));
std::unique_ptr<int> p2 = p1; //Compile error.
std::unique_ptr<int> p3 = std::move(p1); //Transfers ownership. p3 now owns the memory and p1 is rendered invalid.
p3.reset(); //Deletes the memory.
p1.reset(); //Does nothing.
```
Until the second line, that worked fine for me when I test it. However, after *moving* the first unique pointer to a second unique pointer, I find that both pointers have access to the same object. I thought the whole idea was for the first pointer to be rendered useless so to speak? I expected a null pointer or some undetermined result. The code I ran:
```
class Figure {
public:
Figure() {}
void three() {
cout << "three" << endl;
}
};
class SubFig : public Figure {
public:
void printA() {
cout << "printed a" << endl;
}
};
int main()
{
unique_ptr<SubFig> testing (new SubFig());
testing->three();
unique_ptr<SubFig> testing2 = move(testing);
cout << "ok" << endl;
int t;
cin >> t; // used to halt execution so I can verify everything works up til here
testing->three(); // why is this not throwing a runtime error?
}
```
Here, `testing` has been moved to `testing2`, so I'm surprised to find I can still call the method `three()` on `testing`.
Also, calling *reset()* doesn't seem to delete the memory like it said it would. When I modify the main method to become:
```
int main()
{
unique_ptr<SubFig> testing (new SubFig());
testing->three();
unique_ptr<SubFig> testing2 = move(testing);
cout << "ok" << endl;
int t;
cin >> t;
testing.reset(); // normally this should have no effect since the pointer should be invalid, but I added it anyway
testing2.reset();
testing2->three();
}
```
Here I expect `three()` not to work for `testing2` since the example from wikipedia mentioned the memory should be deleted by resetting. I'm still printing out *printed a* as if everything is fine. That seems weird to me.
So can anyone explain to me why:
* moving from one unique pointer to another unique pointer doesn't make the first one invalid?
* resetting does not actually *remove* the memory? What's actually happening when `reset()` is called? | 2016/06/25 | [
"https://Stackoverflow.com/questions/38027402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2959880/"
] | Essentially you invoke a member function through a null pointer:
```
int main()
{
SubFig* testing = nullptr;
testing->three();
}
```
... which is undefined behavior.
From 20.8.1 Class template unique\_ptr (N4296)
>
> 4 Additionally, u can, upon request, transfer ownership to another
> unique pointer u2. Upon completion of such a transfer, the following
> **postconditions** hold:
>
>
> * u2.p is equal to the pre-transfer u.p,
> * **u.p is equal to nullptr**, and
> * if the pre-transfer u.d maintained state, such state has been transferred to u2.d.
>
>
>
(emphasis mine) | On calling `std::unique_ptr<int> p3 = std::move(p1);` your original pointer `p1` is in undefined state, as such using it will result in undefined behavior. Simply stated, never ever do it. |
951,473 | Let A be matrix $2\times 2$ and take integer $k \geq 2$. Show that if $A^k = 0$ then we must have that $A^2 = 0$ | 2014/09/29 | [
"https://math.stackexchange.com/questions/951473",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/179403/"
] | Suppose that $A$ has an inverse matrix. Then, multiplying the both sides of
$$A^k=O$$
by $\left(A^{-1}\right)^k$ gives us $I=O$ where $I$ is the identity matrix, which is a contradiction.
Hence, if we set $A=\begin{pmatrix} a&b\\c&d\end{pmatrix}$, then we have $ad-bc=0$. So, by the Cayley–Hamilton theorem, we have
$$A^2=(a+d)A-(ad-bc)I=(a+d)A.\tag1$$
Hence, we have
$$A^3=(a+d)^2A,\ \ A^4=(a+d)^3A,\cdots, A^k=(a+d)^{k-1}A.$$
Since $A^k=O$, we have
$$a+d=0\ \ \ \text{or}\ \ \ A=O.$$
From $(1)$, in either case, we have $A^2=O$. | Here is a laboured way of explaining a more general case (you have $k=2$). But it relies on more general theory.
Presumably it is a matrix over a field $\mathbb F$. Once a basis is chosen for a vector space $V$ of dimension $k$ over $\mathbb F$, a $k\times k$ matrix $M$ represents a linear map on $V=\mathbb F^k$.
Let $I\_n$ be the image of $V$ under $M^n$ with $I\_0=V$. Note that for $n\ge 1$we have $M^{n+1}V=M^n(MV)$. Because $MV\subset V$ we then have $I\_{n+1}\subset I\_n$.
Now suppose $\dim I\_n=\dim I\_{n+1}\gt 0$. Since the dimensions are equal, and $I\_{n+1}\subset I\_n$ we have $I\_{n+1}=I\_n$, and $MI\_n=I\_n\neq 0$. This implies that $M^rI\_n=I\_n\neq 0$ for all positive integers $r$, which contradicts the fact that $M$ is nilpotent.
We therefore have $\dim I\_n \leq \max(\dim V-n,0)$ and in particular $\dim I\_k=0$ whence $M^k=0$ |
3,262,904 | Can anyone solve the matrix equation $A^5=I$ where $I$ is the $2 \times 2$ identity matrix and $A$ is such that $\det(A)$ is non-zero and $A^n \neq I$ for $n \lt 5.$
I have tried to solve it but I do not know how to solve matrix equations.I actually want to find an infinite group in GL(2,R) such that infinitely many elements of that group has an order of 5. | 2019/06/15 | [
"https://math.stackexchange.com/questions/3262904",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] | OP indicates that what's wanted is a matrix $A$ with real entries. That means its characteristic polynomial $p(x)$ must be a factor of $(x^5-1)/(x-1)=x^4+x^3+x^2+x+1$ with real coefficients. Letting $z$ stand for $e^{2\pi i/5}$, the zeros of $p(x)$ (which are the eigenvalues of $A$) must be $z$ and $z^{-1}$, or $z^2$ and $z^{-2}$.
Taking the first case, $p(x)=x^2-(z+z^{-1})x+zz^{-1}=x^2-2\cos(2\pi/5)x+1$. One matrix that works is the [companion matrix](https://en.wikipedia.org/wiki/Companion_matrix) to this polynomial, $$A\_1=\pmatrix{0&-1\cr1&2\cos(2\pi/5)\cr}$$ which evidently has trace $2\cos(2\pi/5)$ and determinant $1$, as required. Any matrix similar to $A\_1$ will also fill the bill, so $B=C^{-1}A\_1C$ is an answer for any invertible real $2\times2$ matrix $C$.
Equivalently, the matrix that rotates everything in ${\bf R}^2$ by $2\pi/5$ counterclockwise, $$A\_1'=\pmatrix{c&-s\cr s&c\cr}$$ where I've written $c$ and $s$ for $\cos(2\pi/5)$ and $\sin(2\pi/5)$, respectively, can be used, so we get $D^{-1}A\_1'D$ as describing exactly the same set of matrices as above.
Now we come back to the other characteristic polynomial, $p(x)=(x-z^2)(x-z^{-2})=x^2-2\cos(4\pi/5)x+1$. This can be treated exactly as above, giving rise to a second infinite family of solutions. These two infinite families give all the solutions. | The firdt answer is true. But there is more. The most general is
$$A=S\begin{pmatrix}
\xi^a & 0\\
0 & \xi^b
\end{pmatrix} S^{-1}$$
For any S, and $(a, b)\in\{0, 1, 2, 3, 4\}^2\backslash\{(0,0)\}$ |
107,822 | I installed Mavericks (upgrading from Mountain Lion) on my MacBook Pro (from early 2011) and the install seemed to go fine. However, this morning while I was working on PowerPoint, it switched off with no warning at all (it was connected to AC power and battery was full). Then, it refused to boot. After the spinning bar under the logo, it just gave a gray screen and was completely unresponsive. I tried to boot into safe mode by pressing ⇧ shift while booting and it reached a blue screen with vertical black stripes and was again unresponsive.
Then I tried clearing the NVRAM with ⌘⌥PR and it again reached an unresponsive gray or blue screen if I waited long enough. Tried Internet Recovery but after downloading something for an hour it again gave the blue screen with vertical stripes.
Any idea what I can do? Can I use a Linux LiveDVD or something to extract some data I have on it?
ETA: Ran the hardware test from the included Applications DVD and it did not find any troubles. Trying to boot with a LiveDVD did not work. Did get to the stage where I select from the range of boot options but then the boot did not complete. Tried with Ubuntu and CentOS. | 2013/10/31 | [
"https://apple.stackexchange.com/questions/107822",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/61206/"
] | Most likely a hardware failure. See here: <http://appleinsider.com/articles/13/10/14/apples-2011-macbook-pro-lineup-suffering-from-sporadic-gpu-failures> | I have the same issue as you. It is a GPU failure. I have a solution for that which is I am using.
First reset the PRAM. It will boot with waves on the screen. The screen will go grey with no Apple logo. It will shutdown itself after sometime. Boot now and it will work. Download a software called gfxCardStatus. Change the GPU to Intel HD. Never use Flash or Phoroshop or any graphics heavy app.
If your Mac is stuck at Boot screen with the wheel, reset PRAM and follow the above instructions. It should work. |
29,782,587 | ```
df <- as.data.frame(cbind(c(1:10), c(15, 70, 29, 64, 57, 29, 10, 80,81, 71)))
V1 V2
1 1 15
2 2 70
3 3 29
4 4 64
5 5 57
6 6 29
7 7 10
8 8 80
9 9 81
10 10 71
cuts <- c(5, 10, 90, 95)
```
I would like to create logical variables for all (in this case, four) cut values `x` (e.g. `P5`, `P10`, `P90` and `P95`) that indicate whether `v2 <= x`. The straightforward way of adding variables "by hand" does not scale beyond a handful:
```
df %<>%
mutate( P5 = V2 <= 5) %>%
mutate(P10 = V2 <= 10) %>%
mutate(P90 = V2 <= 90) %>%
mutate(P95 = V2 <= 95)
V1 V2 P5 P10 P90 P95
1 1 15 FALSE FALSE TRUE TRUE
2 2 70 FALSE FALSE TRUE TRUE
3 3 29 FALSE FALSE TRUE TRUE
4 4 64 FALSE FALSE TRUE TRUE
5 5 57 FALSE FALSE TRUE TRUE
6 6 29 FALSE FALSE TRUE TRUE
7 7 10 FALSE TRUE TRUE TRUE
8 8 80 FALSE FALSE TRUE TRUE
9 9 81 FALSE FALSE TRUE TRUE
10 10 71 FALSE FALSE TRUE TRUE
```
Obviously, to keep the data in "tidy" format, a final `gather(year, islegal, c(3;6))` should be applied.
An alternative that I tried is to do
```
do.call(rbind, lapply(cuts, function(x) {
df %>% mutate(year = x, islegal = V2 <= x)
})) %>% spread(year, islegal)
V1 V2 5 10 90 95
1 1 15 FALSE FALSE TRUE TRUE
2 2 70 FALSE FALSE TRUE TRUE
3 3 29 FALSE FALSE TRUE TRUE
4 4 64 FALSE FALSE TRUE TRUE
5 5 57 FALSE FALSE TRUE TRUE
6 6 29 FALSE FALSE TRUE TRUE
7 7 10 FALSE TRUE TRUE TRUE
8 8 80 FALSE FALSE TRUE TRUE
9 9 81 FALSE FALSE TRUE TRUE
10 10 71 FALSE FALSE TRUE TRUE
```
Obviously, I would drop the final `spread()` to keep the data in "tidy" format.
**Question**: are there better or more generic ways of using `{dplyr}` than the second approach for automating variable creation (quantile-like cutoffs like here, or dummies or similar), that do not require explicitly typing out the contents of `cuts` like the first approach? | 2015/04/21 | [
"https://Stackoverflow.com/questions/29782587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/819272/"
] | Surely you don't need dplyr for something this simple.
```
names(cuts) <- paste0("p", cuts)
data.frame(df, lapply(cuts, function(x) df$V2 <= x))
V1 V2 p5 p10 p90 p95
1 1 15 FALSE FALSE TRUE TRUE
2 2 70 FALSE FALSE TRUE TRUE
3 3 29 FALSE FALSE TRUE TRUE
4 4 64 FALSE FALSE TRUE TRUE
5 5 57 FALSE FALSE TRUE TRUE
6 6 29 FALSE FALSE TRUE TRUE
7 7 10 FALSE TRUE TRUE TRUE
8 8 80 FALSE FALSE TRUE TRUE
9 9 81 FALSE FALSE TRUE TRUE
10 10 71 FALSE FALSE TRUE TRUE
``` | If you plan to eventually convert your data to a tidy data, you may simply start with one:
```
library(dplyr)
df <- as.data.frame(cbind(c(1:10), c(15, 70, 29, 64, 57, 29, 10, 80,81, 71)))
cuts <- data_frame(P=c(5, 10, 90, 95))
p_df <- df %>% tidyr::crossing(cuts) %>%
mutate(flag=V2<=P)
p_df
# V1 V2 P flag
#1 1 15 5 FALSE
#2 1 15 10 FALSE
#3 1 15 90 TRUE
#4 1 15 95 TRUE
#5 2 70 5 FALSE
#...
```
If the original format is really what you want, `tidyr::spread` the result
```
p_df %>%
tidyr::spread(P, flag, sep="")
# V1 V2 P5 P10 P90 P95
#1 1 15 FALSE FALSE TRUE TRUE
#2 2 70 FALSE FALSE TRUE TRUE
#3 3 29 FALSE FALSE TRUE TRUE
#4 4 64 FALSE FALSE TRUE TRUE
#5 5 57 FALSE FALSE TRUE TRUE
#6 6 29 FALSE FALSE TRUE TRUE
#7 7 10 FALSE TRUE TRUE TRUE
#8 8 80 FALSE FALSE TRUE TRUE
#9 9 81 FALSE FALSE TRUE TRUE
#10 10 71 FALSE FALSE TRUE TRUE
``` |
31,632,078 | In my application, I want to check whether or not the server I am connecting to is trustable. Instead of using SSL, which would come with the cost of a certificate , I thought about creating my own identity check, where I would send a random string to the server at connection. The server would rsa encrypt the string with a hard-coded private key and send the result back. The client application would then decrypt the result with a hard coded public key (it has only the public key, not the private one). If the string it sent and the string it decrypted matched, the server's identity would be proven and the tcp communication would just be encrypted with AES (The AES key is transferred in rsa encrypted format after the server identity was proven).
Questions:
1. Is this approach viable and if yes, where are the weaknesses?
(besides me having to keep the private key secret, obviously)
2. What advantages would I gain by using SSL with a bought certificate in this circumstance?
3. Would a self-signed SSL certificate also be enough in this circumstance? I plan to make the service publicly available. | 2015/07/25 | [
"https://Stackoverflow.com/questions/31632078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4119197/"
] | >
> I want to check whether or not the server I am connecting to is trustable.
>
>
>
Both your approach and the approach with using SSL can not provide any information about how trustable the server is but offer only a way to identify the server, i.e. to make sure that your are talking with the expected server. The server can still be hacked and serve malware so you should not trust it just based on the identification.
>
> I thought about creating my own identity check, where I would send a random string to the server at connection ... rsa encrypt ... hard-coded private key ... hard coded public key ...
>
>
>
You are effectively trying to re-invent TLS with certificate pinning. It is not a requirement of TLS that certificates need be be bought from a public CA. You can simply create self-signed certs as long as the expected certificate or public key is known to the client in advance, i.e. before connecting. The main point of using certificates signed by a public CA instead of self-signed is, that it does not scale to have each certificate on the world installed into the clients browser/OS but it scales to have a few trust anchors (root CA) installed.
For more information on how to use TLS with certificate/public key pinning the this [page at OWASP](https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning) which even includes code examples for various languages. | I recommend that you use TLS. Over time, mistakes in TLS have been found and fixed. To start with your own design and make the assumption that you could not make similar mistakes is a big risk.
You can create your own server certificate for free, especially if you are embedding the server public key in the client because then you are not dependent on a public CA to authenticate the server's identity.
You also introduce a weakness by using the private key to encrypt and the public key to decrypt, which is not what RSA was designed for (the *public* key is used to encrypt). To make the assumption that this is just fine, is another big risk. |
4,607,594 | I am working on a LAMP(PHP) stack.
Scenario - I want to redirect the incoming traffic to the site to a different website based on a percentage.
Example : Main www.a.com. I have few other sites - www.a1.com, www.a2.com, www.b1.com, www.b2.com.
Now when the traffic comes to my main site www.a.com, I would like to divide the traffic like -
```
33% of traffic redirected to www.a1.com
33% of traffic redirected to www.a2.com
30% of traffic redirected to www.b1.com
4% of traffic redirected to www.b2.com
```
how can i achieve this? I am a php developer so would like to do it through php, but also would like to know if any other technologies are involved.
------ updates ----
I want to achieve this functionality once the user clicks on the logout button on the main site.
Thanks,
Tanmay | 2011/01/05 | [
"https://Stackoverflow.com/questions/4607594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/351062/"
] | Generate a random number between 1 and 100,
```
0-32 redirected to www.a1.com
33-65% redirected to www.a2.com
66-95% redirected to www.b1.com
96-99% redirected to www.b2.com
```
you can provide these functionalities using your server. Check out those keywords: nginx, round robin. | ```
$route_decider = rand(0, 99);
/**
/* Remember there should not be an output before the header response. Browsers must see HTTP header
/* response first! Upon logout redirect to a page containing this code.
/*
**/
if ( $router_decider >= 0 && $route_decider <= 32) # 33 %
header( 'Location: http://www.a1.com' );
if ( $router_decider >= 33 && $route_decider <= 65) # 33 %
header( 'Location: http://www.a2.com' );
if ( $router_decider >= 66 && $route_decider <= 95) # 30 %
header( 'Location: http://www.b1.com' );
if ( $router_decider >= 96 && $route_decider <= 99) # 4 %
header( 'Location: http://www.b2.com' );
``` |
54,095,476 | I am trying to run my server and have my app.component.html load on localhost:8000. Instead, I am receiving this error
>
> compiler.js:7992 Uncaught Error: Expected 'styles' to be an array of strings.
> at assertArrayOfStrings (compiler.js:7992)
> at >CompileMetadataResolver.push../node\_modules/@angular/compiler/fesm5/compiler.j>s.CompileMetadataResolver.getNonNormalizedDirectiveMetadata >>(compiler.js:17325)
> at >CompileMetadataResolver.push../node\_modules/@angular/compiler/fesm5/compiler.j>s.CompileMetadataResolver.\_getEntryComponentMetadata (compiler.js:17970)
> at compiler.js:17630
> at Array.map ()
> at >CompileMetadataResolver.push../node\_modules/@angular/compiler/fesm5/compiler.j>s.CompileMetadataResolver.getNgModuleMetadata (compiler.js:17630)
> at >JitCompiler.push../node\_modules/@angular/compiler/fesm5/compiler.js.JitCompile>r.\_loadModules (compiler.js:24899)
> at >JitCompiler.push../node\_modules/@angular/compiler/fesm5/compiler.js.JitCompile>r.\_compileModuleAndComponents (compiler.js:24880)
> at >JitCompiler.push../node\_modules/@angular/compiler/fesm5/compiler.js.JitCompile>r.compileModuleAsync (compiler.js:24840)
> at CompilerImpl.push../node\_modules/@angular/platform-browser->dynamic/fesm5/platform-browser-dynamic.js.CompilerImpl.compileModuleAsync >>(platform-browser-dynamic.js:143)
>
>
>
I tried messing around with the syntax and checked my angular.json file.
```
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'public';
}
```
Any idea on how to solve this? This is blocking me from loading my google | 2019/01/08 | [
"https://Stackoverflow.com/questions/54095476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10885103/"
] | I had the same console error, spent a few days reading every hit on Google...
Solved!
The story:
I had to add functionality to an existing Angular project. When I performed git clone, ng serve, open browser -> error assert....
I decided to upgrade to Angular 8 and see if the problem goes away, and it didn't. Eventually, I created a new Angular 8 app using "ng new ..."
Compared package.json and angular.json of both existing and new project. I found out, the brand new Angular app, had no *loader* packages In package.json, while the existing did have. Also the existing project was specifying a webpack devDependancy, i removed all loaders, and webpack, deleted package-lock.json and node\_modules folder -> npm install.
Solved. I guess there is some bit of code that was being forced to a specific version, conflicting with what Angular really needs. | changing scss loader in webpack.config.js fixed it for me.
It should look like this:
```
{
test: /\.scss$/,
exclude: [/node_modules/, /\.global\.scss$/],
use: ["to-string-loader", "css-loader", "sass-loader"]
}
```
and in package json:
```
"to-string-loader": "^1.1.6",
"css-loader": "^3.4.2",
"sass-loader": "^8.0.2"
``` |
6,592,318 | ```
int numbers*;
numbers = malloc ( sizeof(int) * 10 );
```
I want to know how is this dynamic memory allocation, if I can store just 10 `int` items to the memory block ? I could just use the array and store elemets dynamically using index. Why is the above approach better ?
I am new to C, and this is my 2nd day and I may sound stupid, so please bear with me. | 2011/07/06 | [
"https://Stackoverflow.com/questions/6592318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305228/"
] | The main reason why `malloc()` is useful is *not* because the size of the array can be determined at runtime - modern versions of C allow that with normal arrays too. There are two reasons:
* Objects allocated with `malloc()` have flexible lifetimes;
That is, you get runtime control over when to create the object, and when to destroy it. The array allocated with `malloc()` exists from the time of the `malloc()` call until the corresponding `free()` call; in contrast, declared arrays either exist until the function they're declared in exits, or until the program finishes.
* `malloc()` reports failure, allowing the program to handle it in a graceful way.
On a failure to allocate the requested memory, `malloc()` can return `NULL`, which allows your program to detect and handle the condition. There is no such mechanism for declared arrays - on a failure to allocate sufficient space, either the program crashes at runtime, or fails to load altogether. | Array is used to allocate memory statically and in one go.
To allocate memory dynamically malloc is required.
e.g. `int numbers[10];`
This will allocate memory statically and it will be contiguous memory.
If you are not aware of the count of the numbers then use variable like count.
```
int count;
int *numbers;
scanf("%d", count);
numbers = malloc ( sizeof(int) * count );
```
This is not possible in case of arrays. |
1,866,584 | I have the following classes...
```
public class Order
{
private Guid id;
public Guid ID
{
get { return id; }
set { id = value; }
}
private List<Items> orderItems;
public List<Items> OrderItems
{
get { return orderItems; }
set { orderItems= value; }
}
}
public class Item
{
private Guid id;
public Guid ID
{
get { return id; }
set { id = value; }
}
private string itemName;
public string ItemName
{
get { return itemName; }
set { itemName = value; }
}
}
```
Then within my application I try the following....
```
ACME.Order newOrder = new ACME.Order();
newOrder.ID = xxx
newOrder.OrderItems = new List<OrderItem> {
new ACME.OrderItem {
ID = xxx
ItemName = xxx
}
}
```
However I get the error "Cannot implicitly convert type `'System.Collections.Generic.List<ACME.Item>'` to `ACME.Item[]`. The strange thing as well is that all I don't have an "Add" option on any of my list objects. | 2009/12/08 | [
"https://Stackoverflow.com/questions/1866584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/222614/"
] | Is your application on the client side of a Web service?
If so, the proxy generator for .asmx and WCF Web services generates an array `T[]` on the client side where a service interface uses a `List<T>` (or, indeed, any other enumerated type).
Your application will need to cast the list to an array (use `.ToArray()`) to set the array property client-side. | Ignoring typos I would recommend turning your generic list on Order to auto initialize. Then you just always deal with the list directly instead of worrying about initialization when adding items. So something like:
```
public class Order
{
public Guid ID { get; set; }
private List<Item> orderItems;
public List<Item> OrderItems
{
get
{
if (orderItems == null)
orderItems = new List<Item>();
return orderItems;
}
}
}
public class Item
{
public Guid ID { get; set; }
public string ItemName { get; set; }
}
```
Then in your application you would do something like:
```
Order newOrder = new Order { ID = new Guid() };
newOrder.OrderItems.Add( new Item() { ID = new Guid(), ItemName = "New Item"});
``` |
41,268,419 | I have this html snippet:
```
<form class="job-manager-form" enctype="multipart/form-data">
<fieldset>
<label>Have an account?</label>
<div class="field account-sign-in">
<a class="button" href="">Sign in</a>
</div>
</fieldset>
<!-- Job Information Fields -->
<fieldset class="fieldset-job_title">
<label for="job_title">Job Title</label>
<div class="field required-field">
<input type="text" class="input-text" required="">
</div>
</fieldset>
<fieldset class="fieldset-job_location">
<label for="job_location">Location <small>(optional)</small></label>
<div class="field ">
<input type="text" class="input-text" name="job_location" id="job_location" placeholder="e.g. "London"" value="" maxlength="">
<small class="description">Leave this blank if the location is not important</small> </div>
</fieldset>
<fieldset class="fieldset-application">
<label for="application">Application email/URL</label>
<div class="field required-field">
<input type="text" class="input-text" name="application" id="application" placeholder="Enter an email address or website URL" value="" maxlength="" required="">
</div>
</fieldset>
</form>
```
And I would like to select first fieldset in the form. This what I am doing:
```
form.job-manager-form:first-child {
background-color: red;
}
```
But it selects all fieldset elements. How does :first-child works?
JSFiddle is [here](https://jsfiddle.net/uycop55x/). | 2016/12/21 | [
"https://Stackoverflow.com/questions/41268419",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385385/"
] | ```
fieldset:first-child {
background-color: red;
}
```
This will work. However, your first-child fieldset is set to display:none; so it will not actually show the background color. | It selects an element if it is the first child of its parent.
Your selector doesn't select any fieldsets. It selects the form.
The fieldsets have a (default) transparent background, so you can see the red through them.
To select the fieldset that is the first child of a form you would need:
```
form.job-manager-form > fieldset:first-child
``` |
56,536,422 | I am trying to create two sections, one left and one right, where one of them is a image and the other one is text. They should always be the same width and height and always square. I use the Avada theme on Wordpress and trying to fix this with their Element Builder and custom css. No luck.
Here is a page where the resault is not square but responsive:
<https://sundlof.se/devskargard/>
I have found some codes that does force div to be square but they don´t take the other square in to the equation. If this requires jQuery, please tell me, I have not yet tried that, I really what to get this done with css if possible.
Any ideas will be much appreciated!
Regards,
Fredrik | 2019/06/11 | [
"https://Stackoverflow.com/questions/56536422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2739771/"
] | You Just go through following links then you will get an idea about the aspect ratios and responsive blocks.
[Learn how to maintain the aspect ratio of an element with CSS.](https://www.w3schools.com/howto/howto_css_aspect_ratio.asp)
[Aspect Ratio Boxes Advanced](https://css-tricks.com/aspect-ratio-boxes/)
```
<div class="container">
<div class="text">1:1 Aspect ratio</div>
</div>
.container {
background-color: red;
position: relative;
width: 100%;
padding-top: 100%; /* 1:1 Aspect Ratio */
}
.text {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
text-align: center;
font-size: 20px;
color: white;
}
```
[Example](https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_aspect_ratio) | Thanks for the help!
I ended up to justify the square with media querys every 200 och 300px to keep it close to square. Not a beautiful solution, but a simple one. |
17,372,572 | I'm trying to authenticate using ADAM and LDAP. I really have no experience with this stuff, but I've been thrown in the deep end at work to figure it out.
Here's what I know. I'm using a program called JXplorer to look at the ADAM server, running on a VM on my computer. [Here are the login details](http://tinypic.com/r/34gn0hx/5)
This works perfectly. What I'm trying to do is replicate this process using VB.NET. I've tried a bunch of stuff and nothing seems to be working, I'm getting constant exceptions, ranging from bad password to unknown error. Here's the code I've started with -
```
Dim userName As String = "ADAM_TESTER"
Dim userPassword As String = "password"
Dim serverAddress As String = "LDAP://10.0.0.142:389"
Private Sub Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim de As DirectoryEntry = New DirectoryEntry("LDAP://10.0.0.142:389/OU=Users,DC=TEST,DC=corp", userName, userPassword)
Dim deSearch As DirectorySearcher = New DirectorySearcher()
deSearch.SearchRoot = de
deSearch.Filter = "(&(objectClass=user) (cn=" + userName + "))"
Dim results As SearchResultCollection = deSearch.FindAll()
If (results.Count > 0) Then
Dim d As DirectoryEntry = New DirectoryEntry(results(0).Path, userName, userPassword)
If (d.Guid.ToString IsNot Nothing) Then
'The directory entry is valid
'DoSomething()
End If
End If
```
I've also tried changing the userName above to the details in User DN in JXplorer. I'm really stuck here and have been looking for answers for hours.
Any help would be appreciated. | 2013/06/28 | [
"https://Stackoverflow.com/questions/17372572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1786580/"
] | Thanks for the thoughts Geoff, I eventually figured it out. It turned out that I needed the connection string not including the OU=Users. The final string ended up being -
LDAP://10.0.0.142:389/DC=TEST,DC=corp
I've no idea why it didn't want the OU=Users. I spend about a day trying all the different combinations until finally this was accepted. | It is almost certainly a need for `userName` to be the full DN. ADAM needs a full DN for logins in most cases. |
605 | Depuis quelques jours, le Colonel Kadhafi fait la une des journaux mondiaux. En anglais, c'est orthographié Gadhafi (CNN) ou Gaddafi (BBC) et, dans les pays francophones, par Kadhafi. L'arabe se prononce [ainsi](http://upload.wikimedia.org/wikipedia/commons/8/86/Ar-Muammar_al-Qaddafi.ogg).
Je pense aussi à [Mikhaël Gorbatchev](http://upload.wikimedia.org/wikipedia/commons/e/e5/Ru-Mikhail_Sergeyevich_Gorbachev.ogg) (français).
Quelle autorité décide de l'orthographe française ? Est-ce basé sur la prononciation ? | 2011/08/26 | [
"https://french.stackexchange.com/questions/605",
"https://french.stackexchange.com",
"https://french.stackexchange.com/users/104/"
] | L'orthographe de noms étrangers a différentes sources:
* une longue tradition (qui peut avoir sa source dans un des points suivants)
* l'orthographe de la langue source
* un approximation phonétique
* un système de translittération (c.-à.-d. une transformation mécanique de l'orthographe étrangère — souvent dans un alphabet étranger — en une orthographe en alphabet latin). Il y a souvent plusieurs systèmes concurrents (exemple pour le chinois, les Français en ont un, les Anglais un autre et les Chinois le leur ; la tendance actuelle est d'utiliser le système Chinois d'où « Beijing » qui remplace « Pékin »). | Dans le cas de [Pékin](http://fr.wikipedia.org/wiki/P%C3%A9kin), l'ortographe usuelle a été recommandée par une certaine [Commission générale de terminologie et de néologie](http://fr.wikipedia.org/wiki/Commission_g%C3%A9n%C3%A9rale_de_terminologie_et_de_n%C3%A9ologie), et [publiée](http://www.legifrance.gouv.fr/affichTexte.do?cidTexte=JORFTEXT000019509867&dateTexte=) au [Journal officiel de la République française](http://fr.wikipedia.org/wiki/Journal_officiel_de_la_R%C3%A9publique_fran%C3%A7aise).
Pour Kadhafi, par contre, ça ne nous aide pas. |
42,571,175 | I have updated android studio from 2.2 to 2.3,then I found **Instant run** not working.
>
> Error while executing: am startservice com.example.codingmaster.testcc/com.android.tools.fd.runtime.InstantRunService
> Starting service: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.codingmaster.testcc/com.android.tools.fd.runtime.InstantRunService }
> Error: Not found; no service started.
>
>
>
I also try reinstall android studio 2.3 but not work. | 2017/03/03 | [
"https://Stackoverflow.com/questions/42571175",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6138207/"
] | [](https://i.stack.imgur.com/CLTQo.png)
from 2.3 There is new icon.
[see this.](https://www.youtube.com/watch?v=lpaByLW_ctw) | * Goto File-settings, "Build, Execution, Deployment"
* click on instantRun
* Uncheck Enable instant run Checkbox
* then apply and ok will solve your problem |
63,810,941 | I wrote a python script which is deployed in a EC2 Instance and lets say this EC2 reside in AWS account **A1**. Now my script from **A1** want to access 10 other AWS account.
And remember I don't have any `AWS_ACCESS_KEY` or `SECRET_KEY` of any account cause using `AWS_ACCESS_KEY` or `SECRET_KEY` is strictly prohibited here.
I can easily do that if I have access key. But I can't figure it out how can I do that without access key?
Is there any possible way to do that? | 2020/09/09 | [
"https://Stackoverflow.com/questions/63810941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7145207/"
] | The EC2 should assume an IAM Role.
Then log in to all your 10 other accounts and create roles there. These roles should give cross account access to the EC2 instance role. It is also in these roles that you define what permissions the EC2 instance should have. | Storing `AWS_ACCESS_KEY` and `AWS_SECRET_KEY` in your code or EC2 instances is generally considered a bad practice.
You should handle permissions by attaching an IAM Role to the EC2 instance that is running your business logic ([Docs here](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html)).
By doing that you will then need an appropriate IAM Role that has enough rights to perform the actions you need in the other accounts ([Docs here](https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_cross-account-with-roles.html)). |
32,870,004 | In my Rivr application I was using
>
> firstTurn.getParameter("nexmo\_caller\_id");
>
>
>
to get caller ID as I saw that parameter passed by Nexmo, but I've changed to Voxeo and obviously that is not working anymore. Does Rivr has any standard method to get Caller ID (remote caller number) in a Dialogue?
Thanks | 2015/09/30 | [
"https://Stackoverflow.com/questions/32870004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194735/"
] | After a bit of playing around I was able to figure out a solution to my problem:
I can see that an extension is added to the experimental instance of Visual Studio when you successfully build the project (I've found no other way of installing the extension (VS2013)). If you try to build the project without the extension installed on the experimental instance, the build fails.
Of course, this would mean that you could never build the project, because you need to build it to install the extension, and the extension needs to be installed for the project to build. Only on the very first build of the project is this not true. You can build without the extension installed, which will then install the extension on the experimental instance and allow future builds of the project.
If, like me, you uninstall the extension on the experimental instance, you're going to get into a catch-22 situation where the build fails, because the extension isn't installed, and you can't install the extension, because the build fails.
The solution to this was simple enough. I just had to run the project, at which point the build would fail, then choose to run the project from the last successful build. This will open the experimental instance without the extension installed, however, if you close the experimental instance, you can then build the project successfully, which will install the extension again.
I don't know exactly why this fixes the problem, but I'd love to know if anyone has any ideas. | This great post shows all the possible solutions:
[http://comealive.io/Vsix-extension-could-not-be-found/](https://web.archive.org/web/20180830055205/http://comealive.io/Vsix-extension-could-not-be-found/)
This one worked for me:
Increasing the version of the package in the .vsixmanifest file |
68,390,320 | Is it possible to add objects into an Arraylist through a for-loop?
I would like to shorten down the code! or do you have any other tips on how to create a word quiz with different classes and methods?
I have three classes, `Main` that drives the game, `Quiz` where the game is constructed, and a class with the Dictionary with all the words.
```java
ArrayList<Sweng> Wordlist = new ArrayList<Sweng>();
Sweng s1 = new Sweng("bil", "car");
Sweng s2 = new Sweng("blå", "blue");
Sweng s3 = new Sweng("baka", "bake");
Sweng s4 = new Sweng("hoppa", "jump");
Sweng s5 = new Sweng("simma", "swim");
Sweng s6 = new Sweng("måne", "moon");
Sweng s7 = new Sweng("väg", "road");
Sweng s8 = new Sweng("snäll", "kind");
Sweng s9 = new Sweng("springa", "run");
Sweng s10 = new Sweng("hus", "house");
Wordlist.add(s1);
Wordlist.add(s2);
Wordlist.add(s3);
Wordlist.add(s4);
Wordlist.add(s5);
Wordlist.add(s6);
Wordlist.add(s7);
Wordlist.add(s8);
Wordlist.add(s9);
Wordlist.add(s10);
``` | 2021/07/15 | [
"https://Stackoverflow.com/questions/68390320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16356260/"
] | Not using a for-loop but this may help you nonetheless.
```
ArrayList<Sweng> Wordlist = new ArrayList<Sweng>();
Wordlist.add(new Sweng("bil", "car"));
Wordlist.add(new Sweng("blå", "blue"));
Wordlist.add(new Sweng("baka", "bake"));
Wordlist.add(new Sweng("hoppa", "jump"));
Wordlist.add(new Sweng("simma", "swim"));
Wordlist.add(new Sweng("måne", "moon"));
Wordlist.add(new Sweng("väg", "road"));
Wordlist.add(new Sweng("snäll", "kind"));
Wordlist.add(new Sweng("springa", "run"));
Wordlist.add(new Sweng("hus", "house"));
``` | **Snippet 1**
```java
List<Sweng> Wordlist = Arrays.asList(
new Sweng("bil", "car"),
new Sweng("blå", "blue"),
new Sweng("baka", "bake"),
new Sweng("hoppa", "jump"),
new Sweng("simma", "swim")
new Sweng("måne", "moon")
new Sweng("väg", "road")
new Sweng("snäll", "kind")
new Sweng("springa", "run")
new Sweng("hus", "house")
);
```
**Snippet 2**
```java
List<Sweng> Wordlist = List.of(
new Sweng("bil", "car"),
// ...
);
```
**Snippet 3 (antipattern)**
[Double Brace initialization](https://stackoverflow.com/questions/1958636/what-is-double-brace-initialization-in-java)
```java
List<Sweng> list = new ArrayList<Sweng>() {{
add(new Sweng("bil", "car"));
// ...
}};
``` |
1,070,949 | I'm using `openssl sess_id -in sess.pem -noout -text` to decode the ssl session parameters in sess.pem file (which i got using sess\_out) into human readable text. I wanted to know if there is a way to do the opposite i.e convert the text into sess.pem kind of format. Basically i just want to change a couple of parameters (session-id, master-key etc) inside the sess.pem file but can't seem to find the right command. | 2021/07/28 | [
"https://serverfault.com/questions/1070949",
"https://serverfault.com",
"https://serverfault.com/users/787748/"
] | The Short Answer is: *it depends*
The Longer Answer is regarding:
### Would a NAS used for storing backup files be a good idea or an overkill?
* In Fact, it is a commonly used practice to do so for short-Term backup
* Long-Term Backups should be saved on Tapes or other medias.
### what kind of NAS do I need to store what above?
The Short Answer is: *it depends*
The Long one is:
It depends on how many drives may you want to have failed at once to still be able to recover.
You may want to read about the [Different Raid Level and Information](https://en.wikipedia.org/wiki/RAID) on Wikipedia, as it would explode the Answer dramatically with non-related stuff.
A Commonly used Raid Level for Storing Backups are Raid 5 or Raid 10 - and yes, again it *depends* on your purposes and needs.
Remind: Raid is NOT a Backup, its just saves you from n-X failed drives.
========================================================================
Where n is your current drives and X the drives where can fail depending on the chosen raid level. | To answer your question about the possibility that two drives fail at the same time: It could happen and it might be more likely than you think. I have seen it happen on a RAID5 system which then got all its data wiped.
Usually the RAID system detects that a drive has gone bad and starts rebuilding on a hot spare or manually replaced bad drive. When this rebuilding takes place all drives in the system will have to work hard and usually all the remaining drives are of the same age, make and model as a drive which has just failed.
On the other hand, I have also seen a raid6 system fail when 6 disks of the same make, model and age decided to give up at the same time. Raid6 would allow 2 disks to give up at the same time, but when 6 of 16 disks gave up all data was lost. |
37,815 | I installed the bitcoind and started it as daemon.
After 10hours I've tried "du -h"
```
ubuntu@ip-172-31-37-93:~/.bitcoin$ du -h
16K ./database
59M ./blocks/index
29G ./blocks
646M ./chainstate
30G .
```
How to know if it synced or not?
UPD found an interesting script to monitor node sync status [How to check Bitcoind block chain download progress level](https://bitcoin.stackexchange.com/questions/10859/how-to-check-bitcoind-block-chain-download-progress-level/12734#12734) | 2015/06/06 | [
"https://bitcoin.stackexchange.com/questions/37815",
"https://bitcoin.stackexchange.com",
"https://bitcoin.stackexchange.com/users/26327/"
] | You can compare the block count from Blockexplorer with your local block count. Something like this:
```
$ wget -q -O- https://blockchain.info/q/getblockcount; echo
359721
$ bitcoin-cli -conf=/u0/bitcoin/bitcoin.conf getblockcount
359721
```
As you can see above my node is synched since the counter is equal. | 29G doesn't look after fully synced up.
But you should use bitcoin-cli (RPC command line app).
Do `bitcoin-cli getinfo` (check the "blocks" value and compare against blockchain or another full node) or `bitcoin-cli getchaintips` (more complicated to read)
Example:
```
:~/node/bitcoin$ ./src/bitcoin-cli getblockchaininfo
{
"version" : 109900,
"protocolversion" : 70002,
"walletversion" : 60000,
"balance" : 0.00000000,
"blocks" : 359646, // <--------------
"timeoffset" : 0,
"connections" : 63,
"proxy" : "",
"difficulty" : 47589591153.62500763,
"testnet" : false,
"keypoololdest" : 1425569670,
"keypoolsize" : 101,
"paytxfee" : 0.00000000,
"relayfee" : 0.00001000,
"errors" : "This is a pre-release test build - use at your own risk - do not use for mining or merchant applications"
}
``` |
15,717,420 | ```
LblExpirydate.Text = dataReader(0).ToString()
```
Output in asp.net form : `01/05/2013 12:00:00 AM`
I want to change format to (`01/05/2013`)
Notes : My database
Column : `Expirydate`
data type : `Date` | 2013/03/30 | [
"https://Stackoverflow.com/questions/15717420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2223728/"
] | You can format the string using .ToString() in several different ways:
```
dataReader(0).ToString("dd/MM/yyyy");
dataReader(0).ToString("d");
```
The second option is better as it will format using the current locale. See this MSDN article for more info:
<http://msdn.microsoft.com/en-gb/library/az4se3k1.aspx> | ```
DateTime thisDate1 = DateTime.Now;
Label1.Text =thisDate1.ToString("MM/dd/yyyy") ;
```
output:
03/30/2013
```
DateTime thisDate1 = DateTime.Now;
Label1.Text =thisDate1.ToString("MM-dd-yyyy") ;
```
output:
03-30-2013
```
DateTime thisDate1 = DateTime.Now;
Label1.Text =thisDate1.ToString("MM,dd,yyyy") ;
```
output:
03,30,2013
```
DateTime thisDate1 = DateTime.Now;
Label1.Text =thisDate1.ToString("MMMM,dd,yyyy") ;
```
output:
March,30,2013
and so on... |
182,733 | I was messing around with base conversion between decimal and Base26 (alphabet) with no 0th case because I needed it for the Google Sheets API in order to find specific cell values from a 3 dimensional list of all of the entered cell values on a spreadsheet. Remember that with spreadsheets, the columns are counted with no 0th case and `A == 1` `Z == 26` `BA == 53`.
Some test cases for conversion between the two bases would be
`"zyz" == 18252`, `"aa" == 27`, `"zz" == 702`
When I went to go write the code, I looked for simple solutions, but could not find anything using recursion so I wrote this in Python:
```
def base10ToBase26Letter(num):
''' Converts any positive integer to Base26(letters only) with no 0th
case. Useful for applications such as spreadsheet columns to determine which
Letterset goes with a positive integer.
'''
if num <= 0:
return ""
elif num <= 26:
return chr(96+num)
else:
return base10ToBase26Letter(int((num-1)/26))+chr(97+(num-1)%26)
def base26LetterToBase10(string):
''' Converts a string from Base26(letters only) with no 0th case to a positive
integer. Useful for figuring out column numbers from letters so that they can
be called from a list.
'''
string = string.lower()
if string == " " or len(string) == 0:
return 0
if len(string) == 1:
return ord(string)-96
else:
return base26LetterToBase10(string[1:])+(26**(len(string)-1))*(ord(string[0])-96)
```
I am aware that the first function outputs lowercase letters which can be bypassed by using `base10ToBase26Letter(num).upper()`.
I used this to test the consistency of the values being output:
```
for x in range(0,100000):
if x == base26LetterToBase10(base10ToBase26Letter(x)):
print(x)
```
1. Is recursion the best way to approach this problem efficiently, or should I be looking for something else?
2. If I were to look at readability, is this way the easiest to read?
3. Does this problem have a shorter solution?
4. It seems that after about 11 letter digits, this program is no longer accurate, is there a way to make the functions accurate further? (Even if such numbers will never be used in a spreadsheet) | 2017/12/14 | [
"https://codereview.stackexchange.com/questions/182733",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/154539/"
] | There is a lot of sound advice in other answers, so I will only touch on aspects that I think are worth considering, but are not yet addressed (or that I misunderstood).
### Recursion
I like recursion. But when I find myself trying to use it in Python I stop and reconsider. Using recursion in Python is possible, but doing so is usually an exercise in snake wrestling more than it is productive programming.
```
while_stmt ::= "while" expression ":" suite
["else" ":" suite]
```
On the other hand, the `while` statement is very similar conceptually. The syntactical differences from recursion are:
1. The test is true when the inductive base case is false.
2. The action on the base case comes at the end.
Other answers show examples of how to use `while` and it might be worth looking at them and trying "to see" them as recursive. It is probably worth using `while` instead of recursion if you plan to share Python code with other people because in the context of Python's community, recursive code is harder to understand.
### Magic Numbers
The [Danish alphabet](https://en.wikipedia.org/wiki/Danish_orthography) has 29 letters. [Icelandic](https://en.wikipedia.org/wiki/Icelandic_orthography) has 32. [Russian](https://en.wikipedia.org/wiki/Russian_alphabet), 33. The length of the Latin alphabet, 26, is hard coded into the functions. These languages use characters that are not directly representable in ASCII. The code assumes that they are and hard codes the offset `97`.
It may be the case that the Latin 26 character alphabet is hard coded into Google Sheets, now. If it is, that assumption should be made explicitly in one place so that maintenance will be easier if Google changes (or if there already is localization). Magic numbers are a "code smell". Sprinkling the same numbers throughout the code is another.
### A => 1
Python is zero indexed. Indexing the Latin alphabet from `1` is fighting against the language. I can follow your rationales for wrestling the snake. But I have to think too much about your rationales in order to understand your code. If you had created a Domain Specific Language in Python and then were writing your functions in that, 1-indexing would make sense. But your code is in Python. The biggest advantage of Python is that people know what to expect. They don't expect 1-indexing.
### Data Architecture
Zero-indexing versus one-indexing is mostly a matter of not conceptually separating the internal data representation of your application from the external interface of the Google API. The architecture of your application is:
```
Deserialize from API -> Manipulate -> Serialize to API
```
The decision to use One-indexing is due to letting the data abstractions of Google's API leak into your Python code. It makes your code brittle and **harder** to reason about. Nobody should have to think about Google's API when looking at the internals of the `Manipulate`portion of the architecture. It is probably better if all your wrestling with Google's API happens in `Deserialize` and `Serialize` and `Manipulate` just works and make sense with zero knowledge of Google (or any other) API's.
### Naming
Consider `deserialize_column_name` and `serialize_column_name` as the names of your functions because those are your functions' functions. Base 26 is not really the important part of how someone uses it. That the output is a letter is not really the important part. Those are implementation details of Google's API protocol that can be described in the `DocString`s. People will have to read the `DocString` with the current names, anyway. | The `column_name_to_column_number` function would be a good match for [using `functools.reduce`](https://docs.python.org/3/library/functools.html?highlight=reduce#functools.reduce). It operates on any sequence type (including `str`, the type of strings) and allows you to build up a result piece by piece while parsing through the sequence. You need to write a 2-param [lambda expression](https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions) or function to process each piece and update the intermediate value. There's even a way to specify a special case creating the starting value (i.e. what's in the intermediate storage before the first element of the sequence is applied).
Or, this also works (though it's ugly and unreadable)
```
transtable=str.maketrans(string.ascii_uppercase,"0123456789ABCDEFGHIJKLMNOP")
return int((chr(1+ord(s[0]))+s[1:]).translate(transtable),26)+1
``` |
192,218 | **What is the best-practice for storing geographic features (lines, polygons and their multipart equivalents) when these features span the antimeridian (±180° longitude), and need to be sent to and recieved from client web applications as GeoJSON?**
---
I am starting work on a server-side web API with support from a Postgres/PostGIS database to work with historical and forecast tropical cyclone tracks and wind radii. Many cyclones in the Pacific Ocean have the unfortunate tendency to cross the antimeridian, sometimes multiple times in their lifespan:
[](https://i.stack.imgur.com/0fFh5.gif)
As a New Zealander living near the antimeridian, I have encountered this problem often enough in regional data to have some coping strategies, but I would like to actually find out what is considered to be best practice. Unfortunately there are no existing questions tagged [antimeridian](/questions/tagged/antimeridian "show questions tagged 'antimeridian'"), so it is hard to search for related questions. Those questions that I have seen struggling this problem all seem to be seeking very application-specific advice. [This question](https://gis.stackexchange.com/questions/42681/how-do-i-represent-the-whole-earth-as-a-polygon) briefly discusses the antimeridian for the case of an earth-spanning GeoJSON polygon with no boundary. [This question](https://gis.stackexchange.com/questions/7064/the-international-date-line-wrap-around) is pretty close to what I'm asking.
I need to store historical and forecast cyclones in a spatial database, but I anticipate that there will be issues with the antimeridian. For instance, a line starting at latitude/longitude `(0,179)` and ending at `(0,-179)` is ambiguous with respect to its direction: whether it takes the short path across the antimeridian, or "wraps" around the entire planet. How should such a path be stored in a spatial database (specifically I'm working with PostGIS but I hope the solution is generic enough)? Some ideas that I have:
1. **Make no change** to feature geometries and shift the ambiguity to client applications.
2. [Split any feature crossing the antimeridian](https://gis.stackexchange.com/a/7067/25417) into a **multipart geometry with a break at the antimeridian**. ([The GeoJSON specification supports named CRSs](http://geojson.org/geojson-spec.html#named-crs).)
3. [Work with **non-global projections**](https://gis.stackexchange.com/a/7070/25417) for different cyclone basins or oceanic regions that don't have such a discontinuity
4. Exploiting the fact that a cyclone has never been observed to travel around the entire planet, store the coordinates of cyclones starting in the latitude range `(90,-90)` **offset by a 360° phase** (keeping the others -180–180°)
5. Exploiting the fact that a cyclone is extremely unlikely south of the southern tip of Africa, use a **break at 30° longitude** (as in the above map).
6. Allow **coordinates to extend beyond the valid range of EPSG 4326**, e.g. > 180° and < -180° for any features that pass the antimeridian.
7. **Delta encoding**, like in TopoJSON (e.g. start at `(0,-179)` and then next coordinate is `-3` latitude west). I have no idea whether or how to implement this when storing data in PostGIS, but this is a great solution for sending data to client applications.
8. Some form of vector notation or polar coordinates. (Seems rather difficult and unusual.)
Of these, I don't like ideas 2–5 because they aren't generic, but I do like them because they make some sense for my particular application. For applications only dealing with data in the Pacific Ocean, they might make a lot of sense, so I don't want to completely discount them as options.
Ideas 6 and 7 were lifted from [Tom MacWright's blog](http://www.macwright.org/2015/03/23/geojson-second-bite.html), which is worth a read but is not conclusive with respect to the antimeridian.
Idea 4 is used by [GeographicaGS' `GeodesicLinesToGISPython`](https://github.com/GeographicaGS/GeodesicLinesToGIS/blob/1d900d92391f4230980df2700cd3482f082dfe17/geodesiclinestogis/geodesicline2gisfile.py#L272), which in turn is using [`fiona.transform.transform_geom`](https://github.com/Toblerity/Fiona/blob/master/fiona/transform.py#L11) with a 360° antimeridian offset. In turn, Fiona is using OGR's `-wrapdateline`. I suppose that's a very solid precedent and actually rather generic.
In conjunction with the issue of storage, I need to consider how such features should be sent to client applications, and how my application should consider data posted back to it (e.g. a human forecaster changing the forecast track of a cyclone in the Pacific). The interchange format will probably be GeoJSON, but does not have to be.
Unfortunately the GeoJSON specification is not explicit about antimeridian issues. This from [Wikipedia](https://en.wikipedia.org/wiki/180th_meridian):
>
> Many geographic software libraries or data formats project the world to a rectangle; very often this rectangle is split exactly at the 180th meridian. This often makes it impossible to do simple tasks (like representing an area, or a line) over the 180th meridian. Some examples:
>
>
> * The GeoJSON specification doesn't mention handling of the 180th meridian in its specification, as such, representations of lines crossing the 180th meridian can just as well be interpreted as going around the world.
> * In OpenStreetMap, areas (like the boundary of Russia) are split at the 180th meridian.
>
>
>
My reading is that GeoJSON has no particular standard representation of antimeridian-spanning features, and it is deliberately left ambiguous (multi-part geometries would perhaps resolve the issue). Similarly in OpenStreetMap there are geometry divisions at the antimeridian, although I don't know if such split features are multipart or are actually discrete records.
This feels rather problematic, especially from the perspective of making bounding box or other spatial requests that span this line, but also in parsing and sanitising input and any updates to feature geometries. This is why I'm trying to determine a best practice that I can seek to conform to. | 2016/05/04 | [
"https://gis.stackexchange.com/questions/192218",
"https://gis.stackexchange.com",
"https://gis.stackexchange.com/users/25417/"
] | Speaking purely from a data storage and analysis perspective, the [`geography` type for PostGIS](http://postgis.net/docs/using_postgis_dbmanagement.html#PostGIS_Geography) was designed with the antimeridian in mind (among several design goals). There are [several functions specifically designed for the `geography` type](http://postgis.net/docs/PostGIS_Special_Functions_Index.html#PostGIS_GeographyFunctions).
For instance, consider a LineString across [Taveuni, Fiji](https://en.wikipedia.org/wiki/Taveuni) ([mapped with Great Circle Mapper](http://www.gcmap.com/mapui?P=17S+179.9E-16.7S+179.8W&MS=wls&DU=km)), which straddles the antimeridian:
```
SELECT ST_Length('LINESTRING(179.9 -17, -179.8 -16.7)'::geography);
```
The length of this [geodesic](https://en.wikipedia.org/wiki/Geodesics_on_an_ellipsoid) is about 46 km. Similarly, ST\_Area would work correctly on a Polygon of the island, even with longitude coordinates jumping between +179 and -179.
Casting a EPSG:4326 `geometry` to a `geography` type also normalizes the coordinates, for example the longitude of the last coordinate is >180:
```
SELECT ST_AsGeoJSON('LINESTRING (179.9 -17, 180.2 -16.7)'::geography);
NOTICE: Coordinate values were coerced into range [-180 -90, 180 90] for GEOGRAPHY
st_asgeojson
------------------------------------------------------------------
{"type":"LineString","coordinates":[[179.9,-17],[-179.8,-16.7]]}
```
is converted back to the exact same `geography` type in the first example, but now with GeoJSON output. You can choose to ignore the NOTICE (or e.g. [`SET client_min_messages TO WARNING;`](http://www.postgresql.org/docs/current/static/runtime-config-logging.html)), and convert all sorts of funny-looking geometries as `geography` types.
---
Showing `geography` types on maps outside PostGIS is a different story, and hopefully better answers will touch on this aspect. | Surely, the preferred answer is (1), i.e., have clients do the "right
thing". A good case to consider is the polygon representing the
continent of Antarctica approximated by this kml file
`<kml>
<Folder>
<name>Antarctica</name>
<Placemark>
<name>Antarctica</name>
<Polygon>
<tessellate>1</tessellate>
<outerBoundaryIs>
<LinearRing>
<coordinates>
-58,-63.1,0
-74,-72.9,0
-102,-71.9,0
-102,-74.9,0
-131,-74.3,0
-163,-77.5,0
163,-77.4,0
172,-71.7,0
140,-65.9,0
113,-65.7,0
88,-66.6,0
59,-66.9,0
25,-69.8,0
-4,-70,0
-14,-71,0
-33,-77.3,0
-46,-77.9,0
-61,-74.7,0
-58,-63.1,0
</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
</Folder>
</kml>`
Delta encoding or shifting where the longitude break occurs won't help
with data like this. Working it a projection specific to Antarctica
will work, but this is hardly a general solution.
Amazingly, Google Earth Pro doesn't display this polygon correctly
(unless you use "outline" mode). See here
[](https://i.stack.imgur.com/ZcgbY.png) |
34,747,746 | I don't want a splash screen for my Cordova project (Android and iOS), how to remove it? I tried to disable the splash screen plugin, but it continues to appear! How to solve?
```
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<widget xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0" id="app.appname" version="1.0.0">
<name>App name</name>
<description>
App name description
</description>
<author email="dev@cordova.apache.org" href="http://cordova.io">
Apache Cordova Team
</author>
<content src="index.html"/>
<plugin name="cordova-plugin-whitelist" spec="1"/>
<access origin="*"/>
<allow-intent href="http://*/*"/>
<allow-intent href="https://*/*"/>
<allow-intent href="tel:*"/>
<allow-intent href="sms:*"/>
<allow-intent href="mailto:*"/>
<allow-intent href="geo:*"/>
<platform name="android">
<allow-intent href="market:*"/>
</platform>
<platform name="ios">
<allow-intent href="itms:*"/>
<allow-intent href="itms-apps:*"/>
</platform>
<preference name="SplashScreen" value="none"/>
</widget>
``` | 2016/01/12 | [
"https://Stackoverflow.com/questions/34747746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5576116/"
] | As you are using cordova for your project, you can easily remove the splash screen by adding this tag to the config.xml
```
<preference name="SplashScreen" value="none"/>
``` | Ah, finally! I struggled with the same problem. It seems - at least for the IOS build - that a a splash screen is mandatory no matter what I tried.
I found that I could add png files for each of the supported/recommended sizes, then the startup would use that one. I chose to have a proper picture, but you can create a blank (white or black) png if you do want.
Phonegap or IOS is picky on having all the various sizes available, so provide them all!
```
<platform name="ios">
<icon platform="ios" src="www/res/icon/ios/icon.png" height="57" width="57" />
<icon platform="ios" src="www/res/icon/ios/icon@2x.png" height="114" width="114" />
<icon platform="ios" src="www/res/icon/ios/icon-40.png" height="40" width="40" />
<icon platform="ios" src="www/res/icon/ios/icon-40@2x.png" height="80" width="80" />
<icon platform="ios" src="www/res/icon/ios/icon-50.png" height="50" width="50" />
<icon platform="ios" src="www/res/icon/ios/icon-50@2x.png" height="100" width="100" />
<icon platform="ios" src="www/res/icon/ios/icon-60.png" height="60" width="60" />
<icon platform="ios" src="www/res/icon/ios/icon-60@2x.png" height="120" width="120" />
<icon platform="ios" src="www/res/icon/ios/icon-60@3x.png" height="180" width="180" />
<icon platform="ios" src="www/res/icon/ios/icon-72.png" height="72" width="72" />
<icon platform="ios" src="www/res/icon/ios/icon-72@2x.png" height="144" width="144" />
<icon platform="ios" src="www/res/icon/ios/icon-76.png" height="76" width="76" />
<icon platform="ios" src="www/res/icon/ios/icon-76@2x.png" height="152" width="152" />
<icon platform="ios" src="www/res/icon/ios/icon-small.png" height="29" width="29" />
<icon platform="ios" src="www/res/icon/ios/icon-small@2x.png" height="58" width="58" />
<icon platform="ios" src="www/res/icon/ios/icon-small@3x.png" height="87" width="87" />
<splash src="splash.png" width="320" height="480" />
<!-- iPhone and iPod touch -->
<splash src="www/res/splash/ios/default.png" platform="ios" width="320" height="480" />
<splash src="www/res/splash/ios/default@2x.png" platform="ios" width="640" height="960" />
<!-- iPhone 5 / iPod Touch (5th Generation) -->
<splash src="www/res/splash/ios/default-568h@2x.png" platform="ios" width="640" height="1136" />
<!-- iPhone 6 -->
<splash src="www/res/splash/ios/default-667h@2x.png" platform="ios" width="750" height="1334" />
<splash src="www/res/splash/ios/default-portrait-736h@3x.png" platform="ios" width="1242" height="2208" />
<!--<splash src="www/res/splash/ios/default-landscape-736h@3x.png" platform="ios" width="2208" height="1242" />-->
<!-- iPad -->
<splash src="www/res/splash/ios/default-portrait.png" platform="ios" width="768" height="1024" />
<!--<splash src="www/res/splash/ios/default-landscape.png" platform="ios" width="1024" height="768" />-->
<!-- Retina iPad -->
<splash src="www/res/splash/ios/default-portrait@2x.png" platform="ios" width="1536" height="2048" />
<!--<splash src="www/res/splash/ios/default-landscape@2x.png" platform="ios" width="2048" height="1536" />-->
</platform>
``` |
453,327 | Why is it not possible to find a Hamiltonian formulation of general relativity as easily as in classical mechanics? There was a remark to this in my lecture but no real explanation as to why this is.
What stops us from creating a Hamiltonian formulation of GR? | 2019/01/10 | [
"https://physics.stackexchange.com/questions/453327",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/-1/"
] | Kirchhoff's voltage law (or loop law) is simply that the sum of all voltages around a loop must be zero:
$$\sum v=0$$
In more intuitive terms, all "used voltage" must be "provided", for example by a power supply, and all "provided voltage" must also be "used up", otherwise charges would constantly accelerate somewhere.
We can think of "used voltage" as negative and "provided voltage" as positive. Or we can, to be more accurate, move around the loop, say, clockwise and give opposite signs to opposite polarities (if a voltage is seen as "plus to minus" then positive and if as "minus to plus" then negative, as we move through the loop). Then simply add them all up according to the law:
$$\sum v=0\quad\Leftrightarrow\\-v\_{\text{resistor1}}-v\_{\text{resistor2}}-v\_{\text{resistor3}}+v\_{\text{power supply}}-v\_{\text{capacitor1}}-v\_{\text{capacitor2}}\,\cdots=0$$
As this example equation shows, naturally all resistors will "use" voltage (there is a voltage *drop* across them), so negative. All power supplies such as batteries etc. "provide" voltage, so positive. And capacitors likewise often "use" voltage, so negative (but keep an eye on them in each case to be sure).
Now, simply plug in formulas for each term in this equation:
* Resistances that follow Ohm's law can be replaced with $v=Ri$,
* the voltage of power supplies is often given, like in your case $v=10\;\mathrm V$,
* and as @WarreG suggests in a comment above, capacitors likewise often have plug-and-play formulas, such as $v=Q/C$.
How you pick a formula depends on which parameters you know already. When the equation is filled in, you are done and can solve for unknowns or whichever parameter you are looking for in this equation. | You will need to specify what kind of voltage is involved. The following assumes a 10 vrms sinusoidal voltage. You will also need to know the frequency, since the impedance of a capacitor depends on frequency.
The resistance (R) of a resistor is a special case of electrical impedance (Z). The current through and voltage across a resistor are said to be “in phase”. The impedance of a resistor is simply its magnitude in ohms. That is
$$Z\_{R}=R$$
Capacitors and inductors are circuit elements in which the current and voltage are 90 degrees out of phase. The magnitude of the impedance of a capacitor is called its capacitive reactance, $X\_C$ and given by
$$X\_{C}=\frac{1}{2πfC}$$
Where $f$ is the frequency of the voltage and C the capacitance.
Its impedance is given by
$$Z\_{C}=-jX\_{C}=\frac{-j}{2πfC}$$
$j$ is the imaginary number equal to the square root of minus 1. The j accounts for the fact that the impedance is -90 degrees in the complex plane. The impedance of a resistor is a real number in the complex plane.
When applying KVL to your series RC circuit, in phasor notation, you will have
$$+10-i3-iR\_{1}-(-jX\_{C})i=0$$
Where $i$ is the sinusoidal current, and it is assumed your 10 volt power supply is a 10 vrms sinusoidal voltage source with no phase angle (v=0 when t=0). To find the current, divide the voltage by the equivalent series impedance, $Z\_{equiv}$
$$Z\_{equiv} = (R\_{1} + 3)-jX\_{C})$$
The rest is complex number algebra.
Hope this helps. |
265,401 | When you try playing Don't Starve Together for the first time, the game recommends you to play Alone mode.
Does Don't Starve Together - Alone mode make the original Don't Starve obsolete, or does the original Don't Starve have unique content in it's own right compared to Don't Starve Together - Alone mode? | 2016/05/12 | [
"https://gaming.stackexchange.com/questions/265401",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/10015/"
] | The two versions of the game are balanced differently in terms of difficulty.
As you can read in [this discussion](http://steamcommunity.com/app/322330/discussions/0/619574421433381738/) on the Steam Community, one of the devs says exactly that: you can play Don't Starve Together as a solo game, to start to grasp the mechanics, but as you start to progress you'll find harder content than the "base" version. Some of the challenges that Together makes you face are not meant to be tackled by yourself. Take for example the [Ewecus](http://dont-starve-game.wikia.com/wiki/Ewecus): its spit can trap you for a few seconds and, while it could be overcome by having a friendly Pigman, having another player come to your aid makes the fight significantly easier.
In addition, at the moment of this writing, Together features the content of the base game and Reign of Giants, but not the Shipwrecked content.
Many things were modified or rebalanced too, due to the intrinsic power of some of the characters, and special encounters and events have been added to adapt to the multiplayer aspect. You can read the whole list of differences on the [wiki page](http://dont-starve-game.wikia.com/wiki/Don%27t_Starve_Together). | Based on you comments I would recommend playing Don't Starve Together Alone, first.
DST has unique content and game mechanics not available in DS. If your trying to warm up to play with a friend then best to warm up with all the same mechanics.
You will find that playing DST alone is more challenging then if you were to play DS. However, you will find that if you play DS then try to transition that knowladge to DST, there will be areas that just seem "off" because of mechanic differences.
A great example is looking at the map. In DS, when you look at the map the game pauses. You can spend a long time looking at the map to try to figure out the place you want to go "today". In DST the game does not pause to look at the map. If you spend too much time trying to figure out where to go you will run out of day time. This small change can be a hard habit to break when transitioning to DST. |
393,488 | I am using a [LM358D](https://www.onsemi.com/pub/Collateral/LM358-D.PDF) dual amplifier at the moment and my goal is to measure over-current on 2 motors. Before I'll be doing that, I made a test setup to test the equations and check the output signal of the op-amp. The gain is set to 100 with standard resistors.

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2flm3aO.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
As you can see (don't mind the op-amp name, forgot to change), a voltage drop between the current sense resistor (something that I will implement later) is 0.02V (20mV). The op-amp amplifies it by 100 in an ideal situation so that I can read it with a STM32.
*However*, when I make this in reality, the Vout is around 0,7v and won't change until I decrease the 4.98 all the way down till 4.1v. When it reaches that point, the Vout changes dramatically when I decrease it slightly and reaches its max output of 3.9v (It's 3.9v because I connected the flexible source to v- and the VCC of the component) when the signal coming in the V- of the op-amp is 4v or lower.
My question is **Why doesn't it amplify the difference between 5v(v+) and 4.98v (v-) but only starts the amplification at 5v(v+) and 4.10v(v-)?**
I have checked the equations with an [online calculator](https://daycounter.com/Calculators/Op-Amp/Op-Amp-Voltage-Calculator.phtml) and used the circuitlab simulator and it should normally work. What am I doing wrong?
My ideal setup would be:

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fhXNZt.png)
**UPDATE 01/09/2018**
I have increased the Vcc voltage for the op amp and thanks to you guys it displays now a somewhat normal behavior. However, I encountered another problem which is actually simple, but I can't seem to grasp it. To know how much current the load takes we use the Ohm's law. So **I = U/R**. Measuring the voltage drop while stopping the motor with my hand while supplying the motor with 7V, will have a drop of around 35mV(0,035V). When I use the equation, **I= U/R = 0,035/1 = 0,035A**. However, I don't think this is actually correct, since the motor is quite hard to hold with a hand. I have also a display in my self-built power supply and when I "load" the motor the current increases to around 2,2A. This might be the current that the resistor uses it up. Does it mean that I have to know the current first before I calculate it?
So, Volt per ampère = 0,035V/2,2A = 0,0159V = 15,9mV per ampère? I've looked it up and most doesn't fully explain it, just the principe of ohm's law.

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2flxajD.png) | 2018/08/30 | [
"https://electronics.stackexchange.com/questions/393488",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/186646/"
] | If you want an example of something that is widely used, but different, look at 1000BASE-T gigabit Ethernet. That uses parallel cables and non-trivial signal encoding.
Mostly, people use serial buses because they are simple. Parallel buses use more cable, and suffer from signal skew at high data rates over long cables. | >
> Why did the serial bit stream become so common?
>
>
>
Using serial links has the advantage that it reduced the physical size of the connection. Modern integrated circuit architectures have so many pins on them that this created a strong need to minimize the physical interconnection demands on their design. This led to developing circuits that operate at extreme speeds at the interfaces of these circuits using serial protocols. For the same reason, it's natural to minimize the physical interconnection demands elsewhere in any other data link.
The original demand for this kind of technology may have its origins in fiber optic data transmission designs, as well.
Once the technology to support high speed links became very common, it was only natural to apply it in many other places, because the physical size of serial connections is so much smaller than parallel connections.
>
> Why are there no widespread system communication protocols that heavily employ some advanced modulation methods for a better symbol rate?
>
>
>
At the encoding level, coding schemes for digital communication can be as simple as [NRZ (Non-Return to Zero)](https://en.wikipedia.org/wiki/Non-return-to-zero), a slightly more complicated [Line Code (e.g. 8B/10B)](https://en.wikipedia.org/wiki/8b/10b_encoding), or much more complicated, like [QAM (Quadrature Amplitude Modulation)](https://en.wikipedia.org/wiki/Quadrature_amplitude_modulation#Digital_QAM).
Complexity adds cost, but choices are also dependent on factors that ultimately rely on information theory and the capacity limits of a link. Shannon's Law, from the [Shannon-Hartley Theorem](https://en.wikipedia.org/wiki/Shannon%E2%80%93Hartley_theorem) describes the maximum capacity of a channel (think of that as "the connection" or "link"):
>
> Maximum Capacity in Bits/Second = Bandwidth \* Log2(1 + Signal/Noise)
>
>
>
For radio links (something like [LTE](https://en.wikipedia.org/wiki/LTE_(telecommunication)) or WiFi), bandwidth is going to be limited, often by legal regulations. In those cases QAM and similarly complex protocols may be used to eke out the highest data rate possible. In these cases, the signal to noise ratio is often fairly low (10 to 100, or, in decibels 10 to 20 dB). It can only go so high before an upper limit is reached under the given bandwidth and signal to noise ratio.
For a wire link, the bandwidth is not regulated by anything but the practicality of implementation. Wire links can have a very high signal to noise ratio, greater than 1000 (30 dB). As mentioned in other answers, bandwidth is limited by the design of the transistors driving the wire and receiving the signal, and in the design of the wire itself (a transmission line).
When bandwidth becomes a limiting factor but signal to noise ratio is not, the designer find other ways to increase data rate. It becomes an economic decision whether to go to a more complex encoding scheme or go to more wire:
You will indeed see serial/parallel protocols used when a single wire is still too slow. [PCI-Express](https://computer.howstuffworks.com/pci-express1.htm) does this to overcome the bandwidth limitations of the hardware by using multiple lanes.
In fiber transmissions, they don't have to add more fibers (although they might use others if they are already in place and not being used). The can use [wave division multiplexing](https://en.wikipedia.org/wiki/Wavelength-division_multiplexing). Generally, this is done to provide multiple independent parallel channels, and the skew issue mentioned in other answers is not a concern for independent channels. |
339,255 | How can I make manpages (from the `man` command) open in a web browser for easier navigation? | 2013/08/30 | [
"https://askubuntu.com/questions/339255",
"https://askubuntu.com",
"https://askubuntu.com/users/176889/"
] | Using the man program
---------------------
Looking at the manpage of man,
```
man man
```
There is the `-H` option, or its equivalent `--html` which will generate the HTML for the manual and open them in the browser.
>
> This option will cause groff to produce HTML output, and will display that output in a web browser. The choice of browser is determined by the optional browser argument if one is provided, by the $BROWSER environment variable, or by a compile-time default if that is unset (usually lynx). This option implies -t, and will only work with GNU troff.
>
>
>
So to open any man page in the browser just use:
```
man -Hfirefox <command>
```
or
```
man --html=firefox <command>
```
Both are the same.
You can use `firefox`, `google-chrome`, `chromium-browser` or any other in place of the `firefox` word.
### Select a default browser permanently
Before calling the `man` command, use the following command:
```
export BROWSER=firefox
```
This way, you can just use `man -H` or `man --html` without specifying the browser each time.
```
man -H ls
```
You can also add the previous `export` command to your `~/.bashrc` so you won't have to type it each time you open a new terminal and try using `man -H`
### Troubleshoot
If you got an error saying something like this:
```
man: command exited with status 3: /usr/bin/zsoelim | /usr/lib/man-db/manconv -f UTF-8:ISO-8859-1 -t UTF-8//IGNORE | preconv -e UTF-8 | tbl | groff -mandoc -Thtml
```
You will need to install the `groff` package.
```
sudo apt-get install groff
```
---
Using Yelp
----------
If a choice of browser is not relevant, you can use the `yelp` command which offers navigation through the man pages.
```
yelp man:<command>
# example: yelp man:ls
```
---
Using the Ubuntu Manpage Repository
-----------------------------------
You can also visit <https://manpages.ubuntu.com/> and check almost all man pages there. All versions of the man pages for all the Ubuntu versions are available there. It also features a search functionality.
Of course, the downside of using the website is that you can't access it without being connected to the Internet. | man2html
--------
### To search man pages
I installed the `man2html` package then navigated to `http://localhost/cgi-bin/man/man2html` to view the man pages. These pages can be viewed offline, link to other man pages and feature a search function.
[Source](https://web.archive.org/web/20150317121959/http://linuxers.org/article/make-manpages-navigable-using-man2html)
### To directly open a page (from command line)
I made this script [here](http://mysticpaste.com/view/5GXoo0rnE4?12) (it's not short), it just navigates directly to the webpage (from `man2html`) for a certain manpage. It can open multiple man pages specified as command line arguments. Save the script somewhere and give it execute permissions (`chmod +x script.sh`). Run it as `~/script.sh` (assuming saved in `~` directory) with pages to open as arguments. To open something like `init(8)`, use `~/script "8 init"`.
---
dwww
----
### To search man pages
Install the `dwww` paackage and navigate to `http://localhost/dwww/man/1` to search the pages. These pages can be viewed offline, link to other man pages and feature a search function.
### To directly open a page (from command line)
I made this script [here](http://mysticpaste.com/view/Pq2R4xWxB7/text) (it's not short), it just navigates directly to the webpage (from `dwww`) for a certain manpage. It can open multiple man pages specified as command line arguments. Save the script somewhere and give it execute permissions (`chmod +x script.sh`). Run it as `~/script.sh page` (assuming saved in `~` directory) with pages to open as arguments. To open something like `init(8)`, use `~/script init/8`. Without `pcregrep`, you need to type the `/8` all the time, with it, just type the name of the page. |
14,314,252 | In my application, when I press the home button the activity is going to `onDestroy()`. It suppose to be called `onPause()` method only right?
Why it is happening so? | 2013/01/14 | [
"https://Stackoverflow.com/questions/14314252",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/746292/"
] | You activity could be destroyed upon pressing the home button if the system is constrained and has determined it needs to free some resources. The [documentation](http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle) states that `onDestroy()` can be called if:
>
> This can happen either because the activity is finishing (someone called finish() on it, or because the system is temporarily destroying this instance of the activity to save space. You can distinguish between these two scenarios with the isFinishing() method.
>
>
>
Additionally, do note that the system can `kill` your program without calling `onDestroy()` after `onStop()` has been called. Therefore, any cleanup/data persistence code should be in either `onPause()` or `onStop()`. | Well, it depends on a lot of factors. If you are facing this issue on Android 3.2+ devices, you should add screenSize property to android:configChanges
```
android:configChanges="keyboardHidden|orientation|screenSize"
```
Besides, also add android:launchMode="singleTop" to your launcher activity. Do note that you'd need to use Android SDK 15 or above as target, however, your app will work on older devices as well. Hope this helps. |
14,515 | Some video cards have two vga outputs. But how to have more than two monitors? | 2009/05/29 | [
"https://serverfault.com/questions/14515",
"https://serverfault.com",
"https://serverfault.com/users/5188/"
] | Take a look at [Matrox](http://www.matrox.com) website - they have triple- and quad-head video cards.
You can also use more than one video card in a single computer - not in SLI or Crossfire mode. Of course your OS must support such configurations. | Use multiple video cards. Some video cards (matrox for example) have two outputs, or one high-density connector (Dell for example) that splits using a converter. Multiple cards can be fitted to provide multiple displays.
Why? Flight simulator games (front, left, right, lowered front and elevated front displays) :O, presentations - exhibitions etc, graphic manipulation (one for working, one for the calibrated display of the final image, and one for palettes), 3d rendering (one for mesh, one for render, one for palettes). The largest multiple monitor scenario I saw was done by an IBM reseller who had a 'Wall of Windows' at erm.. 12 wide, but 8 deep? Why? Because they could. |
7,624,562 | I have something where it randomly generates words using PHP...
I have a iFrame currently linking to dictionary.com...
I don't like this because it's old and ugly.
I want to get the definition of a word and display it how I want!
Is this possible by using PHP? | 2011/10/02 | [
"https://Stackoverflow.com/questions/7624562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/974866/"
] | You can do this, but you still have to keep the `new` keyword, and create the nested class as a path-dependent type:
```
class Bippy(x: Int) {
class Bop {
def getIt = x
}
}
val bip = new Bippy(7)
val bop = new bip.Bop
bop.getIt // yields 7
val bop2 = new bip.Bop{ override def getIt = 42 }
bop2.getIt // yields 42
``` | I don't think it's possible. However, a common pattern is to add a parameter to factory methods which takes a function modifying the created object:
```
trait MyClass {
var name = ""
def doStuff():Unit
}
class Foo extends MyClass {
def doStuff() { println("FOO: " + name) }
}
trait MyClassFactory {
def make: MyClass
def apply( body: MyClass => Unit ) = {
val mc = make
body(mc)
mc
}
}
object FooFactory extends MyClassFactory {
def make = new Foo
}
```
You can then create and modify instance with a syntax close to your example:
```
val foo = FooFactory { f=>
f.name = "Joe"
f.doStuff
}
``` |
5,256,718 | How to Redirect <http://example.com> to <http://www.example.com> using htaccess | 2011/03/10 | [
"https://Stackoverflow.com/questions/5256718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/276030/"
] | use a `.htaccess` file with following content:
```
RewriteEngine on
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\.example\.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
```
In case of IIS make sure, that the host listens to all urls you want to use for your block (including www.example.com and example.com)
Then use the rewrite module of the IIS:
<http://learn.iis.net/page.aspx/460/using-the-url-rewrite-module>
You can easily import rules from Apache mod\_rewrite into ISS:
<http://learn.iis.net/page.aspx/470/importing-apache-modrewrite-rules> | By having a correct configured DNS.
Make sure you have following line:
```
@ IN A your.server.ip.address
```
Which says anyone requesting yourdomain.bla will be sent to the server with the given IP. In your case, the IP-address would be the same as the CNAME configuration for "www".
Though, if you use a web hotel service they are too often not letting the customer make a default config. It might be then that you're not able to make the config needed. |
44,503 | Not to be confused with the common parsnip that is usually found in regular supermarkets. Either online or in specialty markets that ship via FedEx would be ideal.
Thank you. | 2014/05/29 | [
"https://cooking.stackexchange.com/questions/44503",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/25190/"
] | Peruvian Parsnips seem to be pretty difficult to find, even online. I found this link that has an "Email me when available" option: <https://www.greenharvest.com.au/Plants/SummerLeafyGreens.html#PeruvianParsnip>
But the website appears to be in Australia and may not ship to the USA, or perhaps if exorbitant shipping costs. I would recommend to also check local health/specialty food stores, they might be able to special-order it through their supply chain.
Another option would be to try and find a substitute that would be "close enough". I don't have suggestions as I have never had Peruvian Parsnips.
---
Another option: growing them!
-----------------------------
I found [this link](http://www.motherearthliving.com/gardening/vegetable-gardening/growing-cooking-root-vegetables-zm0z14sozpit.aspx) which mentioned growing it.
>
> Root vegetables are easy to grow for gardeners at any level. In most parts of the country, roots you plan to harvest in the fall and winter need to be in the ground by mid- to late-summer. If you live in a warmer climate, you have additional time. Whether you’re going to squeeze in a few roots this year or are already planning next year’s garden, use these tips for root gardening success.
>
>
>
Seems like this tuber mostly grows in more tropical climates, so it may be difficult. I also found [this other article](http://www.realseeds.co.uk/unusualtubers.html) which has information about growing unusual tubers.
If you have questions about that, feel welcome to try our [Gardening Stack Exchange](https://gardening.stackexchange.com/) site! | It is very hard to find it. Also it has many names depending on the country: Mandioquinha, Batata Salsa, Peruvian carrot, etc... The latin is *Arracacia xanthorrhiza E.N. Bancroft*.
It seems you can find them online at this place in the US (but I have not yet bought them yet).
In general, you will find only frozen. It is impossible to find it fresh in the USA.
<http://www.latinfoodsmarket.com/Colombian_Food_Products-Arracacha_Yellow_Cassava_DeliFood.html>
Growing them is not an easy option:
1. Seeds are impossible to find since it usually is propagated by tubers, not seeds.
2. Importing tubers requires too much paper work and sanitary inspections.
3. Even in Puerto Rico, where it is suppose to grow, I was not able to find it in the markets. |
48,675,377 | I am trying to get Intellij to recognize my properties using gradle. I have followed the steps [here](https://docs.spring.io/spring-boot/docs/current/reference/html/configuration-metadata.html#configuration-metadata-annotation-processor). So this means I have a `@ConfigurationProperties` annotated class with some properties.
I added the spring dependency to process them:
```
dependencies {
optional "org.springframework.boot:spring-boot-configuration-processor"
}
compileJava.dependsOn(processResources)
```
I added the plugin (I've tried not using the plugin and just making it a compile dependency, no change)
```
buildscript {
repositories {
maven { url 'http://repo.spring.io/plugins-release' }
}
dependencies { classpath 'io.spring.gradle:propdeps-plugin:0.0.9.RELEASE' }
}
apply plugin: 'propdeps'
apply plugin: 'propdeps-maven'
apply plugin: 'propdeps-idea'
```
When I run the build, I see a `build/classes/java/main/META-INF/spring-configuration-metadata.json` file is created based off of my properties.
When I try to use the property in either `application.yml` or `application.properties`, Intellij says it cannot resolve it.
The docs does say it should be called `additional-spring-configuration-metadata.json` and may expect it to be called that to process it, but I do not see a way to make the build name it that way nor configure Intellij to expect otherwise.
Has anyone got this working with gradle? Or is this a bug.
**Edit** I created a [repo](https://github.com/phospodka/properties-playground) with a pair of projects to demonstrate this. One for gradle and one for maven. I created the projects from start.spring.io and basically just added the properties configuration. I also used a straight compile dependency in both cases instead of optional / compileOnly.
I had not confirmed this before, but the code assist does work for maven, but not gradle. Both create a `spring-configuration-metadata.json` in the `META-INF` in their respective build folders. I am not exactly sure who is not picking it up.
### Misc relevant versions
```
Intellij: 2017.3.4
Springboot: 1.5.9
Gradle: 4.4.1
Java: 8.161
``` | 2018/02/08 | [
"https://Stackoverflow.com/questions/48675377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3884529/"
] | * [Turn the annotation processing on](https://www.jetbrains.com/help/idea/annotation-processors.html)
* Do not [delegate IDE build/run actions to Gradle](https://www.jetbrains.com/help/idea/runner.html)
* Rebuild your project in IDE: **Build** -> **Rebuild Project** | As far as I can tell, IntelliJ (at the time of this writing, 2018.1.2) wants the `spring-configuration-metadata.json` file to either be in a main source root (`src/main/resources/META-INF/ or src/main/java/META-INF/`) or in its default output directory for it to pick it up for autocompletion of properties in your source tree. To expand on phospodka's comment, you can add something like this to your build.gradle to satisfy IntelliJ.
```
task copyConfigurationMetadata(type: Copy) {
from(compileJava) {
include 'META-INF/spring-configuration-metadata.json'
}
into "out/production/classes"
}
compileJava {
dependsOn processResources
finalizedBy copyConfigurationMetadata
}
``` |
316,338 | Let's say we have a list of players in our `Event` class. And we have a dictionary with the score of each player. We can add a score to a player using the `addScore` method:
```
public class Event {
private List<Player> players;
private Map<Player, Integer> score;
public void addScore(Player p, int playerScore) { /* ... */ }
}
```
Now say we cannot allow the player to be either null or not to be contained of the player list defined in the event.
I just asked about null values and it seems the best approach would be to throw an exception. But trying to add a score to a player that doesn't belong to that event is another story:
```
public void addScore(Player p, int playerScore) {
if (p == null) throw new IllegalArgumentException("The player cannot be null");
if (!players.contains(p))
// ???
// the rest of the method
}
```
What should I do? What's the best approach? Should I throw a similar exception? Should I just do nothing? Or should I do something else? | 2016/04/20 | [
"https://softwareengineering.stackexchange.com/questions/316338",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/223143/"
] | The best idea to follow here is known as "fail fast". The basic philosophy goes as follows:
* When the program's data is in an invalid state, errors occur which cause the program to not do what it's intended to do.
* Depending on how widely different the invalid data is from the expected data, it's possible for the incorrect data to propagate for quite a long time, causing more and more errors, before it's detected.
* The sooner an error is detected and execution is halted, the less damage it can do.
* The closer an error is detected to the point of its underlying cause, the simpler it is to track down and fix the underlying cause.
* Therefore, you want to *fail fast*: raise an exception, crash the whole program if necessary, *as soon as possible, rather than allow data corruption to propagate.* | What does your documentation say? I can't see any reason why you would treat null and a player outside your players list differently. If it's a bug, anyone calling it incorrectly won't handle your exception reasonably. Use an assertion at development time. Check with your local coding standards what you should do in a shipping product: Either silently ignore the error (or maybe log it), or assert as well.
Or it's not a bug; your documentation says "no action will be taken if player is null or not in the list of players". Then do that. In that case I'd call the method "addScoreIfPlayerValid". Then I'll call it without hesitation without checking myself whether the player is valid. If it's called "addScore" I'll assume that you check. |
1,207,688 | A friend of mine is writing a book on female scientists and mathematicians, and one of the subjects will be Alicia Boole Stott, a British mathematician who studied 4D geometry and polytopes. Are there any books people could recommend for someone who is new to the topic that explain 4D well or help with the visual understanding? | 2015/03/26 | [
"https://math.stackexchange.com/questions/1207688",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/70732/"
] | You did it upside down ;). Just invert your final answer, which is correct. Solve for the radius...
$$-1 \le {{x-\pi} \over {2}} \le 1$$
$$-2 \le {x-\pi} \le 2$$
$$ \pi-2 \le x \le \pi+2$$
Looks like the radius is $2$. | You are trying to use the ratio test, but you have the formula inverted. It should be $\lim\_{n\to \infty} \frac {|a\_{n+1}|} {|a\_n|} $. As in, the $|a\_{n+1}|$ term should be on $\textit {top}.$
Zach's answer is not correct. The radius of convergence is not $\pi$. Rather, the power series is $\textit centered$ at $\pi$. The interval of convergence (which is the center plus/minus the radius of convergence) is $[2-\pi, 2+\pi]$ (make sure to check the endpoints for convergence as well). |
9,467 | I have a very good (I assume) point and shoot high end camera with me. Model is Panasonic Fz35. I think it has very nice features and using the camera in manual mode is nice too.
However, with all the nice in-built features in my camera, can I say it's equivalent to any base SLR camera (ignoring additional lens for SLRs)? Can I use my camera as an SLR itself? If not, what basic things are missing from my camera to any basic SLR?
In short, what differentiates a high end point and shoot camera from an SLR? | 2011/03/05 | [
"https://photo.stackexchange.com/questions/9467",
"https://photo.stackexchange.com",
"https://photo.stackexchange.com/users/1272/"
] | To be an SLR the camera has to have a mirror and optical viewfinder as cabbey states. The optical viewfinder has several advantages, namely a crisper image for easier manual focus (as you're getting the full resolving power of the lens, instead of a small LCD screen) and zero lag (as what you're seeing is happening in real time!) which can be useful for sports etc. There are a few disadvantages as well, you can't zoom an optical viewfinder, nor can you preview image settings (you can set an electronic viewfinder to show you the image in black and white for example).
Whilst the viewfinder is the only difference *by definition* there is another important distinction which impacts shooting, and that is that digital SLRs almost always have much larger sensors than compact bridge cameras like the FZ35. A larger sensor allows you to capture much more light giving the SLR much better performance in low light.
To visualise just how much bigger the sensor is in an SLR here's a visual comparison between the FZ35 (which is typical of bridge and compact cameras) and the Canon 1100D, a typical entry level digital SLR:
[](https://web.archive.org/web/20120108085819/http://www.mattgrum.com/photo_se/sensor_sizes.png)
Some compacts do have SLR sized sensors (eg. Sigma DP2, Fuji x100), but they tend to have a very limited zoom range. You certainly wouldn't be able to get a 18x zoom on anything but a small sensor! The ability to produce small light zoom lenses is the reason manufacturers have stuck to small sensors.
In addition to capturing more light, the larger sensor also gives you a shallower depth of field (when matching the field of view of a small sensor camera). This means the range of distances from the camera that are in focus is much smaller. This can be used to artistic effect allowing you to isolate the subject and blur out the background.
The only way to get blurred backgrounds with a small sensor compact is to use a long focal length (zoom in a lot), or get really close to a small subject (using the macro or close up function).
I would say shallow depth of field is the biggest difference in terms of the images, as nothing can be done to replicate the look of an SLR when producing images with shallow DoF in certain circumstances (except by faking it in Photoshop which is difficult and time consuming). When I see an image with shallow depth of field, especially if it's a moderately wide angle I can tell instantly it's from an SLR not a bridge camera. | Others have pointed out that an SLR has a mirror while a P&S does not, which is true. Another important difference is the autofocus mechanism; a P&S uses contrast detection off the image captured by the image sensor, an SLR has an entirely separate set of autofocus sensors that reads part of the image reflected off the mirror. This technical detail is important because the phase-detection focus system of an SLR can focus a lens almost instantly (given that the AF motor of the lens is up to it, which is sometimes true and sometimes not) while the contast-detection system relies on a lot of trial and error and can take a LOT of time to get into focus. This makes the SLR a lot more responsive, with less lag between pressing the shutter and actually taking the picture. |
55,757,339 | I am trying to print variables to my file by using a sh file, but it doesn't work.
It is very simple code. How can I fix it? And I don't understand at a point. the script works in command as I expected. But it shows me totally different result when I move the scripts to a `sh` file.
```
#! /bin/bash
var=12345
echo -e "first sentence
second sentence
$var:$var th sentence
"
```
I expected
```
first sentence
second sentence
12345:12345 th sentence
```
but it shows me
```
first sentence
second sentence
th sentence
``` | 2019/04/19 | [
"https://Stackoverflow.com/questions/55757339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11382235/"
] | One thing to be aware of, is that when you write:
```
class BottomPanel extends React.Component<Props, {}> {
dropDownUpdate = e => this.setState({ dropDownValue: e.currentTarget.textContent });
}
```
This (currently) is not valid ES6 syntax. You can't assign a class variable with an equals sign that way. The reason it works is because of the `transform-class-properties` babel plugin, more on that below.
See this question and answer for more details:
[ES6 class variable alternatives](https://stackoverflow.com/questions/22528967/es6-class-variable-alternatives)
Technically, the right way to declare a class variable is with the `this` keyword like:
```
class BottomPanel extends React.Component<Props, {}> {
constructor(props) {
this.dropDownUpdate = this.dropDownUpdate.bind(this)
}
dropDownUpdate(e) {
this.setState({ dropDownValue: e.currentTarget.textContent });
}
}
```
For why you can't just do:
```
class BottomPanel extends React.Component<Props, {}> {
constructor(props) {
this.dropDownUpdate =e => this.setState({ dropDownValue: e.currentTarget.textContent });
}
}
```
see this post: [Can I use arrow function in constructor of a react component?](https://stackoverflow.com/questions/43600967/can-i-use-arrow-function-in-constructor-of-a-react-component)
Now the thing is - I assume that you are using Create React App - which comes with the `transform-class-properties` babel plugin - which is why that first declaration works.
Take a look at this question as to why you would want to to the `this.dropDownUpdate = this.dropDownUpdate.bind(this);` trick. It's not necessary - but you run into a debugger issue (the browser not being aware of the `transform-class-properties` babel transform).
[Chrome, Firefox debuggers not displaying the correct value for 'this' in a react app](https://stackoverflow.com/questions/53513424/chrome-firefox-debuggers-not-displaying-the-correct-value-for-this-in-a-react)
Otherwise you can just clear your class methods like:
```
class BottomPanel extends React.Component<Props, {}> {
dropDownUpdate = e => this.setState({ dropDownValue: e.currentTarget.textContent });
}
``` | Since dropDownUpdate is an Arrow function, It should work as expected without
`this.dropDownUpdate = this.dropDownUpdate;` Or
`this.dropDownUpdate = this.dropDownUpdate.bind(this);`
In Arrow functions, value of `this` is lexically bound, unlike regular functions where the value of `this` changes based on the context in which the function is called. |
730,999 | These are tables I have:
```
Class
- id
- name
Order
- id
- name
- class_id (FK)
Family
- id
- order_id (FK)
- name
Genus
- id
- family_id (FK)
- name
Species
- id
- genus_id (FK)
- name
```
I'm trying to make a query to get a list of Class, Order, and Family names that does not have any Species under them. You can see that the table has some form of hierarchy from Order all the way down to Species. Each table has Foreign Key (FK) that relates to the immediate table above itself on the hierarchy.
Trying to get this at work, but I am not doing so well.
Any help would be appreciated! | 2009/04/08 | [
"https://Stackoverflow.com/questions/730999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191083/"
] | Well, just giving this a quick and dirty shot, I'd write something like this. I spend most of my time using Firebird so the MySQL syntax may be a *little* different, but the idea should be clear
```
select f.name
from family f left join genus g on f.id = g.family_id
left join species s on g.id = species.genus_id
where ( s.id is null )
```
if you want to enforce there being a genus then you just remove the "left" portion of the join from family to genus.
I hope I'm not misunderstanding the question and thus, leading you down the wrong path. Good luck!
edit: Actually, re-reading this I think this will just catch families where there's no species within a genus. You could add a " and ( g.id is null )" too, I think. | Sub-select to the rescue...
```
select f.name from family as f, genus as g
where
f.id == g.family_id and
g.id not in (select genus_id from species);
``` |
26,209 | My 16 GB Nexus 7 arrived a few days ago. It's my first mobile device, believe it or not, and I've already found it to be incredibly useful. It has performed flawlessly, but there is one small issue that's an annoyance, nothing more. The screen flickers.
It happens in dimmer light, and only for a second or two at a time. I suspect, though I can't prove this, that it occurs during WiFi transmissions. Has anyone else encountered this? Is there a fix for this, even if it has to be some sort of warranty thing? | 2012/07/21 | [
"https://android.stackexchange.com/questions/26209",
"https://android.stackexchange.com",
"https://android.stackexchange.com/users/17159/"
] | There just was a [Blog on Land of Droid](http://www.landofdroid.com/2012/nexus-7-screen-flicker/) covering this issue. The author summed up a few conditions under which this "flicker" occurs:
* back-light is dimmed under 30%
* a weak WiFi signal
* the device is accessing the net
According to that report, these 3 things are "AND-connected" (i.e. the flicker occurs when all of the 3 conditions are met). He's also hoping for a fix to come soon.
You might as well want to read the comments there, some seem to indicate possible solutions (including flashing a new stock ROM), but so far none of them are yet confirmed. | Turning off auto brightness worked for me. |
494,303 | **Can I simply hook up an opamp inputs, (either using a differential or in-amp topology that is/are also powered from a floating power supply), across a device under test that itself has exceeding voltages for the opamp (<50Vdc) ?**
so idea is to build smth that uC's ADC can measure and eventually for PC to read (via serial).
The DUT can go as high as 50V and is only DC.
Differentially I am not expecting anything higher than 2-5V across the inputs, worst case.
Thus I was wondering, **How does a multimeter achieve differential measurement ?** Without worrying about the voltage that the measurand is actually at, as long as the voltage between probes remain in the spec, I'm fine...
(I do not want to build a multimeter (nor differential probes), but the functionality is the same...).
**->** **My understanding is** that I should be able to hook up an independently powered opamp (dif-amp, in-amp ?) across another device's resistor, read out the voltage drop (by subtracting one input from another), without being connected to the ground with the Device Under Test. Right ?

[simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2f901Vk.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
I have tried to simulate different topologies but to no avail. At least Micro-Cap won't simulate floating power sources that well.. it seems.. I get errors and strange values.
a) If simulation won't allow me to detect floating power source, do I really need to connect the DUT and my measurement circuit to common GND at one point ? - Meaning the common mode voltage range should become an issue as both systems are tied to single reference... for me it doesn't add up.
* That's why I want to have a floating measurement circuit, so I shouldn't worry about grounding (such as a voltmeter), but that's where simulation fails for me and I am unsure.
* Another idea was to take two opamps, make them as buffers (maybe add an amplification stage as well) and just read each of them with separate ADC inputs and do the subtraction in Software - anyway my problem persists - **Can an opamp measure these differences when being powered from floating power ?**
---
I'm also referencing few topics, which should've lead me in a somewhat correct direction, but seems I'm missing something. I also started to think about possible grounding issues and reference points:
[Differential Voltage Measurement](https://electronics.stackexchange.com/questions/262285/differential-voltage-measurement)
[A question about differential measurement system](https://electronics.stackexchange.com/questions/330552/a-question-about-differential-measurement-system) | 2020/04/19 | [
"https://electronics.stackexchange.com/questions/494303",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/123589/"
] | 1) There's only two points, how much data you must send within some given time frame, and which baud rates your microcontroller is capable of with the master clock they have. Some have only simple baud rate generators that divide with an integer, some have more complex ones that have a fractional baud rate generator. For example, an AVR running at 4 MHz crystal can't go up to 38400 baud unless you switch the oversampling from 16x to 8x with U2X bit. Even then, the baud rate will be 0.16% off from 38400 baud, but the error is insignificant.
2) You can't send more bits per second than what your bits per second rate is! It defines the rate of bits you can send. If you need to send more, then increase baud rate.
3) Synchronous serial does use a bit clock for the data. But it does not mean that a 16 MHz CPU uses 16 MHz clock for everything. You can still use a divided down baud rate clock for example for 9600 baud rate, just as you would with only an internal clock except it stays within the chip and does not come out.
4) Baud rates have to match, but only to a certain degree that is within tolerance limits. By oversampling you have only one sixteenth of time difference between the sampled start bit edge and the real received edge, so you can start counting when to sample the middle of the data bits. So the clocks only need to be sufficiently close to each other during transmission of one byte, and depending on a lot of factors, it does not need to be more than 1% to 2% percent accurate. Which means devices with less precise clocks can be used and make them cheaper.
4.1) That is how it is in general done. Sample the middle, but to avoid a spike of noise just at the sampling moment, majority logic takes in 3 samples and gives out the result.
4.2) Of course you could change oversampling from 16 to only 8, but then you need tighter tolerance baud rate clocks, because you can be almost up to one eighth of a bit already wrong when detecting the start bit edge, instead of only one sixteenth. The sampling of three bits is for combating a noise spike at the sampling instance, if there would only be one sampling instance. | >
> 4) What's the essence of oversampling (8,16) of the data on the RX
> side? if the baud rates are the same on both TX and RX
>
>
>
They are not the same rates and that is the point.
Even if both sides were using a 1.843200 MHz or a multiple of, there would be error as no two crystals are exactly the same and they are affected by temperature, etc. Just put two on the same scope at the same time, trigger on one and watch the other drift. It is generally more of a problem for ethernet than uart, but depends on how you are using the uart (rarely would you have a problem). And the (clock drift) problem is related to long periods of sustained data not so much trying to get from one edge to another on the receiver.
It is more of a case that say 8000000/(16\*115200) = 4.34. 4 \* 115200 \* 16 = 7372800. 8000000 / (16\*4) = 125000. So you think you set for 115200 but instead 125000. The other side may for the same reasons be set for some other speed, like lets say 115200. 8.68 us vs 8.00 us. or 0.5425 vs 0.5 per sample at 16x. should be able to survive 10 bit cells (8N1). 125000/115200 = 1.08
What about 12000000/(16\*115200) = 6.5...so we put 7 in there 12000000/(16\*7) = 107142. 125000/107142 = 1.1666. 17 percent difference. 16x will be able to track the mid bit cell of the incoming better than 8x (naturally the higher the oversampling the better) and adapt adjust sooner (assuming there are edges close enough together).
If you were to just go straight 1x mid bit cell of your divided clock you can see where you can start to get into trouble, the higher the oversampling the better. The receiver can only adjust where there are edges, so if the payload is all zeros or all ones then you cant have it drift more than a half bit cell over that period otherwise the receiver will sample at the wrong place and be one bit short or long (relative to the clock that generated it). Then depending on what is on the line next determines if the receiver sees a fault or keeps going because of what is coming in. Eventually and periodically it should fault when it doesnt see a start or stop bit in the right place. 2x, 4x, 8x ... gives you more tolerance of drift relative to your clock and the other side (since they are assumed to not be going the same speed).
The 8x is simply so that you can go slower and still have a decent divisor.
16\*115200 = 1843200
8x115200 = 921600
Assuming the uart doesnt support fractions:
1843200/(16\*115200) divisor of 1
2000000/(16\*115200) divisor of 1
3000000/(16\*115200) divisor of 2 (rounded up, rounded down is much worse)
115200 vs
125000 vs
93750 <- that is pretty bad
but if that same uart supported 8x as well
1843200/(8\*115200) divisor of 2
2000000/(8\*115200) divisor of 2
3000000/(8\*115200) divisor of 3
115200
125000
125000 <- much higher chance of it working
Much less error at 3MHz using 8x vs 16x a trade off but generally worth it.
That is the bigger problem trying to be solved with the oversampling is that often one or both sides is not on the mark for the rate, they are off by some amount, so even if one side is off and the other isnt or worse they are both off in different directions you want some oversampling to attempt to survive the worst case of a character with no state changes.
16 is best if you can afford it, but 8x will do in a pinch. Where I do see tables (might not be ST might be TI) they are basically computing the above for you, this oscillator this serial bit rate this is the divisor and the error. You should do the above math just like I did where possible when these choices are available. If your divisor gets to be a small single digit number you certainly want to do the math and you may want to re-think that baud rate. Or where possible use a PLL to up the system clock rate if that makes sense for the application so that the uart has a better chance of working. (PLLs introduce jitter which creates issues, but jittery with oversampling and a bigger divisor value is still more accurate and gives better odds). |
21,262,815 | I have two paths: application root path and target path. What is the simplest way to ensure that the target path is the children of application root path?
Basically the target path provided by the user is to be displayed by my server. But I want to constrain my server so only the files under the application root path are displayable. So I want to check that the target path is under the root path.
The root path can contain nested directories. | 2014/01/21 | [
"https://Stackoverflow.com/questions/21262815",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/474597/"
] | Another way:
```
def child?(root, target)
raise ArgumentError, "target.size=#{target.size} < #{root.size} = root.size"\
if target.size < root.size
target[0...root.size] == root &&
(target.size == root.size || target[root.size] == ?/)
end
root = "/root/app"
p child?(root, "/root/app/some/path") # => true
p child?(root, "/root/apple") # => false
p child?(root, "/root/app") # => true
p child?(root, "/root") # => ArgumentError: target.size = 5 < 9 = root.size
``` | You haven't provided any use case, thus I assume the following variables apply to your case
```
root = "/var/www/"
target = "/var/www/logs/something/else.log"
```
You can use a regular expression or even more simple [`String#start_with?`](http://ruby-doc.org/core-2.1.0/String.html#method-i-start_with-3F)
```
target.start_with?(root)
``` |
70,045,427 | Consider this input dictionary:
```py
my_dict = {
'group1':{
'type1': {'val1' : 45, 'val2' : 12, 'val3' : 65},
'type2': {'val5' : 65, 'val6' : 132, 'val7' : 656},
},
'group2':{
'type3': {'val11' : 45, 'val12' : 123, 'val13' : 3},
'type4': {'val51' : 1, 'val61' : 2, 'val71' : 3, },
},
}
```
I would like to remove the last 'level' (the one that only has numbers), and get something like:
```py
new_dict = {
'group1':{
'type1': ['val1', 'val2', 'val3'],
'type2': ['val5', 'val6', 'val7'],
},
'group2':{
'type3': ['val11', 'val12', 'val13'],
'type4': ['val51', 'val61', 'val71'],
},
}
```
I am currently doing it by manually looping and so on, but I wonder if there is a way to do it more efficiently. | 2021/11/20 | [
"https://Stackoverflow.com/questions/70045427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14917037/"
] | install and uninstall kotlin plugin.it Worked for me | Updating ktx implementation and syncing gradle worked for me! |
14,829,648 | How should I understand this? And how this can happens?
Go into django shell:
```
>>> from customauth.models import Profile
>>> p = Profile.objects.get(user_id=1)
>>> p.status
u'34566'
>>> p.status = 'qwerty'
>>> p.status
'qwerty'
>>> p.save()
>>> p.status
'qwerty'
>>> p = Profile.objects.get(user_id=1)
>>> p.status
u'qwerty'
>>>
```
Exit and go into django shell again:
```
>>> from customauth.models import Profile
>>> p = Profile.objects.get(user_id=1)
>>> p.status
u'qwerty'
>>>
```
Everything seems OK. But go into dbshell now:
```
mysql> select user_id, status from customauth_profile where user_id=1;
+---------+--------+
| user_id | status |
+---------+--------+
| 1 | 34566 |
``` | 2013/02/12 | [
"https://Stackoverflow.com/questions/14829648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/897413/"
] | I was having the same problem, I'm using Django and Mongo... the data wasn't persisted after `object.save()`... Them, I used it to solve:
```
object.save_base(force_update=True)
```
Now is working for me, hope can help. | The shell session is a single database transaction. Connections outside that won't see the changes, because of transaction isolation. You'll need to commit the transaction - the easiest way would be to quit the shell and restart.
In a normal request, Django commits automatically at the end of the request, so this behaviour isn't an issue. |
511,101 | I searched for this and was surprised to hear that “dipped in shit” meant a measure of surprise.
I’ve always heard it used as being lucky or untouchable.
“I blew through that speed trap and as the cop started coming after me, another car crashed into him. I’m dipped in shit!” | 2019/09/10 | [
"https://english.stackexchange.com/questions/511101",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/237446/"
] | **Cull** complexity (for the ruthless connotations)
**Trim** the requirements.
**Decimate** complexity (also ruthless, but in the literal sense only paring down to 9/10, so maybe not as far reaching as you'd like)
**Skeletonize** the requirements (i.e. reducing them to bare bones..., also image processing lingo with appropriate connotations)
**Thin** the requirements
**Erode** the requirements (only applicable if you exclusively communicate with people who are into image processing, otherwise the meaning is lost or even reversed)
**Axiomate** the requirements (invented word, referencing axioms as the irreducible foundations of something)
**Distill** the requirements (by getting rid of all the diluting fluff)
**Crack** the requirements (only for specific audience; <https://en.wikipedia.org/wiki/Cracking_(chemistry)>)
**Condense** the requirements (Changing them from the hot-air-like gaseous phase to something much less voluminous...) | "*Pare down*" seems to fit in your context -
>
> Pare down
> =========
>
>
> : To reduce the size or amount of something by gradually taking away
> parts of it.
>
>
>
([Source](https://idioms.thefreedictionary.com/pare+down))
Another definition -
>
> Pared-down
> ==========
>
>
> : With no unnecessary features; reduced to a very simple form.
>
>
>
([Source](https://www.collinsdictionary.com/dictionary/english/pared-down))
---
Taking [lbf's](https://english.stackexchange.com/questions/511097/is-there-a-single-english-word-that-is-closest-to-the-meaning-of-ruthlessly-rem/511106#511106) example, you could say -
>
> *Frustrated, he set about to **pare down** unnecessary requirements from the software.*
>
>
> |
37,481,539 | I have an array of objects where i need sum of object property values in new array of objects,
Input:
```
var inputArray = [
{ subject: 'Maths', marks: '40', noOfStudents: '5' },
{ subject: 'Science', marks: '50', noOfStudents: '16' },
{ subject: 'History', marks: '35', noOfStudents: '23' },
{ subject: 'Science', marks: '65', noOfStudents: '2' },
{ subject: 'Maths', marks: '30', noOfStudents: '12' },
{ subject: 'History', marks: '55', noOfStudents: '20' },
.
.
.
];
```
Output i need,
```
var outputArray = [
{ subject: 'Maths', marks: '70', noOfStudents: '17' },
{ subject: 'Science', marks: '115', noOfStudents: '18' },
{ subject: 'History', marks: '95', noOfStudents: '43' },
.
.
.
];
```
I want sum of marks and no of students of subjects in new object array. There would be N number of other subject objects (i.e-Geography, Physics etc) in the input array. | 2016/05/27 | [
"https://Stackoverflow.com/questions/37481539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3748892/"
] | Simple `reduce` solution :
```js
const data = [
{ subject: 'Maths', marks: '40', noOfStudents: '5' },
{ subject: 'Science', marks: '50', noOfStudents: '16' },
{ subject: 'History', marks: '35', noOfStudents: '23' },
{ subject: 'Science', marks: '65', noOfStudents: '2' },
{ subject: 'Maths', marks: '30', noOfStudents: '12' },
{ subject: 'History', marks: '55', noOfStudents: '20' }];
const result = data.reduce((cur, val) => {
let alreadyIn = cur.find(e => e['subject'] == val['subject']);
if (alreadyIn) {
alreadyIn['marks'] = (parseInt(alreadyIn['marks']) + parseInt(val['marks'])).toString();
alreadyIn['noOfStudents'] = (parseInt(alreadyIn['noOfStudents']) + parseInt(val['noOfStudents'])).toString();
} else {
cur.push(val);
}
return cur;
}, []);
console.log(result);
``` | The solution using `Array.forEach`, `parseInt` and `Object.keys` functions:
```
var summed = {}, result;
inputArray.forEach(function (obj) {
obj['marks'] = parseInt(obj['marks']);
obj['noOfStudents'] = parseInt(obj['noOfStudents']);
var subj = obj['subject'];
if (!summed[subj]) {
summed[subj] = obj;
} else {
summed[subj]['marks'] += obj['marks'];
summed[subj]['noOfStudents'] += obj['noOfStudents'];
}
}, summed);
result = Object.keys(summed).map((k) => summed[k]);
console.log(JSON.stringify(result, 0, 4));
```
The output:
```
[
{
"subject": "Maths",
"marks": 70,
"noOfStudents": 17
},
{
"subject": "Science",
"marks": 115,
"noOfStudents": 18
},
{
"subject": "History",
"marks": 90,
"noOfStudents": 43
}
]
``` |
30,623,688 | I'm not sure how to explain this since the plan/idea is mostly in my head since I don't know how to execute it, but I'll try (comment with questions!):
I have a sheet that lists which department of "my" company made an error, which type of error, and how many of that specific error in the department per fiscal month. (See attachment) .
I would like to write a macro that would add up the total number of errors (column E) per department (column D) (month or type of error is not a factor in this macro). I've been experimenting with an array/For Next loop using vlookup to the number of entries, but to no avail since I don't have enough experience with arrays. Any ideas? Here's what I've started:
```
Option Explicit
Option Base 1
Sub Total_Errors()
Dim Assembly() As Double, CSR() As Double
'... more dept names
Dim i As Integer, RowCount As Integer
RowCount = Range("D" & Rows.Count).End(xlUp).Row
ReDim Assembly(1 To RowCount) As Double, CSR(1 To RowCount) As Double
' ... more redimmed dept names
Assembly(i) = Application.WorksheetFunction.VLookup("Assembly", Range(Range("D" & i + 1), Range("E" & RowCount)), 2, False)
Range("H2").Value = Assembly(i)
For i = 2 To RowCount
Assembly(i) = Application.WorksheetFunction.VLookup("Assembly", Range(Range("D" & i + 1), Range("E" & RowCount)), 2, False)
Range("H2").Value = Assembly(i - 1) + Assembly(i)
Next i
End Sub
```
Unfortunately, it will only do as I told it and only add the previous value to the current value :p funny how that works. Anyways, what i'd like to have happen with this code is that it will simply add a value to the previous value in the cell. The add method has seemed to be more involved that what I'm trying to do.
All suggestions welcome, and thanks in advance! | 2015/06/03 | [
"https://Stackoverflow.com/questions/30623688",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4293071/"
] | Well color me surprised. [PostSharp lets you do exactly what you're looking for](http://doc.postsharp.net/control-visibility#types). In a nutshell, you'd use the `ComponentInternalAttribute` to control visibility of a type:
```
public class Item {
[ComponentInternal(typeof(Manager))]
public Item(...) {
}
...
}
```
According to their documentation linked above, attempting to invoke `Item`'s constructor outside of `Manager` will yield a compile-time warning:
>
> Method Item.ctor cannot be referenced from *[some other method]* because of the [ComponentInternal] constraint.
>
>
>
You can make it an error by changing the severity level of the attribute:
```
public class Item {
[ComponentInternal(typeof(Manager), Severity = SeverityType.Error)]
public Item(...) {
}
...
}
``` | There are way better ways to achieve your goal than your current approach, **given that you can actually change that code**.
You could for example mark the contructor of Item class as private and add a static factory method to Item class which would be responsible for creating an instance of the class.
Another way is to move Item class to another assembly, mark its constructor as internal and implement another class (a factory) which would be responsible for creating different Item objects. Then you class is visible from other assemblies, but it cannot be directly instantiated, so forces the code user to use provided factory. |
853,262 | I'm working on an iphone app that needs to display superscripts and subscripts. I'm using a picker to read in data from a plist but the unicode values aren't being displayed corretly in the pickerview. Subscripts and superscripts are not being recognized. I'm assuming this is due to the encoding of the plist as utf-8, so the question is how do a convert a plist string encoding from utf-8 to utf-16 ?
Just a little more elaboration:
If I do this it displays properly at least in a textfield:
NSString \*equation = @"x\u00B2 + y\u00B2 = z\u00B2"
However if I define the same string in a plist and try to read it in and assign it to a string and display it on a pickerview it just displays the the encoding and not the superscripts.
@Matt: thanks for your suggestion the unicode is being escaped that is \u00B2 => \u00B2. Googling for "escaped values in plists" returned no useful results, and I haven't been able to use the keyboard cmd-ctrl-shift-+ to work. Any further suggestions would be greatly appreciated!! | 2009/05/12 | [
"https://Stackoverflow.com/questions/853262",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/86837/"
] | The \u variants only work when presented to the C compiler. For UTF-8, if you really want to type character codes rather than simply typing them (the companion to the character palette is the keyboard viewer, which will update as you press modifier keys so you can search for specific characters that way), then you'll have to use XML entities, i.e. `²`. | Doesn't seem to work with longer unicode like
>
> `𢌾`
>
>
>
header of the plist:
```
<?xml version="1.0" encoding="UTF-8"?>
2 <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3 <plist version="1.0">
``` |
4,003,087 | >
> **Possible Duplicate:**
>
> [Difference between a Structure and a Union in C](https://stackoverflow.com/questions/346536/difference-between-a-structure-and-a-union-in-c)
>
>
>
I could understand what a struct means. But, i am bit confused with the difference between union and struct. Union is like a share of memory. What exactly it means.? | 2010/10/23 | [
"https://Stackoverflow.com/questions/4003087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/484153/"
] | I've used unions to convert bytes to and from other types. I find it easier than bit-shifting.
```
union intConverter {
int intValue;
struct {
byte hi;
byte lo;
} byteValue;
}
intConverter cv;
cv.intValue =1100;
printf("%X %X\n", cv.byteValue.hi, cv.byteValue.lo);
```
Where int is 16-bit (was used on a micro controller). | Run this program and find out the output.
#include < stdio.h >
```
int main()
{
union _testUnion
{
long long x;
long long y;
} testUnion;
struct _testStruct
{
long long x;
long long y;
}testStruct;
printf("Sizeof Union %d\n",sizeof(testUnion));
printf("Sizeof Struct %d\n",sizeof(testStruct));
return;
}
```
You will find that the size of struct is double than that of union. This is because union has allocated space for only one variable while struct has allocated for two. |
10,171,709 | I am using [Flex slide](http://www.woothemes.com/flexslider/)r for one project. I need to control two sliders on one page with same controls.
One part is main slider that will show images, and the second one is text (in this case it will be taken from "the\_excerpt" in WP ).
Basically, this is the code I am using to call two slides on one page:
```
$(window).load(function() {
$('#main-slider').flexslider({
animation: 'slide',
controlsContainer: '.flex-container'
});
$('#secondary-slider').flexslider();
});
```
Now, I need to "connect" both of them to same controls, so when I click on arrow, it will slide/fade both of them. | 2012/04/16 | [
"https://Stackoverflow.com/questions/10171709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1103763/"
] | You could accomplish what you're trying to do by ditching the controlsContainer setting and creating your own navigation that you then link to both sliders. Here's an idea of how (please note it's untested)
Your markup would look something like this. Note the rel attribute on the links - we'll use them below. Also note that the values start from 0 - this matches the values for the slides (e.g. the first slide is 0, the second is 1 etc).
```
<a rel="0" class="slide_thumb" href="#">slide link 1</a>
<a rel="1" class="slide_thumb" href="#">slide link 2</a>
<a rel="2" class="slide_thumb" href="#">slide link 3</a>
<a rel="3" class="slide_thumb" href="#">slide link 3</a>
<div id="main-slider" class="flexslider">
<ul class="slides">
<li>
<img src="image1.jpg" />
</li>
<li>
<img src="image2.jpg" />
</li>
<li>
<img src="image3.jpg" />
</li>
<li>
<img src="image4.jpg" />
</li>
</ul>
</div>
<div id="secondary-slider" class="flexslider">
<ul class="slides">
<li>
<p>Text 1</p>
</li>
<li>
<p>Text 2</p>
</li>
<li>
<p>Text 3</p>
</li>
<li>
<p>Text 4</p>
</li>
</ul>
```
Then you set up the call to flexslider
```
<script type="text/javascript" charset="utf-8">
jQuery(document).ready(function($) {
$('#main-slider').flexslider({
animation: "slide",
slideToStart: 0,
start: function(slider) {
$('a.slide_thumb').click(function() {
$('.flexslider').show();
var slideTo = $(this).attr("rel")//Grab rel value from link;
var slideToInt = parseInt(slideTo)//Make sure that this value is an integer;
if (slider.currentSlide != slideToInt) {
slider.flexAnimate(slideToInt)//move the slider to the correct slide (Unless the slider is also already showing the slide we want);
}
});
}
});
$('#secondary-slider').flexslider({
animation: "slide",
slideToStart: 0,
start: function(slider) {
$('a.slide_thumb').click(function() {
$('.flexslider').show();
var slideTo = $(this).attr("rel")//Grab rel value from link;
var slideToInt = parseInt(slideTo)//Make sure that this value is an integer;
if (slider.currentSlide != slideToInt) {
slider.flexAnimate(slideToInt)//move the slider to the correct slide (Unless the slider is also already showing the slide we want);
}
});
}
});
});
</script>
```
Basically both sliders are controlled by the same set of navigation links. Think this should get you moving in the right direction but shout if you need anything explained. | So, I have been having the same issue and it can be a real drag... But I have come to a quick solution that is easy as pie. This will work for 1 child or a hundred children controlled by on parent flexslider. Works for all actions. Hopefully I can talk them into fixing this and allowing an array of jquery objects for there sync method.
```
<div id="main-slider" class="flexslider">
<ul class="slides">
<li><img src="image1.jpg" /></li>
<li><img src="image2.jpg" /></li>
<li><img src="image3.jpg" /></li>
<li><img src="image4.jpg" /></li>
</ul>
</div>
<div class="flexslider_children">
<ul class="slides">
<li><p>Text 1</p></li>
<li><p>Text 2</p></li>
<li><p>Text 3</p></li>
<li><p>Text 4</p></li>
</ul>
</div>
<div class="flexslider_children">
<ul class="slides">
<li><p>Text 1</p></li>
<li><p>Text 2</p></li>
<li><p>Text 3</p></li>
<li><p>Text 4</p></li>
</ul>
</div>
```
Then for your javascript just run this.
```
/**
* Create the children flexsliders. Must be array of jquery objects with the
* flexslider data. Easiest way is to place selector group in a var.
*/
var children_slides = $('.flexslider_children').flexslider({
'slideshow': false, // Remove the animations
'controlNav' : false // Remove the controls
});
/**
* Set up the main flexslider
*/
$('.flexslider').flexslider({
'pauseOnHover' : true,
'animationSpeed': 2000,
'slideshowSpeed': 5000,
'initDelay': 3000,
// Call the update_children_slides which itterates through all children slides
'before' : function(slider){ // Hijack the flexslider
update_children_slides(slider.animatingTo);
}
});
/**
* Method that updates children slides
* fortunately, since all the children are not animating,
* they will only update if the main flexslider updates.
*/
function update_children_slides (slide_number){
// Iterate through the children slides but not past the max
for (i=0;i<children_slides.length;i++) {
// Run the animate method on the child slide
$(children_slides[i]).data('flexslider').flexAnimate(slide_number);
}
}
```
Hope this helps!! Please note I added this cause it closely resembles what i was trying to do, Seems like I am not the only one looking to use multiple syncs in flexslider. |
51,981,643 | On page load date-picker working fine but after refresh the div it is not working
it gives error like
>
> jquery-ui.js:8633 Uncaught TypeError: Cannot read property 'settings'
> of undefined error
>
>
>
my code is below
```
<!DOCTYPE html>
<html>
<head>
<title>Image Select</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
</head>
<body>
<div class="subscription-container">
<input id="hiddenDate" type="hidden"/>
<button type="button" id="pickDate" class="btn btn-trial">Change shipping date</button>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#hiddenDate').datepicker({
minDate: 0
});
jQuery(document).on('click','#pickDate',function (e) {
// $('#pickDate').click(function (e) {
jQuery('#hiddenDate').datepicker("show");
// e.preventDefault();
});
});
jQuery(document).on('change','#hiddenDate',function(){
jQuery('#hiddenDate').datepicker("hide");
if(confirm("are you sure to reload")==true){
jQuery('.subscription-container').load(window.location.href+" .subscription-container>*","");
}
});
</script>
</body>
</html>
``` | 2018/08/23 | [
"https://Stackoverflow.com/questions/51981643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4910709/"
] | >
> How to catch exception message with skip method in spring batch?
>
>
>
You can do that by implementing the `SkipListener` interface or extending the `SkipListenerSupport` class. All methods in the `SkipListener` interface have a `Throwable` parameter which is the exception thrown and that caused the item to be skipped. This is where you can get the exception message. Here is an example:
```
import java.util.Arrays;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.SkipListener;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.support.ListItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@EnableBatchProcessing
public class MyJob {
@Autowired
private JobBuilderFactory jobs;
@Autowired
private StepBuilderFactory steps;
@Bean
public ItemReader<Integer> itemReader() {
return new ListItemReader<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
}
@Bean
public ItemWriter<Integer> itemWriter() {
return items -> {
for (Integer item : items) {
System.out.println("item = " + item);
}
};
}
@Bean
public ItemProcessor<Integer, Integer> itemProcessor() {
return item -> {
if (item.equals(7)) {
throw new IllegalArgumentException("Sevens are not accepted!!");
}
return item;
};
}
@Bean
public Step step() {
return steps.get("step")
.<Integer, Integer>chunk(5)
.reader(itemReader())
.processor(itemProcessor())
.writer(itemWriter())
.faultTolerant()
.skip(IllegalArgumentException.class)
.skipLimit(3)
.listener(new MySkipListener())
.build();
}
@Bean
public Job job() {
return jobs.get("job")
.start(step())
.build();
}
public static class MySkipListener implements SkipListener<Integer, Integer> {
@Override
public void onSkipInRead(Throwable t) {
}
@Override
public void onSkipInWrite(Integer item, Throwable t) {
}
@Override
public void onSkipInProcess(Integer item, Throwable t) {
System.out.println("Item " + item + " was skipped due to: " + t.getMessage());
}
}
public static void main(String[] args) throws Exception {
ApplicationContext context = new AnnotationConfigApplicationContext(MyJob.class);
JobLauncher jobLauncher = context.getBean(JobLauncher.class);
Job job = context.getBean(Job.class);
jobLauncher.run(job, new JobParameters());
}
}
```
In this example, `MySkipListener` implements `SkipListener` and gets the message from the exception as you are trying to do. The example reads numbers from 1 to 10 and skips number 7. You can run the `main` method and should see the following output:
```
item = 1
item = 2
item = 3
item = 4
item = 5
item = 6
item = 8
item = 9
item = 10
Item 7 was skipped due to: Sevens are not accepted!!
```
I hope this helps. | I couldn't get it to work either with implementing SkipListener (would be nice to know why) but in the end I went with the annotation way which is only briefly mentioned in the docs. Also somebody had a similar issue here using the implementation method ([question](https://stackoverflow.com/questions/7638924/spring-batch-skiplistener-not-called-when-exception-occurs-in-reader)) and the guy in the answer uses this annotation method instead of implementing the interface.
Example bean:
```
@Component
public class CustomSkippedListener {
@OnSkipInRead
public void onSkipInRead(Throwable throwable) {
}
@OnSkipInWrite
public void onSkipInWrite(FooWritingDTO fooWritingDTO, Throwable throwable) {
LOGGER.info("balabla" + throwable.getMessage());
}
@OnSkipInProcess
public void onSkipInProcess(FooLoaderDTO fooLoaderDTO, Throwable throwable) {
LOGGER.info("blabla" + throwable.getMessage());
}
private static final Logger LOGGER = LoggerFactory.getLogger(CustomSkippedListener.class);
}
```
then autowire and include in the step chain as you did. |
58,906,149 | Does anyone know any way of converting DXF files to either PNG or PDF?
I have a huge list of DXF Files and I want to convert them to Images to view them quicker.
If its possible, how could you extract the DXF file values, like the thickness or measurements of that drawing that's in the DXF File. | 2019/11/17 | [
"https://Stackoverflow.com/questions/58906149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12139409/"
] | EDIT!!!
```py
import matplotlib.pyplot as plt
import ezdxf
from ezdxf.addons.drawing import RenderContext, Frontend
from ezdxf.addons.drawing.matplotlib import MatplotlibBackend
# import wx
import glob
import re
class DXF2IMG(object):
default_img_format = '.png'
default_img_res = 300
def convert_dxf2img(self, names, img_format=default_img_format, img_res=default_img_res):
for name in names:
doc = ezdxf.readfile(name)
msp = doc.modelspace()
# Recommended: audit & repair DXF document before rendering
auditor = doc.audit()
# The auditor.errors attribute stores severe errors,
# which *may* raise exceptions when rendering.
if len(auditor.errors) != 0:
raise exception("The DXF document is damaged and can't be converted!")
else :
fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
ctx = RenderContext(doc)
ctx.set_current_layout(msp)
ctx.current_layout.set_colors(bg='#FFFFFF')
out = MatplotlibBackend(ax)
Frontend(ctx, out).draw_layout(msp, finalize=True)
img_name = re.findall("(\S+)\.",name) # select the image name that is the same as the dxf file name
first_param = ''.join(img_name) + img_format #concatenate list and string
fig.savefig(first_param, dpi=img_res)
if __name__ == '__main__':
first = DXF2IMG()
first.convert_dxf2img(['GT-010.DXF'],img_format='.png')
```
@hamza-mohammed shared a solution that works marvellously!
Full credit goes to: <https://github.com/Hamza442004/DXF2img>
Above is the version with out the GUI in case anyone wants the real deal! | [Dia](https://wiki.gnome.org/Apps/Dia/) from the `GNOME` project can convert `dxf` to `png`, it also has a `Python` [interface allowing for scripting](https://wiki.gnome.org/Apps/Dia/Python). |
18,584,960 | I have the following table,
```
CREATE TABLE [dbo].[Catalogs]
(
[ID] [INT] IDENTITY(1,1) NOT NULL,
[Name] NVARCHAR(255) NOT NULL,
[Description] NVARCHAR(500) NULL,
[Icon] NVARCHAR(255) NULL,
[Order] INT NOT NULL,
[ParentID] INT NULL,
[CreatorID] INT NOT NULL,
[LastModifierID] INT NOT NULL,
[CreationDate] DATETIME NOT NULL,
[LastModifiedDate] DATETIME NOT NULL,
PRIMARY KEY (ID)
)
```
Now I want to select all catalogs with HasChildren column.
**Edit:** HasChildren will be generated at run time. If the row's ID does not available in ParentID column in all rows. | 2013/09/03 | [
"https://Stackoverflow.com/questions/18584960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/960567/"
] | ```
SELECT *,
CASE WHEN EXISTS (SELECT * FROM [dbo].[Catalogs] c WHERE c.ParentID = p.Id)
THEN 1 ELSE 0 END AS HasChildren
FROM [dbo].[Catalogs] p
``` | ```
SELECT * ,
CASE WHEN(SELECT COUNT(*) FROM Table1 as child
WHERE parent.[ID]=child.[ParentID])>0 THEN 1 ELSE 0 END
AS HasChildren
FROM Table1 as parent
```
**[FIDDLE](http://www.sqlfiddle.com/#!3/ffd1a/17)** |
56,861 | National Science Foundation (NSF) in US enforces a limit on salary compensation over all grants, often referred to as the [**two-ninths-rule**](http://www.nsf.gov/pubs/policydocs/pappguide/nsf08_1/aag_5.jsp):
>
> Summer salary for faculty members on academic-year appointments is
> limited to no more than two-ninths of their regular academic-year
> salary. This limit includes summer salary received from all NSF-funded
> grants.
>
>
>
So, for a 9-mo faculty who can fill up to 3 months of their own summer salary, NSF as the sole source of salary compensation doesn't work no matter how many grants one has.
Compared to the NIH model where there is no such limit, in fact 100% of salary can be recovered in theory via NIH grants, this is a rather strong limit.
What is the motivation of the NSF two-ninths-rule? Why not three-ninths to cover the whole summer salary? | 2015/10/25 | [
"https://academia.stackexchange.com/questions/56861",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/386/"
] | I don't know for sure if this is historically accurate, but the story I've always heard is that the two-ninths rule was an attempt to avoid the vacation issue. If you take three months of summer salary, then that leaves no time at all for any vacation, since you can't accept summer salary for any time not spent on research. The fear was that if three months of summer salary were allowed, lots of people would request it (since a 9% salary increase would be tough to resist), but the public would be concerned that many of them were probably cheating and going on holiday with their families for part of that time anyway. The two-ninths rule minimizes the extent to which the NSF has to deal with this issue, since there's one month reserved for vacation or other activities.
Incidentally, this fits consistently with Bill Barth's answer: solving the vacation problem this way is probably more attractive for an agency that has less money in the first place. | One way to look at this is actually look at your question slightly differently - what assumptions do NSF vs. NIH funding make about who you are, and why they're funding you.
The NIH model is *clearly* meant to support dedicated, purely-NIH funded research positions run on 100% soft money, or something very, very near to it (a floating hard money fund for like, 5% effort to cover proposal development time, for example, is somewhat common). This implicitly implies that the NIH is funding the usual employment-related absences - sick days, vacation, etc. And that anything they *don't* pay for might as well not exist, in the case of a 100% soft money position.
In contrast, the NSF model is clearly paying for directed research time, under the assumption that someone else (presumably state/university funding) is picking up the rest of the tab. There's no reason then, for them to pay for things like vacation time or the other things. They only want to pay for the time one might reasonably be expected to be working directly on NSF-funded projects, and between other summer responsibilities and travel, that's probably not your entire summer. As some other's have said, that they're also cash constrained probably helps inform that position. |
55,376,125 | I have a 2d np.array with 3 columns, coming from 4 categories of registrations. I want to implement K-means on this 3-columns np array to test if it can automatically be clustered to 4 3-dimensional good-enough clusters. So I initiate my centroids from the medians of the real categories (3 medians \* 4 categories i want to cluster), and not from means because they all come from a non-parametric distribution. I scaled my data and created an np.array of medians (3\*4) but i get this error:
```
clean=[[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3]]
init_medians=np.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9], [0.01, 0.02, 0.03]])
model = KMeans(n_clusters=4, max_iter=300, init=init_medians)
model.fit(clean)
```
>
> TypeError: 'builtin\_function\_or\_method' object is not subscriptable
>
>
>
I have tried changing the array to np array, stack etc but it seems I cannot enter 3 medians per cluster. I think K-means can cluster on 3-dimensional spaces right?
It worked when i intiated the centroids with 4 single values but this is not what I want. The error is caused by the array i input to the init= . Is there a problem on my logic or K- means knowledge or some syntax problem? | 2019/03/27 | [
"https://Stackoverflow.com/questions/55376125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7919440/"
] | **PART 1:**
>
> TypeError: 'builtin\_function\_or\_method' object is not subscriptable
>
>
>
This is a pure `numpy` error and it appears because you have forgotten to use **parentheses** () in order to define the numpy array.
---
**PART 2:**
**First of all, in the `init_medians` you pass 4 lists but they did not have the same dimensions. The last list has 4 elements (i.e. `[0.01, 0.02, 0.03, 0.04]`) instead of 3 in order to represent the cluster medians.**
Second, the KMeans's `init` argument expects as input a ndarray of shape (n\_clusters, n\_features).
In your case, this should be a (4, 3) numpy array like the following:
```
init_medians=np.array( [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9], [0.01, 0.02, 0.03]] )
model = KMeans(n_clusters=4, max_iter=300, init=init_medians)
model.fit(clean)
```
---
**PART 3:**
**The data matrix X should be a numpy array not list of lists.**
The full code:
```
clean=np.array([[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3],[0.1, 0.2, 0.3]])
init_medians=np.array([[0.1, 0.2, 0.3], [0.4, 0.5, 0.6], [0.7, 0.8, 0.9], [0.01, 0.02, 0.03]])
model = KMeans(n_clusters=4, max_iter=300, init=init_medians)
model.fit(clean)
``` | Did you not simply forget to put brackets around np.array?
```
init_medians=np.array([...])
``` |
45,315,582 | I am creating an IOS app for a school project where the user ask the app to encrypt/decrypt strings using an asymmetric algorithm.
I would like the user to be able to 'talk' to the machine as if where talking to another human. For example the user could ask the app "Could you encrypt 'How are you?' for me, using Johns public key?" The app will then return 'How are you' encrypted with Johns public key.
I have watched the WWDC17 sessions on core ML. However I am not sure if it is applicable to my use case. Should I use Core ML or NLP? Or should I just look for key words in the sentence? If I should use Core ML what framework should be used to create the Model? | 2017/07/26 | [
"https://Stackoverflow.com/questions/45315582",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8366709/"
] | A simple way to get this working is to use the Speech framework that @dannymout mentioned to turn the user's speech into text. But I suggest you take two steps:
In the first step the user says something like "Encrypt please" or "I want to decrypt", but not the actual text yet. So here you just look for the word "encrypt" or "decrypt" to figure out what to do. (You could use some basic NLP for this or just do a string search.)
Then the app says, "What text would you like to encrypt?" Now the user speaks again, and you take that input and encrypt it and show the results.
(I guess for decrypting they would type in the encrypted text rather than say it, but you can have the app speak the text once it is decrypted.) | So, if I understand correctly, you're trying to build a chatbot. I'd suggest using NLP and the [Speech](https://developer.apple.com/documentation/speech) framework for voice dictation or just looking for the key words using the input from Speech.
CoreML would be a lot more complicated to get setup, not really suited for your use case, and offers nothing more than NLP, and would be more difficult to use. NLP was made for doing things like this.
Looking for key words might be even more easier, as the input your app would be getting probably won't be any more broad than, "encrypt this using this algorithm". |
43,260,832 | I am currently using Ansible to provision bare metal using an IPv6 link local address. Once the servers are provisioned, ansible will run a series of tests on the server, as one shell command, to ensure provisioning was successful. These tests take approximately 10 minutes to run.
The issue that I'm facing is that the connection seems to timeout before the command completes.
Here is the error from Ansible:
```
fatal: [fe80::5054:ff:XXXX:XXXX%eth0]: UNREACHABLE! => {
"changed": false,
"msg": "Failed to connect to the host via ssh: Shared connection to fe80::5054:ff:XXXX:XXXX%eth0 closed.\r\n",
"unreachable": true
}
```
By looking at this error, one might think there is an issue with the SSH connection. The SSH connection itself is good since several other tasks run successfully on the same host prior to this task.
How can I increase the timeout so that Ansible will wait for the command to finish? Can this timeout be increased within the Ansible configuration, or do I need to modify the command itself to increase the timeout? | 2017/04/06 | [
"https://Stackoverflow.com/questions/43260832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7128479/"
] | TL;DR
=====
Add this one liner to your `ansible.cfg` located on `/etc/ansible/ansible.cfg`
```bash
echo -e "[persistent_connection]\ncommand_timeout = 60\n" | sudo tee -a /etc/ansible/ansible.cfg
```
---
I searched about this and in the [`Ansible` official documents](https://docs.ansible.com/ansible/latest/network/getting_started/network_connection_options.html) mentioned:
The three options for controlling the connection timeout are as follows.
### Using vars (per task):
```yaml
- name: save running-config
cisco.ios.ios_command:
commands: copy running-config startup-config
vars:
ansible_command_timeout: 30
```
### Using the environment variable:
```bash
$export ANSIBLE_PERSISTENT_COMMAND_TIMEOUT=60
```
### Using the global configuration (in ansible.cfg):
```
[persistent_connection]
command_timeout = 60
``` | I was having almost the similar issue and -vvv did not give me much info. But checking the syslog in the guest showed me I was running out of memory when running the ansible script. It would be good if you can see the syslog entry to see if you have any issues in the guest when running ansible script. |
82,379 | [A full FAQ post has been written on meta.chem.SE](https://chemistry.meta.stackexchange.com/questions/3779/everything-you-need-to-know-about-synthesis-golf), explaining the premise of synthesis golf and the 'rules'. Please take a look at this before answering (if you haven't already).
---
This fifth round of golf concerns the synthesis of `(−)-α-(3,4-Dimethoxyphenethylaminomethyl)-4-hydroxybenzylalcohol` (denopamine), a synthetic drug indicated for use in the treatment of angina.
[![4-[(1R)-2-{[2-(3,4-dimethoxyphenyl)ethyl]amino}-1-hydroxyethyl]phenol](https://i.stack.imgur.com/CcRPc.png)](https://i.stack.imgur.com/CcRPc.png)
The challenge is to propose a route to denopamine. You may start with anything that has **less than 10 carbons**, but it must be available in the Sigma-Aldrich catalogue. A method should also be included to set the oxymethine stereocentre (no buying it!).
Given the relative simplicity of the target and the need for large quantities of the drug, consideration to step count and scalability should also be taken. | 2017/09/09 | [
"https://chemistry.stackexchange.com/questions/82379",
"https://chemistry.stackexchange.com",
"https://chemistry.stackexchange.com/users/21296/"
] | OK, new route. Retrosynthesis:
[](https://i.stack.imgur.com/cMEEL.png)
Denopamine **1** can be made by a reductive amination between amine **2** and aldehyde **3** (either of the two reductive amination disconnections are fairly obvious choices).
The requisite amine **2** contains 10 carbons and so it becomes necessary to make it using some other means - in this case, reduction of a nitroolefin **4**, which can itself be made via a nitroaldol reaction from 3,4-dimethoxybenzaldehyde **5** and nitromethane **6**.
The chiral α-hydroxyketone **3** can probably be made in numerous ways. Earlier I proposed organoocatalytic oxygenation with PhNO, but another possibility is to have an addition of "formaldehyde anion" to 4-hydroxybenzaldehyde **7**. Nitromethane **6** was chosen as the acyl anion equivalent, as the asymmetric Henry reaction is well-established methodology, e.g. by the Evans group ([*J. Am. Chem. Soc.* **2003,** *125* (42), 12692–12693](https://doi.org/10.1021/ja0373871)).
The forward synthesis is fairly straightforward:
[](https://i.stack.imgur.com/TPi9F.png)
[](https://i.stack.imgur.com/cDeKp.png)
[](https://i.stack.imgur.com/GSwGw.png)
5 steps from cheap starting materials, with longest linear sequence being 3 steps. | A synthesis using Sharpless dihydroxylation for stereoinduction:
 |
3,457,372 | Given an array of strings
```
["the" "cat" "sat" "on" "the" "mat"]
```
I'm looking to get all combinations of items in sequence, from any starting position, e.g.
```
["the"]
["the" "cat"]
["the" "cat" "sat"]
...
["cat" "sat" "on" "the" "mat"]
["sat" "on" "the" "mat"]
["on" "the" "mat"]
...
["sat" "on"]
["sat" "on" "the"]
```
Combinations out of the original sequence or with missing elements are disallowed, e.g.
```
["sat" "mat"] # missing "on"
["the" "on"] # reverse order
```
I'd also like to know if this operation has a particular name or if there's a neater way of describing it.
Thanks. | 2010/08/11 | [
"https://Stackoverflow.com/questions/3457372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/160406/"
] | If you're into one-liners, you might try
```
(0..arr.length).to_a.combination(2).map{|i,j| arr[i...j]}
```
BTW, I think those are called "all subsequences" of an array. | here you can get all the combinations
```
(1...arr.length).map{ | i | arr.combination( i ).to_a }.flatten(1)
``` |
21,853,070 | I'm doing my first maven spring Rest project which includes an embedded tomcat service and some MongoDb queries. I'm very new to both Maven and Spring, and can't seem to understand this error.
```
Exception in thread "main" java.lang.IllegalAccessError: tried to access method org.springframework.core.io.support.SpringFactoriesLoader.loadFactoryNames(Ljava/lang/Class;Ljava/lang/ClassLoader;)Ljava/util/List; from class org.springframework.boot.SpringApplication
at org.springframework.boot.SpringApplication.getSpringFactoriesInstances(SpringApplication.java:260)
at org.springframework.boot.SpringApplication.initialize(SpringApplication.java:226)
at org.springframework.boot.SpringApplication.<init>(SpringApplication.java:200)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:920)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)
at com.cave.spring.firstSpring.Application.main(Application.java:12)
```
This is the exception I'm getting. I'm trying to start an embedded tomcat service, but I keep getting errors. I think there are some incompatabilities in my pom.xml:
```
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework</groupId>
<artifactId>gs-rest-service</artifactId>
<version>0.1.0</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.0.0.RC1</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.11.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.3.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>3.1.2.RELEASE</version>
</dependency>
</dependencies>
<properties>
<start-class>com.cave.spring.firstSpring.Application</start-class>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>tomcat-maven-plugin</artifactId>
<configuration>
<url>http://127.0.0.1:8080/manager</url>
<server>TomcatServer</server>
<path>/firstSpring</path>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots><enabled>true</enabled></snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots><enabled>true</enabled></snapshots>
</pluginRepository>
</pluginRepositories>
</project>
``` | 2014/02/18 | [
"https://Stackoverflow.com/questions/21853070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1998234/"
] | You get circular dependency when:
A depends on B and B depends on A.
If you think both need this dependency then they should belong to one project. | you can move **FetchDetails()** to another project and reference to this project from both **xml** and **synchronise** projects |
9,288,394 | What is the real use of the security:http element in the spring security configurations. Is it applicable only for the web applications?
Please see the following code:
```
<security:http use-expressions="true">
<security:intercept-url pattern="/client/**"
access="isAuthenticated()" />
<security:intercept-url pattern="/**" access="permitAll" />
<security:form-login></security:form-login>
<security:logout />
<security:remember-me />
<security:session-management
invalid-session-url="/timeout.jsp">
<security:concurrency-control
max-sessions="1" error-if-maximum-exceeded="true" />
</security:session-management>
</security:http>
```
Explain it if you can. | 2012/02/15 | [
"https://Stackoverflow.com/questions/9288394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/421753/"
] | The `<http>` element is only applicable to web applicaitons. You should probably start with [the namespace chapter](http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ns-minimal) of the manual.
There is also an [appendix](http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#appendix-namespace), which lists each element/attribute and their function. | I found the xsd documentation helpful. check this out.
<http://www.springframework.org/schema/security/spring-security.xsd> |
1,633,790 | Does $x^{y^z}$ equal $x^{(y^z)}$? If so, why?
Why not simply apply the order of the operation from left to right? Meaning $x^{y^z}$ equals $(x^y)^z$?
I always get confused with this and I don't understand the underlying rule. Any help would be appreciated! | 2016/01/30 | [
"https://math.stackexchange.com/questions/1633790",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/245761/"
] | In the usual computer science jargon, exponentiation in mathematics is [right-associative](https://en.wikipedia.org/wiki/Operator_associativity), which means that $x^{y^z}$ should be read as $x^{(y^z)}$, not $(x^y)^z$.
In expositions of the [BODMAS](https://www.mathsisfun.com/operation-order-bodmas.html) rules that are careful enough to address this question, the rule is to evaluate the top exponent first. One way to help remember this convention is to note that $(x^y)^z = x^{yz}$ (i.e., $x^{(yz)}$), so it would be silly if out of the two possibilities, $x^{y^z}$ meant the one that can be expressed without using two tiers of superscripts. | The exponent is evaluated first if it is an expression. Examples are $3^{x+1}=3^{\left(x+1\right)}$ and $e^{5x^3+8x^2+5x+10}$ (the exponent is a cubic polynomial) and $10^{0+0+0+10^{15}+0+0+0}=10^{10^{15}}$. The left-associativity simply fails when the exponent contains multiple terms. |
24,805,738 | I'm trying to store the value from the class below as a variable, so i could used it later on, but I can't get it working.
Any ideas?
```
class Dates {
public function __construct($date) {
$this->DateCompare($date);
}
public function DateCompare($date) {
$date1 = new DateTime("2015-04-08");
$date2 = new DateTime($date);
$diff=date_diff($date1,$date2);
return $diff->format("%a");
}
}
echo $test = new Dates("2015-05-04");
```
Error I'm getting: *Catchable fatal error: Object of class Dates could not be converted to string in /virtual/index.php*
As said before, I don't want to echo that out, just store it in the `$test` variable, but if I can't even echo that out, then I'm not storing it either. | 2014/07/17 | [
"https://Stackoverflow.com/questions/24805738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3628153/"
] | As a contestant for the ugliest hack of the day:
```
sh$ TERMPID=$(ps -ef |
grep gnome-terminal | grep myWindow123 |
head -1 | awk '{ print $2 }')
sh$ kill $TERMPID
```
---
A probably better alternative would be to record the PID of the terminal at launch time, and then kill by that pid:
```
sh$ gnome-terminal --title "myWindow123" -x "watch ls /tmp"
sh$ echo $! > /path/to/my.term.pid
...
...
# Later, in a terminal far, far away
sh$ kill `cat /path/to/my.term.pid`
``` | In the script that starts the terminal:
```
#!/bin/bash
gnome-terminal --title "myWindow123" --disable-factory -x watch ls /tmp &
echo ${!} > /var/tmp/myWindow123.pid
```
In the script that shall slay the terminal:
```
#!/bin/bash
if [ -f /var/tmp/myWindow123.pid ]; then
kill $(cat /var/tmp/myWindow123.pid && rm /var/tmp/myWindow123.pid)
fi
``` |
23,736,315 | I'm trying to find a way to get a php variable value (in admin.php file) on the javascript.js file.
This is the javascript.js file. And the `from` variable is the variable that should get the value from the admin.php file.
```
var from;
function table() {
var atttHeader1 = document.createAttribute("data-hide");
var newtHeader1 = document.createElement("th");
atttHeader1.value="phone";
newtHeader1.setAttributeNode(atttHeader1);
var colName = document.createTextNode(from);
newtHeader1.appendChild(colName);
}
```
This is the admin.php file. And the `name` variable should be passed to javascript.js.
```
<?php
$name = "Homer";
?>
```
Is there a way to include a php file inside of a js file, giving me the possibility to use global variables and call functions? | 2014/05/19 | [
"https://Stackoverflow.com/questions/23736315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3584897/"
] | Just removing folder **[workspace].metadata.plugins\org.eclipse.wst.validation** and restarting eclipse solved the problem for me | Go to the .metadata and then inside the folder go to org.eclipse.wst.validation directory of the workspace and delete the dep.index file, and restart eclipse. |
22,302,327 | ```
package Message;
public class Example_R {
public static void main (String args[])
int n=1;
int input[]={1, 2, 1, 3, 4};
for (int j=0; j<=4; j++) {
int Add = 0;
for (int i=0; i<=4; i++) {
if (input[j] !=input[i]) {
Add+=input[i];
}
}
System.out.println(Add);
}
}
}
```
Output of This program is: 9 9 9 8 7 sum of all the other elements in the array that are not equal to the element.
Now I want to extend the program so I can print the Largest sum of any of it's element, (In this case 9 is the largest sum.) Do you have any suggestions? For this assignment I am restricted from using additional array, hashmap etc. not allowed. Arrays.sort(..) | 2014/03/10 | [
"https://Stackoverflow.com/questions/22302327",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3402001/"
] | Hint: use a variable that is holding "the largest sum reached so far". You will update it very time you compute a new sum.
You will need to find "how and when do I initialize this variable ?" and "how do I update it ?" | You can use variables of type `Comparable` and use the `compareTo()` method.
1. `one.compareTo(two)` will return > 0 if `one > two`
2. `one.compareTo(two)` will return < 0 if `one < two`
3. `one.compareTo(two)` will return 0 if `one` and `two` are equal
Go through the array, compare the current index with the previous index, and update a variable that holds the currentLargest value. |
44,401,103 | If I call filter() on a list, say:
```
>>> filter(lambda x: x > 1, [1,2,3,4])
[2, 3, 4]
```
Is this:
a) creating a totally new list in memory with the results
or
b) is it just pop()-ing items from the existing list and returning the same list? | 2017/06/06 | [
"https://Stackoverflow.com/questions/44401103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/849354/"
] | For the sake of completeness, I'll just leave this here.
```
>>> a = [i for i in range(10)]
>>> b = list(filter(lambda x: x > 1, a))
>>> id(a)
4510567816
>>> id(b)
4500803808
>>> id(a) == id(b)
False
```
If you know python, you'll know `id` gives you a unique reference identifier. If they're not equal, it means they're different. | not really
```
class Person:
def __init__(self, age) -> None:
self.age = age
p1 = Person(1)
p2 = Person(2)
p3 = Person(3)
p4 = Person(4)
p5 = Person(5)
p6 = Person(6)
list1= [p1, p2, p3, p4, p5, p6]
list2 = list(filter(lambda p : p.age > 3, list1))
list2[0].age = 100
print(p4.age)
print(p5.age)
print(p6.age)
```
output:
```
100
5
6
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.