text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Sorting A Custom List C#
I have a list of windows but it is not in the order I want them. I'm able to get the windows into string from the title - they are being put into a list of windows. I want to sort this list in a specific order with Estimate 1st, Control Center 2nd, and Login 3rd. This is the order I desire. I have know idea on how to go about it but I want to sort it before it goes into the foreach loop.
private void CloseMainWindows(IEnumerable<Window> Windows)
{
var winList = Windows.ToList();
winList.Sort()//This is where I want to sort the list.
foreach (Window window in winList)
{
if (window.Title.Contains("Estimate"))
{
Estimate.closeEstimateWindow();
}
if (window.Title.Contains("Control Center"))
{
ContorlCenter.CloseContorlCenter();
}
if (window.Title.Contains("Login"))
{
login.ClickCanel();
}
}
}
A:
One way would be to have a lookup function:
int GetTitleIndex(string s)
{
if (s.Contains("Estimate")) return 0;
if (s.Contains("Control Center")) return 1;
if (s.Contains("Login")) return 2;
}
Then, to sort, you lookup the indexes:
winList.Sort((x, y) => GetTitleIndex(x).CompareTo(GetTitleIndex(y)));
Alternatively, you could create the list directly using LINQ's OrderBy:
var winList = Windows.OrderBy(GetTitleIndex).ToList();
And in fact in your case you don't even need the intermediate list:
foreach (var window in Windows.OrderBy(GetTitleIndex))
{
...
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Joomla 3 temporary accounts
Developing a testing system as a diploma.
Got a question. registration for users who will take the test should be avoided.
I thought to create temporary accounts, which after the passage will be deleted.
1) If you create such a mechanism in the module in which the test is created, will it be safe?
2) How to request contact information when you first enter?
A:
If you are creating a test questionnaire page where visitors fill out test questions as guests and submit their answers, then the whole process is usually handled by secure session/user/csrf tokens which is (created and) submitted together with their filled out tests Forms. The questionnaire Form should include fields like name, email address and CSRF form token (as hidden field) beside the test questions.
You can study of creating front-end forms in Joomla 3 deeper here: https://docs.joomla.org/J3.x:Developing_an_MVC_Component/Adding_a_front-end_form
Joomla Form creation extensions, I think, all have solved this question already.
So the approach of understanding and answering your question is the same as web stores solved this issue by letting visitors to place an order in web shops without registration - as guest users. If I understood your question correctly. I hope this can help you.
Additionally, you can also password protect your test questionnaire Form (pages) with available Joomla extensions, thus it will be unavailable for unintended public. You do not really need registration that way.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
UIImageView+AFNetworking image not loading correctly in UITableViewCell
I'm using the setImageWithURL to lazily load images into my tableview cells but there is a problem. It loads the images fine but there seems to be a refresh problem on the device where the images only show when you scroll them out of the view and back in again.
It works perfectly in the simulator. The device is running iOS 5.1.1 on a iPhone 4S
This table is displayed in a UINavigation controller and as the images are cached I expect the images to appear pretty quickly when I revisit the screen. They do, but the show up at half their original size.
The images are 60x30 in size.
Is this an issue with loading images into a retina screen that they are half the size and what would cause this refresh problem?
Code snippet below...
- (UITableViewCell *)tableView:(UITableView *)tableview cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableview dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
...
[cell.imageView setImageWithURL:url placeholderImage:[UIImage imageNamed:@"transparent_shade"]];
...
return cell;
}
Thanks in advance for any insights
A:
I would suggest loading/preparing the images before the cellForRowAtIndexPath method. The reason you are seeing the images after scrolling is because the images were previously downloading at the time this method was called, hence the files were not yet available.
Make a NSMutableArray inside your view's viewWillAppear method (override it if non-existent) for instance, and put all the images inside the array. Then, in the cellForRowAtIndexPath simply get the images from the array and assign them as needed; they should be displayed on demand, without delays.
Let us know how this works for you.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Arr.includes(item) - Can I Use with a Multidimensional Array?
I'm trying to use the arr.includes(item). The function should return True if the item is an element of the array. But it doesn't seem to be able to do so with a multidimensional array. Take a look at this screenshot (running node in the console):
I got a similar result on my Google Chrome.
Is it because it's an EC6 function, and not yet completely functional?
No information on such a problem on the Mozille page.
A:
No, you can't use it on deep structures, because it performs an === test that checks that the operands are the same object, and not two (different) objects that happen to have the same contents.
On the MDN page you linked to there's a polyfill where you can see that === test within the sameValueZero() nested function.
For the above reasons, this would actually return true:
let a = [0, 1];
let b = [1, 2];
let c = [a, b];
c.includes(b);
> true
because the object passed to .includes really is the same object that's contained in c.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Preserving Embedded Fonts in iText
I have a java application which splits a pdf into sections using itext, then stitches a selection of these up together again. The original pdf has many embedded fonts varying in type (all non-system fonts). When I stitch the pdf's up again, some of the embedded fonts are missing.
For example, this is a clipping from the original fonts list:
This is a clipping from the generated pdf font list:
I am using PdfWriter and PdfReader to copy the pages into the new document, with PdfContent and addTemplate().
A:
Finally found the answer! The problem was the level of Pdf was set too low:
writer.setPdfVersion(PdfWriter.VERSION_1_2);
I changed this to:
writer.setPdfVersion(PdfWriter.VERSION_1_7);
and now all fonts are embedded correctly.
I actually forgot that piece of code was in there - I had borrowed it from a project I had done in the past.
Lesson learned ;)
I would love to know why this is the case though.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to reply to comments received for any question
Possible Duplicate:
How do comment @replies work?
I have posted a question and have received a comment to the question. I want to reply to the comment and also inform the commenter of the reply. How can I perform this task?
A:
You can either reply with another comment like:
@Username: Your comment goes here.
or just add detail to your original question or answer if you are the OP and it is applicable.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
validate if 1 to 3 chekboxes are cheked but with different id
I have a little problem here, so I have a form, inside I have 8 chekboxes in one section
all are with images above them so if the user click over the image to check their specific chekboxes to .
Here is the code of my chekboxex and the script to validate them:
function logotype() {
var group = document.newlogo.ltype;
for (var i=0; i<group.length; i++) {
if (group[i].checked)
break;
}
if (i==group.length)
return alert("Please select 1 to 3 Logo Types");
}
<div class="thumb1" >
<label for="letter"><img class="img" src="images/my2.jpg" /></label>
<input type="checkbox" class="chk" name="ltype[]" id="letter" value="letter" />
<hr>
<p><strong>Letter Mark Logo</strong></p>
</div>
<div class="thumb1">
<label for="emblerm"><img class="img" src="images/my3.jpg" /></label>
<input type="checkbox" class="chk" name="ltype[]" id="emblerm" value="emblerm" />
<hr>
<p><strong>Emblerm Logo</strong></p>
</div>
As you may see the id="ltype" if i make all my checkboxes with the same id it works with validating but after this my checkboxes can't be checked from images because for="anothername" if i put ltype it makes all jujst select one field . .
So the question is: Can I somehow validate the checkboxes based on their class names so that at least 1 to three checkboxes are checked when submit?
A:
You can use getElementsByClassName() method to access the checkboxes using classname, and validate them as follows:
function logotype() {
var failure = true,
count =0,
group = document.getElementsByClassName("chk");
for (var i=0; i<group.length; i++) {
if (group[i].checked)
count++;
if(count>=3){
failure =false;
break;
}
}
if (failure){
alert("Please select 1 to 3 Logo Types");
return false;
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Help determining Maintenance Item table structure best practice
I have two different existing Database design's in the legacy apps I inherited. On one side they created two tables; tblAdminMaintCategory and tblAdminMaintItems. On the other side individual tables for everything; tblAdminPersonTitle and tblAdminRace.
Method #1
Now in the first example there would be an entry in tblAdminMaintCategory for Race(say ID is #2) and then in tblAdminMaintItems each individual race would have an entry with the corressponding categoryID. Then to query it for race options, for example, would go --> SELECT * FROM tblAdminMaintItems WHERE CategoryID = 2
Method #2
Now in the second example there would just be an entry in tblAdminRace for each individual race option. To query that would go --> SELECT * FROM tblAdminRace.
Now, I am trying to figure out, going forward, which of these paths I want to follow in my own apps. I don't like that the First Method, seemingly, introduces magic numbers. I don't like that the Second Method introduces many, many, small tables but I am not sure that is the END OF THE WORLD!!
I am curious as to others opinions on how they would proceed or how they have proceeded. What worked for you? What are some reasons I shouldn't use one or the other?
Thanks!
A:
It is reasonable design to have separate entities in different tables; like: Race, Car, Person, Location, Maintenance task, Maintenance schedule. If you don't like joins in queries, simply design several views. I may have misunderstood the example, but here is one suggestion.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using groovy to append to a certain line number in a file
Rather than appending to the end of a file, I am trying to replace or append to a certain line using groovy File manipulation.
Is there a method to do this?
append adds to end of file while write overwrites existing file:
def file = new File("newFilename")
file.append("I wish to append this to line 8")
A:
In general, with Java and Groovy file handling, you can only append to the end of files. There is no way to insert information, although you can overwrite data anywhere without shifting the position of what follows.
This means that to append to a specific line that is not at the end of the file you need to rewrite the whole file.
For example:
def file = new File("newFilename")
new File("output").withPrintWriter { out ->
def linenumber = 1
file.eachLine { line ->
if (linenumber == 8)
out.print(line)
out.println("I wish to append this to line 8")
} else {
out.println(line)
}
linenumber += 1
}
}
A:
For small files you can use the following piece of code:
def f = new File('file')
def lines = f.readLines()
lines = lines.plus(7, "I'm a new line!")
f.text = lines.join('\n')
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to bind an event to a dynamically created element within another dynamically created element?
Binding events to a dynamically created element that has a static ancestor is fairly easy using jQuery, as demonstrated in this answer:
$(staticAncestors).on(eventName, dynamicChild, function() {});
But what if the dynamicChild is of a dynamicAncestor? Is there any way to make the following work:
$(dynamicAncestors).on(eventName, dynamicChild, function() {});
A:
When using on, you should bind to the nearest static parent element. In some cases, that may be body:
$('body').on(eventName, 'dynamic-element', function() { });
Binding all events to body is generally bad practice though, so it's difficult to answer your question more thoroughly without seeing your DOM. But binding to the nearest static parent will work for what you're trying to achieve.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Download audio from Firebase storage
I'm trying to create a voice messaging android app using firebase storage as backend, but i'm having issue while downloading mp3 file while it uploads successfully.
Can somebody please provide simple code just to download an audio file from storage.
I'm new at android development , so sorry for being noob
i've added all the permissions in my manifest file like bellow
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Tis is my uploading code
private void uploadAudio() {
pd=new ProgressDialog(this);
pd.setMessage("Uploading");
pd.show();
StorageReference filepath = mstorage.child("Audio").child("New_Audio");
Uri uri = Uri.fromFile(new File(mFileName));
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pd.dismiss();
}
});
}
And for downloading
private void startdownload() {
down = mstorage.child("Audio/");
File localFile = null;
try {
localFile = File.createTempFile("Audio", "mp3");
} catch (IOException e) {
e.printStackTrace();
}
down.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
@Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(),"Downloded",Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
}
});
}
A:
Make sure your StorageReference for the upload and download method is the same.
//upload
StorageReference filepath = mstorage.child("Audio").child("New_Audio.mp3");
//download
down = mstorage.child("Audio").child("New_Audio.mp3");
To save the file in the external storage, you can follow this Android Developers guide
An example:
try {
File localFile = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "New_Audio.mp3");
localFile .createNewFile();
down.getFile(localFile);
} catch (IOException e) {
e.printStackTrace();
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Google Docs Spreadsheet - Parse Error
Not sure why this formula does not work. I just want the value to be zero if 60-D15 is negative
=MAX(60-D15,0)
also tried
=MAX(D15,0)
=MAXA(D15,0)
Any clues?
A:
German locale requires a ; instead of , as the argument separator in functions.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
VBA Excel - Resolving Error 13 when deleting text from a field
Have a spreadsheet I am editing for a project at work. The sheet uses string values in col 1, 3, 4, and 5. Multiple people will be accessing this sheet so in order to maintain a clean appearance I have set the sheet to capitalize the values in each of those columns upon entry.
Dim letter as String
Select Case Target.Column
Case Is = 1, 3, 4, 5
Application.EnableEvents = False
letter = Target.Value
letter = UCase(letter)
Target.Value = letter
End Select
Application.EnableEvents = True
This works great except for when you drag and select multiple fields to delete. It returns run-time error 13 and I know it is from the letter string becoming " " and the program can't capitalize a blank string.
I can't wrap my brain around how to bypass this Select if the letter string is blank. I've spent some considerable time looking for the answer but can't seem to find something that applies to this situation. Any input is appreciated. Thank you
A:
As I mentioned in my comment, your problem is not in the UCase line.
Try this:
Dim letter as String
Dim cell As Variant
Application.EnableEvents = False
For each cell in Target
Select Case cell.column
Case Is = 1, 3, 4, 5
Cell.Value = UCase(Cell.Value)
End Select
Next cell
Application.EnableEvents = True
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Visual Studio 2010 crashes after build
I have a VB.Net windows forms application that has been around for a very long time. I am working the project in Visual Studio 2010 Premium, on my Windows 7 x64 workstation. Everything has been going along fine till a couple days ago. No every time I build this project Visual Studio 2010 crashes.
The only thing i have to go on is this from another Visual Studio 2010 instance that attached the debugger to the dieing process.
...
The thread 'Win32 Thread' (0x177c) has exited with code -2147023895 (0x800703e9).
The thread 'Win32 Thread' (0xc44) has exited with code -2147023895 (0x800703e9).
The program '[4224] devenv.exe: Native' has exited with code -2147023895 (0x800703e9).
No one else on my team has this issue, and I don't have problems with any other projects.
This is .Net 4.0.
Any thoughts or suggestions are much appreciated,
Beezler
A:
It might be wise to start VS with the /safemode parameter.
I also had this problem and I solved it by uninstalling the Achievements extension.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
We get a lot of answers here... should we implement some system changes that will encourage users to review existing answers before adding their own?
Recently it came to my attention that there are per-site configuration settings that allow us to create some extremely minor barriers to answering questions when more than n answers already exist. This is currently implemented on the site but the threshold for tripping it is set at 30 answers.
The difference is that, instead of an answer field, there's a button that reads "Answer this question" which, when clicked, creates a popup with the following text:
This question has more than {x} answers already.
Did you read through all the existing answers first to make sure your answer will be contributing something new?
Also, please note that you can click the edit link on any of these answers to improve them.
This doesn't prevent answers, per se, but it does ask users to be cognizant of the existing answers before posting their own.
Should we request this limit to be lowered, and to what?
As a note, questions are automatically flagged by the system when a question receives ten answers within seven days. We largely ignore these flags because there's not much for us to do about them, considering the vast quantity of answers we get here. I'm also interested in changing this auto flag, which is apparently also configurable. This doesn't affect the users as the only people who see it are mods but we need to request it on meta to have it changed.
I think that, since the system sees fit to flag at 10 answers, we might consider something lower than that for the "answer this question" button - perhaps something around seven.
A:
1. Raise the autoflag threshold to 15.
We have issues on Worldbuilding with questions that get lots of answers. The HNQ effect means that many get 10 or more, and our record is at least 30 or 40, I think. However, we (the Worldbuilding mods) did there what we (the IPS mods) do here, and let the answer autoflags sit for a while. So we got the threshold raised, to 15 answers, and we've been extremely happy. We might as well raise the threshold to 15 answers for IPS, because otherwise, we just accumulate a bunch of flags that we won't touch for a couple days. And that's a bit annoying.
Plus, the IPS question rates is low enough that, with the help of community flaggers, we can catch low-quality answers decently quickly. So not getting notified when there are 10 answers to a question within a short period of time (which may include one or two that may require deletion) isn't a huge problem for us.
2. Lower the popup threshold to 7-10.
I don't have a great idea of when, on average, questions start to get duplicate answers. Is it 5 (probably not)? 15 (maybe)? 20 (definitely)? I'd feel good about something in the range of 7-10, according to my gut. As I said before, we've got a good flagging/commenting community, and they can be our first line of defense against these posts (sure, getting them after they're posted, but still). That's in part why I'm not necessarily going along with 7; I think we can afford to go a bit higher. But certainly not more than 10.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Excel macro loop thru column to assign cell name box
I want to populate the name box for a cell with the value from an adjacent cell. This macro works.
Sub NameBox()
' populates name box w/ value from adjacent cell
ActiveCell.Name = ActiveCell.Offset(0, -1).Value
' steps down to next cell
ActiveCell.Offset(1, 0).Select
End Sub
I assign a key stroke and iterate through each cell in the column which is pretty easy but I think it can be improved with a loop.
I tried this.
Sub NameBoxLoop()
Dim cel As Range
For Each cel In Range("C:C").Cells
If cel.Value <> "" Then
cel.Name = cel.Offset(0, -1).Value
End If
Next cel
End Sub
But I get the following debug error
cel.Name = Application-defined or object-defined error
The loop logic looks right, if I replace the variable cel.Name with cel.Value the loop will complete.
Searches haven't provided an answer to the cel.Name error. Any help in resolving this error is appreciated.
A:
Your formula works. But maybe your environment is not optimal, because you have no error-correction there - and names have limitations.
So I am guessing eigther you don't have values in column B or column B has values which are already used as names for other cells.
In both cases your loop would break.
Try this to loop anyways, but consider error-proving your code:
Sub NameBoxLoop()
On Error Resume Next
Dim cel As Range
For Each cel In Range("C:C").Cells
If cel.Value <> "" Then
cel.Name = cel.Offset(0, -1).Value
End If
Next cel
end sub
Edit:
as a suggestion, you might want to consider using the Names listing.
Here is an example from excel-help:
ActiveWorkbook.Names.Add Name:="test", RefersTo:="=sheet1!$a$1:$c$20"
And here some of the objectmembers:
Add
Item
Count
|
{
"pile_set_name": "StackExchange"
}
|
Q:
angular CLI, add /wwwroot to Index js scripts urls on ng build
We have an application of angular 2 inside asp.net core, which runs in a cluster of Azure Service Fabric, the small problem we have is that when you run ng build, the index.html file is with the following references:
<script type = "text/javascript" src = "inline.bundle.js"> </ script>
<script type = "text/javascript" src = "polyfills.bundle.js"> </ script>
<script type = "text/javascript" src = "styles.bundle.js"> </ script>
<script type = "text/javascript" src = "vendor.bundle.js"> </ script>
<script type = "text/javascript" src = "main.bundle.js"> </ script>
but we need them to be as follows:
<script type="text/javascript" src="/Meteoro/Meteoro.UI/inline.bundle.js">
</script>
<script type="text/javascript"src="/Meteoro/Meteoro.UI/polyfills.bundle.js"
</script>
<script type="text/javascript" src="/Meteoro/Meteoro.UI/styles.bundle.js">
</script>
<script type="text/javascript" src="/Meteoro/Meteoro.UI/vendor.bundle.js">
</script>
<script type="text/javascript" src="/Meteoro/Meteoro.UI/main.bundle.js">
</script>
That is, add "/Meteoro/Meteoro.UI/{file}.js" to the URL
Thank you
A:
You can configure this in your angular-cli.json
"apps": [
{
"deployUrl": "/Meteoro/Meteoro.UI/"
}
]
This will append that path to your index.html resources. Alternatively you can add it to your build command
ng build --deploy-url=/Meteoro/Meteoro.UI/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is Google Sign-In not supported on Firefox?
I'm trying to run the default example code (using my Client ID) linked at:
https://developers.google.com/identity/sign-in/web/
The code runs correctly on Google Chrome browser (returning all user infos) while it throws an exception using Firefox:
"uncaught exception: [object Object]"
Can anyone help me?
Best Regards
A:
Please delete all cookies from google and clear your cache then restart Firefox. If does not work go back into cookies and clear everything that you know you do not need. Also check your Firewall software see if anything adds up to google and can put a exemption in maybe. Also turn off any adblockers when go to the site.
If that does not work https://support.mozilla.org/en-US/kb/refresh-firefox-reset-add-ons-and-settings
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Text selection listener in Android(API level 7)
I need a listener which is called every time the selection in an EditText changes.
I googled around but I couldn't find anything useful for API level 7.
I'm writing a Text Editor and I want the bold/italic/underlined button appear selected every time the user selects bold/italic/underlined text.
A:
Pretty old question, but someone might still need this, so here's my solution : since the text selection accomplished with long press on the text, I simply used the following :
editText.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
// do whatever you need to do on text selection
}
});
This allows for custom behavior on text selection and doesn't prevent the user from copying/pasting.
A:
The better way to do it would be to extend the EditText and then based upon how you would want to manage the changing text, you could override one of the 2 methods to work out your customized behavior.
If you want the selection changed then you could use the onSelectionChanged() method and implement your code there.
In case you want to implement something when the text changes in your editor then you could use, onTextChanged().
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Halving a number loses fractional part
I want to show the halved value of a number on a UILabel. To do so, I tried getting the number using a UITextField, formatted the number from a NSString to a NSNumber and then divided by 2.
After that I wanted to show it on the UILabel but it doesn't show anything after the comma (decimal mark). Any idea how to solve this? I just need two digits after the comma.
This is my current UIButton code:
// first get the input
NSString *inputValue = self.numberInput.text;
NSLog(@"given number: %@", inputValue);
// divide the input by 2 & get the output
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *myNumber = [formatter numberFromString:inputValue];
NSNumber *toDivide = [NSNumber numberWithFloat:2];
NSNumber *dividedNumber = [NSNumber numberWithInt:[myNumber floatValue] / [toDivide floatValue]];
NSLog(@"divided value: %@", dividedNumber);
// print it out on the firstBill Label
self.firstBill.text = [NSString stringWithFormat:@"%.2f",[dividedNumber floatValue]];
Example Output:
2015-08-18 20:03:02.021 Week one[1364:37640] given number: 123.54
2015-08-18 20:03:02.022 Week one[1364:37640] divided value: 61
and I need something like
2015-08-18 20:03:02.021 Week one[1364:37640] given number: 123.54
2015-08-18 20:03:02.022 Week one[1364:37640] divided value: 61.77
A:
You're using numberWithInt: to store the result of the division; this discards any fractional part.
You would do better to use NSNumber boxing:
@([myNumber floatValue] / [toDivide floatValue])
The compiler knows the type of the expression and will use the correct NSNumber constructor for you.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Local domains vs "relay domains"
I have a vague notion but I'm not clear on the difference between local domains and "relay domains"
I believe that local domains are "localhost" and any other aliases you set the server up to mean "self".
I believe "relay" domains are "everything else?" Like if a DNS has foobar.com point to this server, then foobar.com is a relay domain? I am not sure about this point.
In the exim setup file - (exim4.template.conf) What does it mean "fallback MX or mail gateway for domains" - what is fallback mx? Does it mean your server is like a DNS server of sorts?
A:
Local domains are any domains which are on the server and mail to those addresses is delivered to a local mailbox (or a local alias), eg. [email protected] and [email protected] both deliver to john's mailbox on the server, no separation.
A virtual domain is similar, but there will be separation (eg. /var/spool/mail/example2.com/john is a mailbox).
A relay domain is one which your mailserver will deliver to as though it is local, without authentication. Eg. you could configure the server to delay to example3.com even though it's not local.
If any of that is wrong, I'd be happy to be shown the error of my ways.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Downloading .ttf files with Node
I'm trying to download a .ttf file like this one using Node.
I'm using mikeal/request to handle HTTP requests.
The actual function looks something like this:
request.get(url, function(err, res, body) {
if(err) throw err;
fs.writeFileSync(path, body);
});
After a quick glance, it behaved exactly as expected; everything ended up in the right place and it looked more or less right.
However, when I tried to load the font into a browser using the following @font-face snippet, the rule was applied, but the font wasn't. No errors, nothing failing to load or being overwritten.
@font-face {
font-family: 'Open Sans';
font-style: normal;
font-weight: 400;
src: local('Open Sans'), local('OpenSans'), url(cJZKeOuBrn4kERxqtaUH3aCWcynf_cDxXwCLxiixG1c.ttf) format('truetype');
}
For a preliminary check I tried to open it with KFontView, but was met with a "Could not read font" error.
I verified this error by wgeting a fresh copy of the file and doing the same. It loaded into the preview fine.
This jogged my memory regarding an optional argument that could be passed to writeFile, so I checked out the encodings of the wget version and the node version.
$ enca wget.ttf -L none
> Unrecognized Encoding
$ enca node.ttf -L none
> Universal transformation format 8 bits; UTF-8
> Mixed line terminators
> Surrounded by/intermixed with non-text data
So, fairly obvious. wget is saving it as a binary whereas node was writing it to file as UTF-8. Quicky confirmed with a file
$ file -i wget.ttf
> wget.ttf: application/x-font-ttf; charset=binary
Quick scan of the Node docs, turns out I can do this
fs.writeFileSync(path, body, 'binary');
Everything looked good, the node version was now showing up as the correct encoding. However, still having the exact same problem in the browser.
Made sure that my version of Chrome supported .ttf font-faces (Version 37.0.2062.94 (64-bit). It does.)
As far as I could see, the file were now the same. Diff was particularly unhelpful.
$ diff wget.ttf node.ttf
> Binary files wget.ttf and node.ttf differ.
There might be a more sensible way to use diff with binary files. Afraid, I don't know enough about it. I decided to go for a primitive manual diff.
I fired up vim, got both files on screen and knocked them into hex mode to have a look. Apple, Microsoft and Adobe all seem to have different specifications for TTF files and I'm not sure which spec this sticks to, but I would guess that first row of bytes is part of a generic header.
After the top row of bytes, the rest of the file is different.
What on earth is happening here? How does Node end up with a different file to wget?
Does either utility pass any strange headers that would affect the file that was served?
Could this be a problem with the way I'm using writeFile?
I'm hoping I've missed something obvious. Otherwise, any suggestions would be welcome.
A:
You need to specify that you want binary encoding by setting encoding to null.
request.get({
url: url,
encoding: null,
}, function (err, res, body) {
Otherwise, it will default to UTF-8 encoding. Documentation: https://github.com/mikeal/request
Really though, you should be letting it stream to a file for you, for efficiency.
request('http://example.com/font.ttf').pipe(fs.createWriteStream('font.ttf'));
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Styling C# Alert Box
I am very new to C#.net programming...I have a good background with Html5 and Css3 and some JavaScript...
I am trying to figure out how to style the below alert box...I have searched the net and forums...this is my first post here...haven't been able to figure it out...
Please let me know if you need anymore info...thank you...
Below is the C# Code
protected void IsValidNumber(object sender, EventArgs e)
{
int num;
if (Int32.TryParse(TextBox1.Text, out num))
{
Response.Redirect("checkin.aspx");
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "myalert", "alert('" + TextBox1.Text + "');", true);
}
}
A:
You can't style alert boxes. Those are the property of the browser alone.
However, what you can do is create the popup using HTML and CSS inside a hidden DIV, and display it whenever you want. Jquery makes this easy
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Array values, error about field used like a type
I am now for the last time make this work, I have some values that should be in an array like down below:
Timereports.Breaks[] breakValue = { _nestedDateStartBreak1,
_nestedDateEndBreak1,
_nestedDateStartBreak2,
_nestedDateEndBreak2 };
Please correct me if I am all wrong about how it should look just have been looking at this article:
http://msdn.microsoft.com/en-us/library/vstudio/9b9dty7d.aspx
I am getting this error:
'transPA.MainPage.Timereports' is a 'field' but is used like a 'type'
So I have been looking in the object browser and found this:
What can I get out of what I am seeing here how can I make my array work. Or am I totally lost?
A:
Updated answer after comments:
TimeReports.Breaks = new[] {
new transPA.ServiceReference.BreakDto {
Started = _nestedDateStartBreak1,
Ended = _nestedDateEndBreak1
},
new transPA.ServiceReference.BreakDto {
Started = _nestedDateStartBreak2,
Ended = _nestedDateEndBreak2
}
};
You can change that to
TimeReports.Breaks = new[] {
new BreakDto {
Started = _nestedDateStartBreak1,
Ended = _nestedDateEndBreak1
},
new BreakDto {
Started = _nestedDateStartBreak2,
Ended = _nestedDateEndBreak2
}
};
if you add a using statement to the beginning of your file.
using transPA.ServiceReference;
or if that using causes a conflict you can be more precise:
using BreakDto = transPA.ServiceReference.BreakDto;
|
{
"pile_set_name": "StackExchange"
}
|
Q:
installing reactive banana-wx or wx on redhat based linux with ghc 7.0.4
hi i'm trying to install, (without having to update or install the latest compiler),reactive-banana-wx and one of the requirement's are failing
cabal install reactive-banana-wx
and heres the error
Configuring wxc-0.90.0.4...
setup: failed
cabal: Error: some packages failed to install:
reactive-banana-wx-0.6.0.1 depends on wxc-0.90.0.4 which failed to install.
wx-0.90.0.1 depends on wxc-0.90.0.4 which failed to install.
wxc-0.90.0.4 failed during the configure step. The exception was:
ExitFailure 1
wxcore-0.90.0.3 depends on wxc-0.90.0.4 which failed to install
when i try to cabal install wxcore ,wx or wxc they all say failed and point towards wxc being required.
here's the error
cabal install wxc
Resolving dependencies...
[1 of 1] Compiling Main ( /tmp/wxc-0.90.0.419410/wxc-0.90.0.4/Setup.hs, /tmp/wxc-0.90.0.419410/wxc-0.90.0.4/dist/setup/Main.o )
Linking /tmp/wxc-0.90.0.419410/wxc-0.90.0.4/dist/setup/setup ...
Configuring wxc-0.90.0.4...
setup: failed
cabal: Error: some packages failed to install:
wxc-0.90.0.4 failed during the configure step. The exception was:
ExitFailure 1
here's my compiler info if it would be useful
ghc -v
Glasgow Haskell Compiler, Version 7.0.4, for Haskell 98, stage 2 booted by GHC version 7.0.4
A:
I've got the same error trying to install phooey with ghc 7.4.1 on Debian tonight. The reason is a bug in the package wxc-0.90.0.4 and it should affect all wxHaskell-based packages. You can fix it, there is no need to downgrade your wxc package...
The easiest way to reproduce it is to do
cabal install wxc
or
cabal install glade
It might be a good idea to make sure that all prerequisites are in place, before you do it. wxc depends on a number of cabal and Linux packages and all of them should be installed and compiled... I did it in the most stupid way possible, just by running
cabal install wxc
and reading error messages which it spills out. This sweetie usually tells you what it wants... For instance, if it complains about cabal package x, just do cabal install x. If it complains about Linux package y, then use your Linux package manager and install the development version of this package, which is called normally lib<y>-dev in Debian. So, for instance, if
cabal install wxc
gives you an error saying that package gtk+2.0 is missing, you want to do
apt-get install libgtk2.0-dev
The same story with cairo, glade2 and other GTK-related libraries
When you are green with all prerequisites, you want to install wxWidgets-2.9, which is currently in the Development stage... so, it doesn't have any binaries for Linux and you should build it yourself. Download the source code from wxWidgets website and build it. It is pretty easy to do, just:
untar/unzip the source code to your favorite directory
run ./config
run ./make
If you are on wxc-0.90.0.4, at this moment you should encounter our little bug... To keep the long story short, it is in the file eljpen.cpp, which you can find in
~/.cabal/packages/hackage.haskell.org/wxc/0.90.0.4/wxc-0.90.0.4.tar.gz
Open the archive, go to the line 159 in the file and replace *_ref = NULL; with _ref = NULL or anything else what makes more sense. Then recreate the archive in the same place with the fixed eljpen.cpp file in it.
run ./make
It should work now.
run sudo make install (normally, you should have root privileges to insatll wxWidgets library...).
after it is done try to do
cabal install wx
again. It should be working now. I guess, after that you can enjoy your reactive-banana-wx, wxHaskell, phooey, etc.
PS http://sourceforge.net/tracker/index.php?func=detail&aid=3576397&group_id=73133&atid=536845. Why didn't I find it earlier? :/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
It is only uploading first row's file input
I have a application which you can access here. If you open the application please click on the "Add" button a couple of times. This will add a new row into a table below. In each table row there is an AJAX file uploader.
Now the problem is that if I click on the "Upload" button in any row except the first row, then the uploading only happens in the first row so it is only uploading the first file input only.
Why is it doing this and how can I get it so that when then the user clicks the "Upload" button, the file input within that row of the "Upload" button is uploaded and not the first row being uploaded?
Below is the full code where it appends the file AJAX file uploaded in each table row:
function insertQuestion(form) {
var $tbody = $('#qandatbl > tbody');
var $tr = $("<tr class='optionAndAnswer' align='center'></tr>");
var $image = $("<td class='image'></td>");
var $fileImage = $("<form action='upload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='startUpload();' >" +
"<p id='f1_upload_process' align='center'>Loading...<br/><img src='Images/loader.gif' /><br/></p><p id='f1_upload_form' align='center'><br/><label>" +
"File: <input name='fileImage' type='file' class='fileImage' /></label><br/><label><input type='submit' name='submitBtn' class='sbtn' value='Upload' /></label>" +
"</p> <iframe id='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px solid #fff;'></iframe></form>");
$image.append($fileImage);
$tr.append($image);
$tbody.append($tr);
}
function startUpload(){
document.getElementById('f1_upload_process').style.visibility = 'visible';
document.getElementById('f1_upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
}
document.getElementById('f1_upload_process').style.visibility = 'hidden';
document.getElementById('f1_upload_form').innerHTML = result + '<label>File: <input name="fileImage" type="file"/><\/label><label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
document.getElementById('f1_upload_form').style.visibility = 'visible';
return true;
}
UPDATE:
Current Code:
var $fileImage = $("<form action='upload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='startUpload(this);' >" +
"<p class='f1_upload_process' align='center'>Loading...<br/><img src='Images/loader.gif' /><br/></p><p class='f1_upload_form' align='center'><br/><label>" +
"File: <input name='fileImage' type='file' class='fileImage' /></label><br/><label><input type='submit' name='submitBtn' class='sbtn' value='Upload' /></label>" +
"</p> <iframe class='upload_target' name='upload_target' src='#' style='wclassth:0;height:0;border:0px solclass #fff;'></iframe></form>");
function stopUpload(success, source_form){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
}
$(source_form).find('.f1_upload_process').style.visibility = 'hidden';
$(source_form).find('.f1_upload_form').innerHTML = result + '<label>File: <input name="fileImage" type="file"/><\/label><label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
$(source_form).find('.f1_upload_form').style.visibility = 'visible';
return true;
}
Why am I getting an error on this line below:
$(source_form).find('.f1_upload_form').style.visibility = 'visible';
A:
Without seeing the full cose, your problem seems to be that you are working with ID's, which must be unique within one document. If several elements are using the same ID, in the best case a browser will use the first one (which it does here), in the worst case nothing will work.
When adding a new upload form, you have to give the elements in it unique ID's. You could do that simply by attaching a counting variable to window, e.g.
$(document).ready( function(){ window.formCount=0; } );
You could then add that number to the ID of the newly added form.
Apart from this, by using the this variable, you can carry a reference to the correct form through, e.g. like onsubmit='startUpload(this);' as well as function startUpload(f){...
You should then be able to access things within the form using $(f).find(...).
There are many ways to make this work and solve the issue of multiple ID's. What I would do: var $fileImage = $("<form action... In this form where it says id I would instead use class. Then as above, change the onsubmit (in the same line) by adding "this" to its brackets. Then change the function startUpload as here:
function startUpload(source_form){
$(source_form).find('.f1_upload_process').css('visibility','visible');
$(source_form).find('.f1_upload_form').css('visibility','hidden');
return true;
}
You have to do the same thing for other functions where you want to access something inside the form that is sending a file. Pass a reference to the form to the function using this in the function call's brackets, then access things inside the form as I showed above.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Show a particular page of pdf file using c#
Is there any way to show a particular page of PDF file using C# / JQuery ?
A:
Adobe defines parameters that allow you to open a PDF document with a command or URL
that specifies exactly what to display (a named destination or specific page), and how to
display it (with a specific view, scrollbars, bookmarks, or highlighting, for example).
http://partners.adobe.com/public/developer/en/acrobat/PDFOpenParams.pdf
|
{
"pile_set_name": "StackExchange"
}
|
Q:
usort won't work after merging to objects
I have the following code:
$content->Vehicles = (object)array_merge((array)$content->List, (array)$content_new->List);
The $content->List and $content_new->List are created from two API calls and is all working as expected.
The problem is I need to sort the object. To do so I use:
usort($content->Vehicles, function($a, $b) {
return ($a->Score < $b->Score) ? -1 : (($a->Score > $b->Score) ? 1 : 0);
});
When I pass in $content->List it works as expected however $content->Vehicles results in usort() expects parameter 1 to be array, object given.
Would love to figure this one out.
A:
Well I fell silly now. Answer as follows:
$content->Vehicles = array_merge((array)$content->List, (array)$content_new->List);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to secure grails web services with spring security
Assume I have the following Domain class:
import grails.rest.Resource
@Resource(formats=['json'], uri='/api/book')
class Book {
String name
static belongsTo = [user: User]
}
I have defined spring security interceptUrlMap in Config.groovy to restrict url access:
'/api/book': ['ROLE_USER']
Lets assume that there are two books and two users in the system and book with id 1 belongs to user 1 and the second book belongs to user 2. User 1 is logged in and the following request should return book 1 (which it does):
localhost:8080/myapp/api/book/1
but if the same user makes a request to the following resource:
localhost:8080/myapp/api/book/2
I want the rest API to return an empty array or "access denied". How do I achieve this? I need an approach there all request types i.e. GET/POST/PUT/DELETE are taken care of.
A:
Solved this issue by generating the corresponding web-service controller:
grails generate-controller Book
And added restriction for every actions, i.e. Index, Show, Save, Update, Delete.
For example the Show action which is used to GET a resource:
localhost:8080/myapp/api/book/1
is changed to look as the following code:
import static org.springframework.http.HttpStatus.*
import grails.transaction.Transactional
@Transactional(readOnly = true)
class BookController {
def springSecurityService
static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]
Code omitted...
def show(Book bookInstance) {
if(bookInstance == null){
notFound()
return
}
def user = springSecurityService.currentUser
if(bookInstance.user.id == user.id) {
respond bookInstance
return
}
notFound()
}
Code omitted...
}
Grails version: 2.4.4
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Retrieving WorkOrder records via REST based on Status
I want to fetch all WorkOrder records with Status = In Progress. I tried using the Query REST resource similar to /services/data/v20.0/query/?q=SELECT+name+from+Account . When I query WorkOrder object, it tells me that this object is not a supported sobject for this request
Do we have any standard endpoint to achieve this? I don't want to go for a custom webservice solution
A:
This is resolved now. I was using an older API version. The version number should be latest one where the Workorder object is supported. I used v44.0 and it worked fine
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is the derivative of $y=\cos(x+y)$?
I know it'll be solved using chain rule but I don't know how to use chain rule formula.
A:
We have $y=\cos(x+y)$
Differentiating using chain rule
$ \dfrac{\mathrm d y}{\mathrm d x} =−\sin(x+y)(x+y) \; \Rightarrow$
$\dfrac{\mathrm d y}{\mathrm d x}=−\sin(x+y)\left(1+\dfrac{\mathrm d y}{\mathrm d x}\right)$
Rewriting,
$\dfrac{\mathrm dy}{\mathrm dx}=−\sin(x+y)−\sin(x+y)\dfrac{\mathrm dy}{\mathrm dx} \; \Rightarrow$
$\dfrac{\mathrm dy}{\mathrm dx}+\sin(x+y)\dfrac{\mathrm dy}{\mathrm dx}=−\sin(x+y)$
Taking $\dfrac{\mathrm dy}{\mathrm dx}$ common,
$\dfrac{\mathrm dy}{\mathrm dx}\left(1+\sin(x+y)\right)=−\sin(x+y)$
Bringing $(1+\sin(x+y))$ to other side,
$\dfrac{\mathrm dy}{\mathrm dx}=−\dfrac{\sin(x+y)}{1+\sin(x+y)}$ will be the final answer.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
OpenGL/GLSL precision error
I have a simple vertex shader:
precision mediump float;
attribute vec4 position;
attribute vec4 color;
varying vec4 f_color;
uniform mat4 projection;
uniform mat4 modelView;
void main(void) {
gl_Position = projection * modelView * position;
f_color = color;
f_texCoord = texCoord;
}
This fails to compile, stating (using getShaderInfoLog()):
ERROR: 0:1: 'precision' : syntax error syntax error
It compiles fine if i remove the line with the precision specifier.
System:
OS: Mac OX 10.9.2
GPU: NVIDIA GeForce 320M 256 MB
GLSL Ver.: 1.20
Someone help me out.
A:
You have already figured out how to solve your problem: just remove the line with the precision qualifier.
The bigger issue is that you haven't decided what version of OpenGL you are using. The GLSL sample you provided seems to be for an old version of the GLSL associated with OpenGL ES, which is designed for mobile devices. Since you are actually running on a desktop/laptop, you want "normal" OpenGL. The error you observed is a result of the differences between the two.
In general you want to go with the latest version of OpenGL that is support by the systems you are targeting. Right now that is probably OpenGL 3.3 (along with GLSL 3.3).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is a primitive type an object?
The start of the Reflection tutorial @ the Java Tutorials states:
Every object is either a reference or primitive type.
Apart from the types used to box primitive types, when and how is a primitive type an object?
A:
It says object, not Object. int, for example, is a primitive type and an object(interpret as the general termn), but not an Object.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there an application that wraps a website in itself?
I am looking for an application that is configurable to open a website on a certain address, having the website's logo as logo in the Launcher, without the browser bar, so I can run the website as if it were an application.
This is preferable for me to opening the website in the browser itself (you'll have to enter the address, or ctrl-tab to the right tab, alt-tab to the right window).
Thanks in advance for any advice. Advice how to customize browsers to do just what I want in this sense is also appreciated.
A:
Epiphany (gnome browser) has that feature.
You have to save that web site as a web app first.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Changing data-content of a button class used in popover
I have a button class which I am using for twitter popover, my code is as follow:
<button class="btn btn-success" id="chaticon" data-original-title="Users Online" data-content="<a href='#'> OMGTEST </a>">
And what I want to do is to modify the data-content via javascript,
Naively I tried to do:
document.getElementById("chaticon").data-content = "new content";
and it didn't work, any ideas on how I can do this?
A:
Use the built in accessors for HTMLElement.
getAttribute(attributeName)
setAttribute(attributeName,newValue);
like this:
var yourElement = document.getElementById("chaticon");
var dataVal = yourElement.getAttribute("data-content");
var newData = "new data";
yourElement.setAttribute("data-content",newData);
here is a simple demo: http://jsfiddle.net/hpfk3/
edit
You should probably have included jquery and popover in the question instead of just asking about a button element. Since these are available, you can change the content like this:
//store chat icon jQuery object
var chatIcon = $("#chaticon");
//change data attribute on element
//change jquery data object content
//call setcontent method
chatIcon.attr("data-content","new data").data('popover').setContent();
//target the popover element and restore its placement definition
chatIcon.data('popover').$tip.addClass(chatIcon.data('popover').options.placement);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ListView SELECT query not returning anything
I am building a library management software and im trying to search books by name. However when I try to use what Ive implemented nothing gets returned.
This is the code behind used to retrieve data from the db.
string constr = ConfigurationManager.ConnectionStrings["LibraryContext"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
string bookTitle = Request.QueryString["BookTitle"];
cmd.Parameters.AddWithValue("@Title", bookTitle);
cmd.CommandText = "SELECT * FROM Books WHERE Title LIKE '%@Title%'";
//cmd.Parameters.AddWithValue("@Title", bookTitle);
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
lvCustomers.DataSource = dt;
lvCustomers.DataBind();
}
}
}
Thank you for you help
A:
Do not put quotes around your parameter
cmd.CommandText = "SELECT * FROM Books WHERE Title LIKE %@Title%";
Quotes aroud the parameters tranform everything inside them to a literal string and of course I suppose that you don't have any book whose title is literally "%@Title%"
also I prefer to use a
cmd.CommandText = "SELECT * FROM Books WHERE Title LIKE @Title";
cmd.Parameters.Add("@Title", SqlDbType.NVarChar).Value = "%" + bookTitle + "%");
AddWithValue is a shortcut with numerous drawback that you need to aware of before trying to use it: Can we stop to use AddWithValue already?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Error: Invoke or BeginInvoke cannot be called on a control until the window handle has been created
Firstly, let me say that I've been on this issue for pretty much 2 days now: tried various alternatives and read tons of questions from your site with similar issues.
First let me paste my code so you get the whole picture.
EDIT: Removed some code that might be unnecessary to the problem, based on request by forum member.
Form 1.cs
namespace TestApp
{
public partial class Form1 : Form
{
//global declarations
private static Form1 myForm;
public static Form1 MyForm
{
get
{
return myForm;
}
}
List<DataSet> DataSets = new List<DataSet>();
int typeOfDataset = 0;
//delegate for background thread to communicate with the UI thread _
//and update the metadata autodetection progress bar
public delegate void UpdateProgressBar(int updateProgress);
public UpdateProgressBar myDelegate;
//***************************
//**** Form Events ********
//***************************
public Form1()
{
InitializeComponent();
if (myForm == null)
{
myForm = this;
}
DataSets.Add(new DSVDataSet());
DataSets[typeOfDataset].BWorker = new BackgroundWorker();
DataSets[typeOfDataset].BWorker.WorkerSupportsCancellation = true;
myDelegate = new UpdateProgressBar(UpdateProgressBarMethod);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//e.Cancel = true;
if (DataSets[typeOfDataset].BWorker != null || DataSets[typeOfDataset].BWorker.IsBusy)
{
Thread.Sleep(1000);
DataSets[typeOfDataset].BWorker.CancelAsync();
}
Application.Exit();
}
//***************************
//*** Menu Items Events ***
//***************************
private void cSVToolStripMenuItem_Click(object sender, EventArgs e)
{
LoadFillDSVData(',');
}
//***************************
//*** DataGridViews Events **
//***************************
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
using (SolidBrush b = new SolidBrush(this.dataGridView1.RowHeadersDefaultCellStyle.ForeColor))
{
e.Graphics.DrawString(e.RowIndex.ToString(System.Globalization.CultureInfo.CurrentUICulture), this.dataGridView1.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);
}
int rowHeaderWidth = TextRenderer.MeasureText(e.RowIndex.ToString(), dataGridView1.Font).Width;
if (rowHeaderWidth + 22 > dataGridView1.RowHeadersWidth)
{
dataGridView1.RowHeadersWidth = rowHeaderWidth + 22;
}
}
private void dataGridView2_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
using (SolidBrush b = new SolidBrush(this.dataGridView2.RowHeadersDefaultCellStyle.ForeColor))
{
e.Graphics.DrawString(e.RowIndex.ToString(System.Globalization.CultureInfo.CurrentUICulture), this.dataGridView2.DefaultCellStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4);
}
int rowHeaderWidth = TextRenderer.MeasureText(e.RowIndex.ToString(), dataGridView2.Font).Width;
if (rowHeaderWidth + 22 > dataGridView2.RowHeadersWidth)
{
dataGridView2.RowHeadersWidth = rowHeaderWidth + 22;
}
}
//***************************
//****** Other Methods ******
//***************************
private void LoadFillDSVData(char delimiter)
{
//load file through openFileDialog
//some more openFileDialog code removed for simplicity
if (DataSets[typeOfDataset].BWorker != null || DataSets[typeOfDataset].BWorker.IsBusy)
{
Thread.Sleep(1000);
DataSets[typeOfDataset].BWorker.CancelAsync();
DataSets[typeOfDataset].BWorker.Dispose();
}
//if file was loaded, instantiate the class
//and populate it
dataGridView1.Rows.Clear();
dataGridView2.Rows.Clear();
typeOfDataset = 0;
DataSets[typeOfDataset] = new DSVDataSet();
DataSets[typeOfDataset].DataGrid = this.dataGridView1;
DataSets[typeOfDataset].BWorker = new BackgroundWorker();
DataSets[typeOfDataset].InputFile = openFileDialog1.FileName;
DataSets[typeOfDataset].FileName = Path.GetFileName(DataSets[typeOfDataset].InputFile);
DataSets[typeOfDataset].InputPath = Path.GetDirectoryName(DataSets[typeOfDataset].InputFile);
DataSets[typeOfDataset].Delimiter = delimiter;
//read file to get number of objects and attributes
DataSets[typeOfDataset].LoadFile(DataSets[typeOfDataset].InputFile, DataSets[typeOfDataset].Delimiter);
//ask to autodetect metadata
DialogResult dr = MessageBox.Show("Auto detect attributes?", "TestApp", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
switch (dr)
{
case DialogResult.Yes:
toolStripStatusLabel1.Text = "Autodetecting attributes...";
toolStripProgressBar1.Value = 0;
toolStripProgressBar1.Maximum = 100;
toolStripProgressBar1.Style = ProgressBarStyle.Continuous;
DataSets[typeOfDataset].AutoDetectMetadata(DataSets[typeOfDataset].Attributes);
break;
case DialogResult.No:
break;
default:
break;
}
}
public void UpdateProgressBarMethod(int progress)
{
if (progress > 99)
{
toolStripProgressBar1.Value = progress;
toolStripStatusLabel1.Text = "Done.";
}
else
{
toolStripProgressBar1.Value = progress;
}
}
}
}
And one more class:
DSVDataSet.cs
namespace TestApp
{
public class DSVDataSet : DataSet
{
static Form1 myForm = Form1.MyForm;
//constructor(s)
public DSVDataSet()
{
InputType = DataSetType.DSV;
}
//autodetects metadata from the file if
//the user wishes to do so
public override void AutoDetectMetadata(List<Attribute> attributeList)
{
BWorker.WorkerReportsProgress = true;
BWorker.WorkerSupportsCancellation = true;
BWorker.DoWork += worker_DoWork;
BWorker.ProgressChanged += worker_ProgressChanged;
BWorker.RunWorkerCompleted += worker_RunWorkerCompleted;
//send this to another thread as it is computationally intensive
BWorker.RunWorkerAsync(attributeList);
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
List<Attribute> attributeList = (List<Attribute>)e.Argument;
using (StreamReader sr = new StreamReader(InputFile))
{
for (int i = 0; i < NumberOfAttributes; i++)
{
Attribute a = new Attribute();
attributeList.Add(a);
}
for (int i = 0; i < NumberOfObjects; i++)
{
string[] DSVLine = sr.ReadLine().Split(Delimiter);
int hoistedCount = DSVLine.Count();
string str = string.Empty;
for (int j = 0; j < hoistedCount; j++)
{
bool newValue = true;
str = DSVLine[j];
for (int k = 0; k < attributeList[j].Categories.Count; k++)
{
if (str == attributeList[j].Categories[k])
{
newValue = false;
}
}
if (newValue == true)
{
attributeList[j].Categories.Add(str);
//removed some code for simplicity
}
}
int currentProgress = (int)((i * 100) / NumberOfObjects);
if (BWorker.CancellationPending)
{
Thread.Sleep(1000);
e.Cancel = true;
return;
}
BWorker.ReportProgress(currentProgress); //report progress
}
}
e.Result = 100; //final result (100%)
}
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
int update = e.ProgressPercentage;
myForm.BeginInvoke(myForm.myDelegate, update);
}
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
return;
}
if (e.Cancelled)
{
return;
}
else
{
int update = (int)e.Result;
myForm.Invoke(myForm.myDelegate, update);
for (int i = 0; i < Attributes.Count; i++)
{
DataGridViewRow item = new DataGridViewRow();
item.CreateCells(DataGrid);
item.Cells[0].Value = Attributes[i].Name;
switch (Attributes[i].Type)
{
case AttributeType.Categorical:
item.Cells[1].Value = "Categorical";
break;
//removed some cases for simplicity
default:
item.Cells[1].Value = "Categorical";
break;
}
item.Cells[2].Value = Attributes[i].Convert;
DataGrid.Rows.Add(item);
}
BWorker.Dispose();
}
}
}
}
Long story short, I have a backGroundWorker in DSVDataset.cs that does some 'heavy computation' so the UI doesn't freeze (new to this), and I use a delegate to have the background thread to communicate with the UI thread to update some progress bar values. If the user decides to make a new DSVDataSet (through cSVToolStripMenuItem_Click or tSVToolStripMenuItem_Click) then I've added some ifs wherever I've found appropriate that check if there's already a backGroundWorker running: if there is, call CancelAsync so it stops whatever it's doing and then .Dispose it.
Now, sometimes when I try to exit the Form1 while a backGroundWorker might be running (check for example Form1_FormClosing) I get the error that is in the title of this post. The error takes me to this chunk of code in DSVDataSet.cs:
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
int update = e.ProgressPercentage;
myForm.BeginInvoke(myForm.myDelegate, update);
}
Pressing F10 takes me to Program1.cs:
Application.Run(new Form1());
Based on another stackoverflow post I read (http://stackoverflow.com/questions/513131/c-sharp-compile-error-invoke-or-begininvoke-cannot-be-called-on-a-control-unti , look at the answer), I implemented that logic by exposing the instance of the Main class itself so it always points to this instance of main.
So in Form1.cs:
private static Form1 myForm;
public static Form1 MyForm
{
get
{
return myForm;
}
}
public Form1()
{
InitializeComponent();
if (myForm == null)
{
myForm = this;
}
}
And in DSVDataset.cs:
static Form1 myForm = Form1.MyForm;
and I use myForm wherever needed.
Still, I'm not able to get past that error, so I can only assume I haven't implemented that solution correctly, or I'm doing something wrong with handling the backGroundWorkers.
Any help would be greatly appreciated and I did my best to be as detailed as a could (hope this wasn't an overkill :)
Regards
A:
The code is too much to understand all of them. But it seems the background worker is still working when you're closing the form, thus, a progress change of background worker will make your program crash.
For the quick solution, check form state when progress change,as I don't have much experiences on winform, but it must exists a method to check if the form is closing or disposing.
This is not suggested as it will couple UI and logic.
A:
As dBear says, it's likely that your background worker is still firing progress changed events after your form has been disposed. It'd be a good idea to either block the form from closing until the background worker is finished, or to kill the background worker before you close the form. Regardless of which of these options you choose, it's better to do this kind of communication using events. Add the following event definition to DSVDataSet, and modify the progress changed event handler:
public event ProgressChangedEventHandler ProgressChanged;
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (ProgressChanged != null) {
ProgressChanged(this, e);
}
}
Once you've done that, you'll need to make a change in Form1, so that once you've created a new instance of DSVDataSet, you add an event handler:
dsv.ProgressChanged += new ProgressChangedEventHandler(dsv_ProgressChanged);
Put whatever code you need to display the progress into the body of dsv_ProgressChanged, something like:
void dsv_ProgressChanged(object sender, ProgressChangedEventArgs e) {
myForm.Invoke(myForm.myDelegate, update);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
mongodb java to join two collections
I am newbie to mongodb. I need to do a query by joinin two collections.
comments
{ uid:12345, pid:444, comment="blah" }
{ uid:12345, pid:888, comment="asdf" }
{ uid:99999, pid:444, comment="qwer" }
users
{ uid:12345, name:"john" }
{ uid:99999, name:"mia" }
query: Select c.pid, c.comment from comments c, users u uwhere c.uid = u.uid;
I need to perform it using java api for mongodb. I know that mongodb doesnot support joins. I have an idea to implement, but I dont know whether its the best one.
idea:
performing two queries by splitting it. ( retrieving the uuid from users collections and checking against uuid of comments collection)
Any other idea to implement it? Could anyone send me the mongodb java code to perform this query by spliting into two queries and getting the result.
A:
for each retrieved user
find every comments for this user
or using DBRef
for each comment
DBRef::fetch(comment.user)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
regex ms word 2013 white line
I am searching on how I can find a replace following:
[white line]
[integer]
[white line]
so anything i would like to copy / replace anything that: has a new line followed by an integer on the new line followed by another new line.
Can this be done?
A:
I've never really worked with regex before but I figure I'd give it a go
^13{2}<[0-9]@>^13{2}
Since this is in Ms-word ^13 finds line breaks and 2 line breaks consecutively will get you a white line, <[0-9]@> is finding a group of integers and then it finds 2 more line breaks for another white line.
Make sure to turn on wildcards!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
webkit transform rotate not working on Safari
Im trying to make the rotation of this CSS animation work on Safari.
@keyframes hexagon {
0% { transform:rotate(0deg); }
50% { transform:rotate(360deg); }
68% { transform:rotate(0deg); transform:scale(1); }
71% { transform:rotate(0deg); transform:scale(1); }
76% { transform:rotate(360deg); transform:scale(1.25); }
85% { transform:rotate(360deg); transform:scale(1); }
86% { transform:rotate(360deg); transform:scale(1); }
100% { transform:rotate(0deg); }
}
You can check it at https://codepen.io/bryceyork/pen/JdRbQw
I have added the webkit- prefix, but its still not working:
@-webkit-keyframes hexagon {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
50% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
}
68% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
-webkit-transform: scale(1);
transform: scale(1);
}
71% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
-webkit-transform: scale(1);
transform: scale(1);
}
76% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
-webkit-transform: scale(1.25);
transform: scale(1.25);
}
85% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
-webkit-transform: scale(1);
transform: scale(1);
}
86% {
-webkit-transform: rotate(360deg);
transform: rotate(360deg);
-webkit-transform: scale(1);
transform: scale(1);
}
100% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
}
You can check it at https://codepen.io/anon/pen/qoQGeL
What am I doing wrong? Should I add anything else?
A:
This problem is vexing, but I think I sort of solved it by brute force. You may want to tweak timing. I didn't touch your original keyframes, but did change the webkit keyframes. Using a different-coded set of keyframes for webkit seems to do the thing you want:
@keyframes hexagon {
0% { transform:rotate(0deg); }
50% { transform:rotate(360deg); }
68% { transform:rotate(0deg); }
71% { transform:rotate(0deg) scale(1); }
76% { transform:rotate(360deg) scale(1.25); }
85% { transform:rotate(360deg) scale(1); }
86% { transform:rotate(360deg); }
100% { transform:rotate(0deg); }
}
@-webkit-keyframes hexagon {
0% {
-webkit-transform:rotate(0deg) scale(1);
}
75% {
-webkit-transform:rotate(360deg) scale(1);
}
75.1% {
-webkit-transform:rotate(0deg) scale(1);
}
80% {
-webkit-transform:rotate(0deg) scale(1);
}
88% {
-webkit-transform:rotate(0deg) scale(1.25);
}
96% {
-webkit-transform:rotate(0deg) scale(1);
}
100% {
-webkit-transform:rotate(0deg) scale(1);
}
}
https://codepen.io/anon/pen/zWeYwL
You'll note in the codepen I also do this:
-webkit-animation: hexagon 3.5s ease infinite;
animation: hexagon 4s ease-in-out
As to WHY this works... honestly I do not know. Feels like a bug. Not tested in IE!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ubuntu adding path/Environment variables
I am trying to install apache maven 3 in Ubuntu 12.04 lts. What I did was open the terminal then I typed the following commands
export M2_HOME=/usr/local/apache-maven/apache-maven-3.0.5 [Then pressed Enter]
export M2=$M2_HOME/bin [Then pressed Enter]
export PATH=$M2:$PATH [Then pressed Enter]
After that I typed
mvn --version
and it displayed all the necessary information but after closing the terminal, again I typed the command mvn --version
then it said that 'mvn' is not recognized
The program 'mvn' can be found in the following packages:
* maven
* maven2
Try sudo apt-get install <selected-page>
is there a way to permanently add a PATH variable in Ubuntu?
A:
Add those export lines to your ~/.profile file.
If you want it to apply to all users on the system, put it in /etc/profile instead;
sudoedit /etc/profile
Once you've edited either, you'll see the effect next time you log in.
See also http://mywiki.wooledge.org/DotFiles
On a side-note, if you instead install maven via the software center or apt-get, you won't need to do any of the above.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Was the Klingon Empire at war with the Federation during the events shown in DS9: The Way of the Warrior?
I have just watched "The Way of the Warrior" (first episode of 4th season of Deep Space Nine) and I found one of Sisko's reactions weird.
He says to Dukat:
Then I'll be there to reason with them. I doubt the Klingons will fire on a Federation ship.
Just a few minutes (hours) after telling his own crew, in DS9's Ops, that:
(...) The Klingons have withdrawn from the Khitomer Accords. The peace treaty between the Federation and the Klingon Empire... has ended.
The reaction to Dukat seems to be the opposite of his reaction to the crew of DS9. What prevents the Klingons from firing based on these events?
Can anyone explain this to me? Is there anything, that I'm missing? Because, for me, this is a clear mistake in a script.
A:
There's a big difference between withdrawing from a peace treaty and going to war.
The Klingon withdrawal from the Khitomer Accords doesn't necessarily mean that they want to go to war with the Federation, which is of course what would happen if they fired on a Federation ship.
There's no peace treaty between the USA and North Korea, but it's still highly unlikely that North Korea would fire on a US ship outside North Korean territory.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
C# Counting properties of Class with child/nested objects
I have the following construction of classes, here simplified as child classes of a 'mother' class called DataClass, which also contains one simple method:
public class DataClass
{
public int num { get; set; }
public string code { get; set; }
public PartClass part { get; set; }
public MemberClass member { get; set; }
public int Count()
{
Type t = typeof(DataClass);
return typeof(DataClass).GetProperties().Length;
}
}
public class PartClass
{
public int seriesNum { get; set; }
public string seriesCode { get; set; }
}
public class MemberClass
{
public int versionNum { get; set; }
public SideClass side { get; set; }
}
public class SideClass
{
public string firstDetail { get; set; }
public string secondDetail { get; set; }
public bool include { get; set; }
}
The issue is, I want to refactor the method so that it can give me an accurate counting of all properties found, including the ones in nested or child classes. In the above example, it only counts properties of DataClass, while I wanted it to return 2 for DataClass + 2 for PartClass + 1 for MemberClass + 3 for SideClass, sums up to 8 properties you may set through DataClass.
Can someone help me with this?
A:
You can introduce interface with Count() method
public interface ICountable
{
int Count();
}
And use this interface to mark all types, which properties are participating in Count() calculation.
You can see the generic abstract class to implement this interface below. Generic T parameter is type whose properties need to be calculated. You implement a calculation logic only once and inherit this class where needed. You also go through all of properties, implementing ICountable, to calculate them as well (some kind of recursion)
public abstract class Countable<T> : ICountable
{
public int Count()
{
Type t = typeof(T);
var properties = t.GetProperties();
var countable = properties.Select(p => p.PropertyType).Where(p => typeof(ICountable).IsAssignableFrom(p));
var sum = countable.Sum(c => c.GetProperties().Length);
return properties.Length + sum;
}
}
and inherit it in your classes
public class DataClass : Countable<DataClass>
{
...
}
public class PartClass : Countable<PartClass>
{
...
}
public class MemberClass : Countable<MemberClass>
{
...
}
public class SideClass : Countable<SideClass>
{
...
}
And this is for the test
var dataClass = new DataClass();
var count = dataClass.Count();
It returns 8 as expected
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to fade in images when loaded with Vue
I created this component that fades in an image once it is loaded to the client. I would think there is a more Vue-like way to solve this, like using Vue events, but could not find it. What is the Vue way to detect when an image is loaded?
https://codepen.io/kslstn/pen/ooaPGW
Vue.component('imageThatFadesInOnLoad',{
data: function(){
return {
src: 'http://via.placeholder.com/350x150',
loaded: false,
}
},
mounted: function () {
var image = new Image()
var that = this
this.loaded = image.addEventListener('load', function(){that.onLoaded()}) // This is the key part: it is basically vanilla JS
image.src = this.src
},
methods:{
onLoaded(){
this.loaded = true
}
},
template: `
<div class="wrapper">
<transition name="fade">
<img class="icon" v-bind:src="src" v-if="loaded">
</transition>
</div>
`
})
new Vue({
el: '#wrapper'
});
.wrapper{
width: 350px;
height: 150px;
background: slategrey;
}
.fade-enter-active {
transition: opacity 3s ease-in-out;
}
.fade-enter-to{
opacity: 1;
}
.fade-enter{
opacity: 0;
}
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="wrapper">
<image-that-fades-in-on-load></image-that-fades-in-on-load>
</div>
A:
You can use the v-on: (or @ shorthand) syntax for binding to any DOM event. In your case the load event, which is triggered when the image is loaded.
Because you are loading the image "the DOM way" you can't use v-if because then Vue will not render the element (but you need it to, so the image src is fetched). Instead you can use v-show, which will render but hide the element.
Vue.component('imageThatFadesInOnLoad', {
data: function() {
return {
src: 'http://via.placeholder.com/350x150',
loaded: false,
}
},
methods: {
onLoaded() {
this.loaded = true;
}
},
template: `
<div class="wrapper">
<transition name="fade">
<img class="icon" v-bind:src="src" v-on:load="onLoaded" v-show="loaded">
</transition>
</div>
`
});
new Vue({
el: '#wrapper'
});
.wrapper {
width: 350px;
height: 150px;
background: slategrey;
}
.fade-enter-active {
transition: opacity 3s ease-in-out;
}
.fade-enter-to {
opacity: 1;
}
.fade-enter {
opacity: 0;
}
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="wrapper">
<image-that-fades-in-on-load></image-that-fades-in-on-load>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a professional etiquette regarding jackets in academia?
So, I’m sure we all know about the stereotype of the professor in the tweed jacket. Based on a cursory web search, it looks like the stereotype started because tweed was a relatively cheap but warm material, and professors were a relatively poorly paid class of professionals, so they kept wearing them until the elbows wore out and they patched them.
I’m aware that these sorts of things can get a degree of momentum of their own, though, so I was wondering if there was any etiquette in modern academia regarding jackets? I’m a master’s student who is planning on doing a PhD afterwards with the intention of getting into academia; would buying a tweed jacket to try to look professional be viewed as presumptuous or anything?
A:
I don't know if I'd call it an etiquette, but there are certainly different ways to dress in different subfields of disciplines. If you attend an academic conference and notice such things you will see the variety by clique. As for tweed, my partner and I wore it as students (bought second-hand in Edinburgh) and we were mostly viewed as the eccentrics we are, as far as I know. Dressing decently generally shows respect for others, though a few people find it an affront to their class consciousness. Dressing expensively can be seen as distancing from those who can't afford it. The main thing is to be confident that you are presenting yourself as who you really are, so then if there are any concerns you can hopefully laugh them off or explain your dress as a matter of personal taste and/or a concern for general aesthetics.
A:
Simple, smart, clean clothes
Stick to conventional office clothing, if you want to convey efficiency. Do not waste money on expensive clothes to impress, but also do not look shabby or unkempt if you can avoid it.
You will (or should be!) judged on the quality of your work, and not on your clothing, unless it is dirty or outstandingly ill-fitting.
I am a professor of medicine. I am glad you are asking your question here, anonymously and you are not one of my students asking me in person: I would rebuke you for wasting time thinking about trivialities, and perhaps even for thinking I am so vain as to spend my every last penny on clothes! I can certainly afford far, far more expensive clothes, car and home than I have, but I don't want to.
When presenting at an external meeting, though, try to look smart. This does not have to be expensive. Wear the clothes your teachers wear in such occasions. If you don't know what they are going to wear (say tomorrow), then make an estimate and "round up". If you are slightly overdressed, nobody will notice. If you are markedly under-dressed, it might attract unfavourable attention.
In my field, the most cost-effective approach for students who don't want to spend much is to have a standard interview suit, and use it for presentations in front of big groups or external audiences, and for interviews. And then stop thinking about it. Work on your research instead.
By the way, my personal approach for myself? I always wear black trousers. They are interchangeable. Any time I need to give a presentation, I use any one of a handful of black suit jackets I keep in various places. It vaguely looks like a suit, in the sense that nobody notices it isn't, and nobody cares. The moment you start to get different coloured suits, you are in for a world of expensive fiddling around where you have to have the particular matching set, and damage to one part of one thing messes up a lot of money in one go. I save my brain cell
time for funner things than colour-matching, like StackExchange.
A:
When I was a masters student (management science) at Imperial College 50 years ago, I chose to wear a suit and tie. Fortunately for me, I must have had other characteristics that compensated for the obvious eccentricity of my dress, so I survived.
I am now a PhD student (statistics) at a leading UK university. I have seen no evidence that any of the academic staff, including full professors, know what a tweed jacket is, let alone would wear a jacket of that or any other kind in their daily work.
From what I know of Australia, I would suppose that it tends to be less formal than the UK.
My conclusion is that you are likely to be overdressed in daily academic life if you wear a jacket. That might or might not be a disadvantage: a friend of mine claimed that his professional career took off because his taste in collars (stiff and high) meant that people remembered him, but he did of course have outstanding professional skills as well.
It all turns on whether you think people will think of you as "that weird guy who wears a jacket all the time" or as "that brilliant guy, you know, the one who wears a jacket."
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Hiding "0" in title of any part of {report} documentclass
I have a report which is structured part just look like this:
\documentclass{report}
\usepackage[compact,explicit]{titlesec}
\begin{document}
\titleformat{\section}[runin]{\large\bfseries}{}{0pt}{#1\quad\thesection}
\section{Pasal}
\section{Pasal}
\section{Pasal}
\section{Pasal}
\section{Pasal}
\end{document}
All the \section{Pasal} generate title section Pasal 0.1, Pasal 0.2, etc. Please help, I don't have any idea to erase the 0.
A:
\documentclass{report}
\usepackage[compact,explicit]{titlesec}
\renewcommand{\thesection}{\arabic{section}}
\begin{document}
\titleformat{\section}[runin]{\large\bfseries}{}{0pt}{#1\quad\thesection}
\section{Pasal}
\section{Pasal}
\section{Pasal}
\section{Pasal}
\section{Pasal}
\end{document}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to simulate ConfigurationManager in LINQPad
I'm trying to test some code in LINQPad. However, the base class calls Configuration Manager. How can I simulate that when testing in LINQPad.
void Main()
{
var tRepo = new TestRepository();
var result = tRepo.GetAsync(1);
result.Dump();
}
public partial class TestRepository : BaseRepository<Customer>, ICustomerRepository
{
// Here base throws the errror
public TestRepository() : base("DbConnString")
{
}
}
Here's the constructor for BaseRepository (from a compiled DLL, so not editable in LINQPad):
protected BaseRepository(string connectionStringName)
{
var connectionString = ConfigurationManager.ConnectionStrings[connectionStringName];
Connection = new SqlConnection(connectionString.ConnectionString);
Connection.Open();
}
A:
The answer can be found on the LinqPad website FAQ
http://www.linqpad.net/faq.aspx
I'm referencing a custom assembly that reads settings from an application configuration file (app.config). Where should I put my application config file so that LINQPad queries will pick it up?
Create a file called linqpad.config in the same folder as LINQPad.exe and put your configuration data there. Don't confuse this with linqpad.exe.config:
•linqpad.exe.config is for the LINQPad GUI
•linqpad.config is for your queries.
A:
Something that might be useful for you, I created it some time ago.
This is an extension method, which you can use to force the reload of configuration from specific file. It uses reflection to change the private fields in the manager, clears the configuration and then conditionally reloads it. It is much easier than manually editing the config file of LINQPad.
public static void ForceNewConfigFile(this Type type, bool initialize = true)
{
var path = type.Assembly.Location + ".config";
if (!File.Exists(path))
throw new Exception("Cannot find file " + path + ".");
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path);
var typeOfConfigManager = typeof(ConfigurationManager);
typeOfConfigManager.GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, 0);
typeOfConfigManager.GetField("s_configSystem", BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, null);
var typeOfClientConfigPaths = typeOfConfigManager.Assembly.GetTypes().Where(x => x.FullName == "System.Configuration.ClientConfigPaths").Single();
typeOfClientConfigPaths.GetField("s_current", BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, null);
if (initialize)
{
var dummy = ConfigurationManager.AppSettings;
}
}
Example usage:
typeof(SomeType).ForceNewConfigFile();
System.Configuration.ConfigurationManager.AppSettings.Dump();
SomeType is just a type contained in the assembly, which will be used as a source for location of the config file. Assumption is: configuration file exists beside the DLL file and is named {Assembly.Location}.config.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What is an "integer"? (TypeError: argument must be integer, not int)
I am trying to use a function from autopy and get the error message
TypeError: argument must be integer<H>, not int
What does this "integer<H>" mean?
My code:
import autopy, os, time
from autopy import key
time.sleep(1)
key.tap(key.K_RETURN)
A:
The error indicates that autopy was not happy with the type of the passed key and that that type was int. What type it expected instead is (at least to me) completely unclear from the error message. integer<H> doesn't really mean anything in Python, AFAIK, so that doesn't make a lot of sense. Maybe this library has its own notation for type constraints.
A comment on the autopy issue tracker mentions
key.toggle(long(key.K_DELETE), True)
as a workaround, which indicates that (in some situations, probably specific to operating system and/or Python version) the expected type is long. Applied to your code, that'd be
key.tap(long(key.K_RETURN))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Navigation and DI
Im trying to make a standard code to use in order to implement in my xamarin.forms apps. What I want to do is to have a way to navigate between viewmodels and a wey to correctly implement dependency injection.
What I'm currently doing for navigation:
await Navigation.PushAsync(new SecondPageView());
And for DI:
var test = DependencyService.Get<ITestService>();
WelcomeMessage = test.GetSystemWelcome();
I know that the correct way to implement Di is creating an interface and proceed from that step but the problem is that when I try, I fail trying to have a good navigation system (like register the view and the view model in a file apart).
Does anyone have a sample example that I can have a look? Or maybe some indications in order to proceed?
PD: I trying to avoid frameworks like MvvMcross things like that.
Thanks in advance!
A:
(I will try to simplify all the code examples as much as possible).
1. First of all we need a place where we could register all our objects and optionally define their lifetime. For this matter we can use an IOC container, you can choose one yourself. In this example I will use Autofac(it is one of the fastest available). We can keep a reference to it in the App so it will be available globally (not a good idea, but needed for simplification):
public class DependencyResolver
{
static IContainer container;
public DependencyResolver(params Module[] modules)
{
var builder = new ContainerBuilder();
if (modules != null)
foreach (var module in modules)
builder.RegisterModule(module);
container = builder.Build();
}
public T Resolve<T>() => container.Resolve<T>();
public object Resolve(Type type) => container.Resolve(type);
}
public partial class App : Application
{
public DependencyResolver DependencyResolver { get; }
// Pass here platform specific dependencies
public App(Module platformIocModule)
{
InitializeComponent();
DependencyResolver = new DependencyResolver(platformIocModule, new IocModule());
MainPage = new WelcomeView();
}
/* The rest of the code ... */
}
2.We will need an object responsible for retrieving a Page (View) for a specific ViewModel and vice versa. The second case might be useful in case of setting the root/main page of the app. For that we should agree on a simple convention that all the ViewModels should be in ViewModels directory and Pages(Views) should be in the Views directory. In other words ViewModels should live in [MyApp].ViewModels namespace and Pages(Views) in [MyApp].Views namespace. In addition to that we should agree that WelcomeView(Page) should have a WelcomeViewModel and etc. Here is a code example of a mapper:
public class TypeMapperService
{
public Type MapViewModelToView(Type viewModelType)
{
var viewName = viewModelType.FullName.Replace("Model", string.Empty);
var viewAssemblyName = GetTypeAssemblyName(viewModelType);
var viewTypeName = GenerateTypeName("{0}, {1}", viewName, viewAssemblyName);
return Type.GetType(viewTypeName);
}
public Type MapViewToViewModel(Type viewType)
{
var viewModelName = viewType.FullName.Replace(".Views.", ".ViewModels.");
var viewModelAssemblyName = GetTypeAssemblyName(viewType);
var viewTypeModelName = GenerateTypeName("{0}Model, {1}", viewModelName, viewModelAssemblyName);
return Type.GetType(viewTypeModelName);
}
string GetTypeAssemblyName(Type type) => type.GetTypeInfo().Assembly.FullName;
string GenerateTypeName(string format, string typeName, string assemblyName) =>
string.Format(CultureInfo.InvariantCulture, format, typeName, assemblyName);
}
3.For the case of setting a root page we will need sort of ViewModelLocator that will set the BindingContext automatically:
public static class ViewModelLocator
{
public static readonly BindableProperty AutoWireViewModelProperty =
BindableProperty.CreateAttached("AutoWireViewModel", typeof(bool), typeof(ViewModelLocator), default(bool), propertyChanged: OnAutoWireViewModelChanged);
public static bool GetAutoWireViewModel(BindableObject bindable) =>
(bool)bindable.GetValue(AutoWireViewModelProperty);
public static void SetAutoWireViewModel(BindableObject bindable, bool value) =>
bindable.SetValue(AutoWireViewModelProperty, value);
static ITypeMapperService mapper = (Application.Current as App).DependencyResolver.Resolve<ITypeMapperService>();
static void OnAutoWireViewModelChanged(BindableObject bindable, object oldValue, object newValue)
{
var view = bindable as Element;
var viewType = view.GetType();
var viewModelType = mapper.MapViewToViewModel(viewType);
var viewModel = (Application.Current as App).DependencyResolver.Resolve(viewModelType);
view.BindingContext = viewModel;
}
}
// Usage example
<?xml version="1.0" encoding="utf-8"?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:viewmodels="clr-namespace:MyApp.ViewModel"
viewmodels:ViewModelLocator.AutoWireViewModel="true"
x:Class="MyApp.Views.MyPage">
</ContentPage>
4.Finally we will need a NavigationService that will support ViewModel First Navigation approach:
public class NavigationService
{
TypeMapperService mapperService { get; }
public NavigationService(TypeMapperService mapperService)
{
this.mapperService = mapperService;
}
protected Page CreatePage(Type viewModelType)
{
Type pageType = mapperService.MapViewModelToView(viewModelType);
if (pageType == null)
{
throw new Exception($"Cannot locate page type for {viewModelType}");
}
return Activator.CreateInstance(pageType) as Page;
}
protected Page GetCurrentPage()
{
var mainPage = Application.Current.MainPage;
if (mainPage is MasterDetailPage)
{
return ((MasterDetailPage)mainPage).Detail;
}
// TabbedPage : MultiPage<Page>
// CarouselPage : MultiPage<ContentPage>
if (mainPage is TabbedPage || mainPage is CarouselPage)
{
return ((MultiPage<Page>)mainPage).CurrentPage;
}
return mainPage;
}
public Task PushAsync(Page page, bool animated = true)
{
var navigationPage = Application.Current.MainPage as NavigationPage;
return navigationPage.PushAsync(page, animated);
}
public Task PopAsync(bool animated = true)
{
var mainPage = Application.Current.MainPage as NavigationPage;
return mainPage.Navigation.PopAsync(animated);
}
public Task PushModalAsync<TViewModel>(object parameter = null, bool animated = true) where TViewModel : BaseViewModel =>
InternalPushModalAsync(typeof(TViewModel), animated, parameter);
public Task PopModalAsync(bool animated = true)
{
var mainPage = GetCurrentPage();
if (mainPage != null)
return mainPage.Navigation.PopModalAsync(animated);
throw new Exception("Current page is null.");
}
async Task InternalPushModalAsync(Type viewModelType, bool animated, object parameter)
{
var page = CreatePage(viewModelType);
var currentNavigationPage = GetCurrentPage();
if (currentNavigationPage != null)
{
await currentNavigationPage.Navigation.PushModalAsync(page, animated);
}
else
{
throw new Exception("Current page is null.");
}
await (page.BindingContext as BaseViewModel).InitializeAsync(parameter);
}
}
As you may see there is a BaseViewModel - abstract base class for all the ViewModels where you can define methods like InitializeAsync that will get executed right after the navigation. And here is an example of navigation:
public class WelcomeViewModel : BaseViewModel
{
public ICommand NewGameCmd { get; }
public ICommand TopScoreCmd { get; }
public ICommand AboutCmd { get; }
public WelcomeViewModel(INavigationService navigation) : base(navigation)
{
NewGameCmd = new Command(async () => await Navigation.PushModalAsync<GameViewModel>());
TopScoreCmd = new Command(async () => await navigation.PushModalAsync<TopScoreViewModel>());
AboutCmd = new Command(async () => await navigation.PushModalAsync<AboutViewModel>());
}
}
As you understand this approach is more complicated, harder to debug and might be confusing. However there are many advantages plus you actually don't have to implement it yourself since most of the MVVM frameworks support it out of the box. The code example that is demonstrated here is available on github. There are plenty of good articles about ViewModel First Navigation approach and there is a free Enterprise Application Patterns using Xamarin.Forms eBook which is explaining this and many other interesting topics in detail.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Document Core Pack fetch
can anyone give me an Example of fetch Condition that i can used for the Document Core Pack fetchxml
i use the DCP for a dynamics crm Template.
A:
You can use advanced find and export Fetch xml and use that.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Does $\pi_1(X, x_0)$ act on $\tilde{X}$?
Let $X$ be a path connected, locally path connected space and let $p:\tilde{X} \to X$ be a covering map. Let $x_0\in X$. Then we have a natural right action of $\pi_1(X, x_0)$ on the fibre $p^{-1}(x_0)$ given by $x'_0\cdot [\gamma] =\tilde{\gamma} (1)$. Where $\tilde {\gamma} $ is the unique lift of $\gamma$ beginning at $x'_0$.
However, is there an action of this group on all of $\tilde {X}$?
A:
As you noted in your question, $\pi_1(X,x_0)$ acts on $p^{-1}(x_0)$ by permuting the points (i.e. the lifts of $x_0$) around. But if you're looking for a group which acts on the entire space $\tilde X$ (which I believe is your question?) then you'd want the group of deck transformations $G(\tilde X)$. This group is the collection of all covering space isomorphisms $f:(\tilde X, \tilde x_0)\to (\tilde X,\tilde x_0)$, i.e. homeomorphisms of $\tilde X$ which satisfy $p=p\circ f$. (So intuitively, a homeomorphism $f$ is an element of $G(\tilde X)$ if the projection or "shadow" of $\tilde X$ onto $X$ looks just like the projection/"shadow" of the 'homeomorphed' space $f(\tilde X)$ onto $X$).
In general, $\pi_1(X)$ and $G(\tilde X)$ are not isomorphic. But if $\tilde X$ is the universal cover then they are. (See, for instance, Proposition 1.39 of Hatcher to see a more general relationship between $G$ and $\pi_1$.) So in that case, the action of $\pi_1$ on the elements of $p^{-1}(x_0)$ does indeed coincide with an action on all of $\tilde X$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Illustrator CC 2017 reset bounding box missing on square
I can't find the reset bounding box option, thing that I was able to do in the previous versions of Illustrator when building an arrow head. I am not looking for a different method on how to make an arrow head but only to understand why I'm not able to see the reset bounding box option.
In a nutshell:
after building a square and rotating it by 45˚ I was right clicking on the square and clicking on the reset bounding box option.
I was using this method so I could scale relative the rotated square shape on a vertical axis. The reset bounding box appears only if I move one of the anchor points.
I hope this is clear enough, if not let me know if you need any other information.
Cheers
A:
When you rotate a shape in Illustrator CC 2017, it remains a live shape. Once you convert the shape to a path (such as by moving an anchor point, as you mentioned), the rectangle ceases to be a live shape and you will be able to reset the bounding box. At this point, you lose the benefits of the live shape (editing rounded corners, for example).
When you first draw the shape, you can expand it (Object -> Shape -> Expand Shape) to regain the Reset Bounding Box command.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Fatou's Lemma application
Above is a theorem from Durrett. Could someone explain how the line "so Fatou's lemma applies"?
A:
To see this in full transparency, first we need to show $\liminf_{n\to\infty} 1_G(Y_n) = 1_{\liminf_{n\to\infty}\,[Y_n\in G]}$. Simplify this a bit by noting that $1_G(Y_n) = 1_{[Y_n\in G]}$. Make one more simplification by replacing the event $[Y_n\in G]$ with an arbitrary event $E_n$, and we are reduced to showing $$\liminf_{n\to\infty} 1_{E_n} = 1_{\liminf_{n\to\infty}E_n}.$$
The event $\liminf_{n\to\infty}E_n$ is defined as
$$
\liminf_{n\to\infty}\,E_n = \bigcup_{n=1}^\infty\bigcap_{k=n}^\infty E_k.
$$
So a point $\omega$ belongs to $\liminf_{n\to\infty}\,E_n$ if and only if $\omega$ eventually belongs to every $E_k$. Thus if $\omega$ belongs to $\liminf_{n\to\infty}E_n$, then $1_{E_n}(\omega) = 1$ for all $n$ sufficiently large, so $\liminf_{n\to\infty}1_{E_n}(\omega) = 1$. If $\omega\notin\liminf_{n\to\infty}E_n$, then $\omega$ belongs to infinitely many $E_n^c$. Hence $1_{E_n}(\omega) = 0$ for infinitely many $n$, so $\liminf_{n\to\infty}1_{E_n}(\omega) = 0$. Hence we have shown
$$
\liminf_{n\to\infty}1_{E_n}(\omega) =
\begin{cases}
1, & \text{if $\omega\in \liminf_{n\to\infty} E_n$}\\
0, & \text{if $\omega\notin\liminf_{n\to\infty} E_n$,}
\end{cases}
$$
so our claim is proved.
Since
$$
1_G(Y_\infty) \le \liminf_{n\to\infty} 1_G(Y_n)=1_{\liminf_{n\to\infty}[Y_n\in G]} \implies P(Y_\infty \in G) \le P\big(\liminf_{n\to\infty}\,[Y_n\in G]\big),
$$
Fatou's lemma implies that
$$
P\big(\liminf_{n\to\infty}\,[Y_n\in G]\big) \le \liminf_{n\to\infty}P(Y_n\in G).
$$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
"Sitting on one's head and make them work" - English counterpart?
Imagine a person who has agreed to do you a favor but he won't do it unless you are physically present in front of him/her. You couldn't expect him to do your work if you tell them once and leave them so they do it when they get time. In my mother-tongue, it's called 'sitting on one's head and make them work'(translated). I was wondering if there's one in English too.
EDIT: I realize sitting on one's head might get misconstrued as to be equal to someone's who is in-charge but actually the people are at same position of responsibility and the person (who agreed to do the favor) knows exactly what to do and how to do the said thing.
EDIT 2: The person who has agreed to do the favor is probably reluctant to do it or just forgets it or simply lacks the sense of urgency, thereby needs to be accompanied by the person asking the favor, so doesn't forget about it and do it instantly before anything else.
A:
Breathing down one's neck can qualify perhaps.
breathe down (someone's) neck:
To threaten by proximity, especially
by pursuing closely.
To watch or monitor closely, often annoyingly:
The boss was breathing down my neck all morning.
Example: If everyone keeps breathing down my neck, how can I get my work done?
|
{
"pile_set_name": "StackExchange"
}
|
Q:
SQL C# How to get each piece of data with a certain attribute
Okay so I have a table of reviews each with a rating and a movieID pertaining to which movie is being rated. I add in multiple ratings to one movieID and want to get the average of the ratings. Right now I'm just attempting to compute the total of the ratings, but unfortunately I'm only coming up with the first entered rating from my database. I'm trying to get all the ratings store them into an ArrayList and compute the total, here is the code...
if (movieId > -1) { //if movie id was found
sql = "select Rating from Reviews where MovieID = '" + movieId + "';";
result.Close();
dbCmd.Connection = dbConn;
dbCmd.CommandText = sql;
result = dbCmd.ExecuteReader();
ArrayList total = new ArrayList();
int i = 0;
while (result.Read())
{
try
{
total.Add((int)result.GetInt16(i));
}
catch (System.IndexOutOfRangeException)
{
MessageBox.Show("Looping, total count: " + total.Count);
break;
}
MessageBox.Show("Looping, total count: " + total.Count);
i++;
}
if (total.Count > 0) //if total was calculated
{
//double avg = (double)result;
int computedTotal = 0;
foreach(int j in total)
{
computedTotal += j;
}
msg = "AVG Reviews successfully computed total result = " + computedTotal;
Any insight would be appreciated.
A:
As Liang hinted at, if you want the sum of ratings you can change your SQL query to:
SELECT SUM(rating) AS totalRating FROM reviews WHERE movieid = 'What you want here'
That way, you can just store an int that is returned and not have to worry about anything else. I would also like to add, that if you want to get the average, you can replace that with the AVG() aggregate function, like this:
SELECT AVG(rating) AS averageRating FROM reviews WHERE movieid = 'What you want here'
I would also like to add that I recommend you use parameterized queries instead of concatenating the string like that. I think you should change the first few lines to this:
dbCmd.Connection = dbConn;
dbCmd.CommandText = "SELECT AVG(rating) AS averageRating FROM reviews WHERE movieID = @movieid";
dbCmd.CommandText.Parameters.AddWithValue("@movieid", movieId");
Here is info on aggregate functions and parameterized queries.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
String to hexadecimal Color Code
in a project I'm making I'm using numerous color codes.
the point is not for them to be Beautiful, just differents.(I also want to be able to constantly have the same colors code for the same fields on refresh (no Random color generators))
I was thinking about taking the name of the fields and turn them to Hex color.
Is there a pre-defined function for this?
Exemple :
$string = "Blablabla";
$colorCode = toColorCode($string);
function toColorCode($initial){
/*MAGIC MADNESS*/
return array("R"=>XXX,"G"=>XXX,"B"=>XXX);
}
FORGOT TO MENTION : it's important that the values are Numbers only.
A:
As far as I can understand, you want to generate a fairly unique color code for a string.
The easies way is to call a checksum function on the string, for example MD5:
function toColorCode($initial){
$checksum = md5($initial);
return array(
"R" => hexdec(substr($checksum, 0, 2)),
"G" => hexdec(substr($checksum, 2, 2)),
"B" => hexdec(substr($checksum, 4, 2))
);
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can I ask reviewers (via the editor) whether they lost track halfway through the paper?
I submitted a paper to a journal in linguistics. It was accepted pending some minor revisions w.r.t. typesetting and a few sentences that had to be reformulated. The reviewers gave eight comments on the introductory section, comprising roughly 1/3 of the paper, and only one on the rest. On the one hand, this may be expected, because I am less proficient with the broader context of the introduction and had most difficulties writing that section. On the other hand, I'm slightly worried that the reviewers lost track of the train of thought halfway through the paper.
I would like to know if the reviewers got lost in the paper, and what I might do to improve it if necessary. However, I have not found a good way to ask the editor. I don't want to suggest that the paper should not be published or that the reviewers may have been lazy or stupid. How can I ask for more feedback? Or should I just assume that no comments means well written?
I do not know how many people reviewed the paper; the editor aggregated the comments before sending them to me.
A:
This sounds like you wrote a good paper with some minor problems in the background/introduction that need fixing/polishing.
If reviewers get lost they should (and most likely will) mention that, and make you work a lot more. If, however, the editor and all reviewers have nothing to complain, your paper should be alright.
A:
I don't think you should ask this of the editors or reviewers at all. It's their job to evaluate the paper for publication, but it's not their job to help you improve it. At this point, they've given you all the comments they felt were necessary.
If you want more feedback on the paper, or suggestions on how it can be improved, then ask someone else - colleagues, collaborators, other researchers in the field. But not the reviewers.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
MySQL Query: Delete from 'table2' where column = 'value' IF column in 'table1' = 'value'
I am trying to execute a MySQL query to delete rows from 'table2' where column = 'value' IF column in 'table1' = 'value'
I have 2 tables...
Table 1 is called accounts
Table 2 is called inventoryitems
The column in question for accounts is called banned
The column in question for inventoryitems is called itemid
I would like to DELETE FROM inventoryitems WHERE itemid = 2340000
IF...
the column banned in accounts has a value of 1
You can join the table accounts to inventoryitems by a 3rd table called characters.
Table accounts has columns: id (primary key) and banned.
Table characters has columns: characterid and accountid (accountid links to id in table accounts).
Table inventoryitems has columns itemid and characterid (characterid links to characterid in table characters)
Hope I have provided enough information...
I have tried:
DELETE FROM inventoryitems
WHERE characterid IN
(SELECT characterid
from characters
WHERE accountid IN
(SELECT id
from accounts
WHERE banned = '1'
)
)
AND itemid = '2340000';
However this deletes all rows in the inventoryitems table where itemid = '234000'. Seems to still ignore the check for '1' in banned column of accounts table.... I think this is close though...
Here are the SHOW CREATE TABLE queries for the 3 tables:
'accounts', 'CREATE TABLE `accounts` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(13) NOT NULL default '',
`password` varchar(128) NOT NULL default '',
`salt` varchar(32) default NULL,
`loggedin` tinyint(4) NOT NULL default '0',
`lastlogin` timestamp NULL default NULL,
`createdat` timestamp NOT NULL default CURRENT_TIMESTAMP,
`birthday` date NOT NULL default '0000-00-00',
`banned` tinyint(1) NOT NULL default '0',
`banreason` text,
`gm` tinyint(1) NOT NULL default '0',
`email` tinytext,
`emailcode` varchar(40) default NULL,
`forumaccid` int(11) NOT NULL default '0',
`macs` tinytext,
`lastknownip` varchar(30) NOT NULL default '',
`lastpwemail` timestamp NOT NULL default '2002-12-31 17:00:00',
`tempban` timestamp NOT NULL default '0000-00-00 00:00:00',
`greason` tinyint(4) default NULL,
`paypalNX` int(11) default NULL,
`mPoints` int(11) default NULL,
`cardNX` int(11) default NULL,
`webadmin` int(1) default '0',
`lastlogininmilliseconds` bigint(20) unsigned NOT NULL default '0',
`guest` tinyint(1) NOT NULL default '0',
`donorpoints` tinyint(1) default NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`),
KEY `forumaccid` (`forumaccid`),
KEY `ranking1` (`id`,`banned`,`gm`)
) ENGINE=InnoDB AUTO_INCREMENT=753 DEFAULT CHARSET=latin1'
'characters', 'CREATE TABLE `characters` (
`id` int(11) NOT NULL auto_increment,
`accountid` int(11) NOT NULL default '0',
`world` int(11) NOT NULL default '0',
`name` varchar(13) NOT NULL default '',
`level` int(11) NOT NULL default '0',
`exp` int(11) NOT NULL default '0',
`str` int(11) NOT NULL default '0',
`dex` int(11) NOT NULL default '0',
`luk` int(11) NOT NULL default '0',
`int` int(11) NOT NULL default '0',
`hp` int(11) NOT NULL default '0',
`mp` int(11) NOT NULL default '0',
`maxhp` int(11) NOT NULL default '0',
`maxmp` int(11) NOT NULL default '0',
`meso` int(11) NOT NULL default '0',
`hpApUsed` int(11) NOT NULL default '0',
`mpApUsed` int(11) NOT NULL default '0',
`job` int(11) NOT NULL default '0',
`skincolor` int(11) NOT NULL default '0',
`gender` int(11) NOT NULL default '0',
`fame` int(11) NOT NULL default '0',
`hair` int(11) NOT NULL default '0',
`face` int(11) NOT NULL default '0',
`ap` int(11) NOT NULL default '0',
`sp` int(11) NOT NULL default '0',
`map` int(11) NOT NULL default '0',
`spawnpoint` int(11) NOT NULL default '0',
`gm` tinyint(1) NOT NULL default '0',
`party` int(11) NOT NULL default '0',
`buddyCapacity` int(11) NOT NULL default '25',
`createdate` timestamp NOT NULL default CURRENT_TIMESTAMP,
`rank` int(10) unsigned NOT NULL default '1',
`rankMove` int(11) NOT NULL default '0',
`jobRank` int(10) unsigned NOT NULL default '1',
`jobRankMove` int(11) NOT NULL default '0',
`guildid` int(10) unsigned NOT NULL default '0',
`guildrank` int(10) unsigned NOT NULL default '5',
`messengerid` int(10) unsigned NOT NULL default '0',
`messengerposition` int(10) unsigned NOT NULL default '4',
`reborns` int(11) NOT NULL default '0',
`mountlevel` int(9) NOT NULL default '1',
`mountexp` int(9) NOT NULL default '0',
`mounttiredness` int(9) NOT NULL default '0',
`petid` int(10) default '0',
`married` int(10) unsigned NOT NULL default '0',
`partnerid` int(10) unsigned NOT NULL default '0',
`cantalk` int(10) unsigned NOT NULL default '1',
`marriagequest` int(10) unsigned NOT NULL default '0',
`omokwins` int(11) NOT NULL default '0',
`omoklosses` int(11) NOT NULL default '0',
`omokties` int(11) NOT NULL default '0',
`matchcardwins` int(11) NOT NULL default '0',
`matchcardlosses` int(11) NOT NULL default '0',
`matchcardties` int(11) NOT NULL default '0',
`MerchantMesos` int(11) default '0',
`HasMerchant` tinyint(1) default '0',
`equipslots` int(11) NOT NULL default '48',
`useslots` int(11) NOT NULL default '48',
`setupslots` int(11) NOT NULL default '48',
`etcslots` int(11) NOT NULL default '48',
`allianceRank` int(10) unsigned NOT NULL default '5',
`clan` tinyint(1) NOT NULL default '-1',
`pvpkills` int(1) NOT NULL default '0',
`pvpdeaths` int(1) NOT NULL default '0',
`omok` int(4) default NULL,
`matchcard` int(4) default NULL,
`zakumlvl` int(10) unsigned NOT NULL default '0',
`gmtext` tinyint(1) unsigned NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `accountid` (`accountid`),
KEY `party` (`party`),
KEY `ranking1` (`level`,`exp`),
KEY `ranking2` (`gm`,`job`)
) ENGINE=InnoDB AUTO_INCREMENT=30792 DEFAULT CHARSET=latin1'
'inventoryitems', 'CREATE TABLE `inventoryitems` (
`inventoryitemid` int(10) unsigned NOT NULL auto_increment,
`characterid` int(11) default NULL,
`storageid` int(10) unsigned default NULL,
`itemid` int(11) NOT NULL default '0',
`inventorytype` int(11) NOT NULL default '0',
`position` int(11) NOT NULL default '0',
`quantity` int(11) NOT NULL default '0',
`owner` tinytext NOT NULL,
`petid` int(11) NOT NULL default '-1',
PRIMARY KEY (`inventoryitemid`),
KEY `inventoryitems_ibfk_1` (`characterid`),
KEY `characterid` (`characterid`),
KEY `inventorytype` (`inventorytype`),
KEY `storageid` (`storageid`),
KEY `characterid_2` (`characterid`,`inventorytype`),
CONSTRAINT `inventoryitems_ibfk_1` FOREIGN KEY (`characterid`) REFERENCES `characters` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=25799280 DEFAULT CHARSET=latin1'
A:
Your statement seems to be correct. It could also be written like this:
DELETE ii
FROM inventoryitems AS ii
WHERE ii.itemid = 2340000
AND EXISTS
( SELECT *
FROM characters AS c
WHERE c.characterid = ii.characterid
AND EXISTS
( SELECT *
FROM accounts AS a
WHERE a.id = c.accountid
AND a.banned = 1
)
) ;
One thing that may be causing this is if you have a character related to many accounts and one of them has banned = 1 while the other have banned = 0. I assume you want the deletion to happen (not with just one but) only if all the related accounts have banned = 1. We can modify the above code to:
DELETE ii
FROM inventoryitems AS ii
WHERE ii.itemid = 2340000
AND EXISTS
( SELECT *
FROM characters AS c
WHERE c.characterid = ii.characterid
AND EXISTS
( SELECT *
FROM accounts AS a
WHERE a.id = c.accountid
AND a.banned = 1
)
AND NOT EXISTS
( SELECT *
FROM accounts AS a
WHERE a.id = c.accountid
AND a.banned = 0
)
) ;
or simpler to:
DELETE ii
FROM inventoryitems AS ii
WHERE ii.itemid = 2340000
AND EXISTS
( SELECT *
FROM characters AS c
JOIN accounts AS a
ON a.id = c.accountid
WHERE c.characterid = ii.characterid
HAVING MIN(a.banned) = 1
) ;
After the clarifications, all the above are void. The problem was that characters table does not have characterid column but only id. So the statement used by the OP was translated/parsed as:
DELETE FROM inventoryitems
WHERE characterid IN
(SELECT inventoryitems.characterid -- notice this
from characters
WHERE accountid IN
(SELECT id
from accounts
WHERE banned = '1'
)
)
AND itemid = '2340000';
which makes the subquery uncorrelated and means "delete all rows with itemid = 2340000" if there exists at least one row (any row, not necessarily related) in the accounts with banned=1"
That's one reason why it's good to always (*) write columns with their full name as tablename.columnname or tablealias.columnname (an error would have been thrown if you had done this and problem would have been solved faster.)
(*) Unless one wants this behaviour to occur, which is a rather extreme case.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I disable a tableview without obscuring the entire screen like in Whatsapp?
How do I disable a tableview without obscuring the entire screen like in Whatsapp? The idea is when the SearchBar in the SearchController is still empty, the tableview gets dark. to SearchController, by default obscure the entire screen. Using obscuresBackgroundDuringPresentation, also obscure the entire screen.
I'm using Xcode 9.3 - Swift 4.
A:
Try this solution
1) Declare view
let keyboardView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width , height: UIScreen.main.bounds.height))
2) Add Notification Observer and view color alpha in viewDidLoad
keyboardView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
2) Remove Notification Observer use
deinit {
NotificationCenter.default.removeObserver(self)
}
3) add Constraints to view
func addConstraints() {
view.addConstraint(NSLayoutConstraint(item: keyboardView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: keyboardView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: keyboardView, attribute: .top, relatedBy: .equal, toItem: self.view.safeAreaLayoutGuide, attribute: .bottom, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: keyboardView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute,multiplier: 1, constant: UIScreen.main.bounds.height))
}
4) Add keyboard show and hide methods
@objc func keyboardWillShow(notification: NSNotification) {
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.storeCollectionView.addSubview(self.keyboardView)
self.addConstraints()
})
}
@objc func keyboardWillHide(notification: NSNotification) {
UIView.animate(withDuration: 0.1, animations: { () -> Void in
self.keyboardView.removeFromSuperview()
})
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
use of json operators inside SQL/SPSS query
I'm trying to parse and sum values from a jsonb field (eventos) in a postgresql table (eventos_detalle) that I'm getting from SPSS Statistics (ODBC GET DATA) The jsonb_to_record function is working but the ->> operator is causing a syntax error. I've quoted and double quoted everything I can but still can get it to work. Any comment will be very appreciated.
Here's the code exactly copied from SPSS Syntax Editor
GET DATA
/TYPE=ODBC
/CONNECT='DSN=PostgreSQL30;DATABASE=informes;SERVER=10.4.0.141;PORT=5432;UID=erubio;PWD=-!7K-X,'+
'-!o/$,:!/,J-,///!$!;SSLmode=disable;ReadOnly=0;Protocol=7.4;FakeOidIndex=0;ShowOidColumn='+
'0;RowVersioning=0;ShowSystemTables=0;Fetch=100;UnknownSizes=0;MaxVarcharSize='+
'255;MaxLongVarcharSize=8190;Debug=0;CommLog=0;UseDeclareFetch=0;TextAsLongVarchar='+
'1;UnknownsAsLongVarchar=0;BoolsAsChar=1;Parse=0;ExtraSysTablePrefixes=;LFConversion='+
'1;UpdatableCursors=1;TrueIsMinus1=0;BI=0;ByteaAsLongVarBinary=1;UseServerSidePrepare='+
'1;LowerCaseIdentifier=0;D6=-101;XaOpt=1'
/SQL='SELECT * FROM informes.public."eventos_detalle", jsonb_to_record(eventos)'
' AS x(hlc text, llc text, event text, fecha text, total real, accion text, fuente text,'
' cliente text, VirtualServer text, destinationip text, eventdirection text, destinationport text),'
' SUM(('eventos'->>'total')::float) AS total'
/ASSUMEDSTRWIDTH=255
A:
If the ->> is indeed the problem and not the invalid use of a string literal instead of a column identifier, you can replace the ->> operator with a function call:
eventos ->> 'total'
can be replaced with:
jsonb_extract_path_text(eventos, 'total')
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What types of UI elements can respond to gestures in tvOS?
I'm new to tvOS and trying to make my app more interactive by adding gesture recognizers to bunch of UI elements, but noticed that I can't do it with some of them.
I noticed that UIButton, UICollectionView or UITableView are the ones that can recognize gestures, but if I create a custom view and add a custom gesture recognizer to it, it doesn't work.
Am I doing something wrong, or there is a list of UI elements that can respond to gestures?!
Any kind of help is highly appreciated.
import UIKit
class TouchViewController: UIViewController{
@IBOutlet weak var myView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
let swipeDown:UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: Selector("swipedDown:"))
swipeDown.direction = .Down
myView.addGestureRecognizer(swipeDown)
let tap = UITapGestureRecognizer(target: self, action: "itemTapped:")
tap.allowedPressTypes = [NSNumber(integer: UIPressType.Select.rawValue)]
myView.addGestureRecognizer(tap)
}
func itemTapped(gesture: UITapGestureRecognizer){
print("tapped")
}
func swipedDown(sender:UISwipeGestureRecognizer){
print("swiped")
}
A:
Every kind of view can recognize gestures, there's nothing special about the classes you mentioned.
Your gestures must not be working for some other reason: can you elaborate on what you're trying to do, and provide some sample code?
Updated based on seeing your code:
Make sure the view that you're attaching these gestures to either (1) is focused, or (2) contains the focused view. Events are delivered to the focused view and may "bubble up" the responder chain from there. If your custom view doesn't contain the focused view, then it won't see any of those events.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Remove trailing spaces and add them as leading spaces
I would like to remove the trailing spaces from the expressions in my column and add them to beginning of the expression. So for instance, I currently have the expressions:
Sample_four_space
Sample_two_space
Sample_one_space
I would like to transform this column into:
Sample_four_space
Sample_two_space
Sample_one_space
I have tried this expression:
UPDATE My_Table
SET name = REPLACE(name,'% ',' %')
However, I would like a more robust query that would work for any length of trailing spaces. Can you help me develop a query that will remove all trailing spaces and add them to the beginning of the expression?
A:
If you know all spaces are at the end (as in your example, then you can count them and put them at the beginning:
select concat(space(length(name) - length(replace(name, ' ', ''))),
replace(name, ' ', '')
)
Otherwise the better solution is:
select concat(space( length(name) - length(trim(trailing ' ' from name)) ),
trim(trailing ' ' from name)
)
or:
select concat(space( length(name) - length(rtrim(name)) ),
rtrim(name)
)
Both these cases count the number of spaces (in or at the end of). The space() function then replicates the spaces and concat() puts them at the beginning.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Angular UI Bootstrap not working with AngularJS event handling
I am new to Angular and have basic problems, getting Angular-UI-Bootstrap to work in combination with AngularJS. Here a simple example, an usual input field that uses ng-change for event handling, and which has a popover. Without the popover attributes, the codes works fine. When the popover attributes are added, the popover is displayed correctly, and looks fine, but the event handler is not called, and also the password model not updated, when the value of the input field changes.
Same problem holds e.g. if I have a button with event handling code and a popover. Same problem also if I do not use popover, but tooltip.
<input type="password" ng-model="password" placeholder="New Password"
ng-change="onPasswordChanged()" popover="I am a popover!"
popover-trigger="mouseenter" />
I am using ui-bootstrap-tpls-0.3.0.js and AngularJS v1.0.7.
Does someone know what the problem is?
A:
Popover directive creates a child scope, so when you bind your model to a primitive, the binding will stay inside that scope (it will not propagate upwards). See "What are the nuances of scope prototypal / prototypical inheritance in AngularJS?" for more info on inheritance.
Workaround is to use a dot notation when referencing your models:
<input type="password" ng-model="data.password" popover="I am a popover!"
popover-trigger="mouseenter" />
DEMO PLUNKER
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to update parameters in SSIS?
I would like to know if I can update the parameter values (mainly timestamp) automatically using any SQL query. Please don't suggest me to use Environments, as the value is constantly changing and I need them to be updated automatically when I run.
A:
you may follow these steps to config your parameter:
create a variable, e.g. User::starttime
add an 'Execute SQL Task': specify the connection info and the query. e.g. SELECT STARTTIME FROM TABLE. set the ResultSet to 'Single row'. in the ResultSet Tab map the result name and variable name.
after the 'Execute SQL Task' executed, the variable 'User::starttime' will be set to the SQL result.
use the variable User::starttime as your parameter.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Как скрывать блок раз и навсегда
Здравствуйте, стоит задача чтобы скрывать блок раз и навсегда, допустим человек зашедший первый раз на сайт его увидел и если он нажмет на кнопку "закрыть" то чтобы это блок больше не появлялся при обновлении страницы, то есть надо заносить данные, что он скрыт в куки. Я пытался это сделать так, но не знаю вообще с чего начать правильно и чем закончить
$('.info__btn').on('click', function() {
$(this).parent().hide(200);
});
if(!Cookie().get('offer')) { $('.info').hide(); }
<div class="info">
<div class="info__btn">Закрыть</div>
</div>
A:
Вариант с php
<script>
$('.info__btn').on('click', function() {
$('html').append("<?=$_COOKIE['info__btn']='true';?>");
});
</script>
<?if(!$_COOKIE['info__btn'])
{?>
<div class="info">
<div class="info__btn">Закрыть</div>
</div>
<?}
Вариант с js:
<div class="info" style="display:none">
<div class="info__btn">Закрыть</div>
</div>
<script>
$(document).ready(function(){
if(!$.cookie('info__btn'))$('.info').show();
$('.info__btn').on('click', function() {
$.cookie('info__btn', 'true');
});
})
</script>
<script type="text/javascript" src="https://raw.githubusercontent.com/carhartl/jquery-cookie/master/src/jquery.cookie.js" ></script>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Basic PHP Object Oriented MYSQL Query
So I've been learning for about 3 months now and am currently using very old procedural techniques and the deprecated mysql extension in my code. So time to take a step forward, ditch my procedural ways and get into object oriented / prepared statements...
This is very basic but I guess everyone has to learn some day. I'm trying to get retrieve and simple dataset from mysql database..
so far I have my connection:
$useri = new mysqli('localhost', 'useri', 'xxx','yyy');
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
I get no errors so I assume this works, and I have my query:
$test_query = "SELECT * FROM t";
$test_query = $useri->real_escape_string($test_query);
echo $test_query;
if($result = $useri->query($test_query)){
while($row = $useri->fetch_object($result)){
echo $row->id;
}
$result->close();
}
$useri->close();
However I get no results... so, 2 questions:
a. what am I doing wrong? and
b. anyone recommend any good tutorials apart from the php manual for this stuff?
Thanks :)
A:
This works for one of the table i have in my db:
$useri = new mysqli('localhost', 'useri', 'xxx','yyy');
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
$test_query = "SELECT * FROM t";
$test_query = $useri->real_escape_string($test_query);
if($result = $useri->query($test_query)){
while ($row = $result->fetch_object()) { //only this is changed
echo $row->id;
}
$result->close();
}else{ //check for error if query was wrong
echo $useri->error;
}
$useri->close();
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ignoring differences in brightness with ImageMagick compare tool
I'm using compare to find if something has changed between two photos. It generally works well, except when the room suddenly becomes a bit darker or brighter. So I'm wondering - is it possible to ignore the difference in brightness when running compare?
So far I'm using the command below:
compare -fuzz 15% -metric ae /path/to/image1.jpg /path/to/image2.jpg /path/to/diff.png
For example, for this set of images, I would get approximately 5% difference, while I would like to bring it below 1% or even less if possible.
Any suggestion?
A:
You could normalize the two images, then compare those:
convert VaoZF.jpg -normalize image1.ppm
convert whgkn.jpg -normalize image2.ppm
compare -fuzz 15% -metric ae image1.ppm image2.ppm diff.png
You can get the difference metric with a single command and without making any temporary files:
magick \( VaoZF.jpg -normalize \) \( whgkn.jpg -normalize \) \
-fuzz 15% -metric ae -compare -format "%[distortion]" info:
If you are on Windows, use "(" and ")" instead of "\(" and "\)" and use a "^" instead of a "\" for suppressing the line break, and replace "%" with "%%".
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should we rename tags subjected to the Structured Tag Cleanup Initiative?
So our first round of proposals for the Structured Tag Cleanup Initiative is about to close, and it's looking like career will be first up to the chopping block. Career questions are tricky in that people, despite the tag wikis and tag wiki excerpts and the constant retags, still use it on a constant basis.
Stack Exchange won't lock (i.e. blacklist) a tag from getting new questions if it has hundreds of questions in it as it provides a bad experience to the user. So instead, what I'd like to propose is renaming career to something more jargony—stci-career—in order to help dissuade random passersby from using it while we clean it up.
This tag would be temporary, and—should there be any questions left—would be renamed back to career once the cleanup is finished. We'd of course have the usual slate of (ineffective) tag wiki warnings saying not to use the tag.
Good idea, bad idea?
A:
Good idea, I like it. Maybe throw a non-printing invisible in the middle of that tag as well.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Get the value of a tag with javascript
I would like to get the value of a tag after clicking on it. I just use javascript and no jquery.
Here's my html :
<div class="touche 1">
<h1>1</h1>
</div>
<div class="touche 2">
<h1>2</h1>
</div>
<div class="touche 3">
<h1>3</h1>
</div>
I need the values 1,2,3, etc... into a variable. The div's work like a calculator button !
Thanks !
A:
Here is the code
function getval(thisa)
{
alert(thisa.innerHTML);
}
<div class="touche 1">
<h1 onclick="getval(this)">1</h1>
</div>
<div class="touche 2">
<h1 onclick="getval(this)">2</h1>
</div>
<div class="touche 3">
<h1 onclick="getval(this)">3</h1>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
c# asp.net for append int value to the label id
I have the following label with ids:
<asp:Label ID="FromName0" runat="server" Visible="true"></asp:Label>
<asp:Label ID="FromName1" runat="server" Visible="true"></asp:Label>
<asp:Label ID="FromName2" runat="server" Visible="true"></asp:Label>
<asp:Label ID="FromName3" runat="server" Visible="true"></asp:Label>
<asp:Label ID="FromName4" runat="server" Visible="true"></asp:Label>
I want to assign the values to the label ids using for loop.
I am using the following tags in c#:
for (int i = 0; i < count; i++)
{
var label = this.Controls.Find("FromName " + i, true) as Label;
label.Text = Session["DeliverAddress" + i].ToString();
}
But ‘Find’ shows error like below:
System.Web.UI.ControlCollections does not have the definition for ‘Find’. But I have already added ‘System.Web.UI’ dll file. Can anyone help me?
I am using dotnet framework 4.0.
Thanks in Advance.
A:
You can do this like this
public Control[] FlattenHierachy(Control root)
{
List<Control> list = new List<Control>();
list.Add(root);
if (root.HasControls())
{
foreach (Control control in root.Controls)
{
list.AddRange(FlattenHierachy(control));
}
}
return list.ToArray();
}
and
protected void Page_Load(object sender, EventArgs e)
{
Control[] allControls = FlattenHierachy(Page);
foreach (Control control in allControls)
{
Label lbl = control as Label;
if (lbl != null && lbl.ID == "FromName0")
{
lbl.ID = "myid";//Do your like stuff
}
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Passing ID data to new page
I am very new to PHP mySQL so please go easy. I'm building a list of theme parks on one page, when you click one of the them parks a new page loads with info on that park. I am having difficultly passing on the theme park ID from one page to next and can't work out what I'm doing wrong. Please help.
The code for the list page:
<?php
try
{
$pdo = new PDO('mysql:host=localhost;dbname=danville_tpf', 'username',
'password');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
$output = 'Unable to connect to the database server.';
include 'output.html.php';
exit();
}
$output = 'Theme Park Database initialized';
include 'output.html.php';
try
{
$sql = 'SELECT park_id, name, town, state, country
FROM tpf_parks ORDER BY name ASC';
$result = $pdo->query($sql);
}
catch (PDOException $e)
{
$error = 'Error fetching parks: ' . $e->getMessage();
include 'error.html.php';
exit();
}
$output = 'Parks Loaded';
include 'output.html.php';
foreach ($result as $row)
{
$parklist[] = array(
'park_id' => $row['park_id'],
'name' => $row['name'],
'town' => $row['town'],
'state' => $row['state'],
'country' => $row['country']
);
}
include 'parks.html.php';
The parks.html.php is this:
<?php foreach ($parklist as $park): ?>
<a href="paging.php?park_id=<?php echo $park['park_id'];?>">
<h2><?php echo $park['name']; ?></h2>
<h3><?php echo $park['town'] , ', ', $park['state'] , ', ', $park['country'] ; ?></h3>
<hr>
</a>
<?php endforeach; ?>
and the content page where the details should load is:
<?php
try
{
$pdo = new PDO('mysql:host=localhost;dbname=danville_tpf', 'username',
'pasword');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
$output = 'Unable to connect to the database server.';
include 'output.html.php';
exit();
}
$output = 'Theme Park Database initialized';
include 'output.html.php';
try
{
$park_id = $_GET['park_id'];
$query="SELECT * FROM tpf_parks WHERE park_id = $park_id";
$result = $pdo->query($sql);
}
catch (PDOException $e)
{
$error = 'Error fetching park details: ' . $e->getMessage();
include 'error.html.php';
exit();
}
?>
I think the park_id is being passed because the URL of the content page shows this at the end paging.php?park_id=2 with the number matching the park_id but I get an error from the query that says
"Error fetching park details: SQLSTATE[42000]: Syntax error or access violation: 1065 Query was empty"
What have I done wrong? please help.
Dan
A:
The problem is the following line which is using the variable $sql which doesn't appear to exist:
$result = $pdo->query($sql);
Try the following:
$park_id = $_GET['park_id'];
$query="SELECT * FROM tpf_parks WHERE park_id = $park_id";
$result = $pdo->query($query);
Noting that I have replaced $sql with $query.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Unable to create new OneDrive folder under root with Microsoft.Graph REST API
I am able to create folders under existing folders but not under the root. I tried URLs with the id of the root and with several variants of the path syntax e.g. "root:/./:", but none of them creates the folder.
I would like to see an example of creating a folder under the root in the docu of the Microsoft.Graph REST API. This could save a lot of time.
Thanks for any answer!
Here is my code:
public static async Task<GameStorageItem> CreateFolderAsync(string parentId, string parentPath,
string name)
{
var obj = new JObject
{
{ "name", name },
{ "folder", new JObject() },
{ "@microsoft.graph.conflictBehavior", "fail" }
};
dynamic json;
string content;
if (parentId == "root")
{
content = await MicrosoftAccount.PerformHttpRequestAsync(HttpMethod.Get,
$"me/drive", obj);
json = JValue.Parse(content);
parentId = json.id;
//parentId = "root:./:";
}
content = await MicrosoftAccount.PerformHttpRequestAsync(HttpMethod.Post, $"me/drive/items/{parentId}/children", obj);
json = JValue.Parse(content);
DateTimeOffset created = json.createdDateTime;
string id = json.id;
var folder = new GameStorageFolder(name, $"{parentPath}/{name}", id, created, false);
return folder;
}
public static async Task<string> PerformHttpRequestAsync(HttpMethod method, string request,
JObject json = null)
{
if (__authResult == null || await ValidateTokenAsync(5) == false)
{
try
{
await SignInAsync();
__authResult = await __client.AcquireTokenSilent(scopes,
__account).ExecuteAsync();
}
catch (MsalUiRequiredException)
{
//A MsalUiRequiredException happened on AcquireTokenSilentAsync.
//This indicates you need to call AcquireTokenAsync to acquire a token
try
{
//User must consent
__authResult = await __client.AcquireTokenInteractive(scopes)
.ExecuteAsync();
}
catch (MsalException ex)
{
//Error acquiring token
throw ex;
}
}
catch (Exception ex)
{
//Error acquiring token silently
throw ex;
}
}
var builder = new UriBuilder(__graphUrl + request);
return await PerformHttpRequestWithTokenAsync(method, builder.Uri,
__authResult.AccessToken, json);
}
private static async Task<string> PerformHttpRequestWithTokenAsync(HttpMethod method,
Uri uri, string token, JObject json = null)
{
HttpResponseMessage response;
var httpClient = new HttpClient();
var request = new HttpRequestMessage(method, uri);
if (json != null)
{
request.Content = new StringContent(json.ToString(), Encoding.UTF8,
"application/json");
}
//Add the token in Authorization header
request.Headers.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
response = await httpClient.SendAsync(request);
return await response.Content.ReadAsStringAsync();
}
A:
You have three different options - I'll just show them as the request and let you translate it to code:
Option 1 - POST to children
POST ../me/drive/root/children
{
"name": "foo",
"folder": {}
}
Option 2 - PUT to child
PUT ../me/drive/root/children/foo
{
"folder": {}
}
Option 3 - PUT to path
PUT ../me/drive/root:/foo
{
"folder": {}
}
Note that all of these URLs reference the root, and then use different mechanisms to create a folder under it.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
March Movie Event!! - Starship Troopers - March 18th at 11pm GMT (7pm EDT)
Movie Night seems to have been a bit quiet recently, so to get things going again I'm nominating the single finest science fiction film ever made as our March Movie night film. That's right people, we're watching Starship Troopers! All are welcome to join in on March 18th at 11pm GMT (7pm EDT)
The more people that come to the chatroom, the merrier it'll be and remember,
"Service guarantees citizenship!"
FAQ
What is a movie night?
Which version will we be watching? The theatrical cut is currently available on Youtube here and here. There are also copies available on DailyMotion, Amazon Prime and Hulu. Amazon Prime members with the STARZ channel can watch it free, or use the STARZ channel 2-week free trial to watch it free.
What if I want to complain loudly about the film being worse than the book? Then prepare to be pelted with popcorn!
I'm doing my part!
A:
Movie night was a great success
We had six active participants (The Dark Lord - First time contributor, MissMonicaE - First time contributor, Kyle Jones, Edlothiad - First time contributor and Himarm). That number goes up to seven if you include CreationEdge who joined us a few minutes after the film ended to say
Oh I missed the movie?
We also had no less than 9 lurkers which brings the grand total to nearly 15 viewers!
Funniest comment goes to MissMonicaE for
Is there really this much public kissing in high school? I'm so glad I
was homeschooled
and The Dark Lord for
Time since last incident: 0 days.
The winner of the 'Captain Obvious' prize goes to Himarm for
shower scene is always fun
and MissMonicaE for
Ladies love a man in uniform
Honourable mention goes to Edlothiad for
Lieutenant Dan?! oh wrong film
What did we learn?
This film was chosen by diktat rather than a democratic vote on Meta.
Historically there seems to be little benefit in allowing the community to choose over simply announcing what film is being shown.
The post was "featured" early (with the date, time and movie name in the title).
Placing it on the main board seems to have attracted no less than six users who've never come into chat before, one of whom then contributed to the event. The vote-count seem to have largely reflected the number of participants.
Making it a featured event in chat seems to have had little impact.
Only two people "registered" for the event.
Picking a film that was accessible online seems to have been a benefit.
At least three of the contributors were watching a version that was streaming from youtube rather than having to download their own copy.
The date and time seem amenable (to most)
Placing it on a weekend evening appears to have been more effective than making it mid-week, something we tried last year with very limited success.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Writing UTF-8 chars in Textfield As3
I have a textfiled (input type) which works with English lang. If I change to different locale in the system tray I am not able to write any text into the textfiled.
How can I enable this capabilty to the TextField or this is connected with locale/Language support in the swf?
A:
In flash IDE, there is an embed button under textfield properties. Open that window and add character range and add the special character that you want to exist to the "also include these characters:" field.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to split points by polygon using ArcGIS Desktop?
I am looking for a way to split points by a county polygon feature class. The attached image shows two feature classes: one composed of points and the other a county polygon feature class. The split tool would be ideal if it allowed points. I would prefer a clean output without additional fields added to the point attributes. Additionally, I would like to have the county name from the polygon feature class defining the new point feature classes (e.g. Kiowa, Clark, Comanche). I appreciate any solutions and advice.
For this example, the final product should be three point feature classes named "Kiowa", "Clark" and "Comanche" produced from one, larger point feature class. An automated solution would be ideal, as I have many, many merged point FCs over dozens of counties to work with (approximately spanning the state of KS).
A:
After using Spatial Join or Intersect to get the County name attribute onto each point, try using Dan Patterson's Split Layer by Attributes tool available on the Geoprocessing Model and Script Tool Gallery.
Alternatively you could use ModelBuilder to automate this using a different approach involving Select Layer by Location (click thumbnail for full image).
Lifted from this thread on the ESRI forums: Batch Selecting by Location and Exporting Shapefiles
A:
Much easier to use the intersect command.
Turn off unwanted fields.
1. Intersect to a new output.
2. Join the output with the original oid.
3. Calculate a new field with the cnty name.
Check out ettools for some enhanced versions of spatial join and split by location.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
IntegrityError: NOT NULL constraint when trying to save a model instance
I know this has been asked a lot but none of the answers were able to help me
I have two models: one that stores messages and one that stores sender info:
class SenderInfo(models.Model):
#to create unique id numbers
sender = models.CharField(max_length=15)
id_number = models.IntegerField(blank=True, null=True, default=None)
class Messages(models.Model):
message = models.ForeignKey(SenderInfo, related_name='messages')
message_body = models.TextField()
And when I try to make an instance and save() it I keep getting IntegrityError: NOT NULL constraint failed: appconvo_messages.message_id
Full traceback:
>>> from appconvo.models import SenderInfo, Messages
>>> s = SenderInfo(sender='charles')
>>> s.save()
>>> m = Messages(message_body='this is a test')
>>> m.save()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:\Users\ELITEBOOK\.virtualenvs\codechallenge\lib\site-packages\django\db\models\base.py", line 808, in save
force_update=force_update, update_fields=update_fields)
File "C:\Users\ELITEBOOK\.virtualenvs\codechallenge\lib\site-packages\django\db\models\base.py", line 838, in save_bas
e
updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Users\ELITEBOOK\.virtualenvs\codechallenge\lib\site-packages\django\db\models\base.py", line 924, in _save_ta
ble
result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "C:\Users\ELITEBOOK\.virtualenvs\codechallenge\lib\site-packages\django\db\models\base.py", line 963, in _do_inse
rt
using=using, raw=raw)
File "C:\Users\ELITEBOOK\.virtualenvs\codechallenge\lib\site-packages\django\db\models\manager.py", line 85, in manage
r_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\ELITEBOOK\.virtualenvs\codechallenge\lib\site-packages\django\db\models\query.py", line 1076, in _inser
t
return query.get_compiler(using=using).execute_sql(return_id)
File "C:\Users\ELITEBOOK\.virtualenvs\codechallenge\lib\site-packages\django\db\models\sql\compiler.py", line 1112, in
execute_sql
cursor.execute(sql, params)
File "C:\Users\ELITEBOOK\.virtualenvs\codechallenge\lib\site-packages\django\db\backends\utils.py", line 79, in execut
e
return super(CursorDebugWrapper, self).execute(sql, params)
File "C:\Users\ELITEBOOK\.virtualenvs\codechallenge\lib\site-packages\django\db\backends\utils.py", line 64, in execut
e
return self.cursor.execute(sql, params)
File "C:\Users\ELITEBOOK\.virtualenvs\codechallenge\lib\site-packages\django\db\utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:\Users\ELITEBOOK\.virtualenvs\codechallenge\lib\site-packages\django\db\backends\utils.py", line 64, in execut
e
return self.cursor.execute(sql, params)
File "C:\Users\ELITEBOOK\.virtualenvs\codechallenge\lib\site-packages\django\db\backends\sqlite3\base.py", line 328, i
n execute
return Database.Cursor.execute(self, query, params)
IntegrityError: NOT NULL constraint failed: appconvo_messages.message_id
>>>
A:
Based on your code, you need to specify the SenderInfo in your Message object.
>>> s = SenderInfo(sender='charles')
>>> s.save()
>>> m = Messages(message=s, message_body='this is a test')
>>> m.save()
Or the same:
m = Messages.objects.create(message=s, message_body='your message')
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to get facebook friend list with emails through new graph api, v2.5?
I am trying to fetch the friend list using the code below
GraphRequest request = GraphRequest.newMyFriendsRequest(
token,
new GraphRequest.GraphJSONArrayCallback() {
@Override
public void onCompleted(JSONArray array, GraphResponse response) {
// Insert your code here
}
});
request.executeAsync();
}
The response returned after code execution is
{Response: responseCode: 200, graphObject: {"data":[],"summary":{"total_count":461}}, error: null}
Persmission to access friends and public profile is granted on login time.
How can i fetch my friend list and their public emails/ facebook emails?
A:
You'll only receive the friends whcih are also using your app, see
https://developers.facebook.com/docs/apps/upgrading#upgrading_v2_0_user_ids
/me/friends returns the user's friends who are also using your app
In v2.0, the friends API endpoint returns the list of a person's friends who are also using your app. In v1.0, the response included all of a person's friends.
And, no, there is no workaround in case you wanted to ask.
A:
You can recive your friends list using graph-api call
/* make the API call */
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"/me/friends",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
/* handle the result */
}
}
).executeAsync();
But the limitation is
api required access token with user_friends permission
only return friends who are also given access permission to the same app you are
using
.
https://developers.facebook.com/docs/graph-api/reference/v2.5/user/friends
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to display a button in random screen position
How do I display a button in a random screen position in android? For example I have a button that is named GO. When I click GO, it will bring me to the second screen. That second screen will display another button (not the START button) in random screen position. How can I do that?
A:
For the second screen use absolute layout, but the button on X=0, Y=0
Once your second screen gets activated. onCreate Method
Button button = (Button)findViewById(R.id.my_button);
AbsoluteLayout.LayoutParams absParams =
(AbsoluteLayout.LayoutParams)button.getLayoutParams();
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
int height = displaymetrics.heightPixels;
Random r = new Random();
absParams.x = r.nextInt(width ) ;
absParams.y = r.nextInt(height );
button.setLayoutParams(absParams);
EDIT User wanted to know how to write AbsoluteLayout
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/my_button"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_x="0dp"
android:layout_y="0dp"
android:text="Yes" />
</AbsoluteLayout>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Django Querysets & dynamic string filtering
It seems that __in is only suitable for integers. I am trying to filter by strings.
I've tried this but it does not work.
groups = ['foo', 'bar']
args = []
for group in groups:
args.append(Q(name=group))
group_ids = Group.objects.filter(*args)
What is the preferred way to dynamically filter a Django queryset using strings?
A:
__in can be used for strings as it translates to a SQL IN operation. Whether or not it is case-sensitive my depend on your table/column collation.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can the infinite cyclic group be understood as the group of all rational numbers under addition?
I've just started the beginnings of abstract algebra and came across the concept of infinite cyclic groups. I've read that such a group can be represented with the group of integers under addition (which makes sense). However, I was wondering if this infinite cyclic group could also be viewed through the lens of the group of real numbers under addition.
If they cannot, could someone please explain why? (My math literacy is not overly sophisticated so I would greatly appreciate simplicity if possible).
Thanks~
A:
Any integer can be expressed by adding together finitely many copies of either $1$ or its inverse $-1$. $1$ (and $-1$) are said to generate the group and the group is said to be cyclic because of this. There is no generator for either the rationals or reals, so they do not form a cyclic group under addition. They do form groups under addition, but they are not cyclic.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to combine lambda and javascript forEach loops?
Here's what I've tried and for some reason the event listeners are not getting called:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>Some sample text inside body
<div id="log"></div>
<script>
var clipboardEventsHandler = ['beforecut', 'cut', 'beforecopy', 'copy', 'paste'].forEach((evt) => {
document.addEventListener(evt, (e) => {
log.innerHTML += ("-" + e.type + "-");
log.innerHTML += (document.queryCommandSupported(e.type) ? "-" + e.type + " supported-" : "-" + e.type + " **not** supported-");
log.innerHTML += (document.queryCommandEnabled(e.type) ? "-" + e.type + " enabled-" : "-" + e.type + " **not** enabled-");
log.innerHTML += (document.queryCommandState(e.type) ? "-" + e.type " state:true-" : "-" + e.type + " state:false/null-");
log.innerHTML += "<br>"
})
});
</script>
</body>
</html>
I'm suspecting that the type of evt parameter passed to addEventListener. I confirmed that its a string by logging typeof evt before passing it to addEventListener. And its says its string. But still the event listeners are not getting called when I do copy a portion of the text inside body. Can someone tell me what's that I'm doing wrong?
A:
First- you had a syntax error - missing + here:
e.type) ? "-" + e.type " state:true-"
^----
Second - it's better access elements using document.getElementById and not directly by their id:
document.getElementById('log')
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>Some sample text inside body
<div id="log"></div>
<script>
var log = document.getElementById('log');
var clipboardEventsHandler = ['beforecut', 'cut', 'beforecopy', 'copy', 'paste'].forEach((evt) => {
document.addEventListener(evt, (e) => {
log.innerHTML += ("-" + e.type + "-");
log.innerHTML += (document.queryCommandSupported(e.type) ? "-" + e.type + " supported-" : "-" + e.type + " **not** supported-");
log.innerHTML += (document.queryCommandEnabled(e.type) ? "-" + e.type + " enabled-" : "-" + e.type + " **not** enabled-");
log.innerHTML += (document.queryCommandState(e.type) ? "-" + e.type + " state:true-" : "-" + e.type + " state:false/null-");
log.innerHTML += "<br>"
})
});
</script>
</body>
</html>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to display Model Relationship in Laravel?
I have this database table: job, department, pcn and this table pcn has properties job_id and department_id on it. So in Laravel I have this definitions on its equivalent models:
class Job extends Model
{
public function pcns(){return $this->hasMany('App\Pcn', 'id');}
}
class Department extends Model
{
public function pcns(){return $this->hasMany('App\Pcn', 'id');}
}
class Pcn extends Model
{
public function job(){return $this->belongsTo('App\Job');}
public function department(){return $this->belongsTo('App\Department');}
}
My problem now is my pcn index that displays list of Pcn is giving me this error:
Trying to get property 'name' of non-object (View: C:\wamp\www\bookersystem\resources\views\pcn\index.blade.php)
in which my index.blade.php has this:
@foreach($pcns as $key => $value)
<td>{{ $value->control_number }}</td>
<td>{{ $value->job->name }}</td>
<td>{{ $value->department->name }}</td>
@endforeach
On my Pcn controller:
public function index()
{
$pcns = Pcn::paginate(50);
return view('pcn.index', compact('pcns'));
}
As for my migrations i have this difinition:
public function up()
{
Schema::create('pcn', function (Blueprint $table) {
$table->engine = "InnoDB";
$table->charset = 'utf8mb4';
$table->collation = 'utf8mb4_general_ci';
$table->bigIncrements('id');
$table->unsignedBigInteger('department_id');
//$table->foreign('department_id')->references('id')->on('department');
$table->unsignedBigInteger('job_id');
//$table->foreign('job_id')->references('id')->on('job');
$table->string('control_number', 45);
$table->string('center', 5);
$table->string('status', 8)->nullable();
$table->unsignedBigInteger('mrf_id')->nullable();
$table->string('degree', 25)->default('Not Recruiting');
$table->timestamps();
});
}
Am i doing wrong here?
A:
Firt thing it's better to remove the id from the relationships definition or declare the right foreign key:
class Job extends Model
{
//this
public function pcns(){return $this->hasMany('App\Pcn');}
//or this
public function pcns(){return $this->hasMany('App\Pcn', 'job_id', 'id');}
}
class Department extends Model
{
//this
public function pcns(){return $this->hasMany('App\Pcn');}
//or this
public function pcns(){return $this->hasMany('App\Pcn', 'department_id', 'id');}
}
Second step: it's better to eager load the relationships to reduce the number of queries needed:
public function index()
{
$pcns = Pcn::with(['job', 'department'])->paginate(50);
return view('pcn.index', compact('pcns'));
}
After that in your view you don't really need $key=>$value in the @foreach:
@foreach($pcns as $pcn)
<td>{{ $pcn->control_number }}</td>
<td>{{ $pcn->job->name }}</td>
<td>{{ $pcn->department->name }}</td>
@endforeach
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Data Correlation in large Databases
We're trying to identify the locations of certain information stored across our enterprise in order to bring it into compliance with our data policies. On the file end, we're using Nessus to search through differing files, but I'm wondering about on the database end.
Using Nessus would seem largely pointless because it would output the raw data and wouldn't tell us what table or row it was in, or give us much useful information, especially considering these databases are quite large (hundreds of gigabytes).
Also worth noting, this system needs to be able to do pattern-based matching (such as using regular expressions). Not just a "dumb search" engine.
I've investigated the use of Data Mining and Data Warehousing in order to find this data but it seems like they're more for analysis of data than actually just finding data.
Is there a better method of searching through large amounts of data in a database to try and find this information? We're using both Oracle 11g and SQL Server 2008 and need to perform the searches on both, so I'd like to stay away from server-specific paradigms (although if I have to rewrite some code to translate from T-SQL to PL/SQL, and vice versa, I don't mind)
A:
On SQL Server for searching through large amounts of text, you can look into Full Text Search.
Read more here http://msdn.microsoft.com/en-us/library/ms142559.aspx
But if I am reading right, you want to spider your database in a similar fashion to how a web search engine spiders web sites and web pages.
You could use a set of full text queries that bring back the results spanning multiple tables.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
check if list exists in exacttarget API
I'm planning to create lists and add user details as subscribers to them using the exacttarget SOAP API in PHP. The code api has sample code on creating a list. I built my custom logic based on it as follows
public function createList($siteId, $siteDescription){
try {
$list = new ExactTarget_List();
// $list->Description = "PHP Created List"; // List for the venue
// $list->ListName = "PHP API Created List"; // Description about the list
$list->Description = $siteDescription; // List for the venue
$list->ListName = $siteId;
$object = new SoapVar($list, SOAP_ENC_OBJECT, 'List', "http://exacttarget.com/wsdl/partnerAPI");
$request = new ExactTarget_CreateRequest();
$request->Options = NULL;
$request->Objects = array($object);
$results = $client->Create($request);
if ($results->OverallStatus == 'OK')
{
echo 'SUCCESS';
}
else
{
echo 'FAILED';
}
}
catch (SoapFault $e) {
// var_dump(e);
$this->success = 0;
}
}
But my workflow is such that in case list already exists I should proceed to next step of adding subscribers (doh!) to it else create the list first and add subscribers. I could not find any example code snippet on checking if the list exists or not using the code API doc and hence am wondering if this is possible at all. My meager understanding of SOAP and XML is playing big time here and hence requesting if any veterans who have better knowledge or idea on this share some details on it to aid my cause.
A:
You can grab all lists fairly easily - for instance, follow the code from the following ET technical doc:
http://docs.code.exacttarget.com/020_Web_Service_Guide/Technical_Articles/Retrieving_a_List_from_an_Account
The article is fairly good (relatively speaking, of course), and I can vouch for its accuracy. Here's the pertinent bit from the PHP section:
$rr = new ExactTarget_RetrieveRequest();
$rr->ObjectType = "List";
$rr->Properties = array();
$rr->Properties[] = "ID";
$rr->Properties[] = "List.ListName";
$rr->Options = NULL;
$rrm = new ExactTarget_RetrieveRequestMsg();
$rrm->RetrieveRequest = $rr;
$results = $client->Retrieve($rrm);
var_dump($results);
To grab a specific list, you create a SimpleFilterPart object and attach it to your RetrieveRequest (note - this part is buggy, untested, terrible PHP code - I wrote it in Python and then translated it here - if you really really need help with this part, message me):
$sfp=new ExactTarget_SimpleFilterPart;
$sfp=>Property = "ListID";
$sfp=>SimpleOperator = new ExactTarget_SimpleOperators->equals;
$sfp=>Value = Array(contact_list);
$retrieverequest=>Filter = $sfp;
Hope that saves some headache for someone.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Command prompt ren wildcard *
I have a bunch of files which look like this:
.
I want to remove all "IMG_20190718_". Why does ren IMG_20190718_* * not work and how do I make it work?
A:
Use a / to delete a prefix. For example: if I have the following files
18-07-2020 17:18 6 IMG_20_14.png
18-07-2020 17:18 6 IMG_20_15.png
18-07-2020 17:18 6 IMG_20_16.png
I can use:
ren "IMG_20_*.png" "///////*.png"
which has as result:
18-07-2020 17:18 6 14.png
18-07-2020 17:18 6 15.png
18-07-2020 17:18 6 16.png
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to search and update JsonObject in JsonArray in an efficient approach?
JsonArray-Example:
[{
"name": "table",
"type": "table",
"reportId": 7,
"componentId": 12,
"width": 0,
"height": 0,
"dataType": "DEFAULT"
},
{
"name": "chart",
"type": "chart",
"reportId": 7,
"componentId": 13,
"width": 0,
"height": 0,
"dataType": "DEFAULT"
}
]
I have to search JsonObject with Key(name,type),if jsonObject exist with the key want to either update or delete the jsonObject from array.
**Normal Solution:**iterate each JsonObject individually,look for the key and perform the operation.
P.S. I want to code all this logic in java not javascript.
A:
You can use "LINQ for JavaScript" library. Very useful library.
For Example. we can update like..
Enumerable.From(JsonArray).Where("$.componentId == 12").First().name= "tableName";
A:
Your solution is good (n complexity). The only way to optimization I see is to have the list sorted (I mean get it ordered by name and type if you load it from database, not sort it in Java) so that you know that you know when to stop searching before getting to the end of the list. I'm not sure if binary search algorithm makes sense for two key values.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to use flexbox to show most recent posts first?
I am using Jekyll to set up a website, and I am using a flexbox model where viewers can click on a post and it will take them to the article page. The problem is that my grid is set up to show 3 posts per row, then wrap. By default, the first published post is the first post you see, and the newest posts end up at the end, so I am trying to use flexbox to reverse this.
If I have only 7 posts on the site, the last post will be on a line of its own, with two empty spaces, so if I use 'wrap-reverse', that post will be the only post on the top row, which isn't what I want. I would like for my posts to show up as: [7,6,5 - 4,3,2 - 1] from left to right, instead of the defaulted [1,2,3 - 4,5,6 - 7], where 7 is the newest article and 1 is the oldest.
I am looking for a possible method to arrange my posts in a clean fashion, so that as I upload new posts, they automatically publish in the top left of the grid layout. Sorry if this may sound confusing. If you have any questions that will help to understand what I am talking about please feel free to ask.
Here is some code from codepen that illustrates what I have.
http://codepen.io/pen/?editors=110
<body>
<div class="container">
<div class='post'>1 (oldest post)</div>
<div class='post'>2</div>
<div class='post'>3</div>
<div class='post'>4</div>
<div class='post'>5</div>
<div class='post'>6</div>
<div class='post'>7 (newest post)</div>
</div>
</body>
.container {
display: flex;
flex-wrap: wrap;
}
.post {
height: 170px;
width: 220px;
background: black;
color: orange;
margin: 10px;
font-size: 24px;
text-align: center;
}
I basically want 7 to replace 1, 6 to replace 2, 5 to replace 3, etc.
Thanks for your help!
A:
To reverse an array with Jekyll you just can reverse this array order, which, by default, is sorted by date :
<div class="container">
{% for post in site.posts reversed %}
<div class='post'>{{post.title}}</div>
{% endfor %}
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Show $|-\ln(\cos (x))-\frac{x^2}2| \le \frac23|x^3| \quad\forall x \in[-\frac{\pi}{4},\frac{\pi}{4}] $
Let
$$f:(-\frac{\pi}{2},\frac{\pi}{2}) \to \Bbb R$$
$$f(x)=-\ln(\cos (x))$$
Show that
$$\left| f(x)-\frac{x^2}2 \right| \le \frac23\left| x^3 \right| \qquad x
\in[-\frac{\pi}{4},\frac{\pi}{4}]$$
My attempt:
We have $\left| -\ln(\cos (x))-\frac{x^2}2 \right| \le \frac23\left| x^3 \right| \iff |\ln(\cos
(x))+\frac{x^2}2\left| \le \frac23 \right|x^3| $
The first thing that comes to my mind is to show that $\cos(\alpha)\ge
\frac{1}{\sqrt2}$ for $\alpha \in[-\frac{\pi}{4},\frac{\pi}{4}]$ (i)
After that, I would have to go on to show that $0 \ge \ln(\beta)$ for
$\beta \in[\frac{1}{\sqrt2},1]$ (ii) which I also don't know how to
prove.
Once that is done we have
$$\left| \frac{x^2}2 \right| \le \frac23\left| x^3 \right|$$ and we are done.
So my question is: how can I go on about (i) and (ii)?
Thanks in advance.
A:
Applying Taylor's theorem with remainder to
$$ \begin{aligned}
f(x) &= -\ln(\cos(x)) & f(0) &= 0 \\
f'(x) &= \tan(x) & f'(0) &= 0\\
f''(x) &= 1 + \tan^2(x) & f''(0) &= 1 \\
f'''(x) &= 2 \tan(x) (1+\tan^2(x))
\end{aligned}$$
gives
$$
f(x) = f(0) + f'(0) x + \frac{f''(0)}{2!} x^2 + \frac{f'''(\xi)}{3!} x^3
= \frac{x^2}{2} + \frac{f'''(\xi)}{6} x^3
$$
for some $\xi$ between $0$ and $x$. The assertion follows because
for $|\xi| \le |x| \le \frac{\pi}{4}$
$$
|\tan(\xi)| \le 1 \Longrightarrow
|f'''(\xi)| \le 4
$$
and therefore
$$
\left\lvert f(x) - \frac{x^2}{2} \right\rvert =
\frac{|f'''(\xi)|}{6} |x|^3 \le \frac 23 |x|^3
$$
Remark: Your approach cannot work because
$$
\left| \frac{x^2}2 \right| \le \frac23\left| x^3 \right|
$$
does not hold for $x$ close to zero.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How does node.js/[my own library/plugin] run on v8?
Does it use any libraries like this:
http://code.google.com/p/v8-juice
http://ui.ajax.org/#o3
https://github.com/tsa/vu8
Or has it written its own libraries? If v8 is written for executing javascript, why do node.js libraries use C code? Just for the filesystem/event stuff? If so, why was that necessary, doesn't v8 need events and filesystem stuff itself?
If I want to work with a database that only supports a C api, how would I go about doing that? Right now I'd probably write a v8-juice plugin.
A:
node.js includes its own embedded version of v8 (not sure if it is customized or not, but it could be).
Javascript itself provides no interface to things like file system I/O, so that you as the embedder (in this case node) have to provide native code objects to expose that functionality. The browser does the same thing for DOM and network features, by the way.
If I want to work with a database that only supports a C api, how would I go about doing that?
You'd need a node.js extension for this (a native code plugin). If you are lucky, someone has already made on for your database system, if not, look at the source code for a similar extension as to how those are written. And here is an introduction article. You'd need to be familiar with writing a v8 extension, because that is what a node extension basically is.
If you are talking to the database over a network connection, and feel like implementing the wire protocol yourself, you could also try to do that in pure Javascript, like someone did for MySQL.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Compartir variables entre funciones
¿Alguien sabe cómo hago para mostrar pos1 y pos2 pero en la otra función? ¿Qué parámetros tendría que usar? a todo esto, tiene que ser void si o si la función.
void encontrarMinimoMatriz(float m[][MESES], int cant,int pos1, int pos2){
int minimo = m[0][0];
for (int i=0;i<cant;i++){
for (int j=0;j<MESES;j++){
if(m[i][j] < minimo){
minimo = m[i][j];
pos1 = i;
pos2 = j;
}
}
}
}
void mostrarMinimo(float m[][MESES], int cant,int pos1, int pos2){
printf("\n-------------------------------\n");
printf("el minimo esta en: \n %d %d",pos1,pos2);
}
A:
Usa punteros:
void encontrarMinimoMatriz(float m[][MESES], int cant,int *pos1, int *pos2){
int minimo = m[0][0];
for (int i=0;i<cant;i++){
for (int j=0;j<MESES;j++){
if(m[i][j] < minimo){
minimo = m[i][j];
*pos1 = i;
*pos2 = j;
}
}
}
}
Con punteros podrás extraer el valor de dentro de la función al punto de llamada de la función, luego se lo puedes pasar a cualquier otra función:
int main(void)
{
float matriz[10][MESES] = { /* Datos */ };
int pos1 = 0, pos2 = 0;
encontrarMinimoMatriz(matriz, 10, &pos1, &pos2);
mostrarMinimo(matriz, 10, pos1, pos2);
return 0;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Explaining unknown person found in family listing in 1940 Federal Census of Iowa?
the 1940 federal census record for my dad's family is 100% accurate for the entire family - names spelled correctly, ages correctly listed - for 2 parents and their 4 children. But the census also lists a 5th sibling, said to have been born in 1936, and so listed as being 4 years old at the time of the census. I have not provided you with names because I know you don't publish personal info, but the census also provides the 4 year old's name. My dad and all his living siblings say no such 5th sibling ever existed and say they know nothing about him. I have briefly searched for IA (where they lived) birth certificates and found nothing. No cousins by the listed name apparently existed. The father of the household worked on the railroad so if a 5th child did exist, he could have been born outside of IA.
Can you offer any insights, or suggestions of sources I could check?
Are errors like this - adding an entire person, not just a typo or spelling mistake - in census data common?
A:
Here are the questions that I would investigate, that might help determine who this extra household member was:
Have you looked at the census page image to verify it was indexed correctly? This is the most frequent issue.
Are there any notes in the margin beside this entry, that point to another page or another family? Indexers almost always ignore these, leading to annoying household mashups or random individuals not attached to the correct household.
Is the household's informant marked (specific to 1940 US census)? If it was a parent, they should know who they are giving information on, although errors can be introduced by the enumerator or later copyists.
Is all the information for the individual consistent with the rest of the family?
Is this 5th child listed after the rest of the family? Are the ages all in sequence?
Is it possible biologically (mother's age, intervals between pregnancies, etc.) for this individual to be a child of the family?
You've looked for birth certificates: what about death certificates? A 4 year old with older siblings shouldn't have been forgotten, but an early death should be checked
You have already investigated possible cousins: could it have been a child's friend or neighbour's child over for a sleepover or for babysitting? It does happen that surnames are sometimes applied across the whole household in error. The relationship should be indicated, but that's any easy error to introduce.
Not possible (yet) in this case, but if there had been an later census (state or federal) or the child older, I would also check the family in other censuses to see if the individual was still with them. I've seen lodgers become foster children become adopted children. And orphaned children raised by grandparents or other relatives.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
tvOS button background color issue where it's not set properly
As you can see, I'm trying to set the button's color to a very light blue, but by default everything but the bezels are being darkened. Is the default button behavior causing this? Is there a workaround besides creating your own button? If I do have to create my own button, how can I reuse the default button's animation behavior? Thanks.
A:
You don't have to create a custom button.
Instead, create an image containing the color you want and use that as a background image. Plus make sure to set the button's background color to default (clearColor), otherwise you will lose the rounded corners.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Bootstrap Toggle Plugin - Checkboxes Not Toggling When Using Angular
I'm using the Bootstrap Toggle plugin to change my checkboxes into toggle switches. I'm also using AngularJS. When I set the checked value, it toggles fine. But when I don't, it does not toggle. You can see in the link to my results, that checkboxes are checked, but they are not toggling. Does anyone know why it's not binding using Angular?
HTML:
<div class="form-group">
<label class="col-sm-7 control-label">
<span>Working Toggle </span>
</label>
<div class="col-sm-5">
<input id="toggle-one" checked type="checkbox">
</div>
</div>
<div class="form-group">
<label class="col-sm-7 control-label">
<span>Color Review Check</span>
</label>
<div class="col-sm-5">
<input type="checkbox" class="pull-right" ng-model="colorReview" >
</div>
</div>
<div class="form-group">
<label class="col-sm-7 control-label">
<span>Type Review Check</span>
</label>
<div class="col-sm-5">
<input type="checkbox" class="pull-right" ng-model="typeReview">
</div>
</div>
<div class="form-group">
<label for=color-review" class="col-sm-7 control-label">
<span>Color Review </span>
</label>
<div class="col-sm-5">
<input type="checkbox" id="color-review" class="pull-right" ng-model="colorReview" >
</div>
</div>
<div class="form-group">
<label for="type-review" class="col-sm-7 control-label">
<span>Type Review </span>
</label>
<div class="col-sm-5">
<input type="checkbox" id="type-review" class="pull-right" ng-model="typeReview">
</div>
Javascript:
// Set The Review Checkboxes To Toggle Switches
$('#color-review').bootstrapToggle();
$('#type-review').bootstrapToggle();
$('#toggle-one').bootstrapToggle();
Results: Here is a link to a picture of my results:
Results
A:
Have you taken a look at https://github.com/cgarvis/angular-toggle-switch?
$scope.topics:[{"on":true,"offLabel":"Off","onLabel":"On"}];
<div ng-repeat="t in topics">
<toggle-switch model="t.switch.on" on-label="t.switch.onLabel" off-label="t.switch.offLabel" switched="doSomethingToggle(t, $index)"></toggle-switch>
</div>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
internal sd card reader works, but without automount
On a new laptop I installed Ubuntu 18.04. Everything works fine, except for auto mount of sd cards. After inserting an sd card in the internal card reader, dmesg says:
mmc0: new high speed SDHC card at address b368
mmcblk0: mmc0:b368 7.46 GiB
mmcblk0: p1
mmcblk0: p1
The driver seems to be working OK because manually mounting works with:
sudo mount /dev/mmcblk0p1 /mnt
However, this makes the sd card read-only for all normal users. From my old laptop with the previous version of ubuntu, I was used to usb drives that automatically mount to /media/{user}/{volumename} and that can be unmounted with a context mouse menu on the menu icon for the drive.
My questions are:
how is this auto mount feature configured?
how do I get this auto mount behaviour to work on my new laptop?
update:
googling the first bullet I found:
https://help.ubuntu.com/stable/ubuntu-help/hardware-cardreader.html.en
with the suggestion to open the Files in the Activities list and do control-L and search for computer:/// . This made the sd card visible. This does not solve my second question, but if this had a solution, it would be mentioned there, and anyway this is a workable situation
A:
It turns out that there is no technical problem, but a new Ubuntu GUI. In the Files activity, under Other Locations, the SD card shows up in a very intuitive way, similar to Computer overview of Windows. To me it seems that this top level overview is rather hidden here.
The documentation in https://help.ubuntu.com/stable/ubuntu-help/hardware-cardreader.html.en is not exactly in sync, as it mentions a device list in the side bar, not under Other Locations.
On my previous ubuntu system a popup would appear at insertion of a usb drive. Removal of the popup could be a feature or a bug :-)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Deatomizing a map
I have atoms in maps, which may or may not be a good idea, but the point is I needed to deref the atoms so I could json-str the maps, and json-str can't handle atoms, so I wrote this:
(defn deatomize- [m]
(cond
(instance? clojure.lang.Atom m) #(deatomize- @m)
(map? m) (zipmap (keys m) (map #(trampoline deatomize- %) (vals m)))
:else m
)
)
(defn deatomize [m] (trampoline deatomize- m))
which seems to work, but a) is it good, b) is there a better way ?
A:
I think your code will work fine.
Some general feedback:
atoms in maps are a bit of an anti-pattern - usually you try to put maps in atoms. The idea is to keep your data structures immutable as much as possible, and have your references hold entire data structures at a fairly granular level. I'd strongly suggest rethinking this design - it will probably hurt you in the long run (for example, most Clojure library functions will assume immutable maps)
you are not deatomising the keys. maybe you never use atoms in keys in which case this is fine, but thought it was worth pointing out.
normally in Clojure closing parentheses don't get their own line and go at the end of the preceding line. this might feel odd at first, but it is good Lisp style that you should probably adopt.
performance of this function might not be that great because it is rebuilding the entire map structure piece by piece, even if nothing changes. reduce can be used to improve this, by only altering the map when you need to.
I think it is better to test for clojure.lang.IDeref rather than clojure.lang.Atom. By doing this, your code will also handle other reference types if needed.
trampoline is going to add overhead and is only needed in the (presumably rare?) case where you have really deep nesting in your data structure that is likely to cause stack overflows. If you need both safe stack handling and good performance then you might consider a recursive implementation and falling back to a trampoline version in the case of a StackOverflowException.
if you find an atom, the function is actually tail-recursive so you can use recur. this will reduce the need to use trampoline!
Here's an alternative to consider:
(defn deatomize [m]
(cond
(instance? clojure.lang.IDeref m)
(recur @m)
(map? m)
(reduce
(fn [current-map [k v]]
(let [nv (deatomise v)]
(if (= v nv) current-map (assoc current-map k nv))))
m
m)
:else m))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to Safely and Transactionally Replace a File on Linux?
The most naive, worst way I can think of to replace the contents of a file is:
f = open('file.txt', 'w')
f.write('stuff')
f.close()
Obviously, if that operation fails at some point before closing, you lose the contents of the original file while not necessarily finishing the new content.
So, what is the completely proper way to do this (if there is one). I imagine it's something like:
f = open('file.txt.tmp', 'w')
f.write('stuff')
f.close()
move('file.txt.tmp', 'file.txt') # dangerous line?
But is that completely atomic and safe? What are the proper commands to actually perform the move. If I have another process with an open connection to file.txt I assume that it will hold on to its pointer to the original file until is closes. What if another process tries to open up file.txt in the middle of the move?
I don't really care what version of the file my processes get as long as they get a complete, uncorrupted version.
A:
Your implementation of move should use the rename function, which is atomic. Processes opening the file will see either the old or the new contents, there is no middle state. If a process already has opened the file it will keep having access to the old version after move.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to keep button enabled while performing asynchronous task
In my xaml I have a Button and a TextBlock
<TextBlock Text="{Binding AText}" FontSize="20"/>
<Button Content="Click" Command="{Binding MyCommand}" Grid.Row="1"/>
and in my ViewModel I have following Code
let aText = self.Factory.Backing(<@ self.AText @>, "Initial Text")
let asyncTask x = async {
self.AText <- "Loading"
do! Async.Sleep(5000)
self.AText <- "Loaded"
}
member self.AText with get() = aText.Value and set(v) = aText.Value <- v
member self.MyCommand = self.Factory.CommandAsyncChecked(asyncTask, fun _ -> true)
When I click the button, It gets disabled and remains so until it finishes the asyncTask. I thought that setting canExecute as true will change the behavior but it did not!
How to control the behaviour of the button?
A:
The Async command support in FSharp.ViewModule was designed specifically so that the commands disable while operating, in order to prevent them from occurring multiple times.
If you don't want that behavior, the simplest option is to just use a normal command, and start the async workflow manually:
let asyncTask () = async {
self.AText <- "Loading"
do! Async.Sleep(5000)
self.AText <- "Loaded"
} |> Async.Start
member self.MyCommand = self.Factory.Command asyncTask
The normal command behavior will always remain enabled.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
When is the best time to collect login credentials during registration?
On a long, multi-screen registration flow, is it better to collect login credentials at the start, at the end, or when the user chooses to save their application and return to it later?
A:
I have never found multi-paged registration processes to be required.
Most of the time I opt for a 'progressive disclosure' model where the user is only asked for details when they are needed for a particular operation.
Lets say that you want to capture the users email, name, postal address, credit card details, and date of birth.
If you ask for it all up front there is a strong chance that they will refuse, get bored, get frustrated or find some other reason to abandon the process.
If, however, you just ask them for an email and password combination and then show them a profile with all the spaces then they can choose what to add and when. If they decide to buy something then you ask them for their credit card details, name and postal address. You might have an offer that they can only qualify for on their birthday - They'll have to go and add their date of birth... Basically you only ask for the details when the are needed to complete the task in hand.
The process can be speeded up by offering incentives for complete profiles (as stack exchange does) or by showing reminders that the users profile is incomplete (as Linked in does).
The point is that once the user has login credentials they can return when they like to add items to their profile or profile items can be collected during other processes and added to the profile.
In other words: Always set the login credentials first.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Verb for doping in sports
I need to know if as a sportsman can say:
I am going to dope?
I need to know how (especially) the Americans use the verb dope.
A:
Your sentence is perfectly understandable. To my ear, the most natural use of the verb "to dope" is in the gerund form as in the following examples,
Mike, are you doping?
The goalie for the US women's hockey team was found guilty of doping.
You certainly can use I dope, you dope, he dopes etc. But it isn't as common in every day language.
In your context I would probably say,
Should I use steroids? [or whatever more specific drug to which you are referring]
or
I am going to use steroids.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jQuery change event not working for input:radio buttons in Handlebars.js template
I'm using Handlebars.js to output a series of question/answer forms. There is only 1 answer per question so I'm using <input type="radio">. The code below produces the desired results however when a radio button is checked the jQuery change event is not firing.
<script id="questions-template" type="text/x-handlebars-template">
{{#questions}}
{{questionIndex @index}}
<article class="question question-{{@index}} clearfix">
<h2>{{question}}</h2>
<form>
{{#each answers}}
<div class="answer">
<input type="radio" name="radios[{{../questionIndex}}]" id="radios-{{../questionIndex}}{{@index}}" value="{{value}}">
<label for="radios-{{../questionIndex}}{{@index}}"><span>{{answer}}</span></label>
</div>
{{/each}}
</form>
</article>
{{/questions}}
</script>
<div id="questions"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.min.js"></script>
<script>
$(function(){
var questions = {
"questions": [
{
"question": "Lorem ipsum dolor sit amet, consectetur adipiscing elit?",
"answers": [
{
"answer": "Answer 1",
"value": 1
},
{
"answer": "Answer 2",
"value": 2
}
]
}
]
};
$(document).ready(function(event) {
var
source = $("#questions-template").html(),
template = Handlebars.compile(source);
Handlebars.registerHelper('questionIndex', function(value) {
this.questionIndex = Number(value);
});
$('#questions').append(template(questions));
});
$('input:radio').change(function(event) {
alert('change');
});
});
</script>
A:
you should be using .on to assign your event handler - because your radio button is generated dynamically. try this:
$("#questions").on("change", "input:radio", function(event) {//assuming questions is already part of the DOM
alert('change');
});
this question here Why use jQuery on() instead of click() gives some good insight over attaching event handlers to dynamically generated elements
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.