id
int64 4
73.8M
| title
stringlengths 10
150
| body
stringlengths 17
50.8k
| accepted_answer_id
int64 7
73.8M
| answer_count
int64 1
182
| comment_count
int64 0
89
| community_owned_date
stringlengths 23
27
⌀ | creation_date
stringlengths 23
27
| favorite_count
int64 0
11.6k
⌀ | last_activity_date
stringlengths 23
27
| last_edit_date
stringlengths 23
27
⌀ | last_editor_display_name
stringlengths 2
29
⌀ | last_editor_user_id
int64 -1
20M
⌀ | owner_display_name
stringlengths 1
29
⌀ | owner_user_id
int64 1
20M
⌀ | parent_id
null | post_type_id
int64 1
1
| score
int64 -146
26.6k
| tags
stringlengths 1
125
| view_count
int64 122
11.6M
| answer_body
stringlengths 19
51k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
43,270,564 | Dividing a form into multiple components with validation | <p>I want to create a single big form with angular 2. But I want to create this form with multiple components as the following example shows.<br><br>
<strong>App component</strong></p>
<pre><code><form novalidate #form1="ngForm" [formGroup]="myForm">
<div>
<address></address>
</div>
<div>
<input type="text" ngModel required/>
</div>
<input type="submit" [disabled]="!form1.form.valid" > </form>
</code></pre>
<p><strong>Address component</strong></p>
<pre><code><div>
<input type="text" ngModel required/> </div>
</code></pre>
<p>When I use the code above it was visible in the browser as i needed but the submit button was not disabled when I delete the text in address component. <br>
But the button was disabled correctly when I delete the text in input box in app component. </p> | 43,277,336 | 6 | 5 | null | 2017-04-07 05:48:48.563 UTC | 24 | 2022-07-26 18:38:41.44 UTC | 2019-03-03 06:30:07.937 UTC | null | 5,736,236 | null | 4,383,820 | null | 1 | 77 | angular|typescript|angular-forms | 59,360 | <p>I would use a reactive form which works quite nicely, and as to your comment:</p>
<blockquote>
<p><em>Is there any other simple example for this one? Maybe the same example without loops</em></p>
</blockquote>
<p>I can give you an example. All you need to do, is to nest a <code>FormGroup</code> and pass that on to the child.</p>
<p>Let's say your form looks like this, and you want to pass <code>address</code> formgroup to child:</p>
<pre><code>ngOnInit() {
this.myForm = this.fb.group({
name: [''],
address: this.fb.group({ // create nested formgroup to pass to child
street: [''],
zip: ['']
})
})
}
</code></pre>
<p>Then in your parent, just pass the nested formgroup:</p>
<pre><code><address [address]="myForm.get('address')"></address>
</code></pre>
<p>In your child, use <code>@Input</code> for the nested formgroup:</p>
<pre><code>@Input() address: FormGroup;
</code></pre>
<p>And in your template use <code>[formGroup]</code>:</p>
<pre class="lang-html prettyprint-override"><code><div [formGroup]="address">
<input formControlName="street">
<input formControlName="zip">
</div>
</code></pre>
<p>If you do not want to create an actual nested formgroup, you don't need to do that, you can just then pass the parent form to the child, so if your form looks like:</p>
<pre class="lang-ts prettyprint-override"><code>this.myForm = this.fb.group({
name: [''],
street: [''],
zip: ['']
})
</code></pre>
<p>you can pass whatever controls you want. Using the same example as above, we would only like to show <code>street</code> and <code>zip</code>, the child component stays the same, but the child tag in template would then look like:</p>
<pre class="lang-html prettyprint-override"><code><address [address]="myForm"></address>
</code></pre>
<p>Here's a </p>
<p><strong><a href="https://stackblitz.com/edit/angular-azzmhu?file=src/app/hello.component.ts" rel="noreferrer">Demo</a></strong> of first option, here's the second <strong><a href="https://stackblitz.com/edit/angular-hzq5vy?file=src/app/app.component.html" rel="noreferrer">Demo</a></strong></p>
<p>More info <a href="https://scotch.io/tutorials/how-to-build-nested-model-driven-forms-in-angular-2" rel="noreferrer"><strong>here</strong></a> about nested model-driven forms.</p> |
9,371,195 | REST api: requesting multiple resources in a single get | <p>I'm trying to design a RESTful API where the users can fetch a single product or list of products in a single GET request. Each product has a unique id.</p>
<p>The single product URL is simple enough:</p>
<pre><code>http://mycompany.com/api/v1/product/id
</code></pre>
<p>This returns the information for a single product. I'm confused as to how the URL for multiple product information should look like.</p>
<p>How about</p>
<pre><code>http://mycompany.com/api/v1/product/ids
</code></pre>
<p>where ids is a comma separated list of ids?</p> | 9,372,477 | 2 | 3 | null | 2012-02-21 02:11:19.077 UTC | 26 | 2022-01-18 21:23:28.973 UTC | 2022-01-18 21:23:28.973 UTC | null | 1,746,685 | null | 824,212 | null | 1 | 105 | rest | 114,215 | <p>Your suggestion of ids separated with commas is good enough. </p>
<p>It would be instructive to examine some public REST APIs to see how they handle. For ex, the StackExchange API separates ids with a semi-colon - <a href="https://api.stackexchange.com/docs/answers-by-ids">https://api.stackexchange.com/docs/answers-by-ids</a></p> |
9,311,188 | Copy data from closed workbook based on variable user defined path | <p>I have exhausted my search capabilities looking for a solution to this. Here is an outline of what I would like to do:</p>
<ul>
<li>User opens macro-enabled Excel file<br></li>
<li>Immediate prompt displays for user to enter or select file path of desired workbooks. They will need to select two files, and the file names may not be consistent</li>
<li>After entering the file locations, the first worksheet from the first file selection will be copied to the first worksheet of the macro-enabled workbook, and the first worksheet of the second file selection will be copied to the second worksheet of the macro-enabled workbook.</li>
</ul>
<p>I've come across some references to ADO, but I am really not familiar with that yet.</p>
<p>Edit: I have found a code to import data from a closed file. I will need to tweak the range to return the variable results. </p>
<pre><code> Private Function GetValue(path, file, sheet, ref)
path = "C:\Users\crathbun\Desktop"
file = "test.xlsx"
sheet = "Sheet1"
ref = "A1:R30"
' Retrieves a value from a closed workbook
Dim arg As String
' Make sure the file exists
If Right(path, 1) <> "\" Then path = path & "\"
If Dir(path & file) = "" Then
GetValue = "File Not Found"
Exit Function
End If
' Create the argument
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xlR1C1)
' Execute an XLM macro
GetValue = ExecuteExcel4Macro(arg)
End Function
Sub TestGetValue()
path = "C:\Users\crathbun\Desktop"
file = "test"
sheet = "Sheet1"
Application.ScreenUpdating = False
For r = 1 To 30
For C = 1 To 18
a = Cells(r, C).Address
Cells(r, C) = GetValue(path, file, sheet, a)
Next C
Next r
Application.ScreenUpdating = True
End Sub
</code></pre>
<p>Now, I need a command button or userform that will immediately prompt the user to define a file path, and import the data from that file.</p> | 9,312,822 | 2 | 5 | null | 2012-02-16 12:21:37.493 UTC | 3 | 2016-11-02 10:15:48.463 UTC | 2015-11-12 01:49:30.433 UTC | null | 1,505,120 | null | 955,289 | null | 1 | 3 | vba|excel|excel-2007|xlm | 64,317 | <blockquote>
<blockquote>
<blockquote>
<p>I don't mind if the files are opened during process. I just didn't want the user to have to open the files individually. I just need them to be able to select or navigate to the desired files</p>
</blockquote>
</blockquote>
</blockquote>
<p>Here is a basic code. This code asks user to select two files and then imports the relevant sheet into the current workbook. I have given two options. Take your pick :)</p>
<p><strong>TRIED AND TESTED</strong></p>
<p><strong>OPTION 1 (Import the Sheets directly instead of copying into sheet1 and 2)</strong></p>
<pre><code>Option Explicit
Sub Sample()
Dim wb1 As Workbook, wb2 As Workbook
Dim Ret1, Ret2
Set wb1 = ActiveWorkbook
'~~> Get the first File
Ret1 = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
, "Please select first file")
If Ret1 = False Then Exit Sub
'~~> Get the 2nd File
Ret2 = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
, "Please select Second file")
If Ret2 = False Then Exit Sub
Set wb2 = Workbooks.Open(Ret1)
wb2.Sheets(1).Copy Before:=wb1.Sheets(1)
ActiveSheet.Name = "Blah Blah 1"
wb2.Close SaveChanges:=False
Set wb2 = Workbooks.Open(Ret2)
wb2.Sheets(1).Copy After:=wb1.Sheets(1)
ActiveSheet.Name = "Blah Blah 2"
wb2.Close SaveChanges:=False
Set wb2 = Nothing
Set wb1 = Nothing
End Sub
</code></pre>
<p><strong>OPTION 2 (Import the Sheets contents into sheet1 and 2)</strong></p>
<pre><code>Option Explicit
Sub Sample()
Dim wb1 As Workbook, wb2 As Workbook
Dim Ret1, Ret2
Set wb1 = ActiveWorkbook
'~~> Get the first File
Ret1 = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
, "Please select first file")
If Ret1 = False Then Exit Sub
'~~> Get the 2nd File
Ret2 = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
, "Please select Second file")
If Ret2 = False Then Exit Sub
Set wb2 = Workbooks.Open(Ret1)
wb2.Sheets(1).Cells.Copy wb1.Sheets(1).Cells
wb2.Close SaveChanges:=False
Set wb2 = Workbooks.Open(Ret2)
wb2.Sheets(1).Cells.Copy wb1.Sheets(2).Cells
wb2.Close SaveChanges:=False
Set wb2 = Nothing
Set wb1 = Nothing
End Sub
</code></pre> |
18,413,969 | Pass variable to function in jquery AJAX success callback | <p>I am trying to preload some images with a jQuery AJAX call, but am having real problems passing a (url) string into a function within the success function of the AJAX call (if that makes sense). </p>
<p>Here is my code as is stands:</p>
<pre><code>//preloader for images on gallery pages
window.onload = function() {
setTimeout(function() {
var urls = ["./img/party/"]; //just one to get started
for ( var i = 0; i < urls.length; i++ ) {
$.ajax({
url: urls[i],
success: function(data,url) {
$(data).find("a:contains(.jpg)").each(function(url) {
new Image().src = url + $(this).attr("href");
});
}
});
};
}, 1000);
};
</code></pre>
<p>One can see my (failed) attempt at passing the url through into the <code>.each()</code> call - <code>url</code> ends up takes the value of increasing integers. Not sure why or what these relate to, maybe the number of jpg files?</p>
<p>...anyway, it should of course take the single value in my original urls array. </p>
<p>Thanks for any help - I always seem to get in a bit of a twist with these callbacks.</p>
<hr>
<p><strong>PROGESS?</strong></p>
<p>So, I mucked around a bit, taking heed of comments from @ron tornambe and @PiSquared and am currently here:</p>
<pre><code>//preloader for images on gallery pages
window.onload = function() {
var urls = ["./img/party/","./img/wedding/","./img/wedding/tree/"];
setTimeout(function() {
for ( var i = 0; i < urls.length; i++ ) {
$.ajax({
url: urls[i],
success: function(data) {
image_link(data,i);
function image_link(data, i) {
$(data).find("a:contains(.jpg)").each(function(){
console.log(i);
new Image().src = urls[i] + $(this).attr("href");
});
}
}
});
};
}, 1000);
};
</code></pre>
<p>I tried putting the <code>image_link(data, i)</code> here there and everywhere (in each nested function etc.) but I get the same result: the value for <code>i</code> is only ever logged as 3. I suspect that this is because all references to <code>i</code> point to the same thing and by the time the asynchronous task actually gets to <code>image_link(data, i)</code> the <code>for...</code> loop is over and done with (and hence has a value of 3). Needless to say this gives <code>urls[i]</code> as 'undefined'.</p>
<p>Any (more) tips how I can get round this? </p> | 20,384,128 | 7 | 5 | null | 2013-08-24 01:15:45.44 UTC | 21 | 2018-08-10 15:56:52.073 UTC | 2016-04-14 02:04:54.24 UTC | null | 4,898,045 | null | 772,333 | null | 1 | 76 | jquery|ajax|callback | 145,277 | <p>Since the settings object is tied to that ajax call, you can simply add in the indexer as a custom property, which you can then access using <code>this</code> in the success callback:</p>
<pre><code>//preloader for images on gallery pages
window.onload = function() {
var urls = ["./img/party/","./img/wedding/","./img/wedding/tree/"];
setTimeout(function() {
for ( var i = 0; i < urls.length; i++ ) {
$.ajax({
url: urls[i],
indexValue: i,
success: function(data) {
image_link(data , this.indexValue);
function image_link(data, i) {
$(data).find("a:contains(.jpg)").each(function(){
console.log(i);
new Image().src = urls[i] + $(this).attr("href");
});
}
}
});
};
}, 1000);
};
</code></pre>
<p><strong>Edit:</strong> Adding in an updated JSFiddle example, as they seem to have changed how their ECHO endpoints work: <a href="https://jsfiddle.net/djujx97n/26/" rel="noreferrer">https://jsfiddle.net/djujx97n/26/</a>.</p>
<p>To understand how this works see the "context" field on the ajaxSettings object: <a href="http://api.jquery.com/jquery.ajax/" rel="noreferrer">http://api.jquery.com/jquery.ajax/</a>, specifically this note: </p>
<blockquote>
<p><em>"The <code>this</code> reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not
specified, this is a reference to the Ajax settings themselves."</em></p>
</blockquote> |
18,279,622 | Print out elements from an Array with a Comma between the elements | <p>I am printing out elements from an <code>ArrayList</code> and want to have a comma after each word except the last word.</p>
<p>Right now, I am doing it like this:</p>
<pre><code>for (String s : arrayListWords) {
System.out.print(s + ", ");
}
</code></pre>
<p>It prints out the words like this:</p>
<pre><code>one, two, three, four,
</code></pre>
<p>The problem is the last comma. How do I solve it?</p> | 18,279,659 | 14 | 1 | null | 2013-08-16 18:10:56.67 UTC | 7 | 2022-08-22 20:59:21.907 UTC | 2022-08-22 20:59:21.907 UTC | null | 17,949,945 | null | 1,299,477 | null | 1 | 21 | java|arrays|string|formatting | 63,872 | <p>Print the first word on its own if it exists. Then print the pattern as comma first, then the next element.</p>
<pre><code>if (arrayListWords.length >= 1) {
System.out.print(arrayListWords[0]);
}
// note that i starts at 1, since we already printed the element at index 0
for (int i = 1; i < arrayListWords.length, i++) {
System.out.print(", " + arrayListWords[i]);
}
</code></pre>
<p>With a <code>List</code>, you're better off using an <code>Iterator</code></p>
<pre><code>// assume String
Iterator<String> it = arrayListWords.iterator();
if (it.hasNext()) {
System.out.print(it.next());
}
while (it.hasNext()) {
System.out.print(", " + it.next());
}
</code></pre> |
19,976,627 | Posting JSON with jquery ajax to PHP | <p>I have a simple php file that decode my json string, passed with ajax, and stamp the result, but I can't keep the <code>$_POST</code> variable, why???</p>
<p>I try to inspect with fireBug and I can see that the POST request is sent correctly, when the <strong>php</strong> script is called, he respond Noooooooob to me, it seem any POST variable is set.</p>
<p>All I want is to have my array =)</p>
<p>JSON String generated by <code>JSON.stringify</code>:</p>
<pre><code>[
{
"id":21,
"children":[
{
"id":196
},
{
"id":195
},
{
"id":49
},
{
"id":194
}
]
},
{
"id":29,
"children":[
{
"id":184
},
{
"id":152
}
]
},
...
]
</code></pre>
<p>JavaScript</p>
<pre><code>$('#save').click(function() {
var tmp = JSON.stringify($('.dd').nestable('serialize'));
// tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
$.ajax({
type: 'POST',
url: 'save_categories.php',
dataType: 'json',
data: {'categories': tmp},
success: function(msg) {
alert(msg);
}
});
});
</code></pre>
<p>save_categories.php</p>
<pre><code><?php
if(isset($_POST['categories'])) {
$json = $_POST['categories'];
var_dump(json_decode($json, true));
} else {
echo "Noooooooob";
}
?>
</code></pre> | 19,976,910 | 4 | 3 | null | 2013-11-14 11:36:14.203 UTC | 1 | 2017-08-08 08:54:50.817 UTC | 2013-11-14 11:43:30.343 UTC | null | 2,385,927 | null | 2,385,927 | null | 1 | 20 | javascript|php|jquery|ajax|json | 90,414 | <p>Your code works if you remove <code>dataType: 'json'</code>, just tested it.</p>
<pre><code>$('#save').click(function() {
var tmp = JSON.stringify($('.dd').nestable('serialize'));
// tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
$.ajax({
type: 'POST',
url: 'save_categories.php',
data: {'categories': tmp},
success: function(msg) {
alert(msg);
}
});
});
</code></pre> |
27,673,000 | Rscript: There is no package called ...? | <p>I want to run R files in batch mode using Rscript, however it does not seem to be loading the libraries that I need. The specific error I am getting is:</p>
<pre><code>Error in library(timeSeries) : there is no package called 'timeSeries'
Execution halted
</code></pre>
<p>However I do have the package <code>timeSeries</code> and can load it from Rstudio, RGui, and R from the command line no problem. The issue seems to only be when running a script using Rscript.</p>
<p>My system/environment variables are configured as:</p>
<pre><code>C:\Program Files\R\R-3.1.0\bin\x64 (Appended to PATH)
R_HOME = C:\Program Files\R\R-3.1.0
R_User = Patrick
</code></pre>
<p>I am running the same version of R in RStudio, RGui, and R from command line. I've also checked <code>.Library</code> from these three sources and got the same output as well.</p>
<p>How can I run Rscript from command line with the packages that I am using (and have installed) in R?</p>
<h1>EDIT:</h1>
<p>I am using Rscript via <code>Rscript script.r</code> at the windows command line in the directory where <code>script.r</code> is located.</p>
<p>The output of <code>Rscript -e print(.Library)</code> is <code>[1] "C:/PROGRA~1/R/R-31~1.0/library"</code></p>
<p>which is consistent with the other three options that I mentioned: <code>[1] "C:/PROGRA~1/R/R-31~1.0/library"</code></p>
<p>However, if I put this in my script:</p>
<pre><code>print(.libPaths())
library(timeSeries) #This is the package that failed to load
</code></pre>
<p>I get an output of:</p>
<pre><code>[1] "C:/Program Files/R/R-3.1.0/library"
Error in library(timeSeries) : there is no package called 'timeSeries'
Execution halted
</code></pre>
<p>The corresponding call in RStudio gives an additional path to where the package is actually installed:</p>
<pre><code>> print(.libPaths())
[1] "C:/Users/Patrick/Documents/R/win-library/3.1" "C:/Program Files/R/R-3.1.0/library"
</code></pre> | 39,901,895 | 5 | 8 | null | 2014-12-28 01:30:25.16 UTC | 6 | 2021-01-02 20:28:23.2 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 2,593,236 | null | 1 | 35 | r|package|rscript | 83,021 | <p>In short, the value returned by calling <code>Sys.getenv('R_LIBS_USER')</code> in R.exe needs to be the same as the value returned by calling this at the command line: </p>
<pre><code>Rscript.exe -e "Sys.getenv('R_LIBS_USER')"
</code></pre>
<p><strong>and</strong> the above value needs to be included in this command line call: </p>
<pre><code>Rscript.exe -e ".libPaths()"
</code></pre>
<p><strong>Note that</strong> the values of <code>R_LIBS_USER</code> may be differ between R.exe and Rscript.exe if the value of <code>R_USER</code> is changed, either in the <a href="https://stackoverflow.com/a/11004871/1519199"><code>.Rprofile</code></a> or the <a href="https://stackoverflow.com/a/36704981/1519199">in target field of user's shortcut to <code>R.exe</code></a>, and in general, I find that the user library (i.e. <code>.libPaths()[2]</code>) is simply not set in Rscript.exe</p>
<p>Since I'm fond of setting <code>R_USER</code> to my <code>USERPROFILE</code>, I include the following block in at the top of <code>.R</code> files that I wish to run on mulitiple computers or in Rscript.exe's <code>.Rprofile</code> (i.e. <code>Rscript -e "path.expand('~/.Rprofile')"</code>): </p>
<pre><code># =====================================================================
# For compatibility with Rscript.exe:
# =====================================================================
if(length(.libPaths()) == 1){
# We're in Rscript.exe
possible_lib_paths <- file.path(Sys.getenv(c('USERPROFILE','R_USER')),
"R","win-library",
paste(R.version$major,
substr(R.version$minor,1,1),
sep='.'))
indx <- which(file.exists(possible_lib_paths))
if(length(indx)){
.libPaths(possible_lib_paths[indx[1]])
}
# CLEAN UP
rm(indx,possible_lib_paths)
}
# =====================================================================
</code></pre> |
15,103,782 | AVD - PANIC: Could not open... - not a path issue | <p>I want to write an Android app and I've started this morning by <em>loading JDK, eclipse, SDK</em> etc, all from the <code>adt-bundle-windows-x86_64-20130219</code> from <a href="http://developer.android.com">http://developer.android.com</a>.</p>
<p>The issue for me right now: </p>
<blockquote>
<p>[2013-02-27 13:36:26 - Test2] Android Launch!<br>
[2013-02-27 13:36:26 - Test2] adb is running normally.<br>
[2013-02-27 13:36:26 - Test2] Performing com.example.test2.MainActivity activity launch<br>
[2013-02-27 13:37:27 - Test2] Launching a new emulator with Virtual Device 'droidX2'<br>
[2013-02-27 13:37:27 - Emulator] PANIC: Could not open: droidX2 </p>
</blockquote>
<p>I've been sifting though posts on the web all morning about <strong>AVD</strong> and I haven't seen one that didn't involve the path being messed up and the <code>.ini</code> not found. I don't think I've got a path issue. AVD is looking for files on <code>D:\USERS\XXX\.android\avd</code> and that's where the files are. So don't understand why the emulator can't open. </p>
<p>I've done the most basic things like remove and re-install everything, read the notes at orace etc. Basically I'm stuck. Any suggestions here?</p>
<p><code>adt-bundle-windows-x86_64-20130219</code> was what I loaded on Windows 7 (32bit).</p>
<p>I'd settle for testing on the mobile that's connected to the PC but I can't get that to work either!</p>
<p>Any direction appreciated.</p> | 15,104,180 | 11 | 1 | null | 2013-02-27 03:42:59.563 UTC | 12 | 2017-04-21 15:58:53.06 UTC | 2013-02-27 03:51:05.287 UTC | null | 1,770,457 | null | 2,113,746 | null | 1 | 37 | android|emulation|avd | 94,717 | <p>This has been asked a few times already, try these:</p>
<blockquote>
<p>Create a environment variable called: ANDROID_SDK_HOME and set it to
C:\Users\Administrator Open Eclipse > Window > Preferences and click
in Run/Debug and String Substitution Add a new variable called:
user.home and set it to C:\Users\Administrator Create an AVD and run
it.</p>
</blockquote>
<p><a href="https://stackoverflow.com/a/9010020/1221203">Original answer by Colin</a></p>
<p>an android project member says <a href="https://code.google.com/p/android/issues/detail?id=19084" rel="nofollow noreferrer">here</a>:</p>
<blockquote>
<p>As a work-around, you can define the environment variable
ANDROID_SDK_HOME to point to the directory containing your .android
directory. The emulator and SDK Manager will pick it up properly.</p>
</blockquote> |
15,310,880 | How does typedef-ing a block works | <p>In C/Obj-C, we do a typedef like this <code>typedef int MYINT;</code> which is clear.</p>
<p>Doing typedef for a block -<code>typedef void (^MyBlock) (int a);</code></p>
<p>Now, we can use <code>MyBlock</code>.</p>
<p>Shouldn't it be like - <code>typedef void (^MyBlock) (int a) MyBlock;</code> similar to <code>#define</code>?</p>
<p>How the syntax works?</p> | 15,311,069 | 2 | 0 | null | 2013-03-09 12:52:28.45 UTC | 11 | 2015-04-11 16:53:01.833 UTC | 2013-03-09 13:08:04.473 UTC | null | 1,395,941 | null | 1,559,227 | null | 1 | 49 | objective-c|objective-c-blocks|typedef | 32,380 | <p>See <a href="http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/Blocks/Articles/bxDeclaringCreating.html#//apple_ref/doc/uid/TP40007502-CH4-SW3" rel="noreferrer">Declaring a Block Reference</a> in "Blocks Programming Topics":</p>
<blockquote>
<p>Block variables hold references to blocks. You declare them using
syntax similar to that you use to declare a pointer to a function,
except that you use ^ instead of *.</p>
</blockquote>
<p>So</p>
<pre><code> typedef void (^myBlock) (int a);
</code></pre>
<p>defines a the type of a block using the same syntax as </p>
<pre><code> typedef void (*myFunc) (int a);
</code></pre>
<p>declares a function pointer.</p>
<p>See e.g. <a href="https://stackoverflow.com/questions/1591361/understanding-typedefs-for-function-pointers-in-c-examples-hints-and-tips-ple">Understanding typedefs for function pointers in C</a> for more information about function pointers.</p> |
15,001,237 | How to apply "first" and "last" functions to columns while using group by in pandas? | <p>I have a data frame and I would like to group it by a particular column (or, in other words, by values from a particular column). I can do it in the following way: <code>grouped = df.groupby(['ColumnName'])</code>.</p>
<p>I imagine the result of this operation as a table in which some cells can contain sets of values instead of single values. To get a usual table (i.e. a table in which every cell contains only one a single value) I need to indicate what function I want to use to transform the sets of values in the cells into single values.</p>
<p>For example I can replace sets of values by their sum, or by their minimal or maximal value. I can do it in the following way: <code>grouped.sum()</code> or <code>grouped.min()</code> and so on.</p>
<p>Now I want to use different functions for different columns. I figured out that I can do it in the following way: <code>grouped.agg({'ColumnName1':sum, 'ColumnName2':min})</code>.</p>
<p>However, because of some reasons I cannot use <code>first</code>. In more details, <code>grouped.first()</code> works, but <code>grouped.agg({'ColumnName1':first, 'ColumnName2':first})</code> does not work. As a result I get a NameError: <code>NameError: name 'first' is not defined</code>. So, my question is: Why does it happen and how to resolve this problem.</p>
<p><strong>ADDED</strong></p>
<p><a href="http://pandas.pydata.org/pandas-docs/dev/groupby.html" rel="noreferrer">Here</a> I found the following example:</p>
<pre><code>grouped['D'].agg({'result1' : np.sum, 'result2' : np.mean})
</code></pre>
<p>May be I also need to use <code>np</code>? But in my case python does not recognize "np". Should I import it? </p> | 15,002,718 | 5 | 1 | null | 2013-02-21 11:33:56.173 UTC | 11 | 2021-11-27 02:12:56.017 UTC | 2019-03-08 18:37:35.213 UTC | null | 3,367,799 | null | 245,549 | null | 1 | 59 | python|pandas|group-by | 78,758 | <p>I think the issue is that there are two different <code>first</code> methods which share a name but act differently, one is for <a href="http://pandas.pydata.org/pandas-docs/stable/groupby.html#splitting-an-object-into-groups" rel="noreferrer">groupby objects</a> and <a href="http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.first.html" rel="noreferrer">another for a Series/DataFrame</a> (to do with timeseries).</p>
<p>To replicate the behaviour of the groupby <code>first</code> method over a DataFrame using <code>agg</code> you could use <code>iloc[0]</code> (which gets the first row in each group (DataFrame/Series) by index):</p>
<pre><code>grouped.agg(lambda x: x.iloc[0])
</code></pre>
<p>For example:</p>
<pre><code>In [1]: df = pd.DataFrame([[1, 2], [3, 4]])
In [2]: g = df.groupby(0)
In [3]: g.first()
Out[3]:
1
0
1 2
3 4
In [4]: g.agg(lambda x: x.iloc[0])
Out[4]:
1
0
1 2
3 4
</code></pre>
<p><em>Analogously you can replicate <code>last</code> using <code>iloc[-1]</code>.</em></p>
<p>Note: This will works column-wise, et al:</p>
<pre><code>g.agg({1: lambda x: x.iloc[0]})
</code></pre>
<p><em>In older version of pandas you could would use the irow method (e.g. <code>x.irow(0)</code>, see previous edits.</em></p>
<hr>
<p>A couple of updated notes:</p>
<p>This is better done using the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.nth.html" rel="noreferrer"><code>nth</code></a> groupby method, which is much faster >=0.13:</p>
<pre><code>g.nth(0) # first
g.nth(-1) # last
</code></pre>
<p><em>You have to take care a little, as the default behaviour for <code>first</code> and <code>last</code> ignores NaN rows... and IIRC for DataFrame groupbys it was broken pre-0.13... there's a <code>dropna</code> option for <code>nth</code>.</em></p>
<p>You can use the strings rather than built-ins (though IIRC pandas spots it's the <code>sum</code> builtin and applies <code>np.sum</code>):</p>
<pre><code>grouped['D'].agg({'result1' : "sum", 'result2' : "mean"})
</code></pre> |
38,298,607 | C - Incompatible Pointer Type | <p>Why does the following code give warnings?</p>
<pre><code>int main(void)
{
struct {int x; int y;} test = {42, 1337};
struct {int x; int y;} *test_ptr = &test;
}
</code></pre>
<p>Results:</p>
<pre><code>warning: initialization from incompatible pointer type [-Wincompatible-pointer-types]
struct {int x; int y;} *test_ptr = &test;
^
</code></pre> | 38,298,636 | 3 | 4 | null | 2016-07-11 03:10:47.343 UTC | 3 | 2016-07-16 21:37:15.59 UTC | 2016-07-11 09:05:44.82 UTC | null | 5,399,734 | null | 4,262,157 | null | 1 | 28 | c|pointers|struct|initialization|incompatibletypeerror | 5,379 | <p>They're two anonymous structure types (they neither have a tag). All such structure types (in a single translation unit) are distinct — they're never the same type. Add a tag!</p>
<p>The relevant sentence in the standard is in §6.7.2.1 <strong>Structure and union specifiers</strong>:</p>
<blockquote>
<p>¶8 The presence of a <em>struct-declaration-list</em> in a <em>struct-or-union-specifier</em> declares a new type,
within a translation unit.</p>
</blockquote>
<p>The <em>struct-declaration-list</em> refers to the material between <code>{</code> and <code>}</code> in the type.</p>
<p>That means that in your code, there are two separate types, one for each <code>struct { … }</code>. The two types are separate; you cannot officially assign a value of one type to the other, nor create pointers, etc. In fact, you can't reference those types again after the semicolon.</p>
<p>That means you could have:</p>
<pre><code>int main(void)
{
struct {int x; int y;} test = {42, 1337}, *tp = &test;
struct {int x; int y;} result, *result_ptr;
result_ptr = &result;
…
}
</code></pre>
<p>Now <code>test</code> and <code>tp</code> refer to the same type (one a structure, one a pointer to the structure), and similarly <code>result</code> and <code>result_ptr</code> refer to the same type, and the initializations and assignments are fine, but the two types are different. It's not clear that you create a compound literal of either type — you'd have to write <code>(struct {int x; int y;}){.y = 9, .x = 8}</code>, but the presence of the <em>struct-declaration-list</em> means that is another new type.</p>
<p>As noted in the comments, there is also section §6.2.7 <strong>Compatible type and composite type</strong>, which says:</p>
<blockquote>
<p>¶1 … Moreover, two structure,
union, or enumerated types declared in separate translation units are compatible if their
tags and members satisfy the following requirements: If one is declared with a tag, the
other shall be declared with the same tag. If both are completed anywhere within their
respective translation units, then the following additional requirements apply: there shall
be a one-to-one correspondence between their members such that each pair of
corresponding members are declared with compatible types; if one member of the pair is
declared with an alignment specifier, the other is declared with an equivalent alignment
specifier; and if one member of the pair is declared with a name, the other is declared
with the same name. For two structures, corresponding members shall be declared in the
same order. For two structures or unions, corresponding bit-fields shall have the same
widths.</p>
</blockquote>
<p>Roughly speaking, that says that if the definitions of the types in the two translation units (think 'source files' plus included headers) are the same, then they refer to the same type. Thank goodness for that! Otherwise, you couldn't have the standard I/O library working, amongst other minor details.</p> |
38,069,145 | Unexpected Machine Code - Will this affect app approval? | <p>This is quite linked to <a href="https://stackoverflow.com/questions/38062907/cordova-unexpected-machine-code-your-upload-contains-both-bitcode-and-native"><strong>this</strong></a> question but it doesn't have any solution.<br>
On uploading a build to iTunes Connect, I received the following message: </p>
<blockquote>
<p>We have discovered one or more issues with your recent delivery for
"Hurdal IL". Your delivery was successful, but you may wish to correct
the following issues in your next delivery:</p>
<p>Unexpected Machine Code - Your upload contains both bitcode and native
machine code. When you provide bitcode, it's not necessary to include
machine code as well. To reduce the size of your upload, use Xcode 7.3
or later, or any other toolchain that removes machine code.</p>
<p>After you’ve corrected the issues, you can use Xcode or Application
Loader to upload a new binary to iTunes Connect. </p>
</blockquote>
<ol>
<li>What is the resolution? </li>
<li>Will the app approval be affected if this build is uploaded ?</li>
</ol> | 38,093,861 | 7 | 5 | null | 2016-06-28 06:58:15.983 UTC | 3 | 2016-06-30 13:16:06.997 UTC | 2017-05-23 12:30:24.063 UTC | null | -1 | null | 541,786 | null | 1 | 29 | ios|iphone|xcode|app-store-connect | 5,389 | <p>I just talked with the Apple Developer Support, the official one. They don't said it clearly, but yes it's a bug.
So, it's confirmed that there's some malfunctioning in their side.</p>
<p>UPDATE: It won't affect the Apps in Production neither Testing!</p> |
8,073,531 | iPhone custom camera overlay (plus image processing) : how-to | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/5156417/how-do-you-create-a-custom-camera-view-instead-of-uiimagepickerviewcontroller">How do you create a custom camera view, instead of UIImagePickerViewController?</a> </p>
</blockquote>
<p>Many image sharing apps available today from the App Store use a custom camera instead of the standard camera picker provided by Apple.</p>
<p>Does anyone know any tutorials or tips for creating a custom camera?</p> | 8,073,641 | 2 | 0 | null | 2011-11-10 00:15:03.023 UTC | 17 | 2011-11-10 02:20:21.517 UTC | 2017-05-23 10:31:06.67 UTC | null | -1 | null | 719,127 | null | 1 | 10 | iphone|objective-c|cocoa-touch|ios5|uiimagepickercontroller | 21,783 | <p>Yes, create a UIImagePickerController from code, adjust its properties, add an overlay onto it, and with you controller, control whatever you want on that overlay : custom controls, overlaying images, etc...</p>
<p>That gives something like this :</p>
<pre><code>self.picker = [[UIImagePickerController alloc] init];
self.picker.sourceType = UIImagePickerControllerSourceTypeCamera;
self.picker.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
self.picker.cameraDevice = UIImagePickerControllerCameraDeviceRear;
self.picker.showsCameraControls = NO;
self.picker.navigationBarHidden = YES;
self.picker.toolbarHidden = YES;
self.picker.wantsFullScreenLayout = YES;
// Insert the overlay
self.overlay = [[OverlayViewController alloc] initWithNibName:@"Overlay" bundle:nil];
self.overlay.pickerReference = self.picker;
self.picker.cameraOverlayView = self.overlay.view;
self.picker.delegate = self.overlay;
[self presentModalViewController:self.picker animated:NO];
</code></pre>
<p><code>OverlayViewController</code> is the controller that you must write to control everything you add onto the overlay.</p>
<p><code>pickerReference</code> is a property you can keep to send orders to the camera. For example, you could call the following from an IBAction coming from a UIButton placed onto the overlay :</p>
<pre><code>[self.pickerReference takePicture];
</code></pre> |
9,305,680 | Apache Virtual Host not parsing PHP | <p>I decided to enable virtual hosts on my Apache server, and chose to make it port-based.</p>
<p>First thing I did, of course, was RTM. I followed the instructions <a href="http://httpd.apache.org/docs/2.0/vhosts/examples.html" rel="noreferrer">found here</a>. Well, it worked -- kind of. As far as the virtual host running, it does. The content pulled from :80 is different from :8080.</p>
<p>But PHP isn't working. The "original site", (port 80) is running PHP just great. The port 8080 site, however, sends the PHP to the browser. I see nothing in the browser, but the source code shows:</p>
<pre><code><?php
echo "It worked!";
?>
</code></pre>
<p>This topic seems to be very loosely documented on a few websites, but either I can't find a solution in them, or the solution listed isn't working for me.</p>
<p>Again, the virtual host itself is running fine. PHP, on the other hand, is not.</p>
<p>Any ideas on what it could be? What content from my httpd.conf file should I provide so I don't blow up my question by copy/pasting the whole thing?</p>
<p>(Sorry I forgot to post that I had these in place, Phil. Adding to avoid further confusion)</p>
<pre><code>Listen 80
Listen 8080
NameVirtualHost *:80
NameVirtualHost *:8080
<VirtualHost *:80>
ServerName mysite.com
DocumentRoot /var/www/vhosts/Site1/httpdocs
</VirtualHost>
<VirtualHost *:8080>
ServerName mysite.com
DocumentRoot /var/www/vhosts/Site2/httpdocs
</VirtualHost>
</code></pre>
<p>I tried adding this inside the tags:</p>
<pre><code>AddHandler php5-script .php
AddType text/html .php
</code></pre>
<p>...but to no avail.</p> | 9,313,316 | 11 | 8 | null | 2012-02-16 04:45:37.277 UTC | 4 | 2021-10-21 10:36:36.13 UTC | 2017-05-05 21:37:47.353 UTC | null | 1,415,724 | null | 1,075,581 | null | 1 | 24 | php|apache | 86,182 | <p>This finally put me on the right path:</p>
<p><a href="http://www.linuxquestions.org/questions/linux-server-73/php-not-working-on-one-vhost-but-works-on-all-others-851093/" rel="noreferrer">http://www.linuxquestions.org/questions/linux-server-73/php-not-working-on-one-vhost-but-works-on-all-others-851093/</a></p>
<p>Here's the solution:</p>
<p>In the <code><Directory></code> section, I included these lines:</p>
<pre><code><IfModule sapi_apache2.c>
php_admin_flag engine on
</IfModule>
<IfModule mod_php5.c>
php_admin_flag engine on
</IfModule>
</code></pre>
<p>Or, a redacted copy/paste of the solution on my server:</p>
<pre><code><Directory "/var/www/vhosts/A2/httpdocs">
<IfModule sapi_apache2.c>
php_admin_flag engine on
</IfModule>
<IfModule mod_php5.c>
php_admin_flag engine on
</IfModule>
(Other configuration parameters)
</Directory>
</code></pre> |
19,415,614 | Better "return if not None" in Python | <p>Is there a <em>better</em> way to write this code in python?</p>
<pre><code>result = slow_function()
if result:
return result
[...]
</code></pre>
<p>The function <code>slow_function</code> can return a value or <code>None</code> and it's slow, so this is not feasible:</p>
<pre><code>if slow_function():
return slow_function()
</code></pre>
<p>There is nothing wrong with the first way, but using a temporary variable seems overkill for python.</p>
<p>This code is pretty useful when you are solving a problem using recursive calls over <code>f</code> and with local assumption, for example you select an item from a list and then check if there is a feasible solution, otherwise you have to choose another one. Something like:</p>
<pre><code>def f(n):
for x in xrange(n):
result = slow_function(x):
if result:
return result
[...]
</code></pre>
<p>Wouldn't it be better something more idiomatic like:</p>
<pre><code>def f(n):
for x in xrange(n):
return slow_function(x) if is not None
</code></pre>
<p>This can be extended to check any kind of value. It would be an easy-to-read <em>return if</em> statement.</p>
<hr>
<h2>Additional example for code lovers</h2>
<p>Imagine you have a list of lists of numbers:</p>
<pre><code>lists = [[1,2,3],[4,5],[6,7,8],[9,10],...]
</code></pre>
<p>and you want to select one item for each list such that there is at most one even number in the selection. There could be a lot of lists, so trying each combination would be wasteful since you can already tell that if you start selecting [1,2,4,...] there could be no feasible solutions.</p>
<pre><code>def check(selected):
even_numbers = filter(lambda n: (n % 2) == 0, selected)
return len(even_numbers) < 2
def f(lists, selected=[]):
if not lists:
return selected
for n in lists[0]:
if check(selected + [n]):
result = f(lists[1:], selected + [n])
if result:
return result
</code></pre>
<p>Wouldn't it be better a syntax like:</p>
<pre><code>def f(lists, selected=[]):
return selected if not lists
for n in lists[0]:
if check(selected + [n]):
return f(lists[1:], selected + [n]) if is not None
</code></pre>
<p>The best I've done so far is to turn the function in a generator of feasible solutions:</p>
<pre><code>def f(lists, selected=[]):
if not lists:
yield selected
else:
for n in lists[0]:
if check(selected + [n]):
for solution in f(lists[1:], selected + [n]):
yield solution
</code></pre> | 19,416,193 | 6 | 11 | null | 2013-10-16 23:18:09.463 UTC | 4 | 2014-11-18 22:12:11.313 UTC | 2013-10-17 08:44:01.18 UTC | null | 1,003,123 | null | 1,003,123 | null | 1 | 39 | python|syntax | 36,343 | <p>Your <a href="https://stackoverflow.com/questions/19415614/better-return-if-not-none-in-python/19416193#comment28782461_19415614">latest comment</a> maybe makes it clearer what you want to do:</p>
<blockquote>
<p>Imagine that you pass f a list and it select an item, then calls itself passing the list without the item and so on until you have no more items. The you check if the solution is feasible, if it is feasible you'll return the solution and this needs to go all the way through the call stack, otherwise you return None. In this way you'll explore all the problems in a topological order but you can also skip checks when you know that the previous chosen items won't be able to create a feasible solution. </p>
</blockquote>
<p>Maybe you can try using <code>yield</code> instead of <code>return</code>. That is, your recursive function won't generate one solution, but will yield all possible solutions. Without a specific example I can't be sure what you're doing exactly, but say before it was like this:</p>
<pre><code>def solve(args, result_so_far):
if not slow_check_is_feasible(result_so_far):
#dead-end
return None
if not args:
#valid and done
return result_so_far
for i, item in enumerate(args):
#pass list without args - slow
new_args = args[:]
del new_args[i]
result = solve(new_args, accumulate_result(result_so_far, item)
if result is not None:
#found it, we are done
return result
#otherwise keep going
</code></pre>
<p>Now it looks like this:</p>
<pre><code>def solve_all(args, result_so_far):
if not slow_check_is_feasible(result_so_far):
#dead-end
return
if not args:
#yield since result was good
yield result_so_far
return
for i, item in enumerate(args):
#pass list without args - slow
new_args = args[:]
del new_args[i]
for result in solve(new_args, accumulate_result(result_so_far, item):
yield result
</code></pre>
<p>The benefits are:</p>
<ul>
<li>You generate all answers instead of just the first one, but if you still only want one answer then you can just get the first result.</li>
<li>Before you used return values both for false checks and for answers. Now you're just only yielding when you have an answer.</li>
</ul> |
8,412,903 | How to access DB config in CodeIgniter? | <p>In my application, I need to know what values are assigned to the DB config items such as <code>database</code>, <code>username</code>, etc. How do I access those information?</p> | 8,413,043 | 6 | 3 | null | 2011-12-07 09:20:54.127 UTC | 3 | 2021-02-25 19:29:37.62 UTC | null | null | null | null | 253,976 | null | 1 | 12 | codeigniter | 38,190 | <p>You can retrieve it with this:
<a href="http://codeigniter.com/user_guide/libraries/config.html" rel="nofollow">http://codeigniter.com/user_guide/libraries/config.html</a></p>
<pre><code>$this->config->item('item name');
</code></pre> |
8,905,432 | What is the use of 'abstract override' in C#? | <p>Just out of curiosity I tried overriding a abstract method in base class, and method the implementation abstract. As below:</p>
<pre><code>public abstract class FirstAbstract
{
public abstract void SomeMethod();
}
public abstract class SecondAbstract : FirstAbstract
{
public abstract override void SomeMethod();
//?? what sense does this make? no implementaion would anyway force the derived classes to implement abstract method?
}
</code></pre>
<p>Curious to know why C# compiler allows writing 'abstract override'. Isn't it redundant? Should be a compile time error to do something like this. Does it serve to some use-case?</p>
<p>Thanks for your interest.</p> | 8,905,465 | 7 | 5 | null | 2012-01-18 05:03:30.24 UTC | 9 | 2019-04-27 20:06:23.83 UTC | null | null | null | null | 93,613 | null | 1 | 56 | c#|overriding|abstract | 25,073 | <p>There's a useful example for this on <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/abstract-and-sealed-classes-and-class-members" rel="noreferrer">Microsoft Docs</a> - basically you can force a derived class to provide a new implementation for a method.</p>
<pre><code>public class D
{
public virtual void DoWork(int i)
{
// Original implementation.
}
}
public abstract class E : D
{
public abstract override void DoWork(int i);
}
public class F : E
{
public override void DoWork(int i)
{
// New implementation.
}
}
</code></pre>
<blockquote>
<p>If a virtual method is declared abstract, it is still virtual to any
class inheriting from the abstract class. <strong>A class inheriting an
abstract method cannot access the original implementation of the
method</strong>—in the previous example, DoWork on class F cannot call DoWork
on class D. <strong>In this way, an abstract class can force derived classes
to provide new method implementations for virtual methods</strong>.</p>
</blockquote> |
5,328,072 | can jqgrid support dropdowns in the toolbar filter fields | <p>i am using jqgrid and the toolbar filter. by default its just gives you a textbox to enter data into. Does it support a dropdown select combobox where i can give it a list of values to choose from to them filter on ??</p> | 5,329,014 | 4 | 0 | null | 2011-03-16 16:02:31.62 UTC | 15 | 2016-10-18 14:45:00.047 UTC | null | null | null | null | 4,653 | null | 1 | 35 | jquery|jqgrid | 45,586 | <p>There are some <a href="http://www.trirand.com/jqgridwiki/doku.php?id=wiki:search_config" rel="noreferrer">common rules</a> for all types of sorting in jqGrid</p>
<pre><code>{
name: 'Category', index: 'Category', width: 200, formatter:'select',
stype: 'select', searchoptions:{ sopt:['eq'], value: categoriesStr }
}
</code></pre>
<p>where <code>categoriesStr</code> are defined as</p>
<pre><code>var categoriesStr = ":All;1:sport;2:science";
</code></pre>
<p>Here additionally to the standard "1:sport;2:science" values are inserted ":All" string which allow you don't filter the the column. You can of course use ":" or ":Select..." and so on.</p>
<p>On <a href="http://www.ok-soft-gmbh.com/jqGrid/ToolbarSearchValidation.htm" rel="noreferrer">the demo</a> prepared for <a href="https://stackoverflow.com/questions/4183300/avoid-special-characters-search-in-jqgrid-toolbar/4184035#4184035">the answer</a> you can see the close results.</p>
<p><strong>UPDATED</strong>: I find your question interesting and made <a href="http://www.ok-soft-gmbh.com/jqGrid/FillToolbarSearchFilter.htm" rel="noreferrer">the demo</a>. It shows how one can build the select comboboxes which can be used in the search toolbar or in the advanced searching dialog <strong>based on the text contain of the corresponding column</strong>. For one column I use additionally <a href="http://jqueryui.com/demos/autocomplete/" rel="noreferrer">jQuery UI autocomplete</a>. You can modify the code to use more different powerful options of the autocomplete. Here is the code of the code:</p>
<pre><code>var mydata = [
{id:"1", Name:"Miroslav Klose", Category:"sport", Subcategory:"football"},
{id:"2", Name:"Michael Schumacher", Category:"sport", Subcategory:"formula 1"},
{id:"3", Name:"Albert Einstein", Category:"science", Subcategory:"physics"},
{id:"4", Name:"Blaise Pascal", Category:"science", Subcategory:"mathematics"}
],
grid = $("#list"),
getUniqueNames = function(columnName) {
var texts = grid.jqGrid('getCol',columnName), uniqueTexts = [],
textsLength = texts.length, text, textsMap = {}, i;
for (i=0;i<textsLength;i++) {
text = texts[i];
if (text !== undefined && textsMap[text] === undefined) {
// to test whether the texts is unique we place it in the map.
textsMap[text] = true;
uniqueTexts.push(text);
}
}
return uniqueTexts;
},
buildSearchSelect = function(uniqueNames) {
var values=":All";
$.each (uniqueNames, function() {
values += ";" + this + ":" + this;
});
return values;
},
setSearchSelect = function(columnName) {
grid.jqGrid('setColProp', columnName,
{
stype: 'select',
searchoptions: {
value:buildSearchSelect(getUniqueNames(columnName)),
sopt:['eq']
}
}
);
};
grid.jqGrid({
data: mydata,
datatype: 'local',
colModel: [
{ name:'Name', index:'Name', width:200 },
{ name:'Category', index:'Category', width:200 },
{ name:'Subcategory', index:'Subcategory', width:200 }
],
sortname: 'Name',
viewrecords: true,
rownumbers: true,
sortorder: "desc",
ignoreCase: true,
pager: '#pager',
height: "auto",
caption: "How to use filterToolbar better locally"
}).jqGrid('navGrid','#pager',
{edit:false, add:false, del:false, search:false, refresh:false});
setSearchSelect('Category');
setSearchSelect('Subcategory');
grid.jqGrid('setColProp', 'Name',
{
searchoptions: {
sopt:['cn'],
dataInit: function(elem) {
$(elem).autocomplete({
source:getUniqueNames('Name'),
delay:0,
minLength:0
});
}
}
});
grid.jqGrid('filterToolbar',
{stringResult:true, searchOnEnter:true, defaultSearch:"cn"});
</code></pre>
<p>Is this what you want?</p>
<p><strong>UPDATED</strong>: One more option could be the usage of <a href="http://ivaynberg.github.io/select2/" rel="noreferrer">select2</a> plugin which combines the advantages of dropdown and comfortable searching by Autocomplete. See <a href="https://stackoverflow.com/a/19404013/315935">the answer</a> and <a href="http://www.ok-soft-gmbh.com/jqGrid/UsageFormetterSelect2.htm" rel="noreferrer">this one</a> (see the demo) for demos (<a href="http://www.ok-soft-gmbh.com/jqGrid/UsageFormetterSelect2.htm" rel="noreferrer">this one</a> and <a href="http://www.ok-soft-gmbh.com/jqGrid/BootsrtapSelectInEditing.htm" rel="noreferrer">this one</a>) and code examples. </p>
<p><strong>UPDATED 2</strong>: <a href="https://stackoverflow.com/a/29141713/315935">The answer</a> contains the modification of above code to work with jqGrid 4.6/4.7 or with <a href="https://github.com/free-jqgrid/jqGrid" rel="noreferrer">free jqGrid 4.8</a>.</p> |
5,354,541 | how to avoid session timeout in web.config | <p>What should I write in web config file in asp.net so that my session time is extended. and please tell me the exact location where should I place the code in web config</p> | 5,354,749 | 6 | 0 | null | 2011-03-18 15:54:21.347 UTC | 2 | 2019-01-29 09:49:44.96 UTC | 2012-08-21 05:48:56.737 UTC | null | 954,725 | null | 649,491 | null | 1 | 8 | c#|asp.net | 46,975 | <p>If you are trying to stop the session from timeing out all the time you can do this rather than increasing the session timeout. </p>
<p>KeepAlive.aspx</p>
<pre><code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="KeepAlive.aspx.cs" Inherits="Pages.KeepAlive" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ OutputCache Location="None" VaryByParam="None" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
KEEP ALIVE
</div>
</form>
</body>
</html>
</code></pre>
<p>Keep Alive.aspx.cs</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Pages
{
/// <summary>
/// Page to keep the session alive
/// </summary>
public partial class KeepAlive : System.Web.UI.Page
{
//- EVENTS ------------------------------------------------------------------------------------------------------------------
#region Events
/// <summary>
/// Page Load
/// </summary>
/// <param name="sender">object</param>
/// <param name="e">args</param>
protected void Page_Load(object sender, EventArgs e)
{
try
{
//Add refresh header to refresh the page 60 seconds before session timeout
Response.AddHeader("Refresh", Convert.ToString((Session.Timeout * 60) - 60));
}
catch (Exception)
{
throw;
}
}
#endregion Events
//---------------------------------------------------------------------------------------------------------------------------
}
}
</code></pre>
<p>Then in your master page create an iFrame that refreshes to keep the session alive</p>
<pre><code><iframe id="Defib" src="KeepAlive.aspx" frameborder="0" width="0" height="0" runat="server">
</iframe>
</code></pre> |
12,116,282 | Handling Push Notifications when App is NOT running | <p>When my App is <strong><em>not</em></strong> running and receives a Push Notification, if I click on that notification, the App is launched - but then it doesn't prompt the user with the Alert-View I set up, asking them whether they want to view the Notification's contents or not. It just launches, and sits there.</p>
<p>The Push Notifications do work <em>perfectly</em> when the App <strong><em>is</em></strong> running - either as the Active app or while in the background - but nothing works correctly when the app is <strong><em>not</em></strong> running.</p>
<p>I tried logging-out the <code>launchOptions</code> NSDictionary in <code>application: didFinishLaunchingWithOptions:</code> to see what load its bringing - but it comes up as "(null)". So It basically contains nothing - which doesn't make sense cause shouldn't it contain the Notification's load?</p>
<p>Anybody have any ideas how to make Push Notifications work when they arrive while the App was NOT running?</p>
<p>EDIT: here's the code I'm using in <code>application: didReceiveRemoteNotification</code> just to see what's what:</p>
<pre><code>if (UIApplicationStateBackground) {
NSLog(@"===========================");
NSLog(@"App was in BACKGROUND...");
}
else if (UIApplicationStateActive == TRUE) {
NSLog(@"===========================");
NSLog(@"App was ACTIVE");
}
else {
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 99];
UIAlertView *BOOM = [[UIAlertView alloc] initWithTitle:@"BOOM"
message:@"app was INACTIVE"
delegate:self
cancelButtonTitle:@"a-ha!"
otherButtonTitles:nil];
[BOOM show];
NSLog(@"App was NOT ACTIVE");
}
</code></pre>
<p>So this is supposed to take care of all the application's states - but its not. Push Notifications are only working when the app is running - either in the background or in the foreground...</p>
<p>================================================</p>
<p>UPDATE/EDIT#2:
as per "@dianz" suggestion (below,) I modified the code of my <code>application: didFinishLaunchingWithOptions</code> to include the following:</p>
<pre><code>UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (localNotif) {
NSString *json = [localNotif valueForKey:@"data"];
UIAlertView *bam = [[UIAlertView alloc] initWithTitle:@"appDidFinishWithOptions"
message:json
delegate:self
cancelButtonTitle:@"cool"
otherButtonTitles:nil];
[bam show];
}
</code></pre>
<p>This does make the AlertView box appear, but there seems to be no payload: the title of the AlertView shows up ("appDidFinishWithOptions"), but the json NSString comes up EMPTY... Will keep tweaking...</p>
<p>======================</p>
<p>EDIT #3 - its now working <em>almost</em> 100% <br/>
So, in <code>didFinishLaunchingWithOptions</code>: </p>
<pre><code>UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (localNotif) {
// Grab the pushKey:
pushKey = [localNotif valueForKey:@"pushKey"];
// "pushKey" is an NSString declared globally
// The "pushKey" in the "valueForKey" statement is part of my custom JSON Push Notification pay-load.
// The value of pushKey will always be a String, which will be the name of the
// screen I want the App to navigate to. So when a Notification arrives, I go
// through an IF statement and say "if pushKey='specials' then push the
// specialsViewController on, etc.
// Here, I parse the "alert" portion of my JSON Push-Notification:
NSDictionary *tempDict = [localNotif valueForKey:@"aps"];
NSString *pushMessage = [tempDict valueForKey:@"alert"];
// Finally, ask user if they wanna see the Push Notification or Cancel it:
UIAlertView *bam = [[UIAlertView alloc] initWithTitle:@"(from appDidFinishWithOptions)"
message:pushMessage
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"View Info", nil];
[bam show];
}
</code></pre>
<p>I next implement the <code>alertView: clickedButtonAtIndex</code> method to see what the user chose on the AlertView and proceed accordingly.</p>
<p>This, along with the <code>didReceiveRemoteNotification</code> logic works perfectly.</p>
<p>HOWEVER... when the app is NOT running, and I send it a Push Notification, if I DON'T click on the Push Notification alert as soon as it arrives and instead wait for it to fade out (which happens after like 3-4 seconds), and <em>then</em> I click on the App's icon - which now has a BADGE of 1 on it - the app launches, but I don't get the Push Notification alert at all when it launches. It just sits there.</p>
<p>Guess I need to figure <em>that</em> permutation next...</p> | 12,118,791 | 8 | 6 | null | 2012-08-24 20:35:57.697 UTC | 35 | 2017-11-28 12:39:47.973 UTC | 2012-08-25 14:38:46.847 UTC | null | 1,010,171 | null | 1,010,171 | null | 1 | 45 | iphone|push-notification|apple-push-notifications | 51,936 | <p>When your app is not running or killed and you tap on push notification this function will trigger;</p>
<pre><code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
</code></pre>
<p>so you should handle it like this,</p>
<pre><code>UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (localNotif) {
NSString *json = [localNotif valueForKey:@"data"];
// Parse your string to dictionary
}
</code></pre> |
12,568,100 | Connecting to Oracle Database through C#? | <p>I need to connect to a Oracle DB (external) through Visual Studio 2010. But I dont want to install Oracle on my machine.
In my project I referenced: <strong>System.Data.OracleClient</strong>. But its not fulfilling the need.
I have an <strong>"Oracle SQL Developer IDE"</strong> in which I run SQL queries against oracle db. </p>
<p>I have this code so far:</p>
<pre><code> private static string GetConnectionString()
{
String connString = "host= serverName;database=myDatabase;uid=userName;pwd=passWord";
return connString;
}
private static void ConnectingToOracle()
{
string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
Console.WriteLine("State: {0}", connection.State);
Console.WriteLine("ConnectionString: {0}",
connection.ConnectionString);
OracleCommand command = connection.CreateCommand();
string sql = "SELECT * FROM myTableName";
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string myField = (string)reader["MYFIELD"];
Console.WriteLine(myField);
}
}
}
</code></pre>
<p>So far I read these blogs: </p>
<p><a href="http://st-curriculum.oracle.com/tutorial/DBXETutorial/index.htm">http://st-curriculum.oracle.com/tutorial/DBXETutorial/index.htm</a></p>
<p><a href="http://blogs.msdn.com/b/kaevans/archive/2009/07/18/connecting-to-oracle-from-visual-studio.aspx">http://blogs.msdn.com/b/kaevans/archive/2009/07/18/connecting-to-oracle-from-visual-studio.aspx</a></p>
<p>So far I have not downloaded anything from Oracle. What steps should I take to make this happen? </p> | 12,568,350 | 5 | 8 | null | 2012-09-24 15:26:10.05 UTC | 19 | 2019-04-26 11:55:22.923 UTC | 2012-09-24 15:30:41.06 UTC | null | 1,329,529 | null | 529,995 | null | 1 | 46 | c#|oracle|c#-4.0 | 243,456 | <p>First off you need to download and install ODP from this site
<a href="http://www.oracle.com/technetwork/topics/dotnet/index-085163.html" rel="noreferrer">http://www.oracle.com/technetwork/topics/dotnet/index-085163.html</a></p>
<p>After installation add a reference of the assembly <strong>Oracle.DataAccess.dll</strong>.</p>
<p>Your are good to go after this.</p>
<pre><code>using System;
using Oracle.DataAccess.Client;
class OraTest
{
OracleConnection con;
void Connect()
{
con = new OracleConnection();
con.ConnectionString = "User Id=<username>;Password=<password>;Data Source=<datasource>";
con.Open();
Console.WriteLine("Connected to Oracle" + con.ServerVersion);
}
void Close()
{
con.Close();
con.Dispose();
}
static void Main()
{
OraTest ot= new OraTest();
ot.Connect();
ot.Close();
}
}
</code></pre> |
44,331,725 | onResume() and onPause() for widgets on Flutter | <p>Right now, a widget only has initeState() that gets triggered the very first time a widget is created, and dispose(), which gets triggered when the widget is destroyed. Is there a method to detect when a widget comes back to the foreground? and when a widget is about to go to the background because another widget just was foregrounded?
It's the equivalent of onResume and onPause being triggered for Android, and viewWillAppear and viewWillDisappear for ios</p> | 44,333,474 | 6 | 3 | null | 2017-06-02 14:48:45.007 UTC | 14 | 2021-12-29 07:35:27.013 UTC | null | null | null | null | 3,217,522 | null | 1 | 44 | android|ios|dart|lifecycle|flutter | 42,540 | <p>The most common case where you'd want to do this is if you have an animation running and you don't want to consume resources in the background. In that case, you should extend your <code>State</code> with <code>TickerProviderStateMixin</code> and use your <code>State</code> as the <code>vsync</code> argument for the <code>AnimationController</code>. Flutter will take care of only calling the animation controller's listeners when your <code>State</code> is visible.</p>
<p>If you want the <code>State</code>s that live in your <code>PageRoute</code> to be disposed when the <code>PageRoute</code> is obscured by other content, you can pass a <a href="https://docs.flutter.io/flutter/widgets/ModalRoute/maintainState.html" rel="noreferrer"><code>maintainState</code></a> argument of <code>false</code> to your <code>PageRoute</code> constructor. If you do this, your <code>State</code> will reset itself (and its children) when it's hidden and will have to re-construct itself in <code>initState</code> using the properties passed in as constructor arguments to its <code>widget</code>. You can use a model or controller class, or <a href="https://docs.flutter.io/flutter/widgets/PageStorage-class.html" rel="noreferrer"><code>PageStorage</code></a>, to hold the user's progress information if you don't want a complete reset.</p>
<p>Here is a sample app that demonstrates these concepts.</p>
<p><a href="https://i.stack.imgur.com/aJOke.png" rel="noreferrer"><img src="https://i.stack.imgur.com/aJOke.png" alt="screen 1"></a>
<a href="https://i.stack.imgur.com/gGezP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gGezP.png" alt="screen 2"></a>
<a href="https://i.stack.imgur.com/5VoJA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5VoJA.png" alt="screen 3"></a></p>
<pre><code>import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(
onGenerateRoute: (RouteSettings settings) {
if (settings.name == '/') {
return new MaterialPageRoute<Null>(
settings: settings,
builder: (_) => new MyApp(),
maintainState: false,
);
}
return null;
}
));
}
class MyApp extends StatefulWidget {
MyAppState createState() => new MyAppState();
}
class MyAppState extends State<MyApp> with TickerProviderStateMixin {
AnimationController _controller;
@override
void initState() {
print("initState was called");
_controller = new AnimationController(vsync: this)
..repeat(min: 0.0, max: 1.0, period: const Duration(seconds: 1))
..addListener(() {
print('animation value ${_controller.value}');
});
super.initState();
}
@override
void dispose() {
print("dispose was called");
_controller.dispose();
super.dispose();
}
int _counter = 0;
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('home screen')
),
body: new Center(
child: new RaisedButton(
onPressed: () {
setState(() {
_counter++;
});
},
child: new Text('Button pressed $_counter times'),
),
),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.remove_red_eye),
onPressed: () {
Navigator.push(context, new MaterialPageRoute(
builder: (BuildContext context) {
return new MySecondPage(counter: _counter);
},
));
},
),
);
}
}
class MySecondPage extends StatelessWidget {
MySecondPage({ this.counter });
final int counter;
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Certificate of achievement'),
),
body: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
new Icon(Icons.developer_mode, size: 200.0),
new Text(
'Congrats, you clicked $counter times.',
style: Theme.of(context).textTheme.title,
textAlign: TextAlign.center,
),
new Text(
'All your progress has now been lost.',
style: Theme.of(context).textTheme.subhead,
textAlign: TextAlign.center,
),
],
),
);
}
}
</code></pre> |
44,006,146 | Laravel: how to force HTTPS? | <p>I'm starting to develop a new big app, and I'm using Laravel this time, and it's the first time.</p>
<p>I need to force HTTPS for all pages, it's not important if from code or by .htaccess, but I'm not able to find a simple tutorial. </p>
<p>The official docs dosn't speak about this problem.</p>
<p>For info, my acutal .htaccess is</p>
<pre><code><IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
</code></pre>
<p>My question is specific to Laravel 5, because I ve no idea on where and how modify this .htaccess file. And also I'am asking you if this is the right way for Laravel or if Laravel has something specific to setup to handle HTTPs. </p>
<p>So please do not close my question and try to be more adherent to the Laravel specific topic. </p>
<p>If you can post a simple way to modify this file AND/OR What to modify in Laravel config to properly handle https. </p>
<p>But in short yes, I want to force every call to transit on HTTPS.</p> | 44,006,385 | 13 | 4 | null | 2017-05-16 15:52:51.367 UTC | 5 | 2022-09-12 02:21:42.873 UTC | 2017-05-17 10:34:57.483 UTC | null | 1,055,279 | null | 1,055,279 | null | 1 | 14 | laravel|.htaccess|mod-rewrite|https|laravel-5.4 | 53,443 | <p>You need adding this to your <code>.htaccess</code> file: </p>
<pre><code>RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://YOURWEBSITEDOMAIN/$1 [R,L]
</code></pre>
<p>See this:
<a href="http://www.inmotionhosting.com/support/website/ssl/how-to-force-https-using-the-htaccess-file" rel="noreferrer">http://www.inmotionhosting.com/support/website/ssl/how-to-force-https-using-the-htaccess-file</a></p> |
3,325,294 | Can I declare that a php function throws an exception? | <p>Can I declare a function in php
that throws an exception?
For example: </p>
<pre><code>public function read($b, $off, $len) throws IOException
</code></pre> | 3,325,302 | 3 | 3 | null | 2010-07-24 13:34:21.137 UTC | 4 | 2019-11-29 11:38:21.183 UTC | 2010-07-24 13:59:22.21 UTC | null | 15,168 | null | 316,016 | null | 1 | 44 | php|exception|throw|throws | 38,143 | <p><strong>I misread the question, see the answer below from Gilad (which should be accepted).</strong></p>
<p>Previous answer:</p>
<p>You could throw a new exception from the body of the function. It's all described <a href="http://php.net/manual/en/language.exceptions.php" rel="nofollow noreferrer">here</a></p>
<p>Example:</p>
<pre><code><?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
else return 1/$x;
}
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
// Continue execution
echo 'Hello World';
?>
</code></pre> |
8,835,426 | get filename and path of `source`d file | <p>How can a <code>source</code>d or <code>Sweave</code>d file find out its own path? </p>
<p>Background:</p>
<p>I work a lot with .R scripts or .Rnw files.
My projects are organized in a directory structure, but the path of the project's base directory frequently varies between different computers (e.g. because I just do parts of data analysis for someone else, and their directory structure is different from mine: I have projects base directories ~/Projects/StudentName/ or ~/Projects/Studentname/Projectname and most students who have just their one Project usually have it under ~/Measurements/ or ~/DataAnalysis/ or something the like - which wouldn't work for me).</p>
<p>So a line like </p>
<pre><code> setwd (my.own.path ())
</code></pre>
<p>would be incredibly useful as it would allow to ensure the working directory is the base path of the project regardless of where that project actually is. Without the need that the user must think of setting the working directory.</p>
<p>Let me clarify: I look for a solution that works with pressing the editor's/IDE's <code>source</code> or <code>Sweave</code> Keyboard shortcut of the unthinking user. </p> | 8,852,960 | 6 | 6 | null | 2012-01-12 12:56:12.547 UTC | 10 | 2017-05-16 14:37:02.843 UTC | 2012-01-12 13:52:49.797 UTC | null | 755,257 | null | 755,257 | null | 1 | 20 | r|sweave | 21,757 | <p>Just FYI, <code>knitr</code> will <code>setwd()</code> to the dir of the input file when (and only when) evaluating the code chunks, i.e. if you call <code>knit('path/to/input.Rnw')</code>, the working dir will be temporarily switched to <code>path/to/</code>. If you want to know the input dir in code chunks, currently you can call an unexported function <code>knitr:::input_dir()</code> (I may export it in the future).</p> |
10,958,748 | Matching a virtual machine design with its primary programming language | <p>As background for a side project, I've been reading about different virtual machine designs, with the JVM of course getting the most press. I've also looked at BEAM (Erlang), GHC's RTS (kind of but not quite a VM) and some of the JavaScript implementations. Python also has a bytecode interpreter that I know exists, but have not read much about.</p>
<p>What I have not found is a good explanation of <strong>why particular virtual machine design choices are made for a particular language</strong>. I'm particularly interested in design choices that would fit with concurrent and/or very dynamic (Ruby, JavaScript, Lisp) languages.</p>
<hr>
<p><strong>Edit:</strong> In response to a comment asking for specificity here is an example. The JVM uses a stack machine rather then a register machine, which was very controversial when Java was first introduced. It turned out that the engineers who designed the JVM had done so intending platform portability, and converting a stack machine back into a register machine was easier and more efficient then overcoming an impedance mismatch where there were too many or too few registers virtual. </p>
<p>Here's another example: for Haskell, the paper to look at is <a href="http://research.microsoft.com/en-us/um/people/simonpj/papers/spineless-tagless-gmachine.ps.gz">Implementing lazy functional languages on stock hardware: the Spineless Tagless G-machine</a>. This is very different from any other type of VM I know about. And in point of fact GHC (the premier implementation of Haskell) does not run live, but is used as an intermediate step in compilation. Peyton-Jones lists no less then 8 other virtual machines that didn't work. I would like to understand why some VM's succeed where other fail.</p> | 11,404,786 | 3 | 8 | null | 2012-06-09 05:52:10.3 UTC | 11 | 2015-06-11 12:02:22.45 UTC | 2015-06-11 12:02:22.45 UTC | null | 317,266 | null | 163,177 | null | 1 | 16 | jvm|language-design|vm-implementation | 891 | <p>I'll answer your question from a different tack: what is a VM? A VM is just a specification for "interpreter" of a lower level language than the source language. Here I'm using the black box meaning of the word "interpreter". I don't care how a VM gets implemented (as a bytecode intepereter, a JIT compiler, whatever). When phrased that way, from a design point of view the VM isn't the interesting thing it's the low level language.</p>
<p>The ideal VM language will do two things. One, it will make it easy to compile the source language into it. And two it will also make it easy to interpret on the target platform(s) (where again the interpreter could be implemented very naively or could be some really sophisticated JIT like Hotspot or V8). </p>
<p>Obviously there's a tension between those two desirable properties, but they do more or less form two end points on a line through the design space of all possible VMs. (Or, perhaps some more complicated shape than a line because this isn't a flat Euclidean space, but you get the idea). If you build your VM language far outside of that line then it won't be very useful. That's what constrains VM design: putting it somewhere into that ideal line. </p>
<p>That line is also why high level VMs tend to be very language specific while low level VMs are more language agnostic but don't provide many services. A high level VM is by its nature close to the source language which makes it far from other, different source languages. A low level VM is by its nature close to the target platform thus close to the platform end of the ideal lines for many languages but that low level VM will also be pretty far from the "easy to compile to" end of the ideal line of most source languages.</p>
<p>Now, more broadly, conceptually any compiler can be seen as a series of transformations from the source language to intermediate forms that themselves can be seen as languages for VMs. VMs for the intermediate languages may never be built, but they could be. A compiler eventually emits the final form. And that final form will itself be a language for a VM. We might call that VM "JVM", "V8"...or we might call that VM "x86", "ARM", etc.</p>
<p>Hope that helps.</p> |
11,357,720 | Java: vertical alignment within JPanel | <p>I am trying to vertically align (center) both JLabels inside one JPanel.</p>
<pre><code>JPanel panel = new JPanel();
panel.setPreferredSize(size);
JLabel label1 = new JLabel(icon);
JLabel label2 = new JLabel("text");
panel.add(label1);
panel.add(label2);
</code></pre>
<p>I have tried using setAligmentY() with no success. Both labels always appear on the top of JPanel.</p>
<p>UPD: Labels should be located next to each other like using FlowLayout, but in the middle of the JPanel.</p> | 11,357,781 | 3 | 3 | null | 2012-07-06 07:28:49.533 UTC | 5 | 2018-01-10 14:53:21.547 UTC | 2012-07-06 07:56:56.63 UTC | null | 1,360,074 | null | 1,360,074 | null | 1 | 20 | java|swing|alignment|jpanel|jlabel | 77,086 | <p>Use a <a href="https://docs.oracle.com/javase/8/docs/api/java/awt/GridBagLayout.html" rel="noreferrer"><code>GridBagLayout</code></a> with the default constraints. Here is a small demo code:</p>
<pre><code>import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestVerticalAlignement {
protected void initUI() {
final JFrame frame = new JFrame();
frame.setTitle("Test vertical alignement");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
JLabel label1 = new JLabel("label1");
JLabel label2 = new JLabel("label2");
panel.add(label1, gbc);
panel.add(label2, gbc);
frame.add(panel);
frame.setSize(300, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TestVerticalAlignement().initUI();
}
});
}
}
</code></pre> |
11,383,775 | Memory Stream as DB | <p>I'm currently thinking of using <code>SQLite</code> as db engine for my C# project, but i ran into the following problem: i can't find any API for memory storage. What i want to achieve is the following:</p>
<p>Upon start of the program i want to load the db file (from HDD) into memory.
During execution of the program i want to use this memory stream as a real db (read,write,insert,select etc).
Upon closing save the stream to the file.</p>
<p>Can anyone point me in the right way or suggest another db engine that would be better suited for this purpose.</p> | 11,385,280 | 1 | 0 | null | 2012-07-08 14:11:56.767 UTC | 24 | 2016-01-13 07:41:56.853 UTC | 2016-01-13 07:41:56.853 UTC | null | 2,263,683 | null | 365,706 | null | 1 | 22 | c#|sqlite|memory | 20,213 | <p>You can use <a href="https://www.sqlite.org/backup.html">SQLite Online Backup API</a> that has ability to copy db file to memory, memory to file.
Native support for <a href="https://www.sqlite.org/backup.html">SQLite Online Backup API</a> is present in System.Data.SQLite from version 1.0.80.0 (with SQLite 3.7.11).</p>
<p>This is simple example how API can be used in C#: </p>
<pre class="lang-cs prettyprint-override"><code>SQLiteConnection source = new SQLiteConnection("Data Source=c:\\test.db");
source.Open();
using (SQLiteConnection destination = new SQLiteConnection(
"Data Source=:memory:"))
{
destination.Open();
// copy db file to memory
source.BackupDatabase(destination, "main", "main",-1, null, 0);
source.Close();
// insert, select ,...
using (SQLiteCommand command = new SQLiteCommand())
{
command.CommandText =
"INSERT INTO t1 (x) VALUES('some new value');";
command.Connection = destination;
command.ExecuteNonQuery();
}
source = new SQLiteConnection("Data Source=c:\\test.db");
source.Open();
// save memory db to file
destination.BackupDatabase(source, "main", "main",-1, null, 0);
source.Close();
}
</code></pre> |
10,894,601 | How to add libgdx as a sub view in android | <p>I have main.xml as follows:</p>
<pre><code> <RelativeLayout>
...
<FrameLayout
android:id="@+id/panel_sheet"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.libgdx.Sheet3DViewGdx
android:id="@+id/m3D"
android:layout_width="1000dp"
android:layout_height="600dp"
/>
</FrameLayout>
...
</RelativeLayout>
</code></pre>
<p>And my main activity class is as follows:</p>
<pre><code>public class Test extends Activity {
MainActivity m3DActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
</code></pre>
<p>My GDX class is as follows which extend ApplicationListener class rather than View.</p>
<pre><code>public class Sheet3DViewGdx implements ApplicationListener{
@Override
public void create() {
InputStream in = Gdx.files.internal("data/obj/Human3DModel.obj").read();
model = ObjLoader.loadObj(in);
}
@Override
public void dispose() {
}
@Override
public void pause() {
}
@Override
public void render() {
Gdx.gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
model.render(GL10.GL_TRIANGLES);
}
@Override
public void resize(int arg0, int arg1) {
float aspectRatio = (float) arg0 / (float) arg1;
}
@Override
public void resume() {
}
}
</code></pre>
<p>Now, how should I add Sheet3DViewGdx as a subview in my main layout?</p> | 10,900,054 | 4 | 0 | null | 2012-06-05 09:15:04.547 UTC | 12 | 2019-03-13 12:36:04.903 UTC | 2013-08-13 09:47:59.747 UTC | null | 923,847 | null | 1,436,940 | null | 1 | 24 | android|libgdx | 13,523 | <p>The AndroidApplication class (which extends activity) has a method named <code>initializeForView(ApplicationListener, AndroidApplicationConfiguration)</code> that will return a <code>View</code> you can add to your layout.</p>
<p>So your Test-class can extend AndroidApplication instead of Activity so that you can call that method and add the View to your layout.</p>
<p>If that's not an option, for some reason, take a look at what <a href="https://github.com/libgdx/libgdx/blob/master/backends/gdx-backend-android/src/com/badlogic/gdx/backends/android/AndroidApplication.java#L223">AndroidApplication source code</a> does, and mimic that.</p> |
11,330,138 | Find columns with all missing values | <p>I am writing a function, which needs a check on whether (and which!) column (variable) has all missing values (<code>NA</code>, <code><NA></code>). The following is fragment of the function:</p>
<pre><code>test1 <- data.frame (matrix(c(1,2,3,NA,2,3,NA,NA,2), 3,3))
test2 <- data.frame (matrix(c(1,2,3,NA,NA,NA,NA,NA,2), 3,3))
na.test <- function (data) {
if (colSums(!is.na(data) == 0)){
stop ("The some variable in the dataset has all missing value,
remove the column to proceed")
}
}
na.test (test1)
Warning message:
In if (colSums(!is.na(data) == 0)) { :
the condition has length > 1 and only the first element will be used
</code></pre>
<p><strong>Q1:</strong> Why is the above error and any fixes ?</p>
<p><strong>Q2:</strong> Is there any way to find which of columns have all <code>NA</code>, for example output the list (name of variable or column number)?</p> | 11,330,265 | 9 | 2 | null | 2012-07-04 13:32:12.393 UTC | 5 | 2021-02-20 15:10:07.723 UTC | 2015-02-25 09:13:19.12 UTC | null | 680,068 | null | 950,349 | null | 1 | 33 | r|dataframe|na | 63,264 | <p>This is easy enough to with <code>sapply</code> and a small anonymous function:</p>
<pre><code>sapply(test1, function(x)all(is.na(x)))
X1 X2 X3
FALSE FALSE FALSE
sapply(test2, function(x)all(is.na(x)))
X1 X2 X3
FALSE TRUE FALSE
</code></pre>
<hr>
<p>And inside a function:</p>
<pre><code>na.test <- function (x) {
w <- sapply(x, function(x)all(is.na(x)))
if (any(w)) {
stop(paste("All NA in columns", paste(which(w), collapse=", ")))
}
}
na.test(test1)
na.test(test2)
Error in na.test(test2) : All NA in columns 2
</code></pre> |
11,108,461 | ImportError: No module named Cython.Distutils | <p>I'm having a strange problem while trying to install the Python library <code>zenlib</code>, using its <code>setup.py</code> file. When I run the <code>setup.py</code> file, I get an import error, saying </p>
<blockquote>
<p>ImportError: No module named Cython.Distutils`</p>
</blockquote>
<p>but I do have such a module, and I can import it on the python command line without any trouble. Why might I be getting this import error?</p>
<p>I think that the problem may have to do with the fact that I am using <a href="https://www.enthought.com/product/enthought-python-distribution/" rel="noreferrer">Enthought Python Distribution</a>, which I installed right beforehand, rather than using the Python 2.7 that came with Ubuntu 12.04.</p>
<p>More background:
Here's exactly what I get when trying to run setup.py:</p>
<pre><code>enwe101@enwe101-PCL:~/zenlib/src$ sudo python setup.py install
Traceback (most recent call last):
File "setup.py", line 4, in <module>
from Cython.Distutils import build_ext
ImportError: No module named Cython.Distutils
</code></pre>
<p>But it works from the command line:</p>
<pre><code>>>> from Cython.Distutils import build_ext
>>>
>>> from fake.package import noexist
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named fake.package
</code></pre>
<p>Note the first import worked and the second throws an error. Compare this to the first few lines of setup.py:</p>
<pre><code>#from distutils.core import setup
from setuptools import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import os.path
</code></pre>
<p>I made sure that the Enthought Python Distribution and not the python that came with Ubuntu is what is run by default by prepending my bash $PATH environment variable by editing <code>~/.bashrc</code>, adding this as the last line:</p>
<pre><code>export PATH=/usr/local/epd/bin:$PATH
</code></pre>
<p>and indeed <code>which python</code> spits out <code>/usr/local/epd/bin/python</code>... not knowing what else to try, I went into my site packages directory, (<code>/usr/local/epd/lib/python2.7/site-packages</code>) and give full permissions (r,w,x) to <code>Cython</code>, <code>Distutils</code>, <code>build_ext.py</code>, and the <code>__init__.py</code> files. Probably silly to try, and it changed nothing.</p>
<p>Can't think of what to try next!? Any ideas?</p> | 13,798,084 | 12 | 4 | null | 2012-06-19 19:59:52.95 UTC | 11 | 2020-04-03 07:07:31.127 UTC | 2018-08-05 17:15:08.34 UTC | null | 3,924,118 | null | 1,467,306 | null | 1 | 61 | python|importerror|enthought | 83,250 | <p>Your sudo is not getting the right python. This is a known behaviour of sudo in Ubuntu. See this <a href="https://stackoverflow.com/questions/257616/sudo-changes-path-why">question</a> for more info. You need to make sure that sudo calls the right python, either by using the full path:</p>
<pre><code>sudo /usr/local/epd/bin/python setup.py install
</code></pre>
<p>or by doing the following (in bash):</p>
<pre><code>alias sudo='sudo env PATH=$PATH'
sudo python setup.py install
</code></pre> |
11,256,228 | What is the difference between [Class new] and [[Class alloc] init] in iOS? | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/3330963/alloc-init-and-new-in-objective-c">alloc, init, and new in Objective-C</a> </p>
</blockquote>
<p>I am a little confused about <code>[Class new]</code> and <code>[[Class alloc] init]</code>. I have defined an object <code>content</code> using <code>[Class new]</code> and <code>[[Class alloc] init]</code>.</p>
<pre><code>(1). NSMutableArray *content = [NSMutableArray new];
(2). NSMutableArray *content = [[NSMutableArray alloc] init];
</code></pre>
<p>My question is about the differences between <code>[Class new]</code> and <code>[[Class alloc] init]</code>. For me, (1) and (2) are similar. If (1) and (2) are similar, then why do we use <code>[[Class alloc] init]</code> most of the time, compared to <code>[Class new]</code>? I think that there must be some difference. </p>
<p>Kindly explain the differences, pros & cons of both?</p> | 11,256,311 | 3 | 1 | null | 2012-06-29 04:53:00.573 UTC | 19 | 2019-07-05 13:40:09.633 UTC | 2017-05-23 11:33:26.943 UTC | null | -1 | null | 1,089,457 | null | 1 | 71 | ios|objective-c|new-operator|allocation|init | 35,291 | <p><strong>Alloc:</strong> Class method of NSObject. Returns a new instance of the receiving class.</p>
<p><strong>Init</strong>: Instance method of NSObject. Implemented by subclasses to initialize a new object (the receiver) immediately after memory for it has been allocated.</p>
<p><strong>New</strong>: Class method of NSObject. Allocates a new instance of the receiving class, sends it an init message, and returns the initialized object.</p>
<p><strong>Release</strong>: Instance method of NSObject delegate. Decrements the receiver’s reference count.</p>
<p><strong>Autorelease</strong>: Instance method of NSObject delegate. Adds the receiver to the current autorelease pool.</p>
<p><strong>Retain:</strong> Instance method of NSObject delegate. Increments the receiver’s reference count.</p>
<p><strong>Copy:</strong> Instance method of NSObject delegate. Returns a new instance that’s a copy of the receiver.</p>
<p>So to conclude we can say that </p>
<p><strong>alloc goes with init</strong></p>
<p><strong>new = alloc + init</strong></p> |
13,120,732 | Difference between mb_substr and substr | <p>Will it make any difference or impact on my result, if I use <code>substr()</code> instead of <code>mb_substr()</code> function?</p>
<p>As my server does not have support for mb_ functions, I have to replace it with <code>substr()</code></p> | 13,120,902 | 3 | 0 | null | 2012-10-29 11:27:53.21 UTC | 3 | 2019-05-21 12:27:38.16 UTC | 2016-12-04 15:17:58.8 UTC | null | 289,317 | null | 504,277 | null | 1 | 35 | php|string|multibyte | 26,285 | <p>It will impact your script if you work with multi-byte text that you substring from. If this is the case, I higly recommend enabling mb_* functions in your php.ini or do this <code>ini_set("mbstring.func_overload", 2);</code></p> |
12,881,854 | How to use GNU Make on Windows? | <p>I installed MinGW and MSYS, added <code>C:\MinGW\bin</code> to <code>PATH</code> but I still can't run Makefile on Windows' <code>cmd</code>. I would like to run cmd.exe and there type, for example, <code>make all</code> but my cmd says that there is no such command. </p>
<p>What should I do? I don't want to use MSYS shell, that's not the point. Any ideas how to use GNU Make in Windows cmd as I can do it in Ubuntu? I'm not interested in <code>Cygwin</code>.</p> | 12,885,705 | 7 | 16 | null | 2012-10-14 11:38:18.533 UTC | 33 | 2022-05-01 00:26:00.947 UTC | 2016-08-29 12:59:14.753 UTC | null | 3,563,993 | null | 1,582,481 | null | 1 | 98 | windows|makefile|gnu-make|cmd | 177,819 | <h3>Explanation</h3>
<p>Inside directory <code>C:\MinGW\bin</code> there is an executable file <code>mingw32-make.exe</code> which is the program <code>make</code> you are trying to run. You can use the keyword <code>mingw32-make</code> and run the program <code>make</code> since you have added the needed directory to the system path, but it is not an easy to remember keyword.</p>
<hr />
<h3>Solution</h3>
<p>Renaming the file from <code>mingw32-make.exe</code> to <code>make.exe</code> will allow you to run program <code>make</code> using the keyword <code>make</code>.</p>
<p>Renaming can be done:</p>
<ol>
<li>Manually by right clicking and renaming the file.</li>
<li>By running the command <code>copy c:\MinGW\bin\mingw32-make.exe c:\MinGW\bin\make.exe</code>.</li>
</ol>
<hr />
<h3>Result</h3>
<p>Now if you type <code>make</code> on command prompt it should output something like:</p>
<pre><code>make: *** No targets specified and no makefile found. Stop.
</code></pre>
<p>Which means the program <code>make</code> ran.</p> |
12,648,543 | AngularJS and its use of Dollar Variables | <p>Does anyone know if the reasoning behind the use of dollar methods and variables in angularJS is to instruct angularJS to avoid checking those values when a digestion is going on? So, if angular comes across <code>$scope.$value</code> and <code>$scope.value</code>, then it will avoid checking the former since it's prefixed with a dollar character in its variable name?</p> | 12,648,794 | 8 | 4 | null | 2012-09-28 23:23:48.55 UTC | 36 | 2017-01-25 06:21:21.74 UTC | 2013-04-18 14:48:52.163 UTC | null | 224,192 | null | 340,939 | null | 1 | 132 | angularjs | 68,403 | <p>There are a few times Angular ignores variables prefixed with the dollar sign:</p>
<ol>
<li>In <a href="https://stackoverflow.com/questions/12648543/angularjs-and-its-use-of-dollar-variables#comment19433906_12648794">Schumli's comment</a> below, where json filters will not output them</li>
<li><p>When using the <code>{{ }}</code> directive, angular will not show <em>nested</em> <code>$</code>
variables. For example this only displays the <code>visible</code> property.</p>
<pre><code><div ng-init="n = { visible: 'foo', $ignore: 'bar' };">{{ n }}</div>
</code></pre></li>
<li><p>Additionally when adding an explicit watcher on a scope object, changes to properties with a leading dollar sign of this object will not trigger the watcher. See <a href="http://jsfiddle.net/R9Tfb/13/" rel="noreferrer">this updated fiddle</a>.</p></li>
<li><p><code>angular.equals()</code> <a href="http://jsfiddle.net/R9Tfb/14/" rel="noreferrer">ignores keys prefixed with <code>$</code></a>.</p></li>
</ol> |
10,930,286 | socket.io rooms or namespacing? | <p>I am investigating nodejs/socket.io for real time chat, and I need some advice for implementing rooms.</p>
<p>Which is better, using namespace or using the room feature to completely isolate grops of chatters from each other?</p>
<p>what is the real technical difference between rooms and namespace?</p>
<p>Is there any resource usage difference?</p> | 11,751,954 | 6 | 0 | null | 2012-06-07 10:48:20.977 UTC | 90 | 2021-02-11 10:14:09.127 UTC | 2015-11-13 06:41:23.883 UTC | null | 2,333,214 | null | 1,418,694 | null | 1 | 184 | node.js|socket.io | 66,744 | <p>This is what namespaces and rooms have <strong>in common</strong> (socket.io v0.9.8 - please note that v1.0 involved a complete rewrite, so things might have changed):</p>
<ul>
<li>Both namespaces (<a href="https://github.com/learnboost/socket.io#restricting-yourself-to-a-namespace" rel="noreferrer" title="io.of('/nsp')">io.of('/nsp')</a>) and rooms (<a href="https://github.com/LearnBoost/socket.io/wiki/Rooms" rel="noreferrer" title="socket.join('room')">socket.join('room')</a>) <strong>are created on the server side</strong></li>
<li>Multiple namespaces and multiple rooms <strong>share the same (WebSocket) connection</strong></li>
<li>The server will <strong>transmit messages over the wire only to those clients</strong> that connected to / joined a nsp / room, i.e. it's not just client-side filtering</li>
</ul>
<p>The <strong>differences</strong>:</p>
<ul>
<li><strong>namespaces are connected to by the client</strong> using <code>io.connect(urlAndNsp)</code> (the client will be added to that namespace only if it already exists on the server)</li>
<li><strong>rooms can be joined only on the server side</strong> (although creating an API on the server side to enable clients to join is straightforward)</li>
<li><strong>namespaces can be <a href="https://github.com/LearnBoost/socket.io/wiki/Authorizing" rel="noreferrer" title="authorization protected">authorization protected</a></strong></li>
<li><strong>authorization is not available with rooms</strong>, but custom authorization could be added to the aforementioned, easy-to-create API on the server, in case one is bent on using rooms</li>
<li><strong>rooms are part of a namespace</strong> (defaulting to the 'global' namespace)</li>
<li><strong>namespaces are always rooted in the global scope</strong></li>
</ul>
<p>To not confuse the concept with the name (room or namespace), I'll use <em>compartment</em> to refer to the concept, and the other two names for the <em>implementations</em> of the concept. So if you</p>
<ul>
<li>need <em>per-compartment authorization</em>, namespaces might be the easiest route to take</li>
<li>if you want <em>hierarchically layered compartments</em> (2 layers max), use a namespace/room combo</li>
<li>if your client-side app consists of different parts that (do not themselves care about compartments but) need to be separated from each other, use namespaces.</li>
</ul>
<p>An example for the latter would be a large client app where different modules, perhaps developed separately (e.g. third-party), each using socket.io independently, are being used in the same app and want to share a single network connection.</p>
<p>Not having actually benchmarked this, it seems to me if you just need simple compartments in your project to separate and group messages, either one is fine.</p>
<p>Not sure if that answers your question, but the research leading up to this answer at least helped me see clearer.</p> |
16,636,433 | MySql count() to return 0 if no records found | <p>I have a set of posts on monthly basis. Now i need an array which contains total records of posts posted in each month. I tried below MySql query, Its working fine, but I was expecting 0(Zero) for months where there is no records. Here its not returning 0.</p>
<p>I read that COUNT() will not return '0', So how do i achieve this?</p>
<p>I tried IFNULL(), and COALESCE() but still getting the same result. Please help with this query. Thank You......</p>
<pre><code>SELECT
count(id) as totalRec
FROM ('post')
WHERE year(date) = '2013'
AND monthname(date) IN ('January', 'February', 'March')
GROUP BY year(date)-month(date)
ORDER BY 'date' ASC
</code></pre>
<p>Got Result:</p>
<pre><code>+----------+
| totalRec |
+----------+
| 7 |
| 9 |
+----------+
</code></pre>
<p>Expected Result (Where there is no posts for January):</p>
<pre><code>+----------+
| totalRec |
+----------+
| 0 |
| 7 |
| 9 |
+----------+
</code></pre>
<p>Sample Data:</p>
<pre><code>+----+---------------------+
| id | date |
+----+---------------------+
| 24 | 2012-12-16 16:29:56 |
| 1 | 2013-02-25 14:57:09 |
| 2 | 2013-02-25 14:59:37 |
| 4 | 2013-02-25 15:12:44 |
| 5 | 2013-02-25 15:14:18 |
| 7 | 2013-02-26 11:31:31 |
| 8 | 2013-02-26 11:31:59 |
| 10 | 2013-02-26 11:34:47 |
| 14 | 2013-03-04 04:39:02 |
| 15 | 2013-03-04 05:44:44 |
| 16 | 2013-03-04 05:48:29 |
| 19 | 2013-03-07 15:22:34 |
| 20 | 2013-03-15 12:24:43 |
| 21 | 2013-03-16 16:27:43 |
| 22 | 2013-03-16 16:29:28 |
| 23 | 2013-03-16 16:29:56 |
| 11 | 2013-03-17 11:35:12 |
+----+---------------------+
</code></pre> | 16,636,590 | 7 | 3 | null | 2013-05-19 15:43:37.393 UTC | 2 | 2021-11-18 03:49:49.743 UTC | 2013-05-19 16:04:59.887 UTC | null | 491,243 | null | 1,570,901 | null | 1 | 14 | mysql|sql | 63,610 | <p>There is no record for the month of <code>January</code> that is why you are getting no result. One solution that works is by joining a subquery with contains list of months that you want to be shown on the list.</p>
<pre><code>SELECT count(b.id) as totalRec
FROM (
SELECT 'January' mnth
UNION ALL
SELECT 'February' mnth
UNION ALL
SELECT 'March' mnth
) a
LEFT JOIN post b
ON a.mnth = DATE_FORMAT(b.date, '%M') AND
year(b.date) = '2013' AND
DATE_FORMAT(b.date, '%M') IN ('January', 'February', 'March')
GROUP BY year(b.date)-month(b.date)
ORDER BY b.date ASC
</code></pre>
<ul>
<li><a href="http://www.sqlfiddle.com/#!2/e0a6e/7">SQLFiddle Demo</a></li>
</ul>
<p>OUTPUT</p>
<pre><code>╔══════════╗
║ TOTALREC ║
╠══════════╣
║ 0 ║
║ 7 ║
║ 9 ║
╚══════════╝
</code></pre> |
16,585,055 | Android Studio doesn't start with connected device | <p>I have installed Android Studio v0.1 on Mac. My project imported and built successfully. AVD shows up whenever I run or debug the project, even though my device is connected and shown in integrated DDMS. I have double checked with <code>adb devices</code> from command-line and it shows my connected device. Please help~</p> | 16,585,266 | 2 | 0 | null | 2013-05-16 10:30:45.473 UTC | 3 | 2015-04-06 10:25:20.557 UTC | 2013-05-16 10:32:27.693 UTC | null | 995,926 | null | 1,885,105 | null | 1 | 32 | android|android-studio | 28,856 | <p>// the very First time it will always selected only emulator options</p>
<p>you need to change it in Create Run Configuration...
in that General Tab select Target Device</p>
<ul>
<li>Show chooser dialog </li>
<li>USB Devices</li>
<li>Emulator</li>
</ul> |
16,626,789 | functools.partial on class method | <p>I'm trying to define some class methods using another more generic class method as follows:</p>
<pre><code>class RGB(object):
def __init__(self, red, blue, green):
super(RGB, self).__init__()
self._red = red
self._blue = blue
self._green = green
def _color(self, type):
return getattr(self, type)
red = functools.partial(_color, type='_red')
blue = functools.partial(_color, type='_blue')
green = functools.partial(_color, type='_green')
</code></pre>
<p>But when i attempt to invoke any of those methods i get:</p>
<pre><code>rgb = RGB(100, 192, 240)
print rgb.red()
TypeError: _color() takes exactly 2 arguments (1 given)
</code></pre>
<p>I guess self is not passed to <code>_color</code> since <code>rgb.red(rgb)</code> works.</p> | 16,626,797 | 2 | 6 | null | 2013-05-18 16:56:03.097 UTC | 12 | 2020-03-12 02:11:18.21 UTC | 2016-01-13 12:39:23.767 UTC | null | 100,297 | null | 366,112 | null | 1 | 58 | python|exception|methods|functools | 31,455 | <p>You are creating partials on the <em>function</em>, not the method. <code>functools.partial()</code> objects are not descriptors, they will not themselves add the <code>self</code> argument and cannot act as methods themselves. You can <em>only</em> wrap bound methods or functions, they don't work at all with unbound methods. This is <a href="http://docs.python.org/2/library/functools.html#partial-objects">documented</a>:</p>
<blockquote>
<p><code>partial</code> objects are like <code>function</code> objects in that they are callable, weak referencable, and can have attributes. There are some important differences. For instance, the <code>__name__</code> and <code>__doc__</code> attributes are not created automatically. Also, <code>partial</code> objects defined in classes behave like static methods and do not transform into bound methods during instance attribute look-up.</p>
</blockquote>
<p>Use <code>property</code>s instead; these <em>are</em> descriptors:</p>
<pre><code>class RGB(object):
def __init__(self, red, blue, green):
super(RGB, self).__init__()
self._red = red
self._blue = blue
self._green = green
def _color(self, type):
return getattr(self, type)
@property
def red(self): return self._color('_red')
@property
def blue(self): return self._color('_blue')
@property
def green(self): return self._color('_green')
</code></pre>
<p>As of Python 3.4, you can use the new <a href="https://docs.python.org/3/library/functools.html#functools.partialmethod"><code>functools.partialmethod()</code> object</a> here; it'll do the right thing when bound to an instance:</p>
<pre><code>class RGB(object):
def __init__(self, red, blue, green):
super(RGB, self).__init__()
self._red = red
self._blue = blue
self._green = green
def _color(self, type):
return getattr(self, type)
red = functools.partialmethod(_color, type='_red')
blue = functools.partialmethod(_color, type='_blue')
green = functools.partialmethod(_color, type='_green')
</code></pre>
<p>but these'd have to be called, whilst the <code>property</code> objects can be used as simple attributes.</p> |
20,762,952 | Most efficient standard-compliant way of reinterpreting int as float | <p>Assume I have guarantees that <code>float</code> is IEEE 754 binary32. Given a bit pattern that corresponds to a valid float, stored in <code>std::uint32_t</code>, how does one reinterpret it as a <code>float</code> in a most efficient standard compliant way?</p>
<pre><code>float reinterpret_as_float(std::uint32_t ui) {
return /* apply sorcery to ui */;
}
</code></pre>
<p>I've got a few ways that I know/suspect/assume have some issues:</p>
<ol>
<li><p>Via <code>reinterpret_cast</code>,</p>
<pre><code>float reinterpret_as_float(std::uint32_t ui) {
return reinterpret_cast<float&>(ui);
}
</code></pre>
<p>or equivalently</p>
<pre><code>float reinterpret_as_float(std::uint32_t ui) {
return *reinterpret_cast<float*>(&ui);
}
</code></pre>
<p>which suffers from aliasing issues.</p></li>
<li><p>Via <code>union</code>,</p>
<pre><code>float reinterpret_as_float(std::uint32_t ui) {
union {
std::uint32_t ui;
float f;
} u = {ui};
return u.f;
}
</code></pre>
<p>which is not actually legal, as it is only allowed to read from most recently written to member. Yet, it seems some compilers (gcc) allow this.</p></li>
<li><p>Via <code>std::memcpy</code>,</p>
<pre><code>float reinterpret_as_float(std::uint32_t ui) {
float f;
std::memcpy(&f, &ui, 4);
return f;
}
</code></pre>
<p>which AFAIK is legal, but a function call to copy single word seems wasteful, though it might get optimized away.</p></li>
<li><p>Via <code>reinterpret_cast</code>ing to <code>char*</code> and copying,</p>
<pre><code>float reinterpret_as_float(std::uint32_t ui) {
char* uip = reinterpret_cast<char*>(&ui);
float f;
char* fp = reinterpret_cast<char*>(&f);
for (int i = 0; i < 4; ++i) {
fp[i] = uip[i];
}
return f;
}
</code></pre>
<p>which AFAIK is also legal, as <code>char</code> pointers are exempt from aliasing issues and manual byte copying loop saves a possible function call. The loop will most definitely be unrolled, yet 4 possibly separate one-byte loads/stores are worrisome, I have no idea whether this is optimizable to single four byte load/store.</p></li>
</ol>
<p>The <code>4</code> is the best I've been able to come up with.</p>
<p>Am I correct so far? Is there a better way to do this, particulary one that will guarantee single load/store?</p> | 20,856,410 | 4 | 19 | null | 2013-12-24 15:03:42.463 UTC | 9 | 2016-10-19 07:25:22.363 UTC | 2016-10-19 07:25:22.363 UTC | null | 1,554,020 | null | 1,554,020 | null | 1 | 32 | c++|c++11|type-conversion|language-lawyer|standards-compliance | 4,833 | <p>Afaik, there are only two approaches that are compliant with strict aliasing rules: <code>memcpy()</code> and cast to <code>char*</code> with copying. All others read a <code>float</code> from memory that belongs to an <code>uint32_t</code>, and the compiler is allowed to perform the read before the write to that memory location. It might even optimize away the write altogether as it can prove that the stored value will never be used according to strict aliasing rules, resulting in a garbage return value.</p>
<p>It really depends on the compiler/optimizes whether <code>memcpy()</code> or <code>char*</code> copy is faster. In both cases, an intelligent compiler might be able to figure out that it can just load and copy an <code>uint32_t</code>, but I would not trust any compiler to do so before I have seen it in the resulting assembler code.</p>
<p><strong>Edit:</strong><br>
After some testing with gcc 4.8.1, I can say that the <code>memcpy()</code> approach is the best for this particulare compiler, see below for details.</p>
<hr>
<p>Compiling</p>
<pre><code>#include <stdint.h>
float foo(uint32_t a) {
float b;
char* aPointer = (char*)&a, *bPointer = (char*)&b;
for( int i = sizeof(a); i--; ) bPointer[i] = aPointer[i];
return b;
}
</code></pre>
<p>with <code>gcc -S -std=gnu11 -O3 foo.c</code> yields this assemble code:</p>
<pre><code>movl %edi, %ecx
movl %edi, %edx
movl %edi, %eax
shrl $24, %ecx
shrl $16, %edx
shrw $8, %ax
movb %cl, -1(%rsp)
movb %dl, -2(%rsp)
movb %al, -3(%rsp)
movb %dil, -4(%rsp)
movss -4(%rsp), %xmm0
ret
</code></pre>
<p>This is not optimal.</p>
<p>Doing the same with </p>
<pre><code>#include <stdint.h>
#include <string.h>
float foo(uint32_t a) {
float b;
char* aPointer = (char*)&a, *bPointer = (char*)&b;
memcpy(bPointer, aPointer, sizeof(a));
return b;
}
</code></pre>
<p>yields (with all optimization levels except <code>-O0</code>):</p>
<pre><code>movl %edi, -4(%rsp)
movss -4(%rsp), %xmm0
ret
</code></pre>
<p>This is optimal.</p> |
4,113,083 | How to return a value from an Object Literal based on a key? | <p>I have an array as follows. How would I retrieve the value of a specific key and put that value in a variable?</p>
<pre><code>var obj = {"one":"1","two":"3","three":"5","four":"1","five":"6"};
</code></pre>
<p>So for instance if I want to get the value of "three" how would I do it in javascript or jQuery?</p> | 4,113,089 | 2 | 2 | null | 2010-11-06 12:35:51.167 UTC | 8 | 2018-02-22 19:57:19.467 UTC | 2018-02-22 19:57:19.467 UTC | null | 543,572 | null | 357,034 | null | 1 | 14 | javascript|jquery | 73,769 | <p>You can do this via <a href="https://developer.mozilla.org/en/JavaScript/Reference/Operators/Member_Operators#Dot_notation" rel="noreferrer">dot</a> or <a href="https://developer.mozilla.org/en/JavaScript/Reference/Operators/Member_Operators#Bracket_notation" rel="noreferrer">bracket</a> notation, like this:</p>
<pre><code>var myVariable = obj.three;
//or:
var myVariable = obj["three"];
</code></pre>
<p>In the second example <code>"three"</code> could be a string in another variable, which is <em>probably</em> what you're after. Also, for clarity what you have is just an object, not an array :)</p> |
4,821,696 | Create a datetime in Rails using month, day, and year | <p>I have <code>params[:month,:day,:year]</code> and I need to convert them into a <code>DateTime</code> that I can place in a hidden input. </p>
<p>What's the best way to do this in Rails 3?</p> | 4,821,740 | 2 | 0 | null | 2011-01-27 20:50:43.17 UTC | 3 | 2015-09-09 17:48:41.607 UTC | 2015-09-09 17:48:41.607 UTC | null | 2,202,702 | null | 142,486 | null | 1 | 35 | ruby|ruby-on-rails-3 | 32,783 | <p>You can do</p>
<pre><code>DateTime.new(params[:year], params[:month], params[:day])
</code></pre> |
10,227,604 | How can I include Core Data to an already created iOS project in Xcode? | <p>I forgot to include Core Data, and now I've completed half of the project and want to include it now.</p>
<p>Is it possible to include Core Data now? If so can anyone tell me how to do that?</p> | 10,227,726 | 3 | 0 | null | 2012-04-19 12:01:30.253 UTC | 8 | 2012-09-14 08:20:20.043 UTC | 2012-09-14 08:09:49.203 UTC | null | 403,018 | null | 1,300,511 | null | 1 | 6 | iphone|objective-c|xcode|core-data | 5,483 | <p>Xcode 4.3.2
To add core-data framework. </p>
<p>Select Target->Summary Pane-> Linked Frameworks & Libraries.</p>
<p><img src="https://i.stack.imgur.com/BR79L.jpg" alt="enter image description here"></p>
<p>In ABOVE image CoreData Framework is already added.
U can click on '+' button below it to add frameworks of ur choice. </p>
<p>ONCE U CICK ON '+' BUTTON U'LL SEE BELOW IMAGE SCREEN.</p>
<p><img src="https://i.stack.imgur.com/NPLMO.png" alt="enter image description here"></p>
<p>To add new files to it go to File-> New File -> iOS tab-> CoreData setion.You can file of ur choice</p>
<p><img src="https://i.stack.imgur.com/TpPe9.png" alt="enter image description here"></p> |
9,660,392 | Rows showing as #DELETED | <p>I have rows of data in a table showing as <strong>#DELETED</strong> on one computer when using Access but they are fine in both the SQL database and on other computers using Access. It seems to be only the latest 200 rows. The Access 2007 versions and ODBC MSJet drivers look to be the same & latest on each computer. One suggestion was to change any PK or FK's to int's, but they already are.</p>
<p>Any ideas for a fix for this?</p> | 9,735,903 | 12 | 0 | null | 2012-03-12 00:37:07.103 UTC | 6 | 2022-06-01 17:48:32.837 UTC | 2016-01-28 17:55:41.503 UTC | null | 122,139 | null | 718,341 | null | 1 | 12 | sql-server|ms-access | 50,393 | <p>This occurs when the tables primary key value, exceeds the range that MS Access supports, usually if you are using the "BigInt" type in SQL Server, if you are only looking to read the data then just create a "snap-shot" query for the table and all rows will display correctly as the "snap-shot" does not need to read all the indexes.</p>
<p>If you need to update the data in these rows at any time then I suggest using an ADO recordset instead.</p> |
10,111,907 | How to focus invalid fields with jQuery validate? | <p>There is <a href="http://docs.jquery.com/Plugins/Validation/validate#toptions" rel="noreferrer"><code>focusInvalid</code></a> option, which is <code>true</code> by default. But it works only when form submission happens. If I validate the form with <a href="http://docs.jquery.com/Plugins/Validation/valid" rel="noreferrer"><code>valid</code></a> method, then it doesn't work. So the question is how to focus invalid field when <code>valid</code> is used?</p>
<p>Please see <a href="http://jsbin.com/ayupob" rel="noreferrer">this demo</a> to see the difference. Just press buttons there.</p> | 10,112,388 | 2 | 1 | null | 2012-04-11 18:35:43.933 UTC | 17 | 2014-10-09 05:54:51.53 UTC | null | null | null | null | 604,388 | null | 1 | 55 | jquery|jquery-validate | 78,739 | <p>First of all you need to save your validator to a variable so you can use it in the click handler:</p>
<pre><code>var validator = $("#test-form").validate({ /* settings */ });
</code></pre>
<p>Then in the validate handler, you can manually call the <code>focusInvalid</code> function from the <code>validator</code> variable:</p>
<pre><code> $("#validate").click(function() {
if ($("#test-form").valid())
alert("Valid!");
else
validator.focusInvalid();
return false;
});
</code></pre>
<p><a href="http://jsbin.com/ayupob/2/edit"><strong>Example</strong></a></p> |
28,289,172 | ~/.gradle/gradle.properties file not being read | <p>There is a similar question here: <a href="https://stackoverflow.com/questions/26331397/gradle-properties-not-being-read-from-gradle-gradle-properties">Gradle properties not being read from ~/.gradle/gradle.properties</a> but it does not solve my problem.</p>
<p>It seems to me that gradle is NOT reading my <code>~/.gradle/gradle.properties</code> file.</p>
<p>I have a gradle.properties file in <code>~/.gradle</code>, and it has properties needed to sign artifacts before uploading to maven central. It looks like this:</p>
<pre><code>signing.keyId=12345678
signing.password=myPassword
signing.secretKeyRingFile=/home/me/.gnupg/secring.gpg
sonatypeUsername=me
sonatypePassword=myOtherPassword
</code></pre>
<p>When I try to build my project, it complains that there's no sonatypeUsername property, thus:</p>
<pre><code>> Could not find property 'sonatypeUsername' on root project 'yourProject'.
</code></pre>
<p>Here's the relevant portion of my project's build.gradle:</p>
<pre><code>uploadArchives {
repositories {
mavenDeployer {
// lots of non-interesting things here
repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") {
authentication(userName: project.property("sonatypeUsername"), password: project.property("sonatypePassword"))
}
}
}
}
</code></pre>
<p>When I try to build the project with debugging, here's what I see regarding properties:</p>
<pre><code>$ ./gradlew --stacktrace --debug build
[INFO] [o.g.BuildLogger] Starting Build
[DEBUG] [o.g.BuildLogger] Gradle user home: /home/me
[DEBUG] [o.g.BuildLogger] Current dir: /home/me/dev/yourProject
[DEBUG] [o.g.BuildLogger] Settings file: null
[DEBUG] [o.g.BuildLogger] Build file: null
[DEBUG] [o.g.i.b.BuildSourceBuilder] Starting to build the build sources.
[DEBUG] [o.g.i.b.BuildSourceBuilder] Gradle source dir does not exist. We leave.
[DEBUG] [o.g.i.DefaultGradlePropertiesLoader] Found env project properties: []
[DEBUG] [o.g.i.DefaultGradlePropertiesLoader] Found system project properties: []
[DEBUG] [o.g.a.i.a.m.DefaultLocalMavenRepositoryLocator] No local repository in Settings file defined. Using default path: /home/me/.m2/repository
[DEBUG] [o.g.i.ScriptEvaluatingSettingsProcessor] Timing: Processing settings took: 0.286 secs
[INFO] [o.g.BuildLogger] Settings evaluated using empty settings script.
[DEBUG] [o.g.i.ProjectPropertySettingBuildLoader] Looking for project properties from: /home/me/dev/yourProject/gradle.properties
[DEBUG] [o.g.i.ProjectPropertySettingBuildLoader] project property file does not exists. We continue!
[INFO] [o.g.BuildLogger] Projects loaded. Root project using build file '/home/me/dev/yourProject/build.gradle'.
</code></pre> | 28,304,823 | 8 | 9 | null | 2015-02-03 00:08:53.163 UTC | 2 | 2022-04-28 15:17:01.69 UTC | 2017-05-23 12:10:26.633 UTC | null | -1 | null | 299,176 | null | 1 | 32 | gradle|build.gradle | 36,783 | <p>The problem was that I made an assumption that wasn't true. If you look at <a href="https://gradle.org/docs/current/userguide/tutorial_this_and_that.html" rel="noreferrer">section 14.2 of the gradle documentation</a>, it says:</p>
<blockquote>
<p>You can place a gradle.properties file in the Gradle user home directory (defined by the “GRADLE_USER_HOME” environment variable, which if not set defaults to USER_HOME/.gradle) or in your project directory.</p>
</blockquote>
<p>My <em>incorrect</em> assumption was that USER_HOME just defaulted to the standard linux HOME environment variable. This is not true.</p>
<p>As soon as I <code>export USER_HOME=$HOME</code> in my <code>~/.bashrc</code> everything works</p> |
11,851,197 | Avoiding recursion with Doctrine entities and JMSserializer | <p>I am building a REST API using Symfony2, Doctrine, FOSRestBundle and JMSSerializer.</p>
<p>The issue I am having is when serializing my entities, the serializer pulls in any related entities. Eg for a task that is part of a story which is part of a board, so when serializing the task I get output that includes the story which includes the board, which then includes all other stories on the board.</p>
<p>Is there an easy way to limit this, and just include the foreignIds instead? </p> | 11,964,707 | 5 | 1 | null | 2012-08-07 17:37:17.863 UTC | 11 | 2016-04-05 10:45:23.167 UTC | 2016-04-05 10:45:23.167 UTC | null | 71,332 | null | 71,332 | null | 1 | 17 | php|symfony|doctrine-orm|fosuserbundle | 15,497 | <p>Check the <a href="https://github.com/schmittjoh/JMSSerializerBundle/blob/master/Serializer/Handler/DoctrineProxyHandler.php" rel="noreferrer">Serializer/Handler/DoctrineProxyHandler.php</a> file on JMSSerializerBundle. Now, if you comment this line:</p>
<pre><code>public function serialize(VisitorInterface $visitor, $data, $type, &$handled)
{
if (($data instanceof Proxy || $data instanceof ORMProxy) && (!$data->__isInitialized__ || get_class($data) === $type)) {
$handled = true;
if (!$data->__isInitialized__) {
//$data->__load();
}
</code></pre>
<p>It will stop lazy loading your entities. If this is what you're looking for, then just go ahead and <a href="http://jmsyst.com/bundles/JMSSerializerBundle/master/cookbook/custom_handlers" rel="noreferrer">create your own handler</a> where you don't lazy load. </p>
<p>If this isn't correct, I recommend that you customize your entities before sending them to JMSSerializerBundle at your taste. For example, in any related entities I want the ID, while in others i need a custom column name like code, or name, or anything. </p>
<p>I just create a copy of my entity object and then start getting the fields I need for relationships. Then, I serialize that copy. JMSSerializerBundle won't lazy load because I already provided the proper fields.</p> |
11,780,115 | Moving an undecorated stage in javafx 2 | <p>I've been trying to move an undecorated stage around the screen, by using the following mouse listeners:</p>
<ul>
<li>onPressed </li>
<li>onReleased </li>
<li>onDragged</li>
</ul>
<p>These events are from a rectangle. My idea is to move the undecorated window clicking on the rectangle and dragging all the window.</p>
<pre>
@FXML
protected void onRectanglePressed(MouseEvent event) {
X = primaryStage.getX() - event.getScreenX();
Y = primaryStage.getY() - event.getScreenY();
}
@FXML
protected void onRectangleReleased(MouseEvent event) {
primaryStage.setX(event.getScreenX());
primaryStage.setY(event.getScreenY());
}
@FXML
protected void onRectangleDragged(MouseEvent event) {
primaryStage.setX(event.getScreenX() + X);
primaryStage.setY(event.getScreenY() + Y);
}
</pre>
<p>All that I've got with these events is when I press the rectangle and start to drag the window, it moves a little bit. But, when I release the button, the window is moved to where the rectangle is.</p>
<p>Thanks in advance.</p> | 11,781,291 | 5 | 1 | null | 2012-08-02 14:51:18.45 UTC | 12 | 2015-11-30 18:46:26.503 UTC | 2012-08-03 11:05:28.14 UTC | null | 1,068,443 | null | 1,428,460 | null | 1 | 26 | javafx-2|stage | 27,073 | <p>I created a <a href="https://gist.github.com/2658491" rel="noreferrer">sample</a> of an animated clock in an undecorated window which you can drag around.</p>
<p>Relevant code from the sample is:</p>
<pre><code>// allow the clock background to be used to drag the clock around.
final Delta dragDelta = new Delta();
layout.setOnMousePressed(new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent mouseEvent) {
// record a delta distance for the drag and drop operation.
dragDelta.x = stage.getX() - mouseEvent.getScreenX();
dragDelta.y = stage.getY() - mouseEvent.getScreenY();
}
});
layout.setOnMouseDragged(new EventHandler<MouseEvent>() {
@Override public void handle(MouseEvent mouseEvent) {
stage.setX(mouseEvent.getScreenX() + dragDelta.x);
stage.setY(mouseEvent.getScreenY() + dragDelta.y);
}
});
...
// records relative x and y co-ordinates.
class Delta { double x, y; }
</code></pre>
<p>Code looks pretty similar to yours, so not quite sure why your code is not working for you.</p> |
11,904,083 | How to get image size (bytes) using PIL | <p>I found out how to use PIL to get the image dimensions, but not the file size in bytes. I need to know the file size to decide if the file is too big to be uploaded to the database.</p> | 11,904,141 | 5 | 5 | null | 2012-08-10 14:46:56.793 UTC | 6 | 2022-09-01 17:33:09.287 UTC | 2017-01-15 15:02:42.967 UTC | null | 562,769 | null | 1,505,086 | null | 1 | 42 | python|python-imaging-library|tornado|filesize | 57,331 | <p>Try:</p>
<pre><code>import os
print os.stat('somefile.ext').st_size
</code></pre> |
12,006,417 | Node.js server that accepts POST requests | <p>I'm trying to allow javascript to communicate with a Node.js server. </p>
<p><strong>POST request (web browser)</strong></p>
<pre><code>var http = new XMLHttpRequest();
var params = "text=stuff";
http.open("POST", "http://someurl.net:8080", true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
alert(http.onreadystatechange);
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
</code></pre>
<p>Right now the Node.js server code looks like this. Before it was used for GET requests. I'm not sure how to make it work with POST requests.</p>
<p><strong>Server (Node.js)</strong></p>
<pre><code>var server = http.createServer(function (request, response) {
var queryData = url.parse(request.url, true).query;
if (queryData.text) {
convert('engfemale1', queryData.text, response);
response.writeHead(200, {
'Content-Type': 'audio/mp3',
'Content-Disposition': 'attachment; filename="tts.mp3"'
});
}
else {
response.end('No text to convert.');
}
}).listen(8080);
</code></pre>
<p>Thanks in advance for your help.</p> | 12,007,627 | 2 | 3 | null | 2012-08-17 13:05:43.227 UTC | 35 | 2021-03-23 18:28:53.59 UTC | 2019-02-18 13:46:01.517 UTC | null | 123,671 | null | 1,558,035 | null | 1 | 73 | javascript|node.js|nodes | 164,677 | <p>The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.</p>
<pre><code>const http = require('http')
const server = http.createServer(function(request, response) {
console.dir(request.param)
if (request.method == 'POST') {
console.log('POST')
var body = ''
request.on('data', function(data) {
body += data
console.log('Partial body: ' + body)
})
request.on('end', function() {
console.log('Body: ' + body)
response.writeHead(200, {'Content-Type': 'text/html'})
response.end('post received')
})
} else {
console.log('GET')
var html = `
<html>
<body>
<form method="post" action="http://localhost:3000">Name:
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
response.writeHead(200, {'Content-Type': 'text/html'})
response.end(html)
}
})
const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)
</code></pre>
<p>If you use something like <a href="http://expressjs.com/" rel="noreferrer">Express.js</a> and <a href="https://www.npmjs.com/package/body-parser" rel="noreferrer">Bodyparser</a> then it would look like this since Express will handle the request.body concatenation</p>
<pre><code>var express = require('express')
var fs = require('fs')
var app = express()
app.use(express.bodyParser())
app.get('/', function(request, response) {
console.log('GET /')
var html = `
<html>
<body>
<form method="post" action="http://localhost:3000">Name:
<input type="text" name="name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>`
response.writeHead(200, {'Content-Type': 'text/html'})
response.end(html)
})
app.post('/', function(request, response) {
console.log('POST /')
console.dir(request.body)
response.writeHead(200, {'Content-Type': 'text/html'})
response.end('thanks')
})
const port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)
</code></pre> |
3,509,032 | How to debug JAVASCRIPT events? Or how to make all functions call trace? | <p>For example there is a button. It is wrapped by <code><div></code>.</p>
<p>When pressing to this button, there is Javascript function call happen, then another function, then calling by ajax to the server and if it's OK, Javascript redirecting this page to another page.</p>
<p>It's hard to debug.</p>
<p>Is it possible to <strong>"catch" this event</strong>? I.e. to know, what function is called after the click on the button? Button doesn't have attribute <code>onclick</code> i.e. event listener is connected in Javascript.</p>
<p>And if it's not possible then is it possible <strong>to make trace</strong>? That is to look at all functions calls, which is called after which?</p>
<p>It would be better in visual way, though in textual is also good:)</p> | 3,509,070 | 4 | 0 | null | 2010-08-18 04:45:44.81 UTC | 9 | 2022-08-19 10:15:54.527 UTC | 2020-12-10 22:38:28.42 UTC | null | 4,370,109 | null | 423,585 | null | 1 | 25 | javascript|events|dom-events|trace | 24,035 | <p>Yeah - this sort of thing is not as simple as you would like.</p>
<p>Google Chrome, Edge and Opera have an <strong>Event Listeners</strong> panel. Right-click your button, then select <strong>Inspect Element</strong>. Make sure the correct element is selected, then check the <strong>Event Listeners</strong> panel on the right.</p>
<p>In <a href="https://firefox-source-docs.mozilla.org/devtools-user/page_inspector/how_to/examine_event_listeners/index.html" rel="nofollow noreferrer">Firefox</a> this feature is implemented differently:</p>
<blockquote>
<p>The inspector shows the word “event” next to elements in the HTML
Pane, that have event listeners bound to them. Click the icon, then
you’ll see a popup listing all the event listeners bound to this
element.</p>
</blockquote>
<p>You can also use the <code>debugger</code> keyword to set a breakpoint in the call stack somewhere. Then use your favorite javascript debugger (built-in dev tools in Safari, Google Chrome & IE8, firebug for Firefox). In each of these, there's a call stack that'll allow you to navigate through the current call stack.</p> |
3,451,863 | When does a UNIX directory change its timestamp | <p>I used "touch" on a file, updating the file's timestamp but the parent directory's timestamp did not change. However, (as expected) when I created a new file within the parent directory, the directory's timestamp did change.</p>
<p>What criteria do UNIX-like operating systems (specifically AIX) use to determine when to update the timestamp of a directory?</p> | 3,451,912 | 4 | 0 | null | 2010-08-10 17:47:53.24 UTC | 7 | 2020-09-05 03:32:28.343 UTC | null | null | null | null | 55,597 | null | 1 | 53 | unix|unix-timestamp | 25,834 | <p>The timestamp is updated when the data that represents the directory changes. A change in a subdirectory of directory D does not change anything in the representation of D because D only points to the subdirectory, not to what's inside it. On the other hand, creating a file in D changes the block of data on disk that represents D.</p> |
3,642,080 | Using python "with" statement with try-except block | <p>Is this the right way to use the python "with" statement in combination with a try-except block?:</p>
<pre><code>try:
with open("file", "r") as f:
line = f.readline()
except IOError:
<whatever>
</code></pre>
<p>If it is, then considering the old way of doing things:</p>
<pre><code>try:
f = open("file", "r")
line = f.readline()
except IOError:
<whatever>
finally:
f.close()
</code></pre>
<p>Is the primary benefit of the "with" statement here that we can get rid of three lines of code? It doesn't seem that compelling to me <strong>for this use case</strong> (though I understand that the "with" statement has other uses).</p>
<p>EDIT: Is the functionality of the above two blocks of code identical?</p>
<p>EDIT2: The first few answers talk generally about the benefits of using "with", but those seem of marginal benefit here. We've all been (or should have been) explicitly calling f.close() for years. I suppose one benefit is that sloppy coders will benefit from using "with".</p> | 3,644,618 | 4 | 2 | null | 2010-09-04 11:35:29.113 UTC | 28 | 2015-10-13 21:25:54.627 UTC | 2010-09-04 12:30:27.843 UTC | null | 136,598 | null | 136,598 | null | 1 | 116 | python|finally|with-statement|try-catch|except | 95,601 | <ol>
<li>The two code blocks you gave are
<strong>not</strong> equivalent</li>
<li>The code you described as <em>old way
of doing things</em> has a serious bug:
in case opening the file fails you
will get a second exception in the
<code>finally</code> clause because <code>f</code> is not
bound.</li>
</ol>
<p>The equivalent old style code would be:</p>
<pre><code>try:
f = open("file", "r")
try:
line = f.readline()
finally:
f.close()
except IOError:
<whatever>
</code></pre>
<p>As you can see, the <code>with</code> statement can make things less error prone. In newer versions of Python (2.7, 3.1), you can also combine multiple expressions in one <code>with</code> statement. For example:</p>
<pre><code>with open("input", "r") as inp, open("output", "w") as out:
out.write(inp.read())
</code></pre>
<p>Besides that, I personally regard it as bad habit to catch any exception as early as possible. This is not the purpose of exceptions. If the IO function that can fail is part of a more complicated operation, in most cases the IOError should abort the whole operation and so be handled at an outer level. Using <code>with</code> statements, you can get rid of all these <code>try...finally</code> statements at inner levels. </p> |
3,793,218 | HTML DOCTYPE Syntax error | <p>I get the following syntax error in Firebug and I don't get what's it:</p>
<pre><code>> syntax error [Break on this error]
> <!DOCTYPE html PUBLIC "-//W3C//DTDXHT...org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n
</code></pre>
<p>Is it because of the final "\n" at the end ?</p>
<p>thanks</p>
<p>ps. I've just realized if I remove all scripts, I don't get that error. For example, if I remove these lines, I don't get it. If I add another script I get it again, so it doesn't depend on the script itself.</p>
<pre><code><script type="text/JavaScript" src="<?php echo $base_url; ?>sites/all/themes/bluemarine/js/main.js"></script>
</code></pre>
<p>CODE:</p>
<pre><code><?php
// $Id: page.tpl.php,v 1.28.2.1 2009/04/30 00:13:31 goba Exp $
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="<?php print $language->language ?>" xml:lang="<?php print $language->language ?>" dir="<?php print $language->dir ?>">
<head>
<?php print $head ?>
<title><?php print $head_title ?></title>
<?php print $styles ?>
<?php print $scripts ?>
<script type="text/JavaScript" src="<?php echo $base_url; ?>sites/all/themes/bluemarine/js/main.js"></script>
<!--<script type="text/JavaScript" src="<?php echo $base_url; ?>sites/all/themes/bluemarine/js/griddy-min.js"></script>
-->
</head>
<body>...
</code></pre> | 3,793,241 | 5 | 1 | null | 2010-09-25 09:25:20.117 UTC | 8 | 2020-11-02 17:38:17.39 UTC | 2010-09-25 09:40:28.233 UTC | null | 257,022 | null | 257,022 | null | 1 | 26 | html | 78,460 | <p><a href="http://blog.ryanrampersad.com/2008/09/syntax-error-break-on-this-error-doctype-html-public-w3cdtd-xhtml3orgtr-xhtml1-dtd-xhtml1-strictdtd/" rel="noreferrer">Ryan Rampersad</a>, blogged about this issue stating</p>
<blockquote>
<p>The error comes from Firebug. The break on this error isn’t a part of the error but it is in the firebug copy dump....</p>
</blockquote>
<p><code>syntax error [Break on this error] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML…3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"></code></p>
<blockquote>
<p>The way I encountered this error was that I forgot to specify a src attribute value for my script tag!</p>
</blockquote>
<p><code><script type="text/javascript" src=""></script></code></p>
<p>Here is the <a href="http://blog.ryanrampersad.com/2008/09/syntax-error-break-on-this-error-doctype-html-public-w3cdtd-xhtml3orgtr-xhtml1-dtd-xhtml1-strictdtd/" rel="noreferrer">blog post</a>.</p> |
3,983,660 | probability in javascript help? | <p>Sorry, I'm new to JS and can't seem to figure this out: how would I do probability?</p>
<p>I have absolutely no idea, but I'd like to do something: out of 100% chance, maybe 0.7% chance to execute function <code>e();</code> and 30% chance to execute function <code>d();</code> and so on - they will add up to 100% exactly with a different function for each, but I haven't figured out exactly how to do this in any form. </p>
<p>What I found is mostly strange high school math tutorials "powered by" Javascriptkit or something.</p> | 3,983,830 | 6 | 2 | null | 2010-10-21 01:36:24.4 UTC | 10 | 2017-06-12 19:33:05.34 UTC | 2010-10-21 01:41:34.373 UTC | null | 313,758 | null | 469,676 | null | 1 | 11 | javascript|math | 14,327 | <p>For instance we define a number of functions</p>
<pre><code>function a () { return 0; }
function b () { return 1; }
function c () { return 2; }
var probas = [ 20, 70, 10 ]; // 20%, 70% and 10%
var funcs = [ a, b, c ]; // the functions array
</code></pre>
<p>That generic function works for any number of functions, it executes it and return the result:</p>
<pre><code>function randexec()
{
var ar = [];
var i,sum = 0;
// that following initialization loop could be done only once above that
// randexec() function, we let it here for clarity
for (i=0 ; i<probas.length-1 ; i++) // notice the '-1'
{
sum += (probas[i] / 100.0);
ar[i] = sum;
}
// Then we get a random number and finds where it sits inside the probabilities
// defined earlier
var r = Math.random(); // returns [0,1]
for (i=0 ; i<ar.length && r>=ar[i] ; i++) ;
// Finally execute the function and return its result
return (funcs[i])();
}
</code></pre>
<p>For instance, let's try with our 3 functions, 100000 tries:</p>
<pre><code>var count = [ 0, 0, 0 ];
for (var i=0 ; i<100000 ; i++)
{
count[randexec()]++;
}
var s = '';
var f = [ "a", "b", "c" ];
for (var i=0 ; i<3 ; i++)
s += (s ? ', ':'') + f[i] + ' = ' + count[i];
alert(s);
</code></pre>
<p>The result on my Firefox</p>
<pre><code>a = 20039, b = 70055, c = 9906
</code></pre>
<p>So <em>a</em> run about 20%, <em>b</em> ~ 70% and <em>c</em> ~ 10%.</p>
<p><br/><strong>Edit</strong> following comments.
<br/></p>
<p>If your browser has a cough with <code>return (funcs[i])();</code>, just replace the funcs array</p>
<pre><code>var funcs = [ a, b, c ]; // the old functions array
</code></pre>
<p>with this new one (strings)</p>
<pre><code>var funcs = [ "a", "b", "c" ]; // the new functions array
</code></pre>
<p>then replace the final line of the function <code>randexec()</code> </p>
<pre><code>return (funcs[i])(); // old
</code></pre>
<p>with that new one</p>
<pre><code>return eval(funcs[i]+'()');
</code></pre> |
3,629,586 | Python "if X == Y and Z" syntax | <p>Does this:</p>
<pre><code>if key == "name" and item:
</code></pre>
<p>mean the same as this:</p>
<pre><code>if key == "name" and if key == "item":
</code></pre>
<p>If so, I'm totally confused about <a href="http://diveintopython.net/object_oriented_framework/special_class_methods.html" rel="noreferrer">example 5.14 in Dive Into Python</a>. How can key be equal to both "name" and item? On the other hand, does "and item" simply ask whether or not item exists as a variable?</p> | 3,629,597 | 8 | 2 | null | 2010-09-02 17:27:28.633 UTC | 2 | 2021-06-20 01:03:50.993 UTC | 2016-03-10 00:46:27.357 UTC | null | 19,405 | null | 298,065 | null | 1 | 15 | python|if-statement | 106,905 | <p><code>if key == "name" and item:</code> means <code>if (key == "name") and (item evaluates to True)</code>. </p>
<p>Keep in mind that <code>(item evaluates to True)</code> is possible in several ways. For example <code>if (key == "name") and []</code> will evaluate to <code>False</code>. </p> |
3,880,307 | Trigger event on body load complete js/jquery | <p>I want to trigger one event on page load complete using javascript/jquery.</p>
<p>Is there any way to trigger event or call a simple function once page loading fully completes.</p>
<p>Please suggest folks if you any reference.</p> | 3,880,336 | 10 | 0 | null | 2010-10-07 09:25:57.303 UTC | 5 | 2020-06-05 18:48:44.12 UTC | 2010-10-07 09:29:55.953 UTC | null | 340,760 | null | 373,142 | null | 1 | 22 | javascript|jquery|html | 136,749 | <p>Everyone's mentioned the <code>ready</code> function (and its shortcuts), but even earlier than that, you can just put code in a <code>script</code> tag just before the closing <code>body</code> tag (this is what the YUI and Google Closure folks recommend), like this:</p>
<pre><code><script type='text/javascript'>
pageLoad();
</script>
</body>
</code></pre>
<p>At this point, everything above that script tag is available in the DOM.</p>
<p>So your options in order of occurrence:</p>
<ol>
<li><p>Earliest: Function call in <code>script</code> tag just before closing the <code>body</code> tag. The DOM <strong>is</strong> ready at this point (according to the Google Closure folks, and they should know; I've also tested it on a bunch of browsers).</p></li>
<li><p>Earlyish: the <code>jQuery.ready</code> callback (and its shortcut forms).</p></li>
<li><p>Late, after <strong>all</strong> page elements including images are fully loaded: <code>window</code> <code>onload</code> event.</p></li>
</ol>
<p>Here's a live example: <a href="http://jsbin.com/icazi4" rel="noreferrer">http://jsbin.com/icazi4</a>, relevant extract:</p>
<pre><code></body>
<script type='text/javascript'>
runPage();
jQuery(function() {
display("From <tt>jQuery.ready</tt> callback.");
});
$(window).load(function() {
display("From <tt>window.onload</tt> callback.");
});
function runPage() {
display("From function call at end of <tt>body</tt> tag.");
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
</script>
</code></pre>
<p>(Yes, I could have used jQuery for the <code>display</code> function, but I was starting with a non-jQuery template.)</p> |
3,940,127 | Intercept back button from soft keyboard | <p>I have the activity with several input fields. When activity started soft keyboard is shown. When back button pressed soft keyboard closes and to close activity I need to press back button one more time. </p>
<p>So the question: is it possible to intercept back button to close soft keyboard and finish activity in one press of back button without creating custom <code>InputMethodService</code>?</p>
<p>P.S. I know how to intercept back button in other cases: <code>onKeyDown()</code> or <code>onBackPressed()</code> but it doesn't work in this case: only second press of back button is intercepted.</p> | 5,811,630 | 10 | 0 | null | 2010-10-15 06:59:30.72 UTC | 40 | 2021-04-29 15:11:29.443 UTC | 2014-09-16 08:47:51.023 UTC | null | 436,938 | null | 436,938 | null | 1 | 88 | android | 94,195 | <p>Yes, it is completely possible to show and hide the keyboard and intercept the calls to the back button. It is a little extra effort as it has been mentioned there is no direct way to do this in the API. The key is to override <code>boolean dispatchKeyEventPreIme(KeyEvent)</code> within a layout. What we do is create our layout. I chose RelativeLayout since it was the base of my Activity.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<com.michaelhradek.superapp.utilities.SearchLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.michaelhradek.superapp"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/white">
</code></pre>
<p>Inside our Activity we set up our input fields and call the <code>setActivity(...)</code> function.</p>
<pre><code>private void initInputField() {
mInputField = (EditText) findViewById(R.id.searchInput);
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
InputMethodManager.HIDE_IMPLICIT_ONLY);
mInputField.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
performSearch();
return true;
}
return false;
}
});
// Let the layout know we are going to be overriding the back button
SearchLayout.setSearchActivity(this);
}
</code></pre>
<p>Obviously, the <code>initInputField()</code> function sets up the input field. It also enables the enter key to execute the functionality (in my case a search).</p>
<pre><code>@Override
public void onBackPressed() {
// It's expensive, if running turn it off.
DataHelper.cancelSearch();
hideKeyboard();
super.onBackPressed();
}
</code></pre>
<p>So when the <code>onBackPressed()</code> is called within our layout we then can do whatever we want like hide the keyboard:</p>
<pre><code>private void hideKeyboard() {
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mInputField.getWindowToken(), 0);
}
</code></pre>
<p>Anyway, here is my override of the RelativeLayout.</p>
<pre><code>package com.michaelhradek.superapp.utilities;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.RelativeLayout;
/**
* The root element in the search bar layout. This is a custom view just to
* override the handling of the back button.
*
*/
public class SearchLayout extends RelativeLayout {
private static final String TAG = "SearchLayout";
private static Activity mSearchActivity;;
public SearchLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SearchLayout(Context context) {
super(context);
}
public static void setSearchActivity(Activity searchActivity) {
mSearchActivity = searchActivity;
}
/**
* Overrides the handling of the back key to move back to the
* previous sources or dismiss the search dialog, instead of
* dismissing the input method.
*/
@Override
public boolean dispatchKeyEventPreIme(KeyEvent event) {
Log.d(TAG, "dispatchKeyEventPreIme(" + event + ")");
if (mSearchActivity != null &&
event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
KeyEvent.DispatcherState state = getKeyDispatcherState();
if (state != null) {
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getRepeatCount() == 0) {
state.startTracking(event, this);
return true;
} else if (event.getAction() == KeyEvent.ACTION_UP
&& !event.isCanceled() && state.isTracking(event)) {
mSearchActivity.onBackPressed();
return true;
}
}
}
return super.dispatchKeyEventPreIme(event);
}
}
</code></pre>
<p>Unfortunately I can't take all the credit. If you check the Android <a href="http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.1_r2/android/app/SearchDialog.java#SearchDialog.SearchBar" rel="noreferrer">source for the quick SearchDialog box</a> you will see where the idea came from.</p> |
3,302,857 | Algorithm to get the excel-like column name of a number | <p>I'm working on a script that generate some Excel documents and I need to convert a number into its column name equivalent. For example:</p>
<pre><code>1 => A
2 => B
27 => AA
28 => AB
14558 => UMX
</code></pre>
<p>I have already written an algorithm to do so, but I'd like to know whether are simpler or faster ways to do it:</p>
<pre><code>function numberToColumnName($number){
$abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
$abc_len = strlen($abc);
$result_len = 1; // how much characters the column's name will have
$pow = 0;
while( ( $pow += pow($abc_len, $result_len) ) < $number ){
$result_len++;
}
$result = "";
$next = false;
// add each character to the result...
for($i = 1; $i<=$result_len; $i++){
$index = ($number % $abc_len) - 1; // calculate the module
// sometimes the index should be decreased by 1
if( $next || $next = false ){
$index--;
}
// this is the point that will be calculated in the next iteration
$number = floor($number / strlen($abc));
// if the index is negative, convert it to positive
if( $next = ($index < 0) ) {
$index = $abc_len + $index;
}
$result = $abc[$index].$result; // concatenate the letter
}
return $result;
}
</code></pre>
<p>Do you know a better way to do it? Maybe something to keep it simpler? or a performance improvement?</p>
<h3>Edit</h3>
<p>ircmaxell's implementation works pretty fine. But, I'm going to add this nice short one:</p>
<pre><code>function num2alpha($n)
{
for($r = ""; $n >= 0; $n = intval($n / 26) - 1)
$r = chr($n%26 + 0x41) . $r;
return $r;
}
</code></pre> | 3,302,991 | 11 | 8 | null | 2010-07-21 19:09:10.207 UTC | 42 | 2021-09-05 20:06:56.977 UTC | 2015-09-04 01:54:00.993 UTC | null | 1,505,120 | null | 244,296 | null | 1 | 111 | php|algorithm|optimization | 61,994 | <p>Here's a nice simple recursive function (Based on zero indexed numbers, meaning 0 == A, 1 == B, etc)...</p>
<pre><code>function getNameFromNumber($num) {
$numeric = $num % 26;
$letter = chr(65 + $numeric);
$num2 = intval($num / 26);
if ($num2 > 0) {
return getNameFromNumber($num2 - 1) . $letter;
} else {
return $letter;
}
}
</code></pre>
<p>And if you want it one indexed (1 == A, etc):</p>
<pre><code>function getNameFromNumber($num) {
$numeric = ($num - 1) % 26;
$letter = chr(65 + $numeric);
$num2 = intval(($num - 1) / 26);
if ($num2 > 0) {
return getNameFromNumber($num2) . $letter;
} else {
return $letter;
}
}
</code></pre>
<p>Tested with numbers from 0 to 10000...</p> |
8,348,401 | Can two separate JavaScript scripts share variables? | <p>If I have two separate scripts in an HTML page with JavaScript are the variables shared between the entire page? Or only within their own declarations?</p>
<p>Example:</p>
<pre><code><script> var title = "Hello World!"; </script>
// random HTML/PHP
<script> document.write(title); </script>
</code></pre>
<p>Will that write "Hello World!"?
This seems like bad coding convention how else could I achieve something like this with proper form.</p> | 8,348,725 | 5 | 0 | null | 2011-12-01 21:15:49.553 UTC | 9 | 2022-06-23 18:12:09.667 UTC | 2022-06-23 18:12:09.667 UTC | null | 1,264,804 | null | 431,203 | null | 1 | 31 | javascript|coding-style | 34,980 | <p>Variable title in your example is declared as a global variable, therefore it will be available to any and all scripts loaded into the same page. Whats more, if there is already a global variable named <code>title</code> on the same page, its value will be overwritten when you assign it the value "Hello World!"</p>
<p>The usual practice to avoid this sort of problem is to declare exactly one global variable, then put all of your other variables inside it. For example:</p>
<pre><code>var bobbyS_vars = {
title: "Hello World!";
};
</code></pre>
<p>Assign that lone global variable a name that no one else is likely to choose, such as your name or employer's name or best-of-all, a domain name that belongs you or your employer.</p>
<p>Another, more common way to handle this problem is to take advantage of of the way that JavaScript handles variable scope within functions. For example, create an anonymous function, declare <em>all</em> of your code inside that function, then call the function at the end of the declaration by putting () at the end of the declaration. For example:</p>
<pre><code>(function() {
var title = "Hello World!";
document.write(title);
})();
// title is not in scope here, so it is undefined,
// unless it were declared elsewhere.
</code></pre>
<p>If you <em>want</em> to share some variables, but not others, have your anonymous function use a combination of approaches:</p>
<pre><code>var bobbyS_vars = {
title: "Hello World!";
};
(function() {
var employeeId = "E 298";
var count = 7;
document.write("<p>" + bobbyS_vars.title + "</p>");
document.write("<p>" + employeeId + "</p>");
})();
// At this point, bobbyS_vars.title is in scope and still has the
// value "Hello World!". Variables employeeId and count are not
// in scope and effectively private to the code above.
</code></pre>
<p>One final note. All of the functions that your code declares are also effectively global variables. So, if you create a function named printTitle, it is 1) available to all other code on the page and 2) could overwrite or be overwritten by another function on the same page also named printTitle. You can protect and/or expose your functions the same way you would any other variable:</p>
<pre><code>var bobbyS_vars = { };
(function() {
// Private functions
var function = addOne(i) {
return i + 1;
};
// Public vars
bobbyS_vars.title: "Hello World!";
// Public functions
bobbyS_vars.printTitle = function() {
document.write("<p>" + bobbyS_vars.title + "</p>");
document.write("<p>" + addOne(41) + "</p>");
};
})();
// At this point, function addOne is not directly accessible,
// but printTitle is.
bobbyS_vars.printTitle();
</code></pre>
<p>Note that although function addOne is effectively a private function within the closure, it is still accessible indirectly, via the printTitle function because addOne and printTitle are both within the same scope.</p> |
7,817,007 | SQL set values of one column equal to values of another column in the same table | <p>I have a table with two DATETIME columns.</p>
<p>One of them is never NULL, but one of them is sometimes NULL.</p>
<p>I need to write a query which will set all the NULL rows for column B equal to the values in column A.</p>
<p>I have tried <a href="https://stackoverflow.com/questions/707371/sql-update-set-one-column-to-be-equal-to-a-value-in-a-related-table-referenced-b">this example</a> but the SQL in the selected answer does not execute because MySQL Workbench doesn't seem to like the FROM in the UPDATE.</p> | 7,817,049 | 5 | 0 | null | 2011-10-19 05:41:36.593 UTC | 10 | 2019-07-16 01:02:52.897 UTC | 2017-05-23 12:03:02.377 UTC | null | -1 | null | 1,002,358 | null | 1 | 113 | mysql|sql | 169,817 | <p>Sounds like you're working in just one table so something like this:</p>
<pre><code>update your_table
set B = A
where B is null
</code></pre> |
8,127,462 | The view must derive from WebViewPage, or WebViewPage<TModel> | <p>I'm following <a href="http://fzysqr.com/2010/04/26/asp-net-mvc2-plugin-architecture-tutorial/" rel="noreferrer">Justin Slattery's Plugin Architecture tutorial</a> and trying to adapt it for Razor, instead of WebForm Views.</p>
<p>Everything else (controllers, plugin assembly loading, etc) seems to be okay. However, I'm not able to get embedded Razor views to work properly. When I try to browse to the "HelloWorld/Index", I get the following error:</p>
<pre class="lang-none prettyprint-override"><code>The view at '~/Plugins/MyProjectPlugin.dll/MyProjectPlugin.Views.HelloWorld.Index.cshtml' must derive from WebViewPage or WebViewPage<TModel>.
</code></pre>
<p>The exception is thrown by <code>System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +262</code></p>
<p>I can include the complete stack trace, if needed.</p>
<p>Can anyone advise as to what I might be doing wrong? </p> | 8,127,539 | 7 | 0 | null | 2011-11-14 20:13:20.473 UTC | 20 | 2017-02-03 17:38:27 UTC | 2017-02-03 17:00:58.77 UTC | null | 2,747,593 | null | 16,522 | null | 1 | 73 | asp.net-mvc-3|razor|embedded-resource|plugin-architecture | 56,258 | <p>You may checkout the <a href="http://www.chrisvandesteeg.nl/2010/11/22/embedding-pre-compiled-razor-views-in-your-dll/">following blog post</a> which is more adapted to Razor. </p>
<p>But to answer your question, since you are now serving your views from a non standard location there is no longer the <code>~/Views/web.config</code> file that applies and allows you to specify the base type for your razor views. So you might need to add the following on the top of each razor view:</p>
<pre><code>@inherits System.Web.Mvc.WebViewPage
@model ...
</code></pre> |
7,865,446 | Google maps Places API V3 autocomplete - select first option on enter | <p>I have successfuly implemented Google Maps Places V3 autocomplete feature on my input box as per <a href="http://web.archive.org/web/20120225114154/http://code.google.com:80/intl/sk-SK/apis/maps/documentation/javascript/places.html" rel="noreferrer">http://web.archive.org/web/20120225114154/http://code.google.com:80/intl/sk-SK/apis/maps/documentation/javascript/places.html</a>. It works nicely, however I would love to know how can I make it select the first option from the suggestions when a user presses enter. I guess I would need some JS magic, but I am very much new to JS and don't know where to start.</p>
<p>Thanks in advance!</p> | 8,157,180 | 18 | 1 | null | 2011-10-23 09:54:37.73 UTC | 48 | 2020-12-22 18:23:06.22 UTC | 2020-06-02 16:55:07.43 UTC | null | 6,262,124 | null | 755,532 | null | 1 | 75 | javascript|google-maps|autocomplete|google-maps-api-3 | 135,449 | <p>I had the same issue when implementing autocomplete on a site I worked on recently. This is the solution I came up with:</p>
<pre><code>$("input").focusin(function () {
$(document).keypress(function (e) {
if (e.which == 13) {
var firstResult = $(".pac-container .pac-item:first").text();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({"address":firstResult }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat(),
lng = results[0].geometry.location.lng(),
placeName = results[0].address_components[0].long_name,
latlng = new google.maps.LatLng(lat, lng);
$(".pac-container .pac-item:first").addClass("pac-selected");
$(".pac-container").css("display","none");
$("#searchTextField").val(firstResult);
$(".pac-container").css("visibility","hidden");
moveMarker(placeName, latlng);
}
});
} else {
$(".pac-container").css("visibility","visible");
}
});
});
</code></pre>
<p><a href="http://jsfiddle.net/dodger/pbbhH/">http://jsfiddle.net/dodger/pbbhH/</a></p> |
4,837,876 | Most appropriate way to get this: $($(".answer")[0]) | <p>Suppose I want to get the first element amongst all the elements of the class ".answer"</p>
<pre><code>$($(".answer")[0])
</code></pre>
<p>I can do the above, but what is the best balance between elegance and speed?</p>
<p>*changed the question to reflect the current discussion</p> | 4,837,885 | 3 | 4 | null | 2011-01-29 16:11:15.847 UTC | 9 | 2017-12-28 16:36:52.277 UTC | 2011-05-30 03:36:27.133 UTC | null | 172,322 | null | 180,663 | null | 1 | 35 | javascript|jquery|performance|jquery-selectors | 1,926 | <p>The following are all equivalent in functionality (though not speed):</p>
<ul>
<li><code>var a0 = $($('.answer')[0]);</code></li>
<li><code>var a0 = $('.answer').first();</code> - see <a href="http://api.jquery.com/first/" rel="nofollow noreferrer">http://api.jquery.com/first/</a></li>
<li><code>var a0 = $('.answer:first');</code> - see <a href="http://api.jquery.com/first-selector/" rel="nofollow noreferrer">http://api.jquery.com/first-selector/</a></li>
<li><code>var a0 = $('.answer').eq(0);</code> - see <a href="http://api.jquery.com/eq/" rel="nofollow noreferrer">http://api.jquery.com/eq/</a></li>
<li><code>var a0 = $('.answer:eq(0)');</code> - see <a href="http://api.jquery.com/eq-selector/" rel="nofollow noreferrer">http://api.jquery.com/eq-selector/</a></li>
</ul>
<p><strong>Which is the best?</strong><br>
It <a href="https://stackoverflow.com/questions/4262928/jquery-what-is-faster-selectors-or-methods/4262951#4262951">has been hypothesized</a> that the selector versions <em>should</em> be faster than the method versions (and the logic makes some sense) but I have not yet found a reliable cross-browser, multi-document benchmark that proves this to be true.</p>
<p><em>And in some cases you cannot use the selector, as you have a jQuery object resulting from chained results and must later pare it down.</em></p>
<p><strong>Edit</strong>: Based on the excellent information from @yc's tests below, following are the current (2011-Feb-4) test results summarized and compared against a baseline of <code>.answer:first</code>:</p>
<pre>
:first :eq(0) .first() .eq(0) $($('...')[0])
Chrome 8+ 100% 92% 224% 266% 367%
FF 3.6 100% 100% 277% 270% 309%
FF 4.0b 100% 103% 537% 521% 643%
Safari 5 100% 93% 349% 352% 467%
Opera 11 100% 103% 373% 374% 465%
IE 8 100% 101% 1130% 1246% 1767%
iPhone 4 100% 95% 269% 316% 403%
=====================================================
Weighted 100% 92% 286% 295% 405%
Major 100% 95% 258% 280% 366%
</pre>
<ul>
<li>The <strong>Weighted</strong> line shows the performance weighted by the number of tests per browser; popular browsers (among those testing) are counted more strongly.</li>
<li>The <strong>Major</strong> line shows the same, only including non-beta releases of the major desktop browsers.</li>
</ul>
<p>In summary: the hypothesis is (currently) wrong. The methods are significantly faster than the Sizzle selectors, and with almost no exception the OP's code <code>$($('.answer')[0])</code> is the fastest of them all!</p> |
14,456,621 | Simple HTML DOM getting all attributes from a tag | <p>Sort of a two part question but maybe one answers the other. I'm trying to get a piece of information out of an
<pre><code><div id="foo">
<div class="bar"><a data1="xxxx" data2="xxxx" href="http://foo.bar">Inner text"</a>
<div class="bar2"><a data3="xxxx" data4="xxxx" href="http://foo.bar">more text"</a>
</code></pre>
<p>Here is what I'm using now. </p>
<pre><code>$articles = array();
$html=file_get_html('http://foo.bar');
foreach($html->find('div[class=bar] a') as $a){
$articles[] = array($a->href,$a->innertext);
}
</code></pre>
<p>This works perfectly to grab the href and the inner text from the first div class. I tried adding a $a->data1 to the foreach but that didn't work. </p>
<p>How do I grab those inner data tags at the same time I grab the href and innertext. </p>
<p>Also is there a good way to get both classes with one statement? I assume I could build the find off of the id and grab all the div information. </p>
<p>Thanks</p> | 14,456,823 | 4 | 0 | null | 2013-01-22 10:39:40.78 UTC | 6 | 2019-07-17 06:03:39.713 UTC | 2013-01-22 14:09:13.487 UTC | null | 1,889,273 | null | 1,950,211 | null | 1 | 6 | php|html|dom | 45,469 | <p>To grab all those attributes, you should before investigate the parsed element, like this:</p>
<pre><code>foreach($html->find('div[class=bar] a') as $a){
var_dump($a->attr);
}
</code></pre>
<p>...and see if those attributes exist. They don't seem to be valid HTML, so maybe the parser discards them.</p>
<p>If they exist, you can read them like this:</p>
<pre><code>foreach($html->find('div[class=bar] a') as $a){
$article = array($a->href, $a->innertext);
if (isset($a->attr['data1'])) {
$article['data1'] = $a->attr['data1'];
}
if (isset($a->attr['data2'])) {
$article['data2'] = $a->attr['data2'];
}
//...
$articles[] = $article;
}
</code></pre>
<p>To get both classes you can use a multiple selector, separated by a comma:</p>
<pre><code>foreach($html->find('div[class=bar] a, div[class=bar2] a') as $a){
...
</code></pre> |
4,488,601 | jQuery - draggable images on iPad / iPhone - how to integrate event.preventDefault();? | <p>I use jQuery, jQuery UI and jQuery mobile to build a web application for iPhone / iPad.
Now I create images and they should be draggable, so I did this:</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Drag - Test</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.css" />
<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0a2/jquery.mobile-1.0a2.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js"></script>
</head>
<body>
<div>
<div style="width:500px;height:500px;border:1px solid red;">
<img src="http://upload.wikimedia.org/wikipedia/en/thumb/9/9e/JQuery_logo.svg/200px-JQuery_logo.svg.png" class="draggable" alt="jQuery logo" />
<img src="http://upload.wikimedia.org/wikipedia/en/a/ab/Apple-logo.png" class="draggable" alt="Apple Inc. logo" />
</div>
</div>
</body>
<script type="text/javascript">
$(document).ready(function() {
$(".draggable").draggable();
});
</script>
</html>
</code></pre>
<p>Here you can see the live example: <a href="http://jsbin.com/igena4/" rel="noreferrer">http://jsbin.com/igena4/</a></p>
<p>The problem is, that the whole page want to scroll. I searched in Apple's HTML5 examples and found this to prevent the scrolling of the page, so that the image is draggable:</p>
<pre><code>...
onDragStart: function(event) {
// stop page from panning on iPhone/iPad - we're moving a note, not the page
event.preventDefault();
...
}
</code></pre>
<p>But the problem is for me, how can I include this into my jQuery? Where do I get <code>event</code>?</p>
<p>Best Regards.</p> | 8,873,831 | 5 | 0 | null | 2010-12-20 10:08:16.917 UTC | 11 | 2016-09-20 08:06:52.457 UTC | null | null | null | null | 224,030 | null | 1 | 16 | jquery|html|jquery-ui|multi-touch|jquery-mobile | 42,508 | <p>Try this library</p>
<p><a href="https://github.com/furf/jquery-ui-touch-punch" rel="nofollow">https://github.com/furf/jquery-ui-touch-punch</a></p>
<blockquote>
<p>Just follow these simple steps to enable touch events in your jQuery
UI app:</p>
<ol>
<li><p>Include jQuery and jQuery UI on your page.</p>
<pre><code><script src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.8.17/jquery-ui.min.js"></script>
</code></pre></li>
<li><p>Include Touch Punch after jQuery UI and before its first use.</p>
<p>Please note that if you are using jQuery UI's components, Touch Punch must be included after jquery.ui.mouse.js, as Touch Punch
modifies its behavior.</p>
<pre><code><script src="jquery.ui.touch-punch.min.js"></script>
</code></pre></li>
<li><p>There is no 3. Just use jQuery UI as expected and watch it work at the touch of a finger.</p>
<pre><code><script>$('#widget').draggable();</script>
</code></pre></li>
</ol>
</blockquote> |
4,474,646 | how to write to a text file using to log4j? | <p>I'm wondering how to convert the following code to output those lines into a text file, and not to standard output:</p>
<pre><code>import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator;
public class HelloWorld {
static final Logger logger = Logger.getLogger(HelloWorld.class);
public static void main(String[] args) {
PropertyConfigurator.configure("log4j.properties");
logger.debug("Sample debug message");
logger.info("Sample info message");
logger.warn("Sample warn message");
logger.error("Sample error message");
logger.fatal("Sample fatal message");
}
}
</code></pre>
<p>The properties file is :</p>
<pre><code>log4j.rootLogger=DEBUG, CA
log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.FA.layout.ConversionPattern=%m%n
</code></pre>
<p>Thanks.</p> | 4,474,790 | 5 | 3 | null | 2010-12-17 20:49:24.993 UTC | 4 | 2018-11-20 12:51:01.133 UTC | 2014-09-17 15:33:28.777 UTC | null | 1,429,387 | null | 530,439 | null | 1 | 24 | java|logging|file|log4j | 89,907 | <p>Change the ConsoleAppender to a FileAppender.</p>
<p>I find the <code>org.apache.log4j.RollingFileAppender</code>
to be useful.
If you use this,
you must add a property for the fileName and
may want to set the maxFileSize as well.
Here is an example (put these in the log4j.properties file):</p>
<pre><code>log4j.appender.NotConsole=org.apache.log4j.RollingFileAppender
log4j.appender.NotConsole.fileName=/some/path/to/a/fileName.log
log4j.appender.NotConsole.maxFileSize=20MB
</code></pre>
<p>There are other appenders.
<code>DailyRollingFileAppender</code> rolls based on time.
<code>FileAppender</code> does not roll.
If you use the <code>RollingFileAppender</code>,
you will need to guess as to a good value for maxFileSize and
then address the size at a future date if it is causing issues.</p> |
4,311,026 | How to get SLF4J "Hello World" working with log4j? | <p>The "Hello World" example from <a href="http://www.slf4j.org/manual.html" rel="noreferrer">SLF4J</a> is not working for me. I guess this is because I added slf4j-log4 to my classpath. Should I configure log4j directly for the hello world to work?</p>
<pre><code>log4j:WARN No appenders could be found for logger (HelloWorld).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
</code></pre>
<p><strong>Update</strong>: I added log4j initialization, and it still doesn't work:</p>
<pre><code>public static void main(String[] params) {
org.apache.log4j.Logger.getRootLogger().addAppender(new ConsoleAppender());
Logger logger = org.slf4j.LoggerFactory.getLogger(TestBase.class);
logger.info("Hello World");
}
</code></pre>
<p>And I'm getting:</p>
<pre><code>log4j:ERROR No output stream or file set for the appender named [null].
</code></pre> | 4,311,178 | 5 | 4 | null | 2010-11-30 06:10:35.397 UTC | 23 | 2020-08-12 09:24:53.417 UTC | 2010-11-30 06:16:02.513 UTC | null | 11,236 | null | 11,236 | null | 1 | 53 | java|logging|log4j|slf4j | 118,472 | <p>If you want to use <code>slf4j simple</code>, you need these <code>jar</code> files on your classpath:</p>
<ul>
<li>slf4j-api-1.6.1.jar</li>
<li>slf4j-simple-1.6.1.jar </li>
</ul>
<p>If you want to use <code>slf4j</code> and <code>log4j</code>, you need these <code>jar</code> files on your classpath:</p>
<ul>
<li>slf4j-api-1.6.1.jar</li>
<li>slf4j-log4j12-1.6.1.jar </li>
<li>log4j-1.2.16.jar</li>
</ul>
<p>No more, no less. Using <code>slf4j simple</code>, you'll get basic logging to your console at <code>INFO</code> level or higher. Using <code>log4j</code>, you must <a href="http://logging.apache.org/log4j/1.2/manual.html" rel="noreferrer">configure it accordingly</a>.</p> |
4,803,063 | What's the difference between PHP's DOM and SimpleXML extensions? | <p>I'm failing to comprehend why do we need 2 XML parsers in PHP.</p>
<p>Can someone explain the difference between those two?</p> | 4,803,264 | 5 | 0 | null | 2011-01-26 09:41:08.957 UTC | 18 | 2014-12-25 12:02:04.287 UTC | 2013-06-23 22:03:39.927 UTC | null | 367,456 | null | 471,891 | null | 1 | 68 | php|simplexml|domdocument | 31,247 | <p>In a nutshell:</p>
<p><strong>SimpleXml</strong> </p>
<ul>
<li>is for simple XML and/or simple UseCases</li>
<li>limited API to work with nodes (e.g. cannot program to an interface that much)</li>
<li>all nodes are of the same kind (element node is the same as attribute node)</li>
<li>nodes are magically accessible, e.g. <code>$root->foo->bar['attribute']</code></li>
</ul>
<p><strong>DOM</strong> </p>
<ul>
<li>is for any XML UseCase you might have</li>
<li><a href="http://www.w3.org/DOM/" rel="noreferrer">is an implementation of the W3C DOM API</a> (found implemented in many languages)</li>
<li>differentiates between various Node Types (more control)</li>
<li>much more verbose due to explicit API (can code to an interface)</li>
<li>can parse broken HTML</li>
<li>allows you to use PHP functions in XPath queries</li>
</ul>
<p>Both of these are based on <a href="http://xmlsoft.org/" rel="noreferrer">libxml</a> and can be influenced to some extend by the <a href="http://de2.php.net/manual/en/book.libxml.php" rel="noreferrer">libxml functions</a></p>
<hr>
<p><strong>Personally</strong>, I dont like SimpleXml too much. That's because I dont like the implicit access to the nodes, e.g. <code>$foo->bar[1]->baz['attribute']</code>. It ties the actual XML structure to the programming interface. The one-node-type-for-everything is also somewhat unintuitive because the behavior of the SimpleXmlElement magically changes depending on it's contents. </p>
<p><sup>For instance, when you have <code><foo bar="1"/></code> the object dump of <code>/foo/@bar</code> will be identical to that of <code>/foo</code> but doing an echo of them will print different results. Moreover, because both of them are SimpleXml elements, you can call the same methods on them, but they will only get applied when the SimpleXmlElement supports it, e.g. trying to do <code>$el->addAttribute('foo', 'bar')</code> on the first SimpleXmlElement will do nothing. Now of course it is correct that you cannot add an attribute to an Attribute Node, but the point is, an attribute node would not expose that method in the first place.</sup></p>
<p><strong>But that's just my 2c. Make up your own mind</strong> :)</p>
<hr>
<p>On a <strong>sidenote</strong>, there is not two parsers, but <a href="http://de2.php.net/manual/en/refs.xml.php" rel="noreferrer">a couple more in PHP</a>. SimpleXml and DOM are just the two that parse a document into a tree structure. The others are either pull or event based parsers/readers/writers.</p>
<p>Also see my answer to</p>
<ul>
<li><a href="https://stackoverflow.com/questions/188414/best-xml-parser-for-php/3616044#3616044">Best XML Parser for PHP</a></li>
</ul> |
4,445,173 | When to use NSInteger vs. int | <p>When should I be using <code>NSInteger</code> vs. int when developing for iOS? I see in the Apple sample code they use <code>NSInteger</code> (or <code>NSUInteger</code>) when passing a value as an argument to a function or returning a value from a function.</p>
<pre><code>- (NSInteger)someFunc;...
- (void)someFuncWithInt:(NSInteger)value;...
</code></pre>
<p>But within a function they're just using <code>int</code> to track a value</p>
<pre><code>for (int i; i < something; i++)
...
int something;
something += somethingElseThatsAnInt;
...
</code></pre>
<p>I've read (been told) that <code>NSInteger</code> is a safe way to reference an integer in either a 64-bit or 32-bit environment so why use <code>int</code> at all?</p> | 4,445,199 | 8 | 0 | null | 2010-12-14 23:03:56.437 UTC | 107 | 2019-08-03 20:59:32.89 UTC | 2014-05-27 18:40:53.33 UTC | null | 603,977 | null | 155,513 | null | 1 | 348 | ios|objective-c|types|nsinteger | 136,344 | <p>You usually want to use <code>NSInteger</code> when you don't know what kind of processor architecture your code might run on, so you may for some reason want the largest possible integer type, which on 32 bit systems is just an <code>int</code>, while on a 64-bit system it's a <code>long</code>. </p>
<p>I'd stick with using <code>NSInteger</code> instead of <code>int</code>/<code>long</code> unless you specifically require them.</p>
<p><code>NSInteger</code>/<code>NSUInteger</code> are defined as *dynamic <code>typedef</code>*s to one of these types, and they are defined like this:</p>
<pre><code>#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif
</code></pre>
<p>With regard to the correct format specifier you should use for each of these types, see the <a href="http://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/Strings/Articles/formatSpecifiers.html#//apple_ref/doc/uid/TP40004265-SW5" rel="noreferrer">String Programming Guide's section on Platform Dependencies</a></p> |
4,262,006 | How to use MAMP's version of PHP instead of the default on OSX | <p>I would like to use MAMP's version of PHP instead of the default installed on my mac. I tried using </p>
<p><code>ln -s /Applications/MAMP/bin/php5.3/bin/php php </code></p>
<p>but I get a "File exists" error. What's the best way to work around this so I can just type php instead of the full path?</p> | 4,262,717 | 10 | 0 | null | 2010-11-23 23:15:07.107 UTC | 55 | 2021-06-20 23:21:15.357 UTC | null | null | null | null | 84,387 | null | 1 | 71 | php|mamp|ln | 87,464 | <p>I would not recommend trying to modify the default version of PHP that is called on the command line. Doing so may break other parts of your system as well as provide you with problems in the future, should you decide to upgrade your OS.</p>
<p>There is an alternative that may meet your needs. You can create an alias to your copy of MAMP's php 5.3. In my case I named the alias phpmamp. Open your terminal and type:</p>
<pre><code>alias phpmamp='/Applications/MAMP/bin/php5.3/bin/php'
</code></pre>
<p>Now, typing phpmamp at the command line will launch the MAMP php interperter. Verify this by typing:</p>
<pre><code>phpmamp --help
</code></pre>
<p>You will most likely want to store this, and any other alias, in a <code>~/.bash_profile</code> This will allow the aliases to persist across reboots. Otherwise, the alias should only last for the particular terminal session you are in. More information about creating a <code>.bash_profile</code> file can be found here:</p>
<p><a href="http://www.redfinsolutions.com/redfin-blog/creating-bashprofile-your-mac" rel="noreferrer">http://www.redfinsolutions.com/redfin-blog/creating-bashprofile-your-mac</a></p> |
4,322,367 | I lost my .keystore file? | <p>Ok folks.. long story short, I was developing on a computer that I no longer have access to. I was able to retrieve the source code, but not the .keystore file used to sign and publish my application to the market (with several updates). Am I, and my poor users, out of luck if I ever want to update?</p>
<p>I know the password used to sign the key (at least it is one of three it could be), so can I create another? There must be a way around this.. what about a hard drive fail?</p> | 4,322,386 | 12 | 2 | null | 2010-12-01 08:13:54.583 UTC | 24 | 2021-01-25 08:02:26.513 UTC | 2011-11-21 07:34:43.573 UTC | null | 114,066 | null | 502,630 | null | 1 | 106 | android|keystore|android-sdk-2.1 | 72,725 | <p>Faced the same problem. I was trying to restore it via deleted files restoring tools, but it failed. So, there is no other way: you should issue another application.</p>
<p>Generally, the only advise that exists on keystores: "always back it up!"</p> |
14,700,821 | How to use SQL "LIKE" operator in SLICK | <p>Maybe a silly question. But I have not found an answer so far. So how do you represent the SQL's "LIKE" operator in <strong><a href="http://slick.typesafe.com/">SLICK</a></strong>?</p> | 14,701,190 | 3 | 0 | null | 2013-02-05 05:34:19.68 UTC | 2 | 2021-05-06 18:20:04.317 UTC | 2013-02-05 05:45:53.58 UTC | null | 1,614,955 | null | 1,614,955 | null | 1 | 32 | scala|scalaquery|slick | 13,964 | <p>Exactly as you normally would!</p>
<pre><code>val query = for {
coffee <- Coffees if coffee.name like "%expresso%"
} yield (coffee.name, coffee.price)
</code></pre>
<p>Will generate SQL like</p>
<pre><code>SELECT name, price FROM coffees WHERE NAME like '%expresso%';
</code></pre> |
14,921,668 | Difference between RESTRICT and NO ACTION | <p>From <a href="http://www.postgresql.org/docs/9.2/static/ddl-constraints.html" rel="noreferrer">postgresql documentation</a>:</p>
<blockquote>
<p>RESTRICT prevents deletion of a referenced row. NO ACTION means that if any referencing rows still exist when the constraint is checked, an error is raised; this is the default behavior if you do not specify anything. (The essential difference between these two choices is that NO ACTION allows the check to be <strong>deferred until later in the transaction</strong>, whereas RESTRICT does not.)</p>
</blockquote>
<p>Lets check it.
Create parent and child table:</p>
<pre><code>CREATE TABLE parent (
id serial not null,
CONSTRAINT parent_pkey PRIMARY KEY (id)
);
CREATE TABLE child (
id serial not null,
parent_id serial not null,
CONSTRAINT child_pkey PRIMARY KEY (id),
CONSTRAINT parent_fk FOREIGN KEY (parent_id)
REFERENCES parent (id)
ON DELETE NO ACTION
ON UPDATE NO ACTION
);
</code></pre>
<p>Populate some data:</p>
<pre><code>insert into parent values(1);
insert into child values(5, 1);
</code></pre>
<p>And test does check is really deffered:</p>
<pre><code>BEGIN;
delete from parent where id = 1; -- violates foreign key constraint, execution fails
delete from child where parent_id = 1;
COMMIT;
</code></pre>
<p>After first delete integrity was broken, but after second it would be restored. However, execution fails on first delete.</p>
<p>Same for update:</p>
<pre><code>BEGIN;
update parent set id = 2 where id = 1; -- same as above
update child set parent_id = 2 where parent_id = 1;
COMMIT;
</code></pre>
<p>In case of deletes I can swap statements to make it work, but in case of updates I just can't do them (it is achivable via deleting both rows and inserting new versions).</p>
<p>Many databases don't make any difference between RESTRICT and NO ACTION while postgres pretends to do otherwise. Is it (still) true? </p> | 14,921,697 | 1 | 0 | null | 2013-02-17 13:38:08.993 UTC | 1 | 2013-02-17 14:41:06.513 UTC | 2013-02-17 14:41:06.513 UTC | null | 73,226 | null | 316,563 | null | 1 | 44 | sql|postgresql|postgresql-9.2 | 30,195 | <p>The difference only arises when you define a constraint as <code>DEFERRABLE</code> with an <code>INITIALLY DEFERRED</code> or <code>INITIALLY IMMEDIATE</code> mode. </p>
<p>See <a href="http://www.postgresql.org/docs/current/static/sql-set-constraints.html" rel="noreferrer"><code>SET CONSTRAINTS</code></a>.</p> |
14,862,009 | Make an html number input always display 2 decimal places | <p>I'm making a form where the user can enter a dollar amount using an html number input tag. Is there a way to have the input box always display 2 decimal places?</p> | 22,361,070 | 11 | 2 | null | 2013-02-13 20:00:39.343 UTC | 10 | 2022-01-09 10:01:39.503 UTC | null | null | null | null | 2,069,788 | null | 1 | 53 | html | 218,638 | <p>So if someone else stumbles upon this here is a JavaScript solution to this problem:</p>
<p><strong>Step 1:</strong> Hook your HTML number input box to an <code>onchange</code> event</p>
<pre><code>myHTMLNumberInput.onchange = setTwoNumberDecimal;
</code></pre>
<p>or in the html code if you so prefer</p>
<pre><code><input type="number" onchange="setTwoNumberDecimal" min="0" max="10" step="0.25" value="0.00" />
</code></pre>
<p><strong>Step 2:</strong> Write the setTwoDecimalPlace method</p>
<pre><code>function setTwoNumberDecimal(event) {
this.value = parseFloat(this.value).toFixed(2);
}
</code></pre>
<p>By changing the '2' in <code>toFixed</code> you can get more or less decimal places if you so prefer.</p> |
14,503,381 | Change repo url in TortoiseGit | <p>We just updated our git repos to a new location and I'm using TortoiseGit with some uncommited changes. Can I change the folder reference anywhere? I'm not seeing the option in the context menus. I'd rather not recreate and merge if avoidable since there are about 14 repos in total. I'm not well versed in git so please let me know if the question is flawed as well.</p> | 17,901,695 | 1 | 0 | null | 2013-01-24 14:15:29.543 UTC | 9 | 2016-03-11 22:02:16.5 UTC | 2016-03-11 22:02:16.5 UTC | null | 3,247,152 | null | 702,664 | null | 1 | 61 | tortoisegit | 31,194 | <p>As far as i understand question. Path to change url of remote repository is:</p>
<ul>
<li>Right click on main folder</li>
<li>TortoiseGit</li>
<li>Settings</li>
<li>Git</li>
<li>Remote </li>
<li>In field remote select origin -> url of repository will appear in field URL: and can be changed from here. </li>
</ul>
<p>Uncommited changes can be stashed, or committed locally.</p> |
2,437,005 | bigtable vs cassandra vs simpledb vs dynamo vs couchdb vs hypertable vs riak vs hbase, what do they have in common? | <p>Sorry if this question is somewhat subjective. I am new to 'could store', 'distributed store' or some concepts like this. I really wonder what do they have in common and want to get an overview on all of them. What do I need to prepare if I want to write a product similar to this?</p> | 2,437,067 | 2 | 1 | null | 2010-03-13 02:13:10.197 UTC | 15 | 2011-05-29 02:52:06.813 UTC | null | null | null | null | 115,781 | null | 1 | 23 | couchdb|cassandra|amazon-simpledb|bigtable|hypertable | 19,529 | <p>The <a href="http://nosql-database.org/" rel="noreferrer">NoSQL Database site</a> summarizes the concept like this:</p>
<blockquote>
<p>Next Generation Databases mostly
address some of the points: being
non-relational, distributed,
open-source and horizontal scalable.
The original intention has been modern
web-scale databases. The movement
began early 2009 and is growing
rapidly. Often more characteristics
apply as: schema-free, replication
support, easy API, eventually
consistency, and more. So the
misleading term "nosql" (the community
now translates it mostly with "not
only sql") should be seen as an alias
to something like the definition
above.</p>
</blockquote>
<p>That site also maintains <a href="http://www.slideshare.net/guestdfd1ec/design-patterns-for-distributed-nonrelational-databases" rel="noreferrer">an archive of articles on NoSQL databases</a>. Most of them seem to focus on particular products but there are some more general overviews. If you are serious about building your own one then <a href="http://www.slideshare.net/guestdfd1ec/design-patterns-for-distributed-nonrelational-databases" rel="noreferrer">Design Patterns for Distributed Non-Relational Databases</a> does a good round up of things you need to consider. </p> |
2,534,116 | How to convert getRGB(x,y) integer pixel to Color(r,g,b,a) in Java? | <p>I have the integer pixel I got from <code>getRGB(x,y)</code>, but I don't have any clue about how to convert it to RGBA format. For example, <code>-16726016</code> should be <code>Color(0,200,0,255)</code>. Any tips?</p> | 2,534,131 | 2 | 0 | null | 2010-03-28 19:00:29.39 UTC | 7 | 2019-10-15 22:51:25.267 UTC | 2019-10-15 22:51:25.267 UTC | null | 6,214,491 | null | 162,414 | null | 1 | 31 | java|image|colors | 57,726 | <p>If I'm guessing right, what you get back is an unsigned integer of the form <code>0xAARRGGBB</code>, so</p>
<pre><code>int b = (argb)&0xFF;
int g = (argb>>8)&0xFF;
int r = (argb>>16)&0xFF;
int a = (argb>>24)&0xFF;
</code></pre>
<p>would extract the color components. However, a quick look at the <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Color.html#Color%28int%29" rel="noreferrer">docs</a> says that you can just do</p>
<pre><code>Color c = new Color(argb);
</code></pre>
<p>or </p>
<pre><code>Color c = new Color(argb, true);
</code></pre>
<p>if you want the alpha component in the Color as well.</p>
<p><strong>UPDATE</strong></p>
<p>Red and Blue components are inverted in original answer, so the right answer will be:</p>
<pre><code>int r = (argb>>16)&0xFF;
int g = (argb>>8)&0xFF;
int b = (argb>>0)&0xFF;
</code></pre>
<p><strong>updated also in the first piece of code</strong></p> |
2,538,245 | Extract part of a git repository? | <p>Assume my git repository has the following structure: </p>
<pre><code>/.git
/Project
/Project/SubProject-0
/Project/SubProject-1
/Project/SubProject-2
</code></pre>
<p>and the repository has quite some commits. Now one of the subprojects (SubProject-0) grows pretty big, and I want to take SubProject-0 out and set it up as a standalone project. Is it possible to extract all the commit history involving SubProject-0 from the parent git repository and move it to a new one? </p> | 2,538,259 | 2 | 1 | null | 2010-03-29 13:38:17.1 UTC | 14 | 2013-01-04 17:17:39.18 UTC | null | null | null | null | 184,061 | null | 1 | 33 | git|repository|extraction | 10,761 | <p>See <a href="http://git-scm.com/docs/git-filter-branch" rel="noreferrer">http://git-scm.com/docs/git-filter-branch</a></p>
<p>I think you need something like</p>
<pre><code>git filter-branch --subdirectory-filter Project/SubProject-0 --prune-empty -- --all
</code></pre>
<p>in a clone of the repository.</p> |
45,873,514 | PostgreSQL Hint: You will need to rewrite or cast the expression. column "state" is of type status but expression is of type character varying | <p>I am trying to create a SQL statement using java. The problem is I am using</p>
<pre><code> stmt.setString(9, ev.getState().status());
</code></pre>
<p>for a variable I am trying to insert into a SQL column of type status </p>
<pre><code> CREATE TYPE STATUS AS ENUM ('APPROVED', 'CLOSED','STARTED', 'WAITING');
</code></pre>
<p>It is throwing me an exception of </p>
<pre><code>column "state" is of type status but expression is of type character varying
Hint: You will need to rewrite or cast the expression.
</code></pre>
<p>Did I make a mistake or do I actually need to cast the value in sql? If yes, how does one cast in this situation?</p>
<p>Full Statement:</p>
<pre><code> PreparedStatement stmt = conn.prepareStatement("INSERT INTO Event (EventNum, EventName, startHour, endHour, startMin, endMin, startDate, endDate, State, depName) VALUES (?, ?, ?, ?, ?, ?, ?::date, ?::date, ?, ?)");
stmt.setInt(1, ev.getEventNum());
stmt.setString(2, ev.getName());
stmt.setInt(3, ev.getStartHour());
stmt.setInt(4, ev.getEndHour());
stmt.setInt(5, ev.getStartMinute());
stmt.setInt(6, ev.getEndMinute());
stmt.setString(7, ev.getStartYear() + "-" + ev.getStartMonth() + "-" + ev.getStartDate());
stmt.setString(8, ev.getEndYear() + "-" + ev.getEndMonth() + "-" + ev.getEndDate());
stmt.setString(9, ev.getState().status());
stmt.setString(10, ev.getDepartment());
stmt.executeUpdate();
</code></pre> | 45,874,274 | 4 | 0 | null | 2017-08-25 02:25:42.213 UTC | 4 | 2022-03-18 08:55:16.2 UTC | null | null | null | null | 6,638,412 | null | 1 | 27 | java|postgresql | 71,214 | <p>You are using Prepared Statements - PostgreSQL get info from client side, so parameter is <code>varchar</code> because you are using <code>setString</code> method. You should to inform Postgres, so input datatype is different with explicit cast.</p>
<pre><code>PreparedStatement stmt = conn.prepareStatement(
"INSERT INTO Event (EventNum, EventName, startHour, endHour, startMin, endMin, startDate, endDate, State, depName)
VALUES (?, ?, ?, ?, ?, ?, ?::date, ?::date, ?::status, ?)");
</code></pre>
<p>All data are passed in text form (it is default) - so there are not a problem with passed values. PostgreSQL uses strict type system - and without explicit casting don't allow cast from <code>varchar</code> to <code>date</code>, <code>enum</code>, <code>int</code>, ...</p> |
29,385,564 | Customize templates for `sphinx-apidoc` | <p>I've recently tried using <a href="http://sphinx-doc.org/man/sphinx-apidoc.html" rel="noreferrer">sphinx-apidoc</a> from <a href="http://sphinx-doc.org/" rel="noreferrer">Sphinx</a> to help generate Sphinx specific reStructuredText from the API of a Python project.</p>
<p>However, the result I'm getting is:</p>
<p><img src="https://i.stack.imgur.com/EVMje.png" alt="Default look of <code>sphinx-api</code> result"></p>
<p>Anyone know if I can customize the template <code>sphinx-api</code> uses for its output? Specifically, I'd like to:</p>
<ul>
<li>Get rid of all the "Submodules", "Subpackages" and "Module contents" headings, and</li>
<li>Have the results from docstring in my <code>__init__.py</code> files appear directly under the packages, so that if I click a package name, the first thing I see is the package documentation. At the moment, this documentation is placed under the slightly weird "Module contents" heading at the very end of each package section.</li>
</ul>
<p>The "Submodules" and "Subpackages" headings are redundant I think, since the normal headings for packages/modules is "xxx.yyy package" and "xxx.yyy.zzz module".</p>
<p>The structure I would like for the above small example is</p>
<ul>
<li>orexplore.components package
<ul>
<li>orexplore.components.mbg120 module</li>
</ul></li>
<li>orexplore.simulators package
<ul>
<li>orexplore.simulators.test package
<ul>
<li>orexplore.simulators.test.mbg120 module</li>
</ul></li>
<li>orexplore.simulators.mbg120 module</li>
</ul></li>
</ul>
<p>Where clicking the packages, the first thing I'd see on the page would be the package documentation.</p>
<p>Or maybe even just</p>
<ul>
<li>orexplore.components
<ul>
<li>orexplore.components.mbg120</li>
</ul></li>
<li>orexplore.simulators
<ul>
<li>orexplore.simulators.test
<ul>
<li>orexplore.simulators.test.mbg120</li>
</ul></li>
</ul></li>
<li>orexplore.simulators.mbg120</li>
</ul>
<p>if there was some way to visually distinguish packages/modules (color? emblem?) instead of the quite wordy " package" and " module".</p> | 29,510,518 | 3 | 0 | null | 2015-04-01 07:53:56.017 UTC | 8 | 2019-10-25 07:53:05.54 UTC | null | null | null | null | 252,857 | null | 1 | 18 | python|python-sphinx | 8,027 | <p>The <strong>sphinx-apidoc</strong> script uses the <a href="https://github.com/sphinx-doc/sphinx/blob/master/sphinx/apidoc.py" rel="nofollow noreferrer">apidoc.py</a> module. I am not able to provide detailed instructions, but in order to remove headings or otherwise customize the output, you'll have to write your own version of this module. There is no other "template".</p>
<p>Note that if the API and module structure is stable, there is no need to run sphinx-apidoc repeatedly. You can post-process the generated rst files to your liking <em>once</em> and then place them under version control. See also <a href="https://stackoverflow.com/a/28481785/407651">https://stackoverflow.com/a/28481785/407651</a>.</p>
<h3>Update</h3>
<p>From Sphinx 2.2.0, sphinx-apidoc supports templates. See <a href="https://stackoverflow.com/a/57520238/407651">https://stackoverflow.com/a/57520238/407651</a>.</p> |
44,915,831 | how to use NodeJS pop up a alert window in browser | <p>I'm totally new to Javascript and I'm wondering how to use node js to pop up a alert window in browser, after sever(Nodejs) received post message from front end?
Do I need to use Ajax?</p> | 44,916,227 | 4 | 0 | null | 2017-07-05 01:31:17.66 UTC | 3 | 2022-02-20 13:51:08.403 UTC | null | null | null | null | 8,210,700 | null | 1 | 5 | node.js | 80,501 | <p>"after sever(Nodejs) received post message from front end?" show a pop up in the browser. This can not be done. I assume you want to show a popup in if the post request is success. Because you mention about Ajax, This is how it is done.<br></p>
<p>in your post router definition in the server do it as follows </p>
<pre><code>router.post('/path', function(req, res){
//do something
res.jsonp({success : true})
});
</code></pre>
<p>something like this. finally you want to send something form the server to the client. after in the client side javascript file send the post request as follows.</p>
<pre><code>$.ajax({
url:"/url/is/here",
method: "POST",
data : {
data : "what you want to send",
put : "them here"
},
cache : false,
success : function (data) {
// data is the object that you send form the server by
// res.jsonp();
// here data = {success : true}
// validate it
if(data['success']){
alert("message you want to show");
}
},
error : function () {
// some error handling part
alert("Oops! Something went wrong.");
}
});
</code></pre> |
28,311,030 | Check Jenkins job status after triggering a build remotely | <p>I have a script to trigger a job on Jenkins remotely using a token. Here is my script:</p>
<pre><code>JENKINS_URL='http://jenkins.myserver.com/jenkins'
JOB_NAME='job/utilities/job/my_job'
JOB_TOKEN='my_token'
curl "${JENKINS_URL}/${JOB_NAME}/buildWithParameters?token=${JOB_TOKEN}"
</code></pre>
<p><strong>After I run it, I get following response:</strong></p>
<pre><code>* Hostname was NOT found in DNS cache
* Trying 10.5.187.225...
* Connected to jenkins.myserver.com (10.5.187.225) port 80 (#0)
> GET /jenkins/job/utilities/job/my_job/buildWithParameters?token=my_token HTTP/1.1
> User-Agent: curl/7.37.1
> Host: jenkins.myserver.com
> Accept: */*
>
< HTTP/1.1 201 Created
* Server nginx/1.6.2 is not blacklisted
< Server: nginx/1.6.2
< Date: Tue, 03 Feb 2015 23:40:47 GMT
< Content-Length: 0
< Location: http://jenkins.myserver.com/jenkins/queue/item/91/
< Connection: keep-alive
< Cache-Control: private
< Expires: Wed, 31 Dec 1969 16:00:00 PST
<
* Connection #0 to host jenkins.myserver.com left intact
</code></pre>
<p>I noticed that it returns the queue url in the header: <a href="http://jenkins.myserver.com/jenkins/queue/item/91" rel="noreferrer">http://jenkins.myserver.com/jenkins/queue/item/91</a>. But I don't know how I should use this return url.</p>
<p>1) I am wondering if anyone knows how I can check the status for the job that I just created?</p>
<p>2) Since the above response does not return the job #, I can't really use this api call: </p>
<pre><code>curl http://jenkins.myserver.com/jenkins/job/utilities/job/my_job/8/api/json
</code></pre>
<p>to check for status. So where can I get the job name and job number after I get the location url from the above response?</p>
<p>Thanks</p> | 28,329,691 | 6 | 0 | null | 2015-02-03 23:51:36.203 UTC | 9 | 2022-05-15 05:57:13.31 UTC | 2016-02-17 14:02:11.517 UTC | null | 1,827,433 | null | 1,881,450 | null | 1 | 27 | jenkins|build|jenkins-plugins|jenkins-cli | 76,067 | <p>When you trigger a job, the job is placed into the queue. The actual build is created only when it starts running and at that point the build gets a build number. If all your executors are busy, it can sometimes take a long time before the build is created and starts running.</p>
<p>The only way to get the build number when triggering a job, is to use the "build" command of the <a href="https://wiki.jenkins-ci.org/display/JENKINS/Jenkins+CLI" rel="nofollow noreferrer">Jenkins CLI</a>. If you use the -w option, the command will not return until the build starts and then it will print "Started build #N"</p>
<p>You do not actually need the java cli.jar, just an ssh client is enough. See <a href="https://wiki.jenkins-ci.org/display/JENKINS/Jenkins+SSH" rel="nofollow noreferrer">https://wiki.jenkins-ci.org/display/JENKINS/Jenkins+SSH</a></p>
<p>Other than that there is no known solution. You might be able to search through the builds and find a one that was triggered around the time your triggered the job, but that's a lot of work.</p> |
22,695,145 | WPF Change Background color of a Combobox | <p>In my WPF app I just want to change the background color of the Combo box. I don't mean the dropdown, I want is just whatever item is selected a background is set.
Like setting the background of a button - when the control is displayed on screen it should have LightYellow background. That's it.
I searched a lot on net, but everywhere could find solutions for drop down background colors. I tried applying SolidColorBrush and Style.Triggers to the TextBlock of Combobox, but no success as wanted. By adding SolidColorBrush lines, I got my dropdown background set, but that's not what I am looking for. My code is :</p>
<pre><code><ComboBox ItemsSource="{Binding MtrCm}" SelectedValue="{Binding WellboreDiameter_Unit, Mode=TwoWay}" Grid.Row="1" Height="23" HorizontalAlignment="Right" Margin="0,26,249,0" x:Name="cboWellDiameter" VerticalAlignment="Top" Width="120" Background="LightYellow" >
<ComboBox.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.WindowBrushKey}" Color="Yellow" />
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Yellow" />
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Yellow" />
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ComboBoxItem}}" Value="True">
<Setter Property="Background" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.Resources>
</ComboBox>
</code></pre>
<p>Can anyone help me set he background of the desired component that am looking for.</p>
<p>Thanks</p> | 22,696,386 | 6 | 0 | null | 2014-03-27 17:37:20.113 UTC | 7 | 2021-01-30 14:24:44.157 UTC | 2017-07-24 11:05:13.497 UTC | null | 4,761,806 | null | 455,979 | null | 1 | 32 | c#|wpf|combobox|background-color | 82,219 | <p>Try this</p>
<pre><code> <Window.Resources> //Put this resourse n Window.Resources or UserControl.Resources
<LinearGradientBrush x:Key="NormalBrush" StartPoint="0,0" EndPoint="0,1">
<GradientBrush.GradientStops>
<GradientStopCollection>
<GradientStop Color="#FFDC3939" Offset="0.0"/>
<GradientStop Color="#FFE80E0E" Offset="1.0"/>
</GradientStopCollection>
</GradientBrush.GradientStops>
</LinearGradientBrush>
<SolidColorBrush x:Key="WindowBackgroundBrush" Color="#FFFBE618" />
<ControlTemplate x:Key="ComboBoxToggleButton" TargetType="ToggleButton">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="20" />
</Grid.ColumnDefinitions>
<Border x:Name="Border" Grid.ColumnSpan="2" CornerRadius="2"
Background="{StaticResource NormalBrush}"
BorderThickness="1" />
<Border
Grid.Column="0"
CornerRadius="2,0,0,2"
Margin="1"
Background="{StaticResource WindowBackgroundBrush}"
BorderThickness="0,0,1,0" />
<Path
x:Name="Arrow"
Grid.Column="1"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Data="M 0 0 L 4 4 L 8 0 Z"/>
</Grid>
</ControlTemplate>
<ControlTemplate x:Key="ComboBoxTextBox" TargetType="TextBox">
<Border x:Name="PART_ContentHost" Focusable="False" Background="{TemplateBinding Background}" />
</ControlTemplate>
<Style x:Key="{x:Type ComboBox}" TargetType="ComboBox">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ComboBox">
<Grid>
<ToggleButton
Name="ToggleButton"
Template="{StaticResource ComboBoxToggleButton}"
Grid.Column="2"
Focusable="false"
IsChecked="{Binding Path=IsDropDownOpen,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}"
ClickMode="Press">
</ToggleButton>
<ContentPresenter
Name="ContentSite"
IsHitTestVisible="False"
Margin="3,3,23,3"
VerticalAlignment="Center"
HorizontalAlignment="Left" />
<TextBox x:Name="PART_EditableTextBox"
Style="{x:Null}"
Template="{StaticResource ComboBoxTextBox}"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Margin="3,3,23,3"
Focusable="True"
Background="Transparent"
Visibility="Hidden"
IsReadOnly="{TemplateBinding IsReadOnly}"/>
<Popup
Name="Popup"
Placement="Bottom"
IsOpen="{TemplateBinding IsDropDownOpen}"
AllowsTransparency="True"
Focusable="False"
PopupAnimation="Slide">
<Grid
Name="DropDown"
SnapsToDevicePixels="True"
MinWidth="{TemplateBinding ActualWidth}"
MaxHeight="{TemplateBinding MaxDropDownHeight}">
<Border
x:Name="DropDownBorder"
Background="{StaticResource WindowBackgroundBrush}"
BorderThickness="1"/>
<ScrollViewer Margin="4,6,4,6" SnapsToDevicePixels="True">
<StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" />
</ScrollViewer>
</Grid>
</Popup>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<ComboBox HorizontalAlignment="Left" Margin="256,57,0,0" VerticalAlignment="Top" Width="120">
</ComboBox>
</Grid>
</code></pre>
<p>Here is the complete style that you can change : <a href="http://msdn.microsoft.com/en-us/library/ms752094%28v=VS.85%29.aspx">http://msdn.microsoft.com/en-us/library/ms752094%28v=VS.85%29.aspx</a></p> |
34,000,074 | pandas - return column of exponential values | <p>Starting from a sample dataframe <code>df</code> like:</p>
<pre><code>a,b
0,0.71
1,0.75
2,0.80
3,0.90
</code></pre>
<p>I would add a new column with exponential values of column <code>b</code>. So far I tried:</p>
<pre><code>df['exp'] = math.exp(df['b'])
</code></pre>
<p>but this method returns:</p>
<pre><code>"cannot convert the series to {0}".format(str(converter)"
TypeError: cannot convert the series to <type 'float'>
</code></pre>
<p>Is there a way to apply a <code>math</code> function to a whole column?</p> | 34,000,104 | 2 | 0 | null | 2015-11-30 13:44:38.817 UTC | 2 | 2019-02-11 17:10:14.69 UTC | null | null | null | null | 2,699,288 | null | 1 | 11 | python|pandas | 39,430 | <p>Well <code>math.exp</code> doesn't understand <code>Series</code> datatype, use numpy <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.exp.html" rel="noreferrer"><code>np.exp</code></a> which does and is vectorised so operates on the entire column:</p>
<pre><code>In [24]:
df['exp'] = np.exp(df['b'])
df
Out[24]:
a b exp
0 0 0.71 2.033991
1 1 0.75 2.117000
2 2 0.80 2.225541
3 3 0.90 2.459603
</code></pre> |
38,938,887 | How to open Visual Studio Code with admin privileges to make effect of the installed extensions | <p>I have Ubuntu 16.04 and I have to download the C# extension for Visual Studio Code, once I installed it, It doesn't make effect. Then, vscode give me and advice that I should open vscode with admin privileges to make effect of the extensions installed, so I wrote on my terminal: </p>
<p><code>sudo code .</code></p>
<p>but it doesn't work, the terminal throws me:</p>
<p><code>It is recommended to start vscode as a normal user. To run as root, you must specify an alternate user data directory with the --user-data-dir argument.
</code></p>
<p>but I don't know how to specify an alternate user data directory. I was searching how to do that in visual studio code docs but there is not a reference for this issue. If you know how to open with admin privileges in linux please help me.</p> | 38,940,160 | 6 | 1 | null | 2016-08-14 03:32:17.757 UTC | 7 | 2021-09-26 21:54:32.13 UTC | 2019-04-23 15:00:47.13 UTC | null | 2,756,409 | null | 3,757,533 | null | 1 | 20 | c#|linux|visual-studio-code | 74,711 | <p>To run with superuser:</p>
<pre><code>$ sudo code --user-data-dir=~/root
</code></pre>
<p>By the way you will be able to run without setting params in the upcoming patch 1.5.0.</p> |
38,889,121 | Give Button and Text on the same line and text to be center of button | <pre><code><input type="button" class="click" id="click" value="Click" style="width: 45px; margin-top: 1.5%; height: 20px; text-align: center; color: white; background: #23b7e5; font-size: 13px; border-color: #23b7e5; border-radius:2px; padding: 0px; ">
<label class="control-label" style="border: thin red solid; margin-top: 10px;">Here to find location</label>
</code></pre>
<p>I want button and text box in the same line which i got but i am not getting text to be center of button. I get this output. I want "Here to find location" to be center of button.</p>
<p>Thank You.
Any help would be grateful.</p>
<p><a href="https://i.stack.imgur.com/Zot2U.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zot2U.png" alt=""></a></p> | 38,889,205 | 3 | 2 | null | 2016-08-11 06:46:31.133 UTC | 1 | 2016-08-11 07:29:33.057 UTC | null | null | null | null | 4,644,335 | null | 1 | 4 | html|css|display | 41,649 | <p><code>display: inline-block</code> and <code>vertical-align:middle</code> will do the trick.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>input, label{
display: inline-block;
vertical-align: middle;
margin: 10px 0;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="button" class="click" id="click" value="Click" style="width: 45px; height: 20px; text-align: center; color: white; background: #23b7e5; font-size: 13px; border-color: #23b7e5; border-radius:2px; padding: 0px; ">
<label class="control-label" style="border: thin red solid;">Here to find location</label></code></pre>
</div>
</div>
</p> |
31,264,148 | FATAL ERROR in native method: JDWP No transports initialized error while starting hybris server in debug mode | <p>While trying to start my <code>hybrisserver</code> in debug mode I got the following error messages and <code>hybrisserver</code> stopped. I tried but not able to solve. Any help please.</p>
<pre><code>FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)<br/>
ERROR: transport error 202: bind failed: Permission denied<br/>
ERROR: JDWP Transport dt_socket failed to initialize, TRANSPORT_INIT(510)<br/>
JDWP exit error AGENT_ERROR_TRANSPORT_INIT(197): No transports initialized [../../../src/share/back/debugInit.c:750]<br/>
JVM exited while loading the application.<br/>
Reloading Wrapper configuration...<br/>
Launching a JVM...<br/>
FATAL ERROR in native method: JDWP No transports initialized, jvmtiError=AGENT_ERROR_TRANSPORT_INIT(197)<br/>
ERROR: transport error 202: bind failed: Permission denied<br/>
ERROR: JDWP Transport dt_socket failed to initialize, TRANSPORT_INIT(510)<br/>
JDWP exit error AGENT_ERROR_TRANSPORT_INIT(197): No transports initialized [../../../src/share/back/debugInit.c:750]<br/>
JVM exited while loading the application.<br/>
</code></pre>
<p>There were 5 failed launches in a row, each lasting less than 300 seconds. <br/> Giving up.<br/>
There may be a configuration problem: please check the logs.<br/></p>
<pre><code><-- Wrapper Stopped<br/>
</code></pre>
<p>An error occurred in the process.</p> | 31,297,836 | 3 | 0 | null | 2015-07-07 09:01:23.333 UTC | 3 | 2017-03-25 15:57:30.653 UTC | 2016-04-07 18:05:50.92 UTC | null | 2,293,534 | null | 2,064,841 | null | 1 | 8 | sap-commerce-cloud | 48,791 | <p>@thijsraets is correct. Either you have to check where is the port (8000) has been occupied or you can override the default value to something else in local.properties file.</p>
<pre><code>tomcat.debugjavaoptions=-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,address=8001,suspend=n
</code></pre>
<p>Run "ant all". This will configure debug for port 8001.</p>
<p>OR</p>
<p>You can change the JVM parameters in wrapper-debug.conf file... </p>
<pre><code>wrapper.java.additional.23=-Xrunjdwp:transport=dt_socket,server=y,address=8001,suspend=n
</code></pre> |
5,804,226 | Get a histogram plot of factor frequencies (summary) | <p>I've got a factor with many different values. If you execute <code>summary(factor)</code> the output is a list of the different values and their frequency. Like so:</p>
<pre><code>A B C D
3 3 1 5
</code></pre>
<p>I'd like to make a histogram of the frequency values, i.e. X-axis contains the different frequencies that occur, Y-axis the number of factors that have this particular frequency. What's the best way to accomplish something like that?</p>
<p>edit: thanks to the answer below I figured out that what I can do is get the factor of the frequencies out of the table, get that in a table and then graph that as well, which would look like (if <code>f</code> is the factor):</p>
<pre><code>plot(factor(table(f)))
</code></pre> | 5,804,454 | 1 | 0 | null | 2011-04-27 12:38:30.877 UTC | 7 | 2011-09-11 06:13:57.317 UTC | 2011-09-11 06:13:57.317 UTC | null | 321,143 | null | 10,098 | null | 1 | 20 | r|plot|histogram|frequency-distribution | 53,710 | <p><strong>Update in light of clarified Q</strong></p>
<pre><code>set.seed(1)
dat2 <- data.frame(fac = factor(sample(LETTERS, 100, replace = TRUE)))
hist(table(dat2), xlab = "Frequency of Level Occurrence", main = "")
</code></pre>
<p>gives:</p>
<p><img src="https://i.stack.imgur.com/s3Ci3.png" alt="histogram of frequency of occurrence in factor"></p>
<p>Here we just apply <code>hist()</code> directly to the result of <code>table(dat)</code>. <code>table(dat)</code> provides the frequencies per level of the factor and <code>hist()</code> produces the histogram of these data.</p>
<hr>
<p><strong>Original</strong></p>
<p>There are several possibilities. Your data:</p>
<pre><code>dat <- data.frame(fac = rep(LETTERS[1:4], times = c(3,3,1,5)))
</code></pre>
<p>Here are three, from column one, top to bottom:</p>
<ul>
<li>The default plot methods for class <code>"table"</code>, plots the data and histogram-like bars</li>
<li>A bar plot - which is probably what you meant by histogram. Notice the low ink-to-information ratio here</li>
<li>A dot plot or dot chart; shows the same info as the other plots but uses far less ink per unit information. Preferred.</li>
</ul>
<p>Code to produce them:</p>
<pre><code>layout(matrix(1:4, ncol = 2))
plot(table(dat), main = "plot method for class \"table\"")
barplot(table(dat), main = "barplot")
tab <- as.numeric(table(dat))
names(tab) <- names(table(dat))
dotchart(tab, main = "dotchart or dotplot")
## or just this
## dotchart(table(dat))
## and ignore the warning
layout(1)
</code></pre>
<p>this produces:</p>
<p><img src="https://i.stack.imgur.com/KEYYv.png" alt="one dimensional plots"></p>
<p>If you just have your data in variable <code>factor</code> (bad name choice by the way) then <code>table(factor)</code> can be used rather than <code>table(dat)</code> or <code>table(dat$fac)</code> in my code examples.</p>
<p>For completeness, package <code>lattice</code> is more flexible when it comes to producing the dot plot as we can get the orientation you want:</p>
<pre><code>require(lattice)
with(dat, dotplot(fac, horizontal = FALSE))
</code></pre>
<p>giving:</p>
<p><img src="https://i.stack.imgur.com/Axnu2.png" alt="Lattice dotplot version"></p>
<p>And a <code>ggplot2</code> version:</p>
<pre><code>require(ggplot2)
p <- ggplot(data.frame(Freq = tab, fac = names(tab)), aes(fac, Freq)) +
geom_point()
p
</code></pre>
<p>giving:</p>
<p><img src="https://i.stack.imgur.com/nXkjV.png" alt="ggplot2 version"></p> |
24,565,589 | Can I pass default value to rails generate migration? | <p>I want to know if I can pass <strong>a default value</strong> to the <code>rails g migration</code> command. Something like:</p>
<pre><code> $ rails generate migration add_disabled_to_users disabled:boolean:false #where false is default value for disabled attribute
</code></pre>
<p>in order to generate:</p>
<pre><code>class AddDisabledToUsers < ActiveRecord::Migration
def change
add_column :users, :disabled, :boolean, default: false
end
end
</code></pre> | 24,565,933 | 4 | 0 | null | 2014-07-04 01:41:50.353 UTC | 6 | 2020-12-26 08:36:38.96 UTC | null | null | null | null | 1,329,461 | null | 1 | 44 | ruby-on-rails|ruby-on-rails-3|rails-migrations | 35,604 | <p>You can't: <a href="https://guides.rubyonrails.org/active_record_migrations.html#column-modifiers" rel="noreferrer">https://guides.rubyonrails.org/active_record_migrations.html#column-modifiers</a></p>
<blockquote>
<p>null and default cannot be specified via command line.</p>
</blockquote>
<p>The only solution is to modify the migration after it's generated. It was the case in Rails 3, still the case in Rails 6</p> |
24,735,311 | What does the slash mean in help() output? | <p>What does the <code>/</code> mean in Python 3.4's <code>help</code> output for <code>range</code> before the closing parenthesis?</p>
<pre><code>>>> help(range)
Help on class range in module builtins:
class range(object)
| range(stop) -> range object
| range(start, stop[, step]) -> range object
|
| Return a virtual sequence of numbers from start to stop by step.
|
| Methods defined here:
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
...
</code></pre> | 24,735,582 | 3 | 0 | null | 2014-07-14 11:15:32.82 UTC | 52 | 2020-06-21 17:35:29.633 UTC | 2020-06-21 17:35:29.633 UTC | null | 4,518,341 | null | 209,019 | null | 1 | 250 | python|python-3.x|parameters|introspection | 42,772 | <p>It signifies the end of the <a href="http://www.python.org/dev/peps/pep-0436/#functions-with-positional-only-parameters" rel="noreferrer"><em>positional only</em> parameters</a>, parameters you <em>cannot</em> use as keyword parameters. Before Python 3.8, such parameters could only be specified in the C API.</p>
<p>It means the <code>key</code> argument to <code>__contains__</code> can only be passed in by position (<code>range(5).__contains__(3)</code>), not as a keyword argument (<code>range(5).__contains__(key=3)</code>), something you <em>can</em> do with positional arguments in pure-python functions.</p>
<p>Also see the <a href="https://docs.python.org/3/howto/clinic.html" rel="noreferrer">Argument Clinic</a> documentation:</p>
<blockquote>
<p>To mark all parameters as positional-only in Argument Clinic, add a <code>/</code> on a line by itself after the last parameter, indented the same as the parameter lines.</p>
</blockquote>
<p>and the (very recent addition to) the <a href="https://docs.python.org/3/faq/programming.html#what-does-the-slash-in-the-parameter-list-of-a-function-mean" rel="noreferrer">Python FAQ</a>:</p>
<blockquote>
<p>A slash in the argument list of a function denotes that the parameters prior to it are positional-only. Positional-only parameters are the ones without an externally-usable name. Upon calling a function that accepts positional-only parameters, arguments are mapped to parameters based solely on their position.</p>
</blockquote>
<p>The syntax is now part of the Python language specification, <a href="https://docs.python.org/3.8/whatsnew/3.8.html#positional-only-parameters" rel="noreferrer">as of version 3.8</a>, see <a href="https://www.python.org/dev/peps/pep-0570/" rel="noreferrer">PEP 570 – <em>Python Positional-Only Parameters</em></a>. Before PEP 570, the syntax was already reserved for possible future inclusion in Python, see <a href="https://www.python.org/dev/peps/pep-0457/" rel="noreferrer">PEP 457 - <em>Syntax For Positional-Only Parameters</em></a>. </p>
<p>Positional-only parameters can lead to cleaner and clearer APIs, make pure-Python implementations of otherwise C-only modules more consistent and easier to maintain, and because positional-only parameters require very little processing, they lead to faster Python code.</p> |
53,020,792 | How to set width of mat-table column in angular? | <p>Here in my mat-table have 6 column when any column has not more words then it looks like Image-1, but when any column has more words then UI looks like Image-2, so how to set UI like Image-1 when any column has more words in angular 6 ?</p>
<p>Image-1</p>
<p><a href="https://i.stack.imgur.com/LIoMd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LIoMd.png" alt="enter image description here"></a></p>
<p>Image-2</p>
<p><a href="https://i.stack.imgur.com/IvoBn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/IvoBn.png" alt="enter image description here"></a></p>
<p>user.component.html</p>
<pre><code><div class="mat-elevation-z8">
<table mat-table [dataSource]="dataSource">
<ng-container matColumnDef="userimage">
<th mat-header-cell *matHeaderCellDef> # </th>
<td mat-cell *matCellDef="let element">
<img src="{{commonUrlObj.commonUrl}}/images/{{element.userimage}}" style="height: 40px;width: 40px;"/>
</td>
</ng-container>
<ng-container matColumnDef="username">
<th mat-header-cell *matHeaderCellDef> Full Name </th>
<td mat-cell *matCellDef="let element"> {{element.username}} ( {{element.usertype}} )</td>
</ng-container>
<ng-container matColumnDef="emailid">
<th mat-header-cell *matHeaderCellDef> EmailId </th>
<td mat-cell *matCellDef="let element"> {{element.emailid}} </td>
</ng-container>
<ng-container matColumnDef="contactno">
<th mat-header-cell *matHeaderCellDef> Contact No. </th>
<td mat-cell *matCellDef="let element"> {{element.contactno}} </td>
</ng-container>
<ng-container matColumnDef="enabled">
<th mat-header-cell *matHeaderCellDef> Enabled </th>
<td mat-cell *matCellDef="let element" style="color: blue">
<ng-container *ngIf="element.enabled == 'true'; else otherss">Enabled</ng-container>
<ng-template #otherss>Disabled</ng-template>
</td>
</ng-container>
<ng-container matColumnDef="action">
<th mat-header-cell *matHeaderCellDef> Action </th>
<td mat-cell *matCellDef="let element" fxLayoutGap="5px">
<button mat-mini-fab color="primary" routerLink="/base/editUserDetails/{{element.userid}}"><mat-icon>edit</mat-icon></button>
<button mat-mini-fab color="primary" routerLink="/base/viewUserDetails/{{element.userid}}"><mat-icon>pageview</mat-icon></button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
<mat-paginator [pageSizeOptions]="[5, 10, 20, 50 ,100]" showFirstLastButtons></mat-paginator>
</code></pre>
<p> </p> | 53,321,457 | 14 | 0 | null | 2018-10-27 10:06:10.463 UTC | 28 | 2022-02-24 22:20:18.763 UTC | 2019-01-29 11:02:29.593 UTC | null | 10,179,287 | null | 10,179,287 | null | 1 | 143 | html|css|angular|angular-material | 304,975 | <p>using css we can adjust specific column width which i put in below code.</p>
<p>user.component.css</p>
<pre><code>table{
width: 100%;
}
.mat-column-username {
word-wrap: break-word !important;
white-space: unset !important;
flex: 0 0 28% !important;
width: 28% !important;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: break-word;
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;
}
.mat-column-emailid {
word-wrap: break-word !important;
white-space: unset !important;
flex: 0 0 25% !important;
width: 25% !important;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: break-word;
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;
}
.mat-column-contactno {
word-wrap: break-word !important;
white-space: unset !important;
flex: 0 0 17% !important;
width: 17% !important;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: break-word;
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;
}
.mat-column-userimage {
word-wrap: break-word !important;
white-space: unset !important;
flex: 0 0 8% !important;
width: 8% !important;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: break-word;
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;
}
.mat-column-userActivity {
word-wrap: break-word !important;
white-space: unset !important;
flex: 0 0 10% !important;
width: 10% !important;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: break-word;
-ms-hyphens: auto;
-moz-hyphens: auto;
-webkit-hyphens: auto;
hyphens: auto;
}
</code></pre> |
37,741,841 | fetch more than 20 rows and display full value of column in spark-shell | <p>I am using <code>CassandraSQLContext</code> from spark-shell to query data from Cassandra. So, I want to know two things one how to fetch more than 20 rows using <code>CassandraSQLContext</code> and second how do Id display the full value of column. As you can see below by default it append dots in the string values. </p>
<p>Code :</p>
<pre><code>val csc = new CassandraSQLContext(sc)
csc.setKeyspace("KeySpace")
val maxDF = csc.sql("SQL_QUERY" )
maxDF.show
</code></pre>
<p>Output:</p>
<pre><code>+--------------------+--------------------+-----------------+--------------------+
| id| Col2| Col3| Col4|
+--------------------+--------------------+-----------------+--------------------+
|8wzloRMrGpf8Q3bbk...| Value1| X| K1|
|AxRfoHDjV1Fk18OqS...| Value2| Y| K2|
|FpMVRlaHsEOcHyDgy...| Value3| Z| K3|
|HERt8eFLRtKkiZndy...| Value4| U| K4|
|nWOcbbbm8ZOjUSNfY...| Value5| V| K5|
</code></pre> | 37,743,170 | 2 | 0 | null | 2016-06-10 06:59:08.617 UTC | 4 | 2019-08-07 06:41:51.327 UTC | 2019-08-07 06:41:51.327 UTC | null | 3,415,409 | null | 2,135,526 | null | 1 | 36 | scala|apache-spark|pyspark|apache-spark-sql | 87,663 | <p>If you want to print the whole value of a column, in <strong>scala</strong>, you just need to set the argument truncate from the <code>show</code> method to <code>false</code> :</p>
<pre><code>maxDf.show(false)
</code></pre>
<p>and if you wish to show more than 20 rows : </p>
<pre><code>// example showing 30 columns of
// maxDf untruncated
maxDf.show(30, false)
</code></pre>
<p>For <strong>pyspark</strong>, you'll need to specify the argument name :</p>
<pre><code>maxDF.show(truncate = False)
</code></pre> |
51,967,866 | Visual Studio 15.8.1 not running MS unit tests | <p>When I updated Visual Studio to the latest version, 1 of my test projects stopped running tests and outputted this message:</p>
<blockquote>
<p>Test project {} does not reference any .NET NuGet adapter. Test
discovery or execution might not work for this project. It is
recommended to reference NuGet test adapters in each test project in
the solution.</p>
</blockquote>
<p>UPDATED: I was using MS Test as opposed to any other test frameworks like Nunit or Xunit.</p> | 51,967,880 | 12 | 0 | null | 2018-08-22 13:20:12.563 UTC | 11 | 2021-11-04 20:38:09.473 UTC | 2021-08-23 13:29:33.733 UTC | null | 542,251 | null | 2,427,755 | null | 1 | 61 | c#|visual-studio|mstest | 36,162 | <p>I had to add the following Nuget packages:</p>
<pre><code>MSTest.TestAdapter
MSTest.TestFramework
Microsoft.NET.Test.Sdk
</code></pre>
<p><a href="https://docs.microsoft.com/en-us/visualstudio/releasenotes/vs2017-relnotes#testadapterextension" rel="noreferrer">Visual Studio release notes</a></p> |
47,726,929 | "Type error: Too few arguments to function App\Http\Controllers\UserController::attendance(), 0 passed and exactly 1 expected" | <p><strong>I have two table in my database which are user and the attendance table. What I want to do now is I want to show the attendance data from database according to the user in their attendance view which is linked with their profile. This is my attendance function in the userController.</strong></p>
<pre><code> public function attendance($id)
{
$user = UserProfile::findOrFail($id);
$this->authorize('modifyUser', $user);
return view ('user.attendance', ['user'=>$user]);
}
</code></pre>
<p><em>This is my route to attendance view.</em></p>
<pre><code>Route::get('/attendance/', ['as' => 'user.attendance', 'uses' => 'UserController@attendance']);
</code></pre>
<p><em>This is my attendance view.</em></p>
<pre><code>@extends('layouts.app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-12">
<h1><i class="fa fa-university"></i> Attendance</h1>
</div>
<div class="row">
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Date</th>
<th>Time</th>
<th>Present</th>
</tr>
<?php $no=1; ?>
<tr>
<td>{{ $no++ }}</td>
<td>{{$user->attendance->date}}</td>
<td>{{$user->attendance->time}}</td>
<td>{{$user->attendance->present}}</td>
</tr>
</table>
</div>
</div>
</div>
@stop
</code></pre>
<p><em>This is the error that i got.</em>
Type error: Too few arguments to function App\Http\Controllers\UserController::attendance(), 0 passed and exactly 1 expected".
<strong>I am new to laravel.</strong></p> | 47,726,951 | 1 | 1 | null | 2017-12-09 08:52:57.34 UTC | null | 2021-06-15 13:05:38.42 UTC | null | null | null | user8062999 | null | null | 1 | 7 | php|laravel | 89,448 | <p>You're getting this error because <code>attendance()</code> method expects an ID and you don't pass it. Change the route to:</p>
<pre><code>Route::get('attendance/{id}', ['as' => 'user.attendance', 'uses' => 'UserController@attendance']);
</code></pre>
<p>And pass an ID when creating a link to the <code>attendance()</code> method:</p>
<pre><code>{{ route('user.attendance', ['id' => 1]) }}
</code></pre>
<p>Or:</p>
<pre><code>{{ url('attendance/1') }}
</code></pre>
<p>If you want to get ID of currently logged in user, do not pass ID. Use <code>auth()-user()</code> instead:</p>
<pre><code>public function attendance()
{
$this->authorize('modifyUser', auth()->user());
return view ('user.attendance');
}
</code></pre> |
24,646,165 | NETSH port forwarding from local port to local port not working | <p>I'm trying to use NETSH PORTPROXY command to forward packets sent to my XP PC (IP <code>192.168.0.10</code>) on port 8001 to port 80 (I've a XAMPP Apache server listening to port 80).</p>
<p>I issued the following:</p>
<pre><code>netsh interface portproxy add v4tov4 listenport=8001 listenaddress=192.168.0.10 connectport=80 connectaddress=192.168.0.10
</code></pre>
<p>Show all confirms that everything is configured correctly:</p>
<pre><code>netsh interface portproxy show all
Listen on IPv4: Connect to IPv4:
Address Port Address Port
--------------- ---------- --------------- ----------
192.168.0.10 8001 192.168.0.10 80
</code></pre>
<p>However, I'm not able to access apache website from <code>http://localhost:8001</code>. I'm able to access through the direct port at <code>http://localhost</code> as shown below. </p>
<p>Additionally, I've also tried the following:
1. Access the Apache website from a remote PC using the link: <code>http://192.168.0.10:8001</code>. Firewall turned off.
2. Changing listenaddress and connectaddress to <code>127.0.0.1</code>.</p>
<p>Without further information, I can't find a way to resolve the problem. Is there a way to debug NETSH PORTPROXY?</p>
<p><img src="https://i.stack.imgur.com/GbpIG.jpg" alt="enter image description here"></p>
<p><em>Note: By the way, if you're wondering why I am doing this, I actually want to map remote MySQL client connections from a custom port to the default MySQL Server port 3306.</em></p> | 24,734,210 | 4 | 0 | null | 2014-07-09 05:47:07.92 UTC | 20 | 2022-05-21 00:06:17.497 UTC | null | null | null | null | 935,270 | null | 1 | 32 | portforwarding|netsh|windows-networking | 113,100 | <p>I managed to get it to work by issuing:</p>
<pre><code>netsh interface ipv6 install
</code></pre>
<p>Also, for my purpose, it is not required to set listenaddress and better to set connectaddress=127.0.0.1, e.g.</p>
<pre><code>netsh interface portproxy add v4tov4 listenport=8001 connectport=80 connectaddress=127.0.0.1
</code></pre> |
2,486,854 | Formatting out of a jQuery UI datepicker | <p>I'm having a problem trying to format the output on the jQuery UI datepicker.</p>
<p>I want the dateformat to be the 'ISO 8601' format, like explained here:</p>
<p><a href="http://jqueryui.com/demos/datepicker/#date-formats" rel="noreferrer">http://jqueryui.com/demos/datepicker/#date-formats</a></p>
<p>This is what my code looks like:</p>
<pre><code>$.datepicker.setDefaults($.datepicker.regional['nl']);
$('.datepicker').datepicker('option', {dateFormat: 'yy-mm-dd' });
</code></pre> | 2,486,868 | 3 | 0 | null | 2010-03-21 11:21:55.04 UTC | 10 | 2013-10-12 09:58:03.09 UTC | 2011-12-08 16:34:01.823 UTC | null | 229,044 | null | 288,606 | null | 1 | 28 | jquery|format|datepicker | 36,415 | <p>Your option setter format is just a bit off, try this:</p>
<pre><code>$('.datepicker').datepicker('option', 'dateFormat', 'yy-mm-dd');
</code></pre>
<p><a href="http://jqueryui.com/demos/datepicker/#option-dateFormat" rel="noreferrer">See the options pane on that page for how to set each one in this way</a></p>
<p>when doing it globally before creating a picker, do this:</p>
<pre><code>$.datepicker.setDefaults($.datepicker.regional['nl']);
$.datepicker.setDefaults({ dateFormat: 'yy-mm-dd' });
//Later..
$('.datepicker').datepicker();
</code></pre>
<p>Also, make sure to include your regional file, or the <code>$.datepicker.regional['nl']</code> doesn't mean anything, this needs to be included before trying to setDefaults to your regional: <a href="http://jquery-ui.googlecode.com/svn/trunk/ui/i18n/" rel="noreferrer">http://jquery-ui.googlecode.com/svn/trunk/ui/i18n/</a></p> |
2,779,797 | What does "in-place" mean? | <blockquote>
<p>Reverse words in a string (words are
separated by one or more spaces). Now
do it in-place.</p>
</blockquote>
<p>What does in-place mean?</p> | 2,779,803 | 3 | 3 | null | 2010-05-06 09:02:35.983 UTC | 11 | 2010-05-06 10:12:40.427 UTC | 2010-05-06 10:12:40.427 UTC | null | 174,375 | null | 174,375 | null | 1 | 29 | semantics | 18,370 | <p>In-place means that you should update the original string rather than creating a new one.</p>
<p>Depending on the language/framework that you're using this could be impossible. (For example, strings are immutable in .NET and Java, so it would be impossible to perform an in-place update of a string without resorting to some evil hacks.)</p> |
3,074,827 | ORA-00060: deadlock detected while waiting for resource | <p>I have a series of scripts running in parallel as a nohup on an AIX server hosting oracle 10g. These scripts are written by somebody else and are meant to be executed concurrently. All the scripts are performing updates on a table. I am getting the error,</p>
<blockquote>
<p>ORA-00060: deadlock detected while
waiting for resource</p>
</blockquote>
<p>As I googled for this, I found,
<a href="http://www.dba-oracle.com/t_deadly_perpetual_embrace_locks.htm" rel="noreferrer">http://www.dba-oracle.com/t_deadly_perpetual_embrace_locks.htm</a></p>
<p>Even though the scripts are performing updation on the same table concurrently, they are performing updates on different records of the table determined by the <code>WHERE</code> clause with no overlaps of records between them. </p>
<p>So would this have caused the error?.</p>
<p>Will this error happen regardless of where the updates are performed on a table?.</p>
<p>Should I avoid concurrent updates on a table at all times?.</p>
<p>Strangely I also found on the nohup.out log,
<code>PL/SQL successfully completed</code> after the above quoted error.</p>
<p>Does this mean that oracle has recovered from the deadlock and completed the updates successfully or Should I rerun those scripts serially?
Any help would be welcome.</p>
<p>Thanks in advance.</p> | 3,075,548 | 4 | 0 | null | 2010-06-19 08:00:08.97 UTC | 8 | 2019-04-07 07:23:12.217 UTC | 2014-12-15 21:20:07.967 UTC | null | 1,665,673 | null | 368,995 | null | 1 | 28 | database|oracle|unix|plsql|aix | 132,951 | <p>You can get deadlocks on more than just row locks, e.g. see <a href="http://www.oratechinfo.co.uk/deadlocks.html" rel="noreferrer">this</a>. The scripts may be competing for other resources, such as index blocks.</p>
<p>I've gotten around this in the past by engineering the parallelism in such a way that different instances are working on portions of the workload that are less likely to affect blocks that are close to each other; for example, for an update of a large table, instead of setting up the parallel slaves using something like <code>MOD(n,10)</code>, I'd use <code>TRUNC(n/10)</code> which mean that each slave worked on a contiguous set of data.</p>
<p>There are, of course, much better ways of splitting up a job for parallelism, e.g. <a href="http://download.oracle.com/docs/cd/E11882_01/appdev.112/e10577/d_parallel_ex.htm" rel="noreferrer">DBMS_PARALLEL_EXECUTE</a>.</p>
<p>Not sure why you're getting "PL/SQL successfully completed", perhaps your scripts are handling the exception?</p> |
2,992,925 | How can I simply "run" lisp files | <p><strong>Python</strong></p>
<p>When I learned Python I installed it on windows with a nice gui installer and all .py files would automatically run in python, from the command line or explorer.</p>
<p>I found this very intuitive and easy, because I could instantly make plain text files and run them.</p>
<p><strong>Lisp</strong></p>
<p>I'm starting to learn lisp and have decided (from reviews) that SBCL is not a bad lisp implementation.</p>
<p>Is there a way to setup SBCL to run .lisp files as easily as with Python?</p>
<p>Are there other lisp implementations that have this?</p> | 2,993,109 | 4 | 1 | null | 2010-06-07 20:30:58.737 UTC | 8 | 2014-02-20 00:01:07.923 UTC | null | null | null | null | 2,118 | null | 1 | 33 | windows|lisp|file-association|sbcl | 26,618 | <p><strong>Executables</strong></p>
<p>SBCL can save executable images, as Greg Harman mentions (see the :EXECUTABLE keyword): <a href="http://www.sbcl.org/manual/index.html#Saving-a-Core-Image" rel="noreferrer">http://www.sbcl.org/manual/index.html#Saving-a-Core-Image</a></p>
<p><strong>Scripts</strong></p>
<p>Lisp files can be executed as scripts, see: <a href="http://www.sbcl.org/manual/#Shebang-Scripts" rel="noreferrer">http://www.sbcl.org/manual/#Shebang-Scripts</a></p>
<p><strong>Command Line Options</strong></p>
<p>SBCL has command line options to evaluate/load lisp code on start: <a href="http://www.sbcl.org/manual/#Command-Line-Options" rel="noreferrer">http://www.sbcl.org/manual/#Command-Line-Options</a></p>
<p><strong>SLIME</strong></p>
<p><a href="http://common-lisp.net/project/slime/" rel="noreferrer">SLIME</a> is an Emacs interface for Common Lisp. One can use SBCL via SLIME from within Emacs. Many people prefer Emacs Lisp listeners over typical shell interfaces.</p>
<p>Most Common Lisp implementations have similar capabilities. For details consult their manual or ask here for specific implementations.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.