text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: report module for sugarcrm 6.2 Which Report module is suitable for making reports in sugarcrm 6.2 . I had installed the zucker Report Module on the local site it works properly but when i used to install them on my server it does not installed
Anyone please help
Thanks
A: KReporter certainly the best Reporting tool in the Marketing for SugarCRM, regardless of edition - be it PRO, ENT, CORP or CE.
The new free Google Charts are really cool
A: I suggest KINAMU Reporter, http://www.sugarforge.org/projects/kinamureporter
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7606044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can I create a device context that is just a portion of another device context? I have subclassed a graphics control that takes a device context handle, HDC, as an input and uses that for drawing. My new control is just the original control centered on top of a larger image. I would like to be able to call the original control's Draw() method for code re-use, but I'm unsure how to proceed.
Here's the idea:
void CCheckBox::DrawCtrl( HDC hdc, HDC hdcTmp, LPSIZE pCtlSize, BYTE alpha ) {
// original method draws a checkbox
}
void CBorderedCheckBox::DrawCtrl( HDC hdc, HDC hdcTmp, LPSIZE pCtlSize, BYTE alpha ) {
// Draw my image here
// Create new hdc2 and hdcTemp2 which are just some portion of hdc and hdcTemp
// For example, hdc2 may just be a rectangle inside of hdc that is 20 pixels
// indented on all sides.
// Call CCheckBox::DrawCtrl() with hdc2 and hdcTemp2
}
A: I think you may be confused of what a device context is. A device context is a place in memory that you can draw to, be it the screen buffer or a bitmap or something else. Since I imagine you only want to draw on the screen, you only need one DC. To accomplish what you want, I would recommend passing a rectangle to the function that tells it where to draw. Optionally, and with poorer performance, you could create a new Bitmap for the smaller area, and give the function the Bitmap's DC to draw on. Now that I think about it, that might have been what you meant in the first place :P Good luck!
A: While not foolproof, you can fake a DC as a subsection of a DC by using a combination of SetViewportOrgEx and SelectObject with a region clipped to the sub area in question.
The problem with this approach is if drawing code already uses these APIs it needs to rewritten to be aware that it needs to combine its masking and offsetting with the existing offsets and clipping regions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4551280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: VBA code to read word document footer I have a folder of completed word document forms and I have an excel file that reads all the answers on the forms into different worksheets in spreadsheet. The worksheet that the data is exported to depends on the filename of the word document.
This currently works fine.
However, I now need it to be able to take into account the version number of the form which is stored in the footer of the word document but I don't know how to reference it.
I'm quite a noob when it comes to VBA so havent tried much.
The VBA that I have tried can be found below but unsurprisingly doesnt work.
Sub ReadWordDoc(filenme As String)
Dim Val As String
Dim WrdDoc As Document
Dim FormFieldCounter As Integer
Dim version As String
Set wordapp = CreateObject("word.Application")
wordapp.Documents.Open filenme
wordapp.ScreenUpdating = False
Set WrdDoc = wordapp.Documents(filenme)
wordapp.Visible = True
version = WrdDoc.Sections(1).Footers(wdHeaderFooterFirstPage).Range.Text
FormFieldCounter = 1
If InStr(version, "5.00") Then
RowCounter = RowCounter + 1
Sheets("Version 5").Cells(RowCounter, FormFieldCounter) = filenme
Do While FormFieldCounter <= 125
WrdDoc.FormFields(FormFieldCounter).Select
Val = WrdDoc.FormFields(FormFieldCounter).result
Sheets("Version 5").Cells(RowCounter, FormFieldCounter + 1) = Val
FormFieldCounter = FormFieldCounter + 1
Loop
wordapp.Documents(filenme).Close SaveChanges:=wdDoNotSaveChanges
wordapp.Quit
Else
'Do something else
End If
End Sub
A: After having a bit of a play and a Google, I found this page which helped me fix my issue
https://msdn.microsoft.com/en-us/library/office/aa221970(v=office.11).aspx
I changed my code as below:
version = WrdDoc.Sections(1).Footers(wdHeaderFooterPrimary).Range.Text
Although I'm not sure why the previous version didnt work as there is a footer on the first page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33232440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Stopping thread Immediately I want to stop a running thread immediately. Here is my code:
Class A :
public class A() {
public void methodA() {
For (int n=0;n<100;n++) {
//Do something recursive
}
//Another for-loop here
//A resursive method here
//Another for-loop here
finishingMethod();
}
}
Class B:
public class B() {
public void runEverything() {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
A a = new A();
a.methodA();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread thread = new Thread(runnable);
thread.start();
}
My problem is that i need to be able to stop the thread in Class B even before the thread is finished. I've tried interrupt() method, but that doesn't stop my thread. I've also heard about using shared variable as a signal to stop my thread, but I think with long recursive and for-loop in my process, shared-variable will not be effective.
Any idea ?
Thanks in advance.
A: I think you should persevere with using Thread.interrupt(). But what you need to do to make it work is to change the methodA code to do something like this:
public void methodA() throws InterruptedException {
for (int n=0; n < 100; n++) {
if (Thread.interrupted) {
throw new InterruptedException();
}
//Do something recursive
}
// and so on.
}
This is equivalent declaring and using your own "kill switch" variable, except that:
*
*many synchronization APIs, and some I/O APIs pay attention to the interrupted state, and
*a well-behaved 3rd-party library will pay attention to the interrupted state.
Now it is true that a lot of code out there mishandles InterruptedException; e.g. by squashing it. (The correct way to deal with an InterruptedException is to either to allow it to propagate, or call Thread.interrupt() to set the flag again.) However, the flip side is that that same code would not be aware of your kill switch. So you've got a problem either way.
A: Thread.interrupt will not stop your thread (unless it is in the sleep, in which case the InterruptedException will be thrown). Interrupting basically sends a message to the thread indicating it has been interrupted but it doesn't cause a thread to stop immediately.
When you have long looping operations, using a flag to check if the thread has been cancelled is a standard approach. Your methodA can be modified to add that flag, so something like:
// this is a new instance variable in `A`
private volatile boolean cancelled = false;
// this is part of your methodA
for (int n=0;n<100;n++) {
if ( cancelled ) {
return; // or handle this however you want
}
}
// each of your other loops should work the same way
Then a cancel method can be added to set that flag
public void cancel() {
cancelled = true;
}
Then if someone calls runEverything on B, B can then just call cancel on A (you will have to extract the A variable so B has a reference to it even after runEverything is called.
A: You can check the status of the run flag as part of the looping or recursion. If there's a kill signal (i.e. run flag is set false), just return (after whatever cleanup you need to do).
A: There are some other possible approaches:
1) Don't stop it - signal it to stop with the Interrupted flag, set its priority to lowest possible and 'orphan' the thread and any data objects it is working on. If you need the operation that is performed by this thread again, make another one.
2) Null out, corrupt, rename, close or otherwise destroy the data it is working on to force the thread to segfault/AV or except in some other way. The thread can catch the throw and check the Interrupted flag.
No guarantees, sold as seen...
A: From main thread letsvsay someTask() is called and t1.interrput is being called..
t1.interrupt();
}
private static Runnable someTask(){
return ()->{
while(running){
try {
if(Thread.interrupted()){
throw new InterruptedException( );
}
// System.out.println(i + " the current thread is "+Thread.currentThread().getName());
// Thread.sleep( 2000 );
} catch (Exception e) {
System.out.println(" the thread is interrputed "+Thread.currentThread().getName());
e.printStackTrace();
break;
}
}
o/P:
java.lang.InterruptedException
at com.barcap.test.Threading.interrupt.ThreadT2Interrupt.lambda$someTask$0(ThreadT2Interrupt.java:32)
at java.lang.Thread.run(Thread.java:748)
the thread is interrputed Thread-0
Only t1.interuuption will not be enough .this need check the status of Thread.interrupted() in child thread.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11911118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: unexpectedly found nil while unwrapping an Optional value on return I am calling Url which will give me Json in get() function.
I am calling get() function from another class and try to return result of Json in Array format. but it shows Found null error on return statement . when I tried to print values of Json it writing correctly.
This is my code in swift.
func get() -> NSArray
{
let postEndpoint: String = "Link_For_JSON_Data"
let session = NSURLSession.sharedSession()
let url = NSURL(string: postEndpoint)!
var jsonArray : NSArray?
var jsonArray1 : NSArray?
session.dataTaskWithURL(url, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
// Make sure we get an OK response
guard let realResponse = response as? NSHTTPURLResponse where
realResponse.statusCode == 200 else
{
print("Not a 200 response")
return
}
// Read the JSON
do
{
if let contentString = NSString(data:data!, encoding: NSUTF8StringEncoding)
{
// Print what we got from the call
jsonArray = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray
print("jsonArray here", jsonArray)
// Update the label
dispatch_async(dispatch_get_main_queue())
{ () -> Void in
self.getDataFormREST(jsonArray!)
}
}
}
catch
{
print("bad things happened")
}
}).resume()
return jsonArray!
}
func getDataFormREST(resultArray: NSArray) //-> NSArray
{
// let resultDictionary = resultArray[(searchDetails)!-1] as! NSDictionary
testArray = resultArray
print("TESTArray ON ",testArray)
}
A: You can't write a function that does an async call and then returns the results as the function result. That's not how async code works. Your function queues up the async dataTaskWithURL request, and then returns before it has even had a chance to send the request, much less receive the results.
You have to rewrite your get() function to be a void function (no result returned) but take a completion block. Then, in your data task's completion handler you get the data from the jsonArray and call the get() function's completion block, passing it the jsonArray.
See this project I posted on Github that illustrates what I'm talking about:
SwiftCompletionHandlers on Github
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35762672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Attempting to load the view of a view controller while it is deallocating. CoreSpotlight I integrate CoreSpotlight in my app. I want that user will find need information in spotlight search and after user will open this information in spotlight information opens in DetailViewController. I made it, spotlight works nice, but when application is opening I see this error Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior (UIAlertController: 0x1245a0560) although I don't use UIAlertController. I made in AppDelegate func which call function of UITableViewController which must to open object by index. But it is not appear. Still there is an error in showData() performSegueWithIdentifier("show", sender: nil)reason: 'Receiver () has no segue with identifier 'show''. Although I add segue ( with show name) and it works when I usually select cell. Please help me.
AppDelegate
func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool {
if userActivity.activityType == CSSearchableItemActionType {
if let identifier = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String {
print(identifier)
checkWord = identifier // checkWord is String
let tableC = TableViewController()
tableC.showData()
return true
}
}
return false
}
func showData() {
let matchString = appDel.checkWord
if mainArray.contains(matchString) {
let ind = mainArray.indexOf(matchString)!
let indexPathMain = NSIndexPath(forItem: ind, inSection: 0)
print(indexPathMain)
self.tableView.selectRowAtIndexPath(indexPathMain, animated: true, scrollPosition: UITableViewScrollPosition.None)
performSegueWithIdentifier("show", sender: nil)
print("Show data")
}
}
A: If you don't implement willContinueUserActivityWithType or if it returns false, it means that iOS should handle activity. And in this case it can show UIAlertController. So to get rid this warning return true for your activity in this delegate call:
func application(application: UIApplication,
willContinueUserActivityWithType userActivityType: String) -> Bool {
return true
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33012529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Getting protractor promise, variables and results synchronized Okay, I have this piece of code I'm trying, and failing, at writing. What I want to do is to make sure an index that is passed to a function is within the bounds of available elements on a page. And, if it is, pass back an element reference.
Suppose I have the following:
<ul>
<li>First row</li>
<li>Second</li>
<li>Third</li>
</ul>
So, I've got this function:
function getRow(index) {
// get count of rows.
var count = $$('li').count();
// Ensure a parameter has been passed.
if (!index) {
throw Error("A parameter must be supplied for function getRow. Valid values are 0 through " + count-1);
}
// Ensure the parameter is within bounds
if (index < 0 || index >= count) {
throw Error("The parameter, " + index + ", is not within the bounds of 0 through " + count-1);
}
return $$('li').get(index);
}
The above will fail because count is not really count, but a promise.
So, I've tried modifying it in various ways. The one I thought would be successful is as follows:
// get count of rows.
var count;
$$('li').count().then(function(c) { count = c; });
or
// get count of rows.
var count = $$('li').count().then(function(c) { return c; });
I've gotten frustrated and tried to throw the whole if block within the thenable function, but it won't "see" index.
(Every time I think I've figured this out, I don't. Thank you for any and all assistance!)
UPDATE:
Following the suggestion below I tried modifying my code to:
function getRow(index) {
//get count of rows.
var count = $$('li').count().then(function(c) {
return function() {
return c;
}
});
protractor.promise.all(count).then(function(count) {
// Ensure a parameter has been passed.
if (!index) {
throw Error("A parameter must be supplied for function getRow. Valid values are 0 through " + count-1);
}
// Ensure the parameter is within bounds
if (index < 0 || index >= count) {
throw Error("The parameter, " + index + ", is not within the bounds of 0 through " + count-1);
}
});
return $$('li').get(index);
}
But it failed because, within the protractor.promise.all().then() block, index is undefined. Also, in the error message, I don't even get a value for count.
> getRow(0);
A parameter must be supplied for function getRow. Valid values are 0 through
A: I think you must use the javascript closures in order to achive it.
Try it:
var count = element(by.css('li')).count().then(function(c){
return function(){
return c
}
});
var value = count();
Your value should be in the "value" variable.
PS: I don't have a protractor environment to test this code now
A: Here's how I solved it.
function getRow(index) {
var count = $$('li').count();
var test = function(index, count) {
// Ensure a parameter has been passed.
if (index == undefined) {
throw Error("A parameter must be supplied for function getRow. Valid values are 0 through " + count-1);
}
// Ensure the parameter is within bounds
if (index < 0 || index >= count) {
throw Error("The parameter, " + index + ", is not within the bounds of 0 through " + count-1);
}
});
count.then(function(count) {
test(index, count);
}
return $$('li').get(index);
}
I'm not sure why this works and my previous attempt didn't. Well, other than I abstracted the function and allowed myself to pass in the index in a clean manner.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37442902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java, Possible to modify method declaration of super class in abstract class hierarchy? I have an abstract class UserdataUpdater which extends Updater
Updater has a method declaration
public abstract void processRow (Cluster cluster, IAppendOnlyData row);
Is there anyway to modify this method declaration inside UserdataUpdater to make it more specific, like
public abstract void processRow (Cluster cluster, IUserData row);
IUserData extends IAppendOnlyData, because I want classes that extends UserdataUpdater to only take IUserData
A: No, you can't. This would break the contract of the superclass, which says: this method accepts a IAppendOnlyData as second argument.
Remember that an instance of a subclass is also an instance of its superclass. So anyone could refer to the subclass instance as its superclass, and call the base method, passing a IAppendOnlyData, without knowing that the instance is actually a subclass instance.
Read more about the Liskov substitution principle.
The only way to do that is to make the superclass generic:
public class Updater<T extends IAppendOnlyData> {
...
public abstract void processRow(Cluster cluster, T row);
}
public class UserdataUpdater extends Updater<IUserData> {
@Override
public void processRow(Cluster cluster, IUserData row) {
...
}
}
A: You cannot modify a method declaration in a derived class. You can only override a superclass method if the derived class method has the exact same method signature. You must use function overloading and make a new method processRow with the new parameter types you mentioned.
A: In my experience, you have to use the first declaration, then in the implementation, check to make sure that:
row instanceof IUserData
of course, this is checked at runtime rather than during compile, but I don't know any other way around it. Of course, you can also just cast the row to the type IUserData, whether blindly or after checking its type (above).
A: Short answer: No.
You can create such a function, but because the signature is different, the compiler will see it as a different function.
If you think about it, what you are trying to do doesn't really make sense. Suppose you wrote a function that takes an Updater as a parameter and calls processRow on it with something that is not IUserData. At compile time, Java has no way to know whether the object passed in an Updater, UserdataUpdater, or some other subclass of Updater. So should it allow the call or not? What should the compiler do?
What you can do is inside UserdataUpdater.processRow, include code that checks the type passed in at runtime and throws an exception or does some other sort of error processing if it is not valid.
A: Assuming you have no control on the Updater class, you can't do that ... you'll have to implement that method with the exact same signature. However you can check for the type of row, inside your implementation and decide whatever processing is appropriate:
public void processRow (Cluster cluster, IAppendOnlyData row)
{
if( row instanceof IUserData )
{
// your processing here
}
else
{
// Otherwise do whatever is appropriate.
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12788742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android Studio resetDrmState message on MediaPlayer release and set to null I have a media player that can play 1 of 46 sounds on button click. Instead of keeping 46 media players and stopping them all when I want to play another, I decided to keep 1 and just reuse it. My whole application works perfectly fine but in my Run box I get a resetDrmState message on every button click.
V/MediaPlayer: resetDrmState: mDrmInfo=null mDrmProvisioningThread=null mPrepareDrmInProgress=false mActiveDrmScheme=false
cleanDrmObj: mDrmObj=null mDrmSessionId=null
Is this a bad message?
Does anyone know a way to get rid of the message?
I use the code:
public void onClick(View view) {
String thisIV=view.getTag().toString();
int resId=getResources().getIdentifier(thisIV,"raw", getPackageName());
if(mediaPlayer!=null && mediaPlayer.isPlaying()){
mediaPlayer.release();
mediaPlayer=null;
}
mediaPlayer= MediaPlayer.create(MainActivity.this, resId);
mediaPlayer.start();
}
for my media player.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71074517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Updating mysqli with Ajax and Jquery is not working I just want to update or edit <td> with Ajax. Edit or Save Button is in a <td> and so far everything is woking.
The Alert() function also shows variable values but the Ajax portion is not running. I am not sure why the data is not updating. Any help would be appreciated.
Question_statistics Page
include "include/connection";
while ($records=mysqli_fetch_array($query)){
$id=$records['id'];
$question=$records['question'];
$question_from=$records['question_from'];
$question_date=$records['question_date'];
?>
<tr id="record-<?php echo $id; ?>" class="record">
<th scope="row"><?php echo $id; ?></th>
<!-- Update or Edit -->
<td class="box" id="box<?php echo $id?>">
<span class="edit" id="<?php echo $id?>">Edit</span>
<span class="save" data-table="questions" id="save<?php echo $id?>">Save</span>
<span id="Q<?php echo $id?>"><?php echo $question; ?></span>
</td>
<td class="text-center"><?php echo $question_from; ?></td>
<td class="text-center"><?php echo $question_date; ?></td>
<!-- Delete Button -->
<td align="center">
<a id="<?php echo $id; ?>" class="delete" data-table="questions">
<img src="../assets/imgs/delete.png">
</a>
</td>
</tr>
Custom javascriptfile:
$(document).ready(function() {
//Update Question
$('.edit').click(function(ae){
ae.preventDefault();
$('.edit').hide();
var id = $(this).attr("id");
$('#box'+id).addClass('editable');
$('#box'+id).attr('contenteditable', 'true');
$('#save'+id).show();
});
$('.save').click(function(){
$('.save').hide();
$('.box').removeClass('editable');
$('.box').removeAttr('contenteditable');
$('.edit').show();
// var id =$(this).attr("id"); here id will show like `save+Id`
var id= $('.edit').attr("id");
var table = $(this).attr("data-table");
var question=$('#Q'+id).text();
alert(id+table+question);
$.ajax({
type: 'get',
url:'include/ajaxserver.php',
// data: variable or key : value, key:value,
data: {
id: id,
edit_me: true,
table: table,
question: question
},
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function(data) {
setTimeout( function ( ) {
alert( 'Data has been Deleted From Database' );
},600 );
}
});
});
});/*end of the ready function*/
ajaxserver file:
include('connection');
if(isset($_GET["edit_me"]) && $_GET["edit_me"]=="true")
{
$id = $_GET["id"];
$table = $_GET["table"];
$question=$_GET["question"];
$query = "UPDATE `{$table}` SET question='$question' WHERE id='$id'";
if (mysqli_query($con, $query)) {
echo "<script>alert('Updated')</script>";
}
else
echo "<script>alert('Not Updated')</script>";
}
A: Notice you are checking if $_GET["edit_me"] == "true" (string true) in the PHP page but that would mean that you should be sending edit_me: "true" in your ajax. Change your $_GET to:
# This will just check the key is filled
if(!empty($_GET["edit_me"]))
Then fix the SQL injection (you can Google that) and then send back instead of that javascript alert string you are doing:
die(json_encode(['success'=>(mysqli_query($con, $query))]));
This would send back to the ajax response {"success":true}if it worked. Since you are not specifically expecting json, you can parse the response:
// I changed the param here from data to response
success: function(response) {
// Parse the response
var data = JSON.parse(response);
// Alert either way
alert((data.success == true)? "Updated" : "Not Updated");
// Do whatever this is
setTimeout( function ( ) {
alert( 'Data has been Deleted From Database' );
},600 );
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48121538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: lottery system pot division I making a lottery system in my web-based application, so it is in JavaScript, but my problem is more mathematical so feel free to write snippets in other language.
I want to distribute the lottery pot over winners in a natural feeling way, example:
var pot = 1000;
var tickets = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
tickets = shuffleArray(tickets); //shuffle tickets for winners
//first half wins something (2 should be changeable)
var winners_count = Math.ceil(tickets.length / 2);
In this scenario i need a way to divide the whole pot over the 10 winners where first place gets the most and last (10th) get fewest.
for(var i=0; i<winners_count; i++){
var ticket = tickets[i];
//formula to determine percentage of pot to gain needed.
}
example outcome: (just to show you where it needs to go, not actual match)
1 - 22%
2 - 18%
3 - 14%
4 - 12%
5 - 10%
6 - 8%
7 - 7%
8 - 5%
9 - 3%
10 - 1%
I am quite bad at mathematics and some pointers and/or code snippets would help me a lot in solving this.
EDIT
Solution from Fabien Roualdes: http://jsfiddle.net/LB8YU/1/
A: I propose you to use an exponential distribution:
for(i=0 ; i<nrWinners ; i++){
value = exp(-lambda*i);
distribution[i] = value;
sum += value;
}
for(i=0 ; i<nrWinners ; i++){
distribution[i] /= sum;
}
Lambda is a positive parameter which will permit you to choose the shape of the distribution:
*
*If lambda is high the first winners will have a big part of the pot;
*On the contrary, the smaller lambda is, the more the distribution will aim towards a fair division of the pot.
I hope it will help you!
EDIT: When I say lambda is high, it is already high if it is equal to 1 for 5 winners.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17887636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Adding controls to a from C# 2015, this.Controls.Add(bla) method not found? public partial class MainWindow : Window
{
private void Window_Loaded(object sender, RoutedEventArgs e)
{
WebBrowser wb = new WebBrowser();
this.Controls.Add(wb);
}
}
This results in an error:
'MainWindow' does not contain a definition for 'Controls' and no extension method accepting a first argument of type 'MainWindow' could be found
Whats wrong here?
This is a WPF Application.
I'm new to C#.
I find it on internet that to add controls to the form the function is
this.Controls.Add(fdfdf)
But here this doesn't contain Controls.
A: In WPF it should be Children. In WPF you need to add items as Childrens of layout panels like your main Grid. For example if you have a Grid set it's name to grid1 and then in the code you can:
grid1.Children.Add(fdfdf)
A: You can add a component like your WebBrowser directly to the content of the Window.
In WPF you are doing it like this:
public partial class MainWindow : Window
{
private void Window_Loaded(object sender, RoutedEventArgs e)
{
WebBrowser wb = new WebBrowser();
this.Content = wb;
}
}
But I suggest to do this via the XAML.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37386108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: python - calculate the number of nodes in a Binary Tree I'm trying to write a function that uses recursion to find the number of nodes, i.e. the size of the binary tree. If the tree is empty there is no node. If it's not empty the number of nodes is 1 (the root) plus the number of nodes of the left subtree and the number of nodes of the right subtree.
I'm meant to use the binary tree class given to me to do this.
This is my Binary Tree class:
class BinaryTree:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def insert_left(self, new_data):
if self.left == None:
self.left = BinaryTree(new_data)
else:
t = BinaryTree(new_data)
t.left = self.left
self.left = t
def insert_right(self, new_data):
if self.right == None:
self.right = BinaryTree(new_data)
else:
t = BinaryTree(new_data)
t.right = self.right
self.right = t
def get_left(self):
return self.left
def get_right(self):
return self.right
def set_data(self, data):
self.data = data
def get_data(self):
return self.data
and this is my recursive function to calculate the size:
def size(my_tree):
count = 0
if my_tree.get_data() is None:
return 0
else:
count += 1 + size(my_tree.get_left()) + size(my_tree.get_right())
return count
However, when I run it with this program:
a = BinaryTree(1)
a.insert_left(2)
a.insert_right(3)
print(size(a))
I get the following error:
Original exception was:
Traceback (most recent call last):
File "prog.python3", line 57, in <module>
print(size(a))
File "prog.python3", line 41, in size
count += 1 + size(my_tree.get_left()) + size(my_tree.get_right())
File "prog.python3", line 38, in size
if my_tree.get_data() is None:
AttributeError: 'NoneType' object has no attribute 'get_data'
when the output should be:
3
I simply don't understand what I'm doing wrong, but I'm pretty sure it must be something to do with the if statement.
A: Just modify your if statement to
if my_tree is None:
return 0
The error arises since you are trying to access get_data property for a NULL data object on recursive call for leaf nodes of the binary tree.
Instead what you actually need to do is return 0 when you reach a NoneType node.
A: What happens if my_tree is None? Then you can't call get_data()...
Try this
if my_tree is None:
return 0
Worth pointing out that you don't care about the node data to find the size of the tree
The more optimal method is to not recurse, and keep the size updated as you insert/remove elements
A: Assuming you pass in a valid root object and recursion occurs as expected, then at what point can you hit upon a NoneType error? Certainly, when my_tree is None, and you try to access an attribute of None. When can my_tree be None? At the leaves. In other words, your base case is malformed.
Note that testing the return value of get_data is completely redundant here, because self.data has nothing to do with the height of the node, or the node itself.
def size(my_tree):
if not my_tree:
return 0
return 1 + size(my_tree.get_left()) + size(my_tree.get_right())
Further nitpicks:
*
*You don't need else; that's implied by control flow.
*You don't need an extra variable to store the count, because you don't do anything else besides return it.
A: You are getting this error because you are calling get_data() on non-existent object. So, you are calling get_data() on a NoneType object.
def size(my_tree):
count = 0
if my_tree is None:
return 0
count += 1 + size(my_tree.get_left()) + size(my_tree.get_right())
return count
The else clause is not needed. Another suggestion to count the binary tree nodes is to have a attribute size on the class, and increase / decrease it as items are added / removed from the tree.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46872046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Restrict list of components when linking in property editor in IDE I have created a new designtime component, which contains a published property Handler of type TComponent and registered it into the Tool Palette.
When i place a component of this type on my form, the property editor of the IDE shows me the property 'Handler' with a dropdown box that allows me to set this property at design time. The dropbox shows all available TComponents on the current form.
How can I restrict the list of components that is shown here (design time) to components of a certain type or with a certain property? i.e. Components that implement a certain (set of) interfaces.
I know that you can also use interface-properties, but also encountered several posts on the internet stating that this is very unstable and raises all kinds of problems.
Is there a method I can call for each of the proposed components where I can determine if they should appear in the list at design time?
Addition after the answer of @David:
Now that I've learned that TComponentProperty is what i was looking for, I also found a related question here: How to modify TComponentProperty to show only particular items on drop down list?
A: *
*Derive a sub class of TComponentProperty.
*Override its GetValues method to apply your filter.
*Register this TComponentProperty as the property editor for your property.
Here is a very simple example:
Component
unit uComponent;
interface
uses
System.Classes;
type
TMyComponent = class(TComponent)
private
FRef: TComponent;
published
property Ref: TComponent read FRef write FRef;
end;
implementation
end.
Registration
unit uRegister;
interface
uses
System.SysUtils, System.Classes, DesignIntf, DesignEditors, uComponent;
procedure Register;
implementation
type
TRefEditor = class(TComponentProperty)
private
FGetValuesProc: TGetStrProc;
procedure FilteredGetValuesProc(const S: string);
public
procedure GetValues(Proc: TGetStrProc); override;
end;
procedure TRefEditor.FilteredGetValuesProc(const S: string);
begin
if S.StartsWith('A') then
FGetValuesProc(S);
end;
procedure TRefEditor.GetValues(Proc: TGetStrProc);
begin
FGetValuesProc := Proc;
try
inherited GetValues(FilteredGetValuesProc);
finally
FGetValuesProc := nil;
end;
end;
procedure Register;
begin
RegisterComponents('Test', [TMyComponent]);
RegisterPropertyEditor(TypeInfo(TComponent), nil, 'Ref', TRefEditor);
end;
end.
This rather useless property editor will only offer you components whose names begin with A. Despite its complete lack of utility, this does illustrate the ability to filter that you desire. You'll likely want to call Designer.GetComponent(...) passing a component name to obtain the component instance, and implement your filtering based on the type and state of that component instance.
A: As @TLama already pointed out you need to change the tpe of handler field/property.
Now in case if you want to ba able to assign specific type of component to this field/property then set this field type to the same type of that compomnent.
But if you want to be able to assign several different component types but not all components make sure that Handler field/property type is the type of the first common ancestor class/component of your desired components that you want to be able to assign to the Handler field/property.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28454634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Copying from a set of cells from one column and paste them in consecutive columns in VBA Excel Macros I have got a set of values in Range 'A' and Range 'B'. I want to compare each consecutive row of Range 'A' and when the previous row is greater than the next row ; I want to copy then set of points below the compared points and paste them in the consecutive columns. for eg. C,G,J etc... I have got the compare part done ..Just the arranging part is taking my time. In my case I am trying to use DO Until and For Loop. But is there any better way ... PLs Advice...
Range("H1").Select
Do Until Range("H1", Range("H1").End(xlDown))
If IsEmpty(ActiveCell) Then
ActiveCell.Offset(1, 0).Select
j = 2
For i = 1 To Range("H1", Range("H1").End(xlDown)).Rows.Count
Cells(i + 1, 8).Select
Selection.Copy
Cells(i + 1, 11 + j).Select
ActiveSheet.Paste
Cells(i + 1, 9).Select
Selection.Copy
Cells(i + 1, 12 + j).Select
ActiveSheet.Paste
Next i
ActiveCell.Offset(1, 0).Select
Else
j = 0
For i = 1 To Range("H1", Range("H1").End(xlDown)).Rows.Count
Cells(i + 1, 8).Select
Selection.Copy
Cells(i + 1, 11 + j).Select
ActiveSheet.Paste
Cells(i + 1, 9).Select
Selection.Copy
Cells(i + 1, 12 + j).Select
ActiveSheet.Paste
Next i
ActiveCell.Offset(1, 0).Select
End If
Loop
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47991227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CDash build ID not set (CTest, CMake) I have a CDash configured to accept posts for automatic builds and tests. However, when any system attempts to post results to the CDash, the following error is produced. The result is that each result gets posted four times (presumably the original posting attempt plus the three retries).
Can anyone give me a hint as to what sets this mysterious build ID? I found some code that seems to produce a similar error, but still no lead on what might be happening.
Build::GetNumberOfErrors(): BuildId not set
Build::GetNumberOfWarnings(): BuildId not set
Submit failed, waiting 5 seconds...
Retry submission: Attempt 1 of 3
Server Response:
A: The buildid for CDash is computed based on the site name, the build name and the build stamp of the submission. You should have a Build.xml file in a Testing/20110311-* directory in your build tree. Open that up and see if any of those fields (near the top) is empty. If so, you need to set BUILDNAME and SITE with -D args when configuring with CMake. Or, set CTEST_BUILD_NAME and CTEST_SITE in your ctest -S script.
If that's not it, then this is a mystery. I've not seen this error occur before...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5265868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I prompt the user to give the name for the writing and reading serialized file? I am making an attempt to prompt the user to create the name for the writing and reading serialized file. E.g. could I do the following:
System.out.print("What would you like to name your file?");
String fileName = scanner.nextLine;
try{
ObjectOutput ostream = new ObjectOutputStream(new FileOutputStream(fileName)) // Would this create a file with the name inputted by the user? If so what would be the extension for the file?
ostream.writeObject(//whatever I want to put in here)
//close
//catch
try{
ObjectInputStream = new ObjectInputStream(new FileInputStream(fileName))
//catch
A: If you want to prompt the user for something from the terminal, the easiest way is probably to use java.io.Console, in particular one of its readLine() methods:
import java.io.Console;
...
Console console = System.console();
if (console == null) {
throw new IllegalStateException("No console to read input from!");
}
String fileName = console.readLine("What would you like to name your file? ");
// Whatever the user inputed is now in fileName
See http://docs.oracle.com/javase/7/docs/api/java/io/Console.html.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25966551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Braces around Java method I just noticed recently, while coding, that surrounding code with braces without any condition (or anything else) lets the code running correctly. For example, the following snippet:
public static void main(String[] args) {
{
System.out.println("Hello world !");
{
System.out.println("Hello subworld !");
{
System.out.println("Hello sub-subworld !");
}
}
}
}
Gives the following output:
Hello world !
Hello subworld !
Hello sub-subworld !
I would like to know: are there any consequences, deeper into execution, of this kind of practice ? And, is it used in any case and proven to be useful ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38246500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Recursively reversing a string in C? I have to reverse a string in a recursive function, but I cannot use loops or strlen to find where the end of the string is. Then I have to pass the reversed string back to main and copy it to a new file. Here's what I have so far:
int reverse(char *str, char *strnew, int p)
{
char temp=str[p];
if(temp=='\0' || temp=='\n')
{
strnew=str;
return p;
}
else
{
reverse(str++, strnew, ++p);
p--;
strnew[p]=str[p];
printf("strnew: %c\n", strnew[p]);
return 0;
}
}
int main(int argc, char *argv[])
{
FILE *fp;
char buffer[100];
char newstr[100];
int pointer=0;
fp=fopen("lab8.txt", "r");
if(fp==NULL)
{
printf("Error opening file\n");
return 0;
}
(fgets(buffer, 100, fp));
reverse(buffer, newstr, pointer);
printf("newstr: %s\n", newstr);
FILE *fp2=fopen("lab8.2.txt", "w");
fputs(newstr, fp2);
fclose(fp);
fclose(fp2);
return 0;
}
I cannot wrap my head around how to reverse the string. I've found where the null character is using p, but how do I copy the string backwards onto a new string?
A: #include <stdio.h>
int reverse(char *str, int pos){
char ch = str[pos];
return (ch == '\0')? 0 : ((str[pos=reverse(str, ++pos)]=ch), ++pos);
}
int main(){
char buffer[100];
scanf("%99[^\n]", buffer);
reverse(buffer, 0);
fprintf(stdout, "%s\n", buffer);
return 0;
}
A: Since this is obviously homework, no complete solution, only ideas.
First, you don't need to limit yourself to one recursive function. You can have several, and a resursive implementation of strlen is trivial enough. my_strlen(char *p) evaluates to 0 if *p = 0, and to 1 + my_strlen(p+1) otherwise.
You can probably do it in a single recursion loop, too, but you don't have to.
One more thing: as you recurse, you can run your code both on the front end of recursion and on the back end. A recursion is like a loop; but after the nested call to self returns, you have a chance to perform another loop, this one backwards. See if you can leverage that.
A: It is quite simple. When you enter the string, you save the character at the position you are are. Call the method recursively more character to the right. When you get to the end of the string, you will have N stack frames, each holding one character of an N character string. As you return, write the characters back out, but increment the pointer as you return, so that the characters are written in the opposite order.
A: I'll try to be nice and give you a little sample code. With some explanation.
The beauty of recursion is that you don't need to know the length of the string, however the string must be null terminated. Otherwise you can add a parameter for the string length.
What you need to think is that the last input character is your first output character, therefore you can recurse all the way to the end until you hit the end of the string. As soon as you hit the end of the string you start appending the current character to the output string (initially set to nulls) and returning control to the caller which will subsequently append the previous character to the output string.
void reverse(char *input, char *output) {
int i;
if(*input) /* Checks if end of string */
reverse(input+1,output); /* keep recursing */
for(i=0;output[i];i++); /* set i to point to the location of null terminator */
output[i]=*input; /* Append the current character */
output[i+1]=0; /* Append null terminator */
} /* end of reverse function and return control to caller */
Finally, lets test the function.
int main(argc, argv) {
char a[]="hello world";
char b[12]="\0";
reverse(a,b);
printf("The string '%s' in reverse is '%s'\n", a, b);
}
Output
The string 'hello world' in reverse is 'dlrow olleh'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23878979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to programmatically grant the "draw over other apps" permission in android? How can I programmatically grant the permission in Settings -> Apps -> Draw over other apps in Android? I want to use system alert window but unable to in Android Marshmallow without forcing the user to go through the Settings app and grant the permission first.
A: Here's the code for automatic granting the SYSTEM_ALERT_WINDOW permission to the package. To run this code, your Android application must be system (signed by platform keys).
This method is based on the following Android source code files: AppOpsManager.java and DrawOverlayDetails.java, see the method DrawOverlayDetails.setCanDrawOverlay(boolean newState).
@TargetApi(Build.VERSION_CODES.KITKAT)
public static void autoSetOverlayPermission(Context context, String packageName) {
PackageManager packageManager = context.getPackageManager();
int uid = 0;
try {
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 0);
uid = applicationInfo.uid;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
return;
}
AppOpsManager appOpsManager = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
final int OP_SYSTEM_ALERT_WINDOW = 24;
try {
Class clazz = AppOpsManager.class;
Method method = clazz.getDeclaredMethod("setMode", int.class, int.class, String.class, int.class);
method.invoke(appOpsManager, OP_SYSTEM_ALERT_WINDOW, uid, packageName, AppOpsManager.MODE_ALLOWED);
Log.d(Const.LOG_TAG, "Overlay permission granted to " + packageName);
} catch (Exception e) {
Log.e(Const.LOG_TAG, Log.getStackTraceString(e));
}
}
}
The code has been tested in Headwind MDM project, it successfully grants "Draw over other apps" permission without any user consent to the Headwind Remote application (disclaimer: I'm the project owner of Headwind MDM and Headwind Remote), when Headwind MDM application is signed by platform keys. The code has been tested on Android 10 (LineageOS 17).
A: You can check and ask for overlay permission to draw over other apps using this
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, 0);
}
A: if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, 0);
}
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
A: Check this question and the answer:
SYSTEM_ALERT_WINDOW - How to get this permission automatically on Android 6.0 and targetSdkVersion 23
"Every app that requests the SYSTEM_ALERT_WINDOW permission and that is installed through the Play Store (version 6.0.5 or higher is required), will have granted the permission automatically."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40355344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: Django - assign m2m relationship in admin In the app I'm building some users have the role "Coder" and are assigned to "Assignments".
What I can't seem to get working is the process of an Admin assigning Coders to Assignments.
Here is the Model-Code I have so far (probably totally wrong):
class Coder(models.Model):
"""Every user can be a coder. Coders are assigned to Assignments"""
user = models.OneToOneField(User)
class Admin:
list_display = ('',)
search_fields = ('',)
def __unicode__(self):
return u"Coders"
class Assignment(models.Model):
"""(Assignment description)"""
title = models.CharField(blank=True, max_length=100)
start_year = models.IntegerField(blank=True, null=True)
end_year = models.IntegerField(blank=True, null=True)
country = models.IntegerField(blank=True, null=True)
coders = models.ManyToManyField(Coder)
class Admin:
list_display = ('',)
search_fields = ('',)
def __unicode__(self):
return u"Assignment"
And this is the admin-code:
class AssignmentCoderInline(admin.StackedInline):
model = Assignment.coders.through
can_delete = False
verbose_name_plural = 'coder'
class AssignmentAdmin(admin.ModelAdmin):
fieldsets = [
('Assignment', {'fields': ['title', 'start_year', 'end_year']})
]
inlines = (AssignmentCoderInline,)
class CoderInline(admin.StackedInline):
model = Coder
can_delete = False
verbose_name_plural = 'coder'
Now, when i'm in the admin, I want to create an assignment and add coders to it.
Yet all I see when trying to do so is this:
How can I add one coder/user to an assignment, so I can later show him in a view all the assignments he has?
This is probably a really dumb question, but please answer anyways, I greatly appreciate any help :)
A: If I'm not mistaken, it looks like you want to call a coder to a view, and then show all the assignments for an a user.
First, I might start by assigning a related_name to the coder and assignment models relationships with each other, so you can easily reference them later.
class Assignment(models.Model):
coders = models.ManyToManyField(Coder, related_name='assignments')
class Coder(models.Model):
user = models.OneToOneField(User, related_name="coder")
I'd then reference the user in a template as such using the one to one relationship:
{% for assignment in user.coder.assignments.all %}
Also, looks like the problem is how you've got yout models setup. After reviewing the django.db.models.base for the "models.Model" class and "ModelBase" class, it looks like there is no "Admin" subclass. You'll probably want to remove those to start with.
Next, the __unicode__ field shows the default visible value which represents the object on the screen. In this case, you've forced it to be "Coders". If you had 5 coders to an assignment, you'd see "Coders, Coders, Coders, Coders, Coders" instead of "admin, user1, bob22, harry8, stadm1in", etc. Let's override the unicode to show something more meaningful. Since the coders field only has the user field, let's reference that by self.user.username. We'll change Assignment()'s unicode to self.title as well.
ModelForm doesn't have an 'Admin' subclass either, so let's remove that.
MODELS:
class Coder(models.Model):
"""Every user can be a coder. Coders are assigned to Assignments"""
user = models.OneToOneField(User, related_name='coder')
def __unicode__(self):
return self.user.username
class Assignment(models.Model):
"""(Assignment description)"""
title = models.CharField(blank=True, max_length=100)
start_year = models.IntegerField(blank=True, null=True)
end_year = models.IntegerField(blank=True, null=True)
country = models.IntegerField(blank=True, null=True)
coders = models.ManyToManyField(Coder, related_name='assignments')
def __unicode__(self):
return self.title
ADMIN:
class AssignmentCoderInline(admin.StackedInline):
model = Assignment.coders.through
can_delete = False
# verbose_name_plural = 'coder'
class AssignmentAdmin(admin.ModelAdmin):
fieldsets = [
('Assignment', {'fields': ['title', 'start_year', 'end_year']})
]
inlines = (AssignmentCoderInline,)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16118433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using JSP to paint a part of page other wise painted by Servlet I am updating an age old application that paints its page using a Servlet. I want to add something to that page and really want to stop adding to that Servlet file.
Is there a way I could paint a part of a page using JSP and all other using Servlet.
A: Yes of course, you can use the
`<jsp:include page="content.jsp">` or
`<%@include file="content.jsp"%>`
If your content is static(copy and paste), you can use `<%@include file="content.jsp"%>`
The `<%@include file="content.jsp">` directive is similiar to "#include" in C programming, including the all contents of the included file and then compiling it like it is part of the including file. Also the included file can be any type (including HTML or text).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32486686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Starting and stopping Apache Camel routes from admin UI I have a Apache Camel context which is part of a large Spring application. The application has a web based admin UI. I'd like to be able to stop/start/suspend/resume the camel routes from within this UI. How can I achieve this?
Currently my Camel context is defined in a Spring context file and autostarts when the Spring application is deployed. My routes are defined in Java classes which extend SpringRouteBuilder.
I have:
camel-context.xml:
<beans>
<!--bootstrap camel context-->
<camelContext xmlns="http://camel.apache.org/schema/spring">
<package>com.package</package>
</camelContext>
</beans>
which is imported in the main Spring context. I then have classes which extend SpringRouteBuilder in com.package
Is there a better way of doing this so that I can programatically control the Camel context when there is an event in the UI?
A: You can also do like we do in hawtio (http://hawt.io/) where we use REST calls to remote manage Camel applications, so we can control routes, see statistic, view routes, and much more. All this is made easier by using an excellent library called jolokia (http://jolokia.org/) that makes JMX exposed as REST services. Each JMX operation/attribute is easily callable as an URI template over REST. And data is in json format.
That what you can build UI consoles that just use REST for communication, and are not tied into the Java or JMX world etc.
Also the Java API on CamelContext allows you to control routes. And there is also the control-bus EIP that has more details: http://camel.apache.org/controlbus
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25136142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Detect activity level of microphone in flex I have to detect avtivityLevel of microphone in Flex. I am using the activityLevel property of Microphone class but as I found out it always return -1 even if I have done Microphone.getMicrophone().
To detect activity level we have to set microphone.setLoopback = true;
Does anybody know how to do this without using loop back as I do not want to hear my sound back just monitor the activity level
Thanks
A: The microphone won't show any activity until it is attached to a NetStream connection. You can use a MockNetStream to fake the connection using OSMF - see my answer here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2890906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: php docker how to use file_get_contents to fetch self domain's result I have a project need to server migration, the new server deployed by docker. but in docker, the file_get_contents() cannot fetch the result from self domain. and I can't use others way (for example reqire_once) to load this file ( this project is too old and code is... you know ).
code:
$json = file_get_content("http://this.site.com/xxx/yyy/get_result.php?params=xxx¶ms2=yyy")
If I use it, will get a warning connect refuese, if I replace the domain to http://127.0.0.1 or http://localhost, will get the same warning, or replace to http://nginx ( nginx is another container's name ) will get content, but not my site's content ( it will get contents the same by using 127.0.0.1 in the broswer, not using http://this.site.com )
So it
A: Your code is running with a docker on another instance so is 127.0.0.1 address is different from your computer's address.
You must enter the external IP address of the container
A: Try using host.docker.internal...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65436768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Keep selected row in table highlighted during fireTableDataChanged is there chance to keep the selected row in a JTable higlithed druing fireTableDataChanged?
Thank you
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27244406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Prism 7 throws and exception when working with nested views I posted similar question few months ago Working with nested views using Prism with IsNavigationTarget which can return false, I'm still not sure what is the proper way to do it.
Imagine you have a view A, in this view A you have declared a region A, then you injected a view B into this region A. Similarly, in View B you have registered region B, and then you injected a view C into this region B. As it shown on the following picture:
In the ViewModelA for ViewA, I have a method SetUpSubViews() where I call:
_regionManager.RequestNavigate("regionA", "ViewB", NavigationCallback);
ViewModelB for View B implements INavigationAware. So that in OnNavigatedTo() method I call:
_regionManager.RequestNavigate("regionB", "ViewC", NavigationCallback);
ViewModelC for View C implements INavigationAware too.
Now, I have in both ViewModelB and ViewModelC in IsNavigationTarget() method:
public bool IsNavigationTarget(NavigationContext navigationContext)
{
return false;
}
It means I want to create new view everytime this view is navigated.
Both ViewB and ViewC implement IRegionMemberLifetime interface, where I set:
#region IRegionMemberLifetime
public bool KeepAlive => false;
#endregion
It means that I don't want to reuse view and I want it to be disposed.
And regions in the view are declared like this:
<ContentControl prism:RegionManager.RegionName="{x:Static localRegions:LocalRegions.RegionB}" />
Now, first time when I call SetUpSubViews() method on ViewModelA all is good. Second time when I call it I see the exception:
Region with the given name is already registered
...
What I need is to have a way to recreate view<->viewmodel pair from scratch everytime when I need. It seems when view is disposed, prism doesn't remove region that was declared in removed view. Question to community and prism developers, how to do it in proper way?
The current solution doesn't make happy, here is what I do:
Step 1 - I set in ViewModelB and ViewModelC in INavigationAware part
public bool IsNavigationTarget(NavigationContext navigationContext)
{
return true;
}
that signals to prism to do not create new views and probably it also means that if any region is found in the view to do not register it in the region manager.
Step 2 - When i need to inject view to region, i remove manually old view and create new one. So my SetUpSubViews() method looks like this:
protected void SetUpSubViews(){
//get region by name
var region = _regionManager.Regions["regionA"];
// push to remove all views from the region
region.RemoveAll();
// navigate to view
_regionManager.RequestNavigate("regionA", "ViewB", NavigationCallback);}
Similarly I have to remove ViewC from region regionB on ViewB. (here is region.RemoveAll() is a key line.)
Step3 - I don't implement IRegionMemberLifetime interface on viewB and viewC.
It works, but it doesn't look correct.
P.S. I also tried scoped manager, but i don't know how to propagate new created scoped manager to the viewmodels, cause they are created automatically, and if i resolve it via constructor I get main global manager instead of scoped.
Thanks.
A: This is quite a troublesome problem. I recommend videos from Brian Lagunas himself where he provides a solution and explanation. For example this one.
https://app.pluralsight.com/library/courses/prism-problems-solutions/table-of-contents
If you can watch it. If not I will try to explain.
The problem I believe is that IRegionManager from the container is a singleton and whenever you use it it is the same instance, so when you are trying to inject a region in an already injected region it will not work and you need to have a separate RegionManager for nested views.
This should fix it.
Create two interfaces
public interface ICreateRegionManagerScope
{
bool CreateRegionManagerScope { get; }
}
public interface IRegionManagerAware
{
IRegionManager RegionManager { get; set; }
}
Create a RegionManagerAwareBehaviour
public class RegionManagerAwareBehaviour : RegionBehavior
{
public const string BehaviorKey = "RegionManagerAwareBehavior";
protected override void OnAttach()
{
Region.Views.CollectionChanged += Views_CollectionChanged;
}
void Views_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (var item in e.NewItems)
{
IRegionManager regionManager = Region.RegionManager;
// If the view was created with a scoped region manager, the behavior uses that region manager instead.
if (item is FrameworkElement element)
{
if (element.GetValue(RegionManager.RegionManagerProperty) is IRegionManager scopedRegionManager)
{
regionManager = scopedRegionManager;
}
}
InvokeOnRegionManagerAwareElement(item, x => x.RegionManager = regionManager);
}
}
else if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach (var item in e.OldItems)
{
InvokeOnRegionManagerAwareElement(item, x => x.RegionManager = null);
}
}
}
private static void InvokeOnRegionManagerAwareElement(object item, Action<IRegionManagerAware> invocation)
{
if (item is IRegionManagerAware regionManagerAwareItem)
{
invocation(regionManagerAwareItem);
}
if (item is FrameworkElement frameworkElement)
{
if (frameworkElement.DataContext is IRegionManagerAware regionManagerAwareDataContext)
{
// If a view doesn't have a data context (view model) it will inherit the data context from the parent view.
// The following check is done to avoid setting the RegionManager property in the view model of the parent view by mistake.
if (frameworkElement.Parent is FrameworkElement frameworkElementParent)
{
if (frameworkElementParent.DataContext is IRegionManagerAware regionManagerAwareDataContextParent)
{
if (regionManagerAwareDataContext == regionManagerAwareDataContextParent)
{
// If all of the previous conditions are true, it means that this view doesn't have a view model
// and is using the view model of its visual parent.
return;
}
}
}
invocation(regionManagerAwareDataContext);
}
}
}
}
Create ScopedRegionNavigationContentLoader
public class ScopedRegionNavigationContentLoader : IRegionNavigationContentLoader
{
private readonly IServiceLocator serviceLocator;
/// <summary>
/// Initializes a new instance of the <see cref="RegionNavigationContentLoader"/> class with a service locator.
/// </summary>
/// <param name="serviceLocator">The service locator.</param>
public ScopedRegionNavigationContentLoader(IServiceLocator serviceLocator)
{
this.serviceLocator = serviceLocator;
}
/// <summary>
/// Gets the view to which the navigation request represented by <paramref name="navigationContext"/> applies.
/// </summary>
/// <param name="region">The region.</param>
/// <param name="navigationContext">The context representing the navigation request.</param>
/// <returns>
/// The view to be the target of the navigation request.
/// </returns>
/// <remarks>
/// If none of the views in the region can be the target of the navigation request, a new view
/// is created and added to the region.
/// </remarks>
/// <exception cref="ArgumentException">when a new view cannot be created for the navigation request.</exception>
public object LoadContent(IRegion region, NavigationContext navigationContext)
{
if (region == null) throw new ArgumentNullException("region");
if (navigationContext == null) throw new ArgumentNullException("navigationContext");
string candidateTargetContract = this.GetContractFromNavigationContext(navigationContext);
var candidates = this.GetCandidatesFromRegion(region, candidateTargetContract);
var acceptingCandidates =
candidates.Where(
v =>
{
var navigationAware = v as INavigationAware;
if (navigationAware != null && !navigationAware.IsNavigationTarget(navigationContext))
{
return false;
}
var frameworkElement = v as FrameworkElement;
if (frameworkElement == null)
{
return true;
}
navigationAware = frameworkElement.DataContext as INavigationAware;
return navigationAware == null || navigationAware.IsNavigationTarget(navigationContext);
});
var view = acceptingCandidates.FirstOrDefault();
if (view != null)
{
return view;
}
view = this.CreateNewRegionItem(candidateTargetContract);
region.Add(view, null, CreateRegionManagerScope(view));
return view;
}
private bool CreateRegionManagerScope(object view)
{
bool createRegionManagerScope = false;
if (view is ICreateRegionManagerScope viewHasScopedRegions)
createRegionManagerScope = viewHasScopedRegions.CreateRegionManagerScope;
return createRegionManagerScope;
}
/// <summary>
/// Provides a new item for the region based on the supplied candidate target contract name.
/// </summary>
/// <param name="candidateTargetContract">The target contract to build.</param>
/// <returns>An instance of an item to put into the <see cref="IRegion"/>.</returns>
protected virtual object CreateNewRegionItem(string candidateTargetContract)
{
object newRegionItem;
try
{
newRegionItem = this.serviceLocator.GetInstance<object>(candidateTargetContract);
}
catch (ActivationException e)
{
throw new InvalidOperationException(
string.Format(CultureInfo.CurrentCulture, "Cannot create navigation target", candidateTargetContract),
e);
}
return newRegionItem;
}
/// <summary>
/// Returns the candidate TargetContract based on the <see cref="NavigationContext"/>.
/// </summary>
/// <param name="navigationContext">The navigation contract.</param>
/// <returns>The candidate contract to seek within the <see cref="IRegion"/> and to use, if not found, when resolving from the container.</returns>
protected virtual string GetContractFromNavigationContext(NavigationContext navigationContext)
{
if (navigationContext == null) throw new ArgumentNullException(nameof(navigationContext));
var candidateTargetContract = UriParsingHelper.GetAbsolutePath(navigationContext.Uri);
candidateTargetContract = candidateTargetContract.TrimStart('/');
return candidateTargetContract;
}
/// <summary>
/// Returns the set of candidates that may satisfiy this navigation request.
/// </summary>
/// <param name="region">The region containing items that may satisfy the navigation request.</param>
/// <param name="candidateNavigationContract">The candidate navigation target as determined by <see cref="GetContractFromNavigationContext"/></param>
/// <returns>An enumerable of candidate objects from the <see cref="IRegion"/></returns>
protected virtual IEnumerable<object> GetCandidatesFromRegion(IRegion region, string candidateNavigationContract)
{
if (region == null) throw new ArgumentNullException(nameof(region));
return region.Views.Where(v =>
string.Equals(v.GetType().Name, candidateNavigationContract, StringComparison.Ordinal) ||
string.Equals(v.GetType().FullName, candidateNavigationContract, StringComparison.Ordinal));
}
}
In your App.xaml
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
containerRegistry.RegisterSingleton<IRegionNavigationContentLoader,ScopedRegionNavigationContentLoader>();
}
protected override void ConfigureDefaultRegionBehaviors(IRegionBehaviorFactory regionBehaviors)
{
base.ConfigureDefaultRegionBehaviors(regionBehaviors);
regionBehaviors.AddIfMissing(RegionManagerAwareBehaviour.BehaviorKey, typeof(RegionManagerAwareBehaviour));
}
Coming to the finish.
Now in your ViewModelB implement IRegionManagerAware and have it as a normal property
public IRegionManager RegionManager { get; set; }
Then at your ViewB implement ICreateRegionManagerScope and have it as a get property
public bool CreateRegionManagerScope => true;
Now it should work.
Again I truly recommend the videos at Pluralsight from Brian on Prism. He has a couple of videos that help a lot when you are starting with a Prism.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63641883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CSRF PHP Prevention Mechanism I have read many articles about CSRF, almost all of them have the same solution which is hidden tokens, so i wrote a code to prevent CSRF and i tried hacking my own page afterwards but it didn't work, i would like to know if my code is CSRF bulletproof, and if there is anyway around it.
i have four pages that has forms in them so in each page i would write the following:
if (isset($_POST['submit'])){
// Check for CSRF token
if ($_SESSION['token'] === $_POST['token']){
// write to db
}else{
// CSRF attack has been detected
die("CSRF :<br>1: $_SESSION[token] <br> 2: $_POST[token]");
}
}else{
// assign CSRF prevention token
$form_token = md5((rand(1,89412) * 256 / 4).$date.time());
$_SESSION['token'] = $form_token;
}
?>
<form action='' method='post'>
<input type='hidden' name='token' value='<?echo $form_token;?>'>
would this method be enough to stop attackers from using CSRF on my website ?
Thanks alot.
A: I'll show you my code for CSRF prevention:
config.php
Configuration file should be auto-loaded in every page using require or include functions.
Best practice would be to write a configuration class (I'll just write down functions in order to simplify my code).
session_start();
if(empty($_SESSION['CSRF'])){
$_SESSION['CSRF'] = secureRandomToken();
}
post.php
This is just an example. In every "post" page you should check if CSRF token is set. Please submit your forms with POST method! I'd also recommend you to take a look at Slim Framework or Laravel Lumen, they provide an excellent routing system which is gonna let you to accept POST requests only on your "post.php" page very easily (they also will automatically add a CSRF token in every form).
if (!empty($_POST['CSRF'])) {
if (!hash_equals($_SESSION['CSRF'], $_POST['CSRF'])) {
die('CSRF detected.');
}
}else{
die('CSRF detected.');
}
view.php
Now you just have to put an hidden input with your CSRF session value in it.
<input type="hidden" name="CSRF" value="<?= $_SESSION['CSRF'] ?>">
I hope that this quick explanation may help you :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18679175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: youku search JS API in english I need the youku (China youtube) API in English or an explanation how to use it.
This is the code from youtube I want to write with youku:
url: 'https://www.googleapis.com/youtube/v3/search',
data: {
'part': 'snippet',
'q': this.searchBox.val(),
'type': 'video',
'key': '***key***'
},
Thank you!
Edit:
This topic was for everyone who wants to work with youku API.
I edited my question and I provided the correct answer.
You have to work with translator (no English version) and this is the correct path:
http://doc.open.youku.com/?docid=318
Please ready the Developer agreement as well:
http://doc.open.youku.com/?docid=312
Good luck.
A: EDIT: I found the correct link, and you can use the browser to translate to english. http://doc.open.youku.com/
The closest thing I can find to help you out this this thread, which contains a link that appears to go to Youku API documentation. I cannot get that link to open however. I hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36367309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ideas to upgrade Excel Income and Expense tracker Sorry for the overly lengthy explanation below but I thought it'll be helpful in getting your ideas:
A few years ago I helped a friend keep track of the income and expenses of his family run guest house (around 10 rooms). The way it works is that his guest house is managed by staff who provide my fiend with regular updates on income and expenses (eg. rooms occupied, income, types and amounts of expenses, referral sources etc).
I built a quick and simple system in Excel with a user form, which the guest house manager uses to log the information. This info gets saved in the same workbook on another sheet. Since my friend lives in another city, the manager then emails the workbook to him on a monthly basis. My friend has a master copy of the same workbook and every time he receives his monthly update, he copies and pastes (appends) the data into his master copy.
The master workbook also has some dashboards built into it which work off the back of some pivots, formulas or the data directly; and provide my friend with key information like monthly profit figures, expense types, most commonly occupied rooms, avg length of stay etc.
All worked well but now, since the dataset has increased hugely, the workbook has started crashing. He has asked me to fix it, but I think it's time to change the underlying technology which would better suit the purpose. He doesn't want to approach a professional developer as the profits don't justify the costs. I can develop something but I'm not sure which is the best way to do it:
I'm good with SQL and Excel. My VBA knowledge is intermediate and I've just started learning Python. My initial thoughts are:
I could host a webpage on my friend's machine which his manager can remotely access to fill in information which then gets stored in the SQL server - Again, I've only got very limited knowledge around web page development and hosting. There could be an Excel file (or Tableau once I've learnt it) linked to it
and serve as a dashboarding platform. Essentially, instead of storing data in Excel it'll be stored in a SQL database.
If any of you could suggest a better/simpler way of implementing this that'll be greatly appreciated.
Many Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45571689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: python time vs datetime The following comparison does not work, is there any way to get number of seconds passed (w.r.t localtime) since epoch from time module?
(datetime.datetime.now() - datetime.datetime.utcfromtimestamp(0)).total_seconds() - time.mktime(time.localtime()) => 3600.9646549224854
OR
(datetime.datetime.now() - datetime.datetime.utcfromtimestamp(0)).total_seconds() - time.time() => 3599.9999861717224
Thanks
A: datetime.now() returns a local datetime, while datetime.utcfromtimestamp() returns a UTC datetime. So of course you will have the difference of your timezone accounted for in your calculation. In order to avoid that, either always use local time, or always use universal time.
>>> (datetime.datetime.utcnow() - datetime.datetime.utcfromtimestamp(0)).total_seconds() - time.time()
0.0
A: Epoch is in GMT, so the number of seconds that have passed since Epoch is the same no matter what timezone you are in. Hence, the correct answer to your question:
is there any way to get number of seconds passed (w.r.t localtime) since epoch from time module?
is
>>> import time
>>> time.time()
1442482454.94842
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32626289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to read a LinkedHashMap written in file? I want to read a particular value from LinkedHashMap written in a .txt file, but is showing "java.io.StreamCorruptedException: invalid stream header: 7B495020"
For writing in LinkedHashMap i tried the method;
public void WriteBasicInfo(String name, String pass) throws IOException, ParseException {
Map<String, String> m;
try {
m = new LinkedHashMap<String, String>();
m.put("Name", name);
m.put("Password", pass);
BufferedWriter bw = new BufferedWriter(new FileWriter(FILE_NAME, false));
bw.write(m.toString());
bw.flush();
bw.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
And it successfully writes in file. But when Iam trying to read the above hashmap using this method
public void readBasicInfo() throws IOException, ParseException, InvocationTargetException, ClassNotFoundException
{
ObjectInputStream is = new ObjectInputStream(new FileInputStream(FILE_NAME));
Map<String, String> myMap=(LinkedHashMap<String, String>) is.readObject();
for(Map.Entry<String,String> m :myMap.entrySet()){
System.out.println(m.getKey()+" : "+m.getValue());
// String val1=m.get("Name");
}
ois.close();
}
it is showing "java.io.StreamCorruptedException: invalid stream header: 7B495020" , and no data is read
I tried to read all the entries written in hashmap, to check whether it is reading or not; but actually I just want read only "name" entry stored in hashmap.
A: You are simply: writing as string, but reading back expecting a binary serialized object!
You know, that is like: you put an egg in a box, and then you expect you can open that box and pour milk from it into a glass! That wont work.
Here:
bw.write(m.toString());
You write the map into that file as raw string. This means that your file now contains human readable strings!
But then you do:
Map<String, String> myMap=(LinkedHashMap<String, String>) is.readObject();
Which expects that the file contains serialized objects.
Long story short, these are your options:
*
*keep writing these strings, but then you need to implement your own parser that reads such text files, and turns them back into objects within maps
*instead of writing raw text strings, use a library such as gson or jackson and serialize your map as JSON string (which requires that all keys/values can be serialized as JSON)
*instead of writing raw text or JSON, use the default Java serialization mechanism and serialize to binary content which requires that all keys/values implement the Serializable interface. See here for a nice tutorial how to do that in detail.
My recommendation: go for option 2, or 3. 2 adds a dependency to a 3rd party library, but I think it is the more "common" practice these days.
A: You need to serialize/deserialize the object, not just reading/writing its toString representation to file.
See: https://javahungry.blogspot.com/2017/11/how-to-serialize-hashmap-in-java-with-example.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56144344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Permission error [winerror 5] access is denied-Selenium chrome webdriver I'm following a tutorial on using selenium and I'm having trouble getting started. Namely, when I try to run the code below, I get the error below. I have seen other users with the same problem, I have tried their solutions, they did not work.
These solutions include:
*
*running pycharm as administrator,
*setting permissions for all
*group/usernames of subprocess.py and service.py
*site-package(and pretty much every file/folder within) to full
access.
from selenium import webdriver
driver = webdriver.Chrome(r"C:\Users\User\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\selenium\webdriver\chrome")
driver.get("http://python.org")
Here is the full error message:
Traceback (most recent call last): File
"C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\common\service.py",
line 76, in start
stdin=PIPE) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py",
line 775, in init
restore_signals, start_new_session) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py",
line 1178, in _execute_child
startupinfo) PermissionError: [WinError 5] Access is denied
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"C:/Users/User/PycharmProjects/PythonProject/DataCollection", line 2,
in
driver = webdriver.Chrome(r"C:\Users\User\AppData\Local\Programs\Python\Python37-32\Lib\site-packages\selenium\webdriver\chrome")
File
"C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\chrome\webdriver.py",
line 73, in init
self.service.start() File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\common\service.py",
line 88, in start
os.path.basename(self.path), self.start_error_message) selenium.common.exceptions.WebDriverException: Message: 'chrome'
executable may have wrong permissions. Please see
https://sites.google.com/a/chromium.org/chromedriver/home
A: first, replace all \ with /
and then add the executable filename in the file location:
driver = webdriver.Chrome(r'C:/Users/User/AppData/Local/Programs/Python/Python37-32/Lib/site-packages/selenium/webdriver/chrome/chromedriver.exe')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64128761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Separate two html buttons and remove the fist button green animation There are two HTML buttons in the code below.
*
*Currently they are stuck together. I need to introduce a gap between them
*When you hover the mouse over the first (top) button, there is a green colour animation would show up around the button. I need to remove that.
Please advise me on how to make the proposed changes.
<body>
<div class="btn">
<div class="btn-back">
<p>Escolha o seu tamanho!</p>
<button class="yp">36</button>
<button class="no">No</button>
<button class="tsete">37</button>
<button class="toito">38</button>
<button class="tnove">39</button>
<button class="qzero">40</button>
<button class="qum">41</button>
<button class="qdois">42</button>
<button class="qtres">43</button>
</div>
<div class="btn-front">Azul</div>
</div>
<script src="script.js"></script>
<style type="text/css" media="screen">
Separate two html buttons and remove the fist button green animation
html, body {
}
body {
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
font-family: 'Montserrat', black;
font-size: 18px;
-webkit-perspective: 1000px;
perspective: 1000px;
background-color: white;
-webkit-box-orient: vertical;
-webkit-box-direction: normal;
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
-webkit-box-pack: center;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-box-align: center;
-webkit-align-items: center;
-ms-flex-align: center;
align-items: center; }
.description {
margin-top: 50px;
text-align: center;
color: #999;
-webkit-transition: opacity 0.3s ease;
transition: opacity 0.3s ease; }
.description a {
color: #4A9DF6;
text-decoration: none; }
.btn.is-open ~ .description {
opacity: 0; }
.btn {
display: block;
position: relative;
min-width: calc(300px + 12px);
min-height: calc(60px + 12px);
border-radius: 100px;
cursor: pointer;
outline: none;
position: relative;
padding: 0px;
-webkit-transition: width 0.8s cubic-bezier(0.23, 1, 0.32, 1), height 0.8s cubic-bezier(0.23, 1, 0.32, 1), -webkit-transform 0.8s cubic-bezier(0.175, 0.885, 0.32, 1.275);
transition: width 0.8s cubic-bezier(0.23, 1, 0.32, 1), height 0.8s cubic-bezier(0.23, 1, 0.32, 1), transform 0.8s cubic-bezier(0.175, 0.885, 0.32, 1.275);
-webkit-transform-style: preserve-3d;
transform-style: preserve-3d;
-webkit-transform-origin: 50% 50%;
-ms-transform-origin: 50% 50%;
transform-origin: 50% 50%;
text-align: center;
}
.btn-front {
position: absolute;
border-radius: 100px;
display: block;
width: 312px;
height: 72px;
line-height: 80px;
background-color: #007edc;
font-family: 'Montserrat', black;
font-weight: 650;
font-size: 25px;
text-transform: uppercase;
letter-spacing: 2px;
color: #fff;
cursor: pointer;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
-webkit-tap-highlight-color: transparent;
-webkit-transition: background 0.15s ease, line-height 0.8s cubic-bezier(0.23, 1, 0.32, 1);
transition: background 0.15s ease, line-height 0.8s cubic-bezier(0.23, 1, 0.32, 1); }
.btn-front:hover {
background-color: #0d98ff; }
.btn-back {
position: absolute;
width: 100%;
height: 100%;
background-color: #eee;
color: #222;
-webkit-transform: translateZ(-2px) rotateX(180deg);
transform: translateZ(-2px) rotateX(180deg);
overflow: hidden;
-webkit-transition: box-shadow 0.8s ease;
transition: box-shadow 0.8s ease; }
.btn-back p {
margin-top: 27px;
margin-bottom: 25px; }
.btn-back button {
padding: 12px 20px;
width: 30%;
margin: 0 5px;
background-color: transparent;
border: 500px;
border-radius: 2px;
font-size: 1em;
cursor: pointer;
-webkit-appearance: none;
-webkit-tap-highlight-color: transparent;
-webkit-transition: background 0.15s ease;
transition: background 0.15s ease; }
.btn-back button:focus {
outline: 0; }
.btn-back button.yp {
background-color: #2196F3;
color: #fff; }
.btn-back button.yp:hover {
background-color: #51adf6; }
.btn-back button.no {
color: #2196F3; }
.btn-back button.no:hover {
background-color: #ddd; }
.btn-back button.tsete {
color: #2196F3; }
.btn-back button.tsete:hover {
background-color: #ddd; }
.btn-back button.toito {
color: #2196F3; }
.btn-back button.toito:hover {
background-color: #ddd; }
.btn-back button.tnove {
color: #2196F3; }
.btn-back button.tnove:hover {
background-color: #ddd; }
.btn-back button.qzero {
color: #2196F3; }
.btn-back button.qzero:hover {
background-color: #ddd; }
.btn-back button.qum {
color: #2196F3; }
.btn-back button.qum:hover {
background-color: #ddd; }
.btn-back button.qdois {
color: #2196F3; }
.btn-back button.qdois:hover {
background-color: #ddd; }
.btn-back button.qtres {
color: #2196F3; }
.btn-back button.qtres:hover {
background-color: #ddd; }
.btn[data-direction="left"] .btn-back,
.btn[data-direction="right"] .btn-back {
-webkit-transform: translateZ(-2px) rotateY(180deg);
transform: translateZ(-2px) rotateY(180deg); }
.btn.is-open {
width: 400px;
height: 210px;
}
.btn.is-open .btn-front {
pointer-events: none;
line-height: 60px; }
.btn.is-open .btn-back {
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.4); }
.btn[data-direction="top"].is-open {
-webkit-transform: rotateX(180deg);
transform: rotateX(180deg); }
.btn[data-direction="right"].is-open {
-webkit-transform: rotateY(180deg);
transform: rotateY(180deg); }
.btn[data-direction="bottom"].is-open {
-webkit-transform: rotateX(-180deg);
transform: rotateX(-180deg); }
.btn[data-direction="left"].is-open {
-webkit-transform: rotateY(-180deg);
transform: rotateY(-180deg); }
@font-face {
font-family: 'Roboto';
font-style: normal;
font-weight: 400;
src: url(https://fonts.gstatic.com/s/roboto/v29/KFOmCnqEu92Fr1Mu72xKOzY.woff2) format('woff2');
unicode-range: U+0460-052F, U+1C80-1C88, U+20B4, U+2DE0-2DFF, U+A640-A69F, U+FE2E-FE2F;
}
.project-title {
position: absolute;
left: 25px;
bottom: 8px;
font-size: 16px;
color: #444;
}
.credits {
position: absolute;
right: 20px;
bottom: 25px;
font-size: 15px;
z-index: 20;
color: #444;
vertical-align: middle;
}
.credits * + * {
margin-left: 15px;
}
.credits a {
padding: 8px 10px;
color: #444;
border: 2px solid #999;
text-decoration: none;
}
.credits a:hover {
border-color: #555;
color: #222;
}
@media screen and (max-width: 1040px) {
.project-title {
display: none;
}
.credits {
width: 100%;
left: 0;
right: auto;
bottom: 0;
padding: 30px 0;
background: #ddd;
text-align: center;
}
.credits a {
display: inline-block;
margin-top: 7px;
margin-bottom: 7px;
}
}
</style>
<script>
var _gaq = [['_setAccount', 'UA-15240703-1'], ['_trackPageview']];
(function(d, t) {
var g = d.createElement(t),
s = d.getElementsByTagName(t)[0];
g.async = true;
s.parentNode.insertBefore(g, s);
})(document, 'script');
window.onload = function() {
var btn = document.querySelector( '.btn' );
var btnFront = btn.querySelector( '.btn-front' ),
btn36 = btn.querySelector( '.btn-back .yp' ),
btnNo = btn.querySelector( '.btn-back .no' );
btn37 = btn.querySelector( '.btn-back .tsete' );
btn38 = btn.querySelector( '.btn-back .toito' );
btn39 = btn.querySelector( '.btn-back .tnove' );
btn40 = btn.querySelector( '.btn-back .qzero' );
btn41 = btn.querySelector( '.btn-back .qum' );
btn42 = btn.querySelector( '.btn-back .qdois' );
btn43 = btn.querySelector( '.btn-back .qtres' );
btnFront.addEventListener( 'click', function( event ) {
var mx = event.clientX - btn.offsetLeft,
my = event.clientY - btn.offsetTop;
var w = btn.offsetWidth,
h = btn.offsetHeight;
var directions = [
{ id: 'top', x: w/2, y: 0 },
{ id: 'right', x: w, y: h/2 },
{ id: 'bottom', x: w/2, y: h },
{ id: 'left', x: 0, y: h/2 }
];
directions.sort( function( a, b ) {
return distance( mx, my, a.x, a.y ) - distance( mx, my, b.x, b.y );
} );
btn.setAttribute( 'data-direction', directions.shift().id );
btn.classList.add( 'is-open' );
} );
btn36.addEventListener( 'click', function( event ) {
btn.classList.remove( 'is-open' );
} );
btnNo.addEventListener( 'click', function( event ) {
btn.classList.remove( 'is-open' );
} );
function distance( x1, y1, x2, y2 ) {
var dx = x1-x2;
var dy = y1-y2;
return Math.sqrt( dx*dx + dy*dy );
}
};
</script>
</body>
<div class="wrap">
<form action="b_657272">
<button class="button">COMPRAR AGORA</button>
<style>
.wrap {
height: 100%;
display: flex;
align-items: center;
justify-content: center;
}
.button {
min-width: 300px;
min-height: 60px;
font-family: 'Montserrat', black;
font-size: 22px;
text-transform: uppercase;
letter-spacing: 5.px;
font-weight: 700;
color: #313133;
background: #4FD1C5;
background: linear-gradient(90deg, rgba(129,230,217,1) 0%, rgba(79,209,197,1) 100%);
border: none;
border-radius: 1000px;
box-shadow: 12px 12px 24px rgba(79,209,197,.64);
transition: all 0.3s ease-in-out 0s;
cursor: pointer;
outline: none;
position: relative;
padding: 10px;
}
button::before {
content: '';
border-radius: 100px;
min-width: calc(300px + 12px);
min-height: calc(60px + 12px);
border: 6px solid #00FFCB;
box-shadow: 0 0 60px rgba(0,255,203,.64);
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
opacity: 0;
transition: all .3s ease-in-out 0s;
}
.button:hover, .button:focus {
color: #313133;
transform: translateY(-6px);
}
button:hover::before, button:focus::before {
opacity: 1;
}
button::after {
content: '';
width: 30px; height: 30px;
border-radius: 100%;
border: 6px solid #00FFCB;
position: absolute;
z-index: -1;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
animation: ring 1.5s infinite;
content: '';
border-radius: 100px;
min-width: calc(300px + 12px);
min-height: calc(60px + 12px);
border: 6px solid #00FFCB;
box-shadow: 0 0 60px rgba(0,255,203,.64);
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
opacity: 0;
transition: all .3s ease-in-out 0s;
}
button:hover::after, button:focus::after {
animation: none;
display: none;
}
@keyframes ring {
0% {
width: 250px;
height: 0px;
opacity: 1;
}
100% {
width: 300px;
height: 150px;
opacity: 0;
}
}
<form action="https://google.com">
</style>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71697754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Text mining with PHP I'm doing a project for a college class I'm taking.
I'm using PHP to build a simple web app that classify tweets as "positive" (or happy) and "negative" (or sad) based on a set of dictionaries. The algorithm I'm thinking of right now is Naive Bayes classifier or decision tree.
However, I can't find any PHP library that helps me do some serious language processing. Python has NLTK (http://www.nltk.org). Is there anything like that for PHP?
I'm planning to use WEKA as the back end of the web app (by calling Weka in command line from within PHP), but it doesn't seem that efficient.
Do you have any idea what I should use for this project? Or should I just switch to Python?
Thanks
A: If you're going to be using a Naive Bayes classifier, you don't really need a whole ton of NL processing. All you'll need is an algorithm to stem the words in the tweets and if you want, remove stop words.
Stemming algorithms abound and aren't difficult to code. Removing stop words is just a matter of searching a hash map or something similar. I don't see a justification to switch your development platform to accomodate the NLTK, although it is a very nice tool.
A: I did a very similar project a while ago - only classifying RSS news items instead of twitter - also using PHP for the front-end and WEKA for the back-end. I used PHP/Java Bridge which was relatively simple to use - a couple of lines added to your Java (WEKA) code and it allows your PHP to call its methods. Here's an example of the PHP-side code from their website:
<?php
require_once("http://localhost:8087/JavaBridge/java/Java.inc");
$world = new java("HelloWorld");
echo $world->hello(array("from PHP"));
?>
Then (as someone has already mentioned), you just need to filter out the stop words. Keeping a txt file for this is pretty handy for adding new words (they tend to pile up when you start filtering out irrelevant words and account for typos).
The naive-bayes model has strong independent-feature assumptions, i.e. it doesn't account for words that are commonly paired (such as an idiom or phrase) - just taking each word as an independent occurrence. However, it can outperform some of the more complex methods (such as word-stemming, IIRC) and should be perfect for a college class without making it needlessly complex.
A: You can also use the uClassify API to do something similar to Naive Bayes. You basically train a classifier as you would with any algorithm (except here you're doing it via the web interface or by sending xml documents to the API). Then whenever you get a new tweet (or batch of tweets), you call the API to have it classify them. It's fast and you don't have to worry about tuning it. Of course, that means you lose the flexibility you get by controlling the classifier yourself, but that also means less work for you if that in itself is not the goal of the class project.
A: Try open calais - http://viewer.opencalais.com/ . It has api, PHP classes and many more. Also, LingPipe for this task - http://alias-i.com/lingpipe/index.html
A: you can check this library https://github.com/Dachande663/PHP-Classifier very straight forward
A: you can also use thrift or gearman to deal with nltk
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2783033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: Second Spinner not receiving the proper info based on the first Spinner's selection I know there are about a million topics on this already, but hear me out.
The title says it all, when i select an item in spinner 1, spinner 2 gets a specific list of choices to pick from (which will then be used to show info). It's essentially a small contacts book.
*UPDATE**
All fixed and working, and an EXTRA special thank you to user FishTruck for helping out(i.e making it work!)
package com.your.package.name;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
public class Contact extends Activity{
public Spinner spinner1, spinner2;
public Button btnSubmit;//not needed yet
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.contact);
findViews();
addItemsOnSpinner1();
addItemsOnSpinner2(0);
}
private void findViews(){
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
}
private void addItemsOnSpinner1() {
List<String> list = new ArrayList<String>();
list.add("Please Select");
list.add("Choice 1");
list.add("choice 2");
ArrayAdapter<String> name = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
name.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(name);
spinner1.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
if(arg2>0)
addItemsOnSpinner2(arg2);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
addItemsOnSpinner2(0);
}}
);
}
private void addItemsOnSpinner2(int selectedIndex) {
int positionTop = selectedIndex;
if(positionTop==0){
List<String> list = new ArrayList<String>();
list.add("Please Select");
ArrayAdapter<String> name0 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
name0.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(name0);
}else if(positionTop==1){
List<String> list1 = new ArrayList<String>();
list1.add("Please Select");
list1.add("item 1");
list1.add("item 2");
ArrayAdapter<String> name1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list1);
name1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(name1);
}else if(positionTop==2){
List<String> list2 = new ArrayList<String>();
list2.add("Please Select");
list2.add("item 3");
list2.add("item 4");
ArrayAdapter<String> name2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list2);
name2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(name2);
}
}
}
Hope this helps!
A: You need to call the addItemsOnSpinner2() function when the first spinner item has got selected.
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
addItemsOnSpinner2();}
A: you are setting both spinner at the beginning of the code ( in onCreate). You should populate the second spinner after the spinner1 data is changed
A: yes as the gentlemen before me said.
In order for the second spinner to get the correct index to set the list,
you need to populate it after the first spinner is clicked.
/* wrong answer deleted */
if this is my code i would change addItemsOnSpinner2() into:
private void addItemsOnSpinner2(int selectedIndex){
int positionTop = selectedIndex;
//rest is the same
/* ... */
}
and again insert these into addItemsOnSpinner1():
spinner1.setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) {
if(arg2>0)
addItemsOnSpinner2(arg2);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
addItemsOnSpinner2(0);
}}
);
that is just how i would do it
i think many ways works here though
edit2:oh and edit the addItemsOnSpinner2() in onCreate() into addItemsOnSpinner2(0)
edit3:you need to call addItemsOnSpinner2() in onCreate(), otherwise your spinner is empty!
edit4:sorry guys, i made a huge mistake into thinking onItemClickListener could be applied here, shame on me :((
btw, if you want to keep the index (under situation like change of screen orientation or back to foreground ) , it needs more complicated work
but here is a much simpler method:
1.set a global static variable: int selectedIndex;
2.in onCreate, set selectedIndex to 0 if savedInstanceState is null
3.in onCreate, after savedInstanceState is nullcheckd, call addItemsOnSpinner2(selectedIndex)
4.in spinner1's listener, set selectedIndex to selected index.
not guarranteed to work on every machine though:(
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15411937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to make the vim plugin "Project" and "Mini Buffer Explorer" work together? As the title says, I need to make these plugins work together well. The mini buffer explorer just automatically opens after I open the second file(press Enter in project plugin window), then Mini Buffer Explorer opens as the third window on the top of my screen.
But after I switch back to project plugin window and press Enter to open the third file, a fourth window opened! It seems project plugin can't overwrite the second file's window.
Project plugin 1.4.1
Mini Buffer Explorer plugin 6.4.0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4704717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Make NUnit not stop at first failure I'm running a NUnit test over a list of numbers.
My code goes something like this:
numbers = GetListOfNumbers()
foreach number in numbers
Assert.IsTrue(TestNumber(number))
My problem is that NUnit will stop the test on the first number it encounters that doesn't pass the test.
Is there anyway to make NUnit still fail the test if any numbers don't pass, but give me the list of all numbers that don't pass?
A: As a workaround, instead of using an Assert.IsTrue like that, you could try something like:
numbers = GetListOfNumbers()
List<number> fails = numbers.Where(currentNum=>!TestNumber(curentNum))
if (fails.Count > 0)
Assert.Fail(/*Do whatever with list of fails*/)
A: NUnit 2.5 has data-driven testing; this will do exactly what you need. It'll iterate over all of your data and generate individual test cases for each number.
Link
A: This can be done in MBUnit using a "RowTest" test method. I'm not aware of a way of doing this in NUnit, however.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/923233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to stop NSTimer with another NSTimer? Note: I am using swift for this project.
I am currently working on my first project and I am trying to stop (invalidate) an NSTimer if a button was not pressed after a certain amount of time. I have found other ways of stopping my NSTimer but none saying how to stop it after a certain amount of time, with that time being reset if the button actually is pressed. Read everything to understand more clearly.
Here is my code now;
@IBOutlet var Text: UILabel!
var timer: NSTimer!
var countdown: Int = 0
@IBAction func StartGame(sender: AnyObject) {
self.countdown = 20
self.timer = NSTimer.scheduledTimerWithTimeInterval(1.5, target: self, selector: "updateCountdown", userInfo: nil, repeats: true)
}
func updateCountdown() {
self.countdown--
if self.countdown == 0 {
self.timer.invalidate()
self.timer = nil
}
let texts: NSArray = ["Test", "Testing"]
let range: UInt32 = UInt32(texts.count)
let randomNumber = Int(arc4random_uniform(range))
let textstring = texts.objectAtIndex(randomNumber)
self.ColorText.text = textstring as? String
}
@IBAction func PlayerbuttonPRESSED(sender: AnyObject) {
if Text.text == "Test" {
//Something happens
}
if Text.text == "Testing" {
//Something happens
}
What I am dying to know is how I make something else happen if the button was not pressed before ColorText.text was changed! (If the button was not pressed before changing the text after 1.5 seconds).
Ps. Sorry for the long code, I think it is necessary. :-)
A: There are different ways of doing this. One way, you could set bool value to true when the button is pressed then in updateCountdown check to the boolean.
For example:
func updateCountdown() {
self.countdown--
if self.countdown == 0 && YOUR_BUTTON_BOOL {
self.timer.invalidate()
self.timer = nil
}
let texts: NSArray = ["Test", "Testing"]
let range: UInt32 = UInt32(texts.count)
let randomNumber = Int(arc4random_uniform(range))
let textstring = texts.objectAtIndex(randomNumber)
self.ColorText.text = textstring as? String
}
However, using NSTimer in this fashion where you have it trigger in a short period of time like 1.5 seconds can become inaccurate. After the timer triggers 20 times the time past will be greater than 30 seconds. If accuracy is important you might be better off setting a second timer for 30 seconds. If the button is pressed it invalidates the 30 second timer if the 30 second timer fires it invalidates the 1.5 second timer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34549166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: React + GraphQL: dataArray.map is not a function I Just started learning graphQL and Apollo.
Below is the sample client side code using Apollo client.
I am providing data from nodemon express server.
console.log(data) shows the output from the server.
However i was trying to display the query result using the apollo client but i was unbale to do so. I am stuck in this , any help will be appreciated.
import React from "react"
import { Query } from "react-apollo";
import gql from "graphql-tag";
export const ExchangeRates = () => (
<Query
query={gql`
{
counterparty {
name
}
}
`}
>
{({ loading, error, data }) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>Error :(</p>;
console.log(data) // Works fine as expected
var a= data.map(x=>{
return x.name
})
return <div> Data {a}</div> // stuck here ..how to display data
}}
</Query>
);
The following codes gives an error and says
TypeError: data.map is not a function
However the console.log(data) works fine and the following output:-
A: Your are doing wrong here... your array is inside data.counterparty...
try this
var a= data.counterparty.map(x=>{
return x.name
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49745422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: doPostback() not refreshing some elements on page correctly Having the following problem:
I have an HTML button which causes a __doPostBack(button.ClientID,'texthere').
Dim button As HtmlButton
button = CType(Me.btnButton, HtmlButton)
button.Attributes.Add("onclick", "__doPostBack('" & btnButton.ClientID & "', 'btnBBHistory');return false;")
In my page_load I have the following:
Dim control_postback = Request("__EVENTARGUMENT")
If control_postback = "texthere"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "Script", "ShowWindow();",
End If
The ShowWindow(); javascript function is displayed using showModalDialog.
Dim s As New StringBuilder
s.Append("<script type=""text/javaScript"">")
s.Append("function ShowWindow() {" & ControlChars.CrLf)
' s.Append("var result = window.showModalDialog('" & url & "','','dialogWidth:1200px;dialogHeight:450px;resizable:yes');" & ControlChars.CrLf)
s.Append("var result = window.showModalDialog('" & url & "','','dialogWidth:1100px;dialogHeight:500px;resizable:yes;help:no;');" & ControlChars.CrLf)
s.Append("if (result) { " & ControlChars.CrLf)
' s.Append("document.getElementById('" & lblwhatever.ClientID & "').innerHTML=result.fullline;" & ControlChars.CrLf)
s.Append("if (result.text.length || result.quantity.length) { " & ControlChars.CrLf)
s.Append("document.getElementById('" & txtwhatever.ClientID & "').value=result.text.concat(result.quantity);" & ControlChars.CrLf)
s.Append("document.getElementById('" & txtqty.ClientID & "').value=result.quantity;" & ControlChars.CrLf)
s.Append("__doPostBack()" & ControlChars.CrLf)
s.Append("}" & ControlChars.CrLf)
s.Append("}" & ControlChars.CrLf)
s.Append("return false;" & ControlChars.CrLf)
s.Append("}" & ControlChars.CrLf)
s.Append("</script>")
If Not ClientScript.IsClientScriptBlockRegistered("ShowWindow") Then
ClientScript.RegisterClientScriptBlock(Me.GetType(), "ShowWindow", s.ToString())
End If
This all works fine and the dialog box with the generated URL is displayed. However, on the originating webpage (the one where the button is initially clicked to produce this dialog box), there is an image (.djvu format). Whenever my code is run, the originating page is refreshed because of the __doPostBack() but in certain version of IE (IE8 and 9 so far) the image does not reload. Is there a chance that the showModalDialog is preventing any further rendering of the page in the background on these versions of IE or that the doPostBack() is not actually doing a complete postback in some way and the image is breaking?
Thanks for any help you might be able to give
A: Fixed: I needed to use window.open instead of showmodaldialog as when using showmodaldialog, the parent/calling page was (i believe) pausing/halting/breaking execution of the parent page until the child page was closed
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25978243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: VB.NET table.sort with multiple columns I have the following but need to add more columns to filter by. I am getting errors with the syntax I am trying.
Dim ldv1 As System.Data.DataView
ldv1 = tbl1.DefaultView
ldv1.Sort = (tbl1.Columns(0).ColumnName) & " Asc" <-- I want to add to this
I am trying to do something like this but failing:
ldv1.Sort = (tbl1.Columns(0).ColumnName) & " Asc",(tbl1.Columns(1).ColumnName) & " Asc"
OR
ldv1.Sort = (tbl1.Columns(0).ColumnName), (tbl1.Columns(1).ColumnName) & " Asc"
Neither seems to be the correct way. How do I sort by more columns?
A: Add a , inside the string after the first Asc.
ldv1.Sort = tbl1.Columns(0).ColumnName + " Asc, " + tbl1.Columns(1).ColumnName + " Asc"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32265570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Temporary captured-variables in lambda functions - C++11 I was trying out something like this to pre-populate a map using a vector-list of strings.
The code is self-explanatory:
Constructor(const vector<string>& names) {
for_each(names.begin(), names.end(),
[this, counter = 1](const String& choice) mutable {
nameMapping.emplace(choice, counter++);
}
);
}
Something I didnt really understand is how does counter work?
FYI: counter is no-where declared outside of the lambda function.
But yet, I am able to create a local-variable in class-scope and modify it in a mutable lambda fn?
Can someone please help me understand whats going on.
A: When you set counter = 1 you're declaring a new temporary counter equal to 1. The compiler does the work of determining the type. This temporary object is deduced to type int by default, and lives while the lambda is alive.
By setting mutable you can both modify counter and this
Aside: since it appears that you're inserting into a map/unordered map, you're probably better off with the following:
#include <algorithm> // For transform
#include <iterator> // For inserter
Constructor(const vector<string>& names) {
auto const example = [counter = 1](const string& item) mutable {
return {item, counter++};
};
std::transform(names.begin(), names.end(),
std::inserter(nameMapping, nameMapping.end()), example);
}
By moving the nameMapping call outside of the lambda, you don't have to confuse yourself with what is in scope and what is not.
Also, you can avoid unnecessary captures, and anything else that might confuse yourself or other readers in the future.
A:
But yet, I am able to create a local-variable in class-scope and modify it in a mutable lambda fn?
Can someone please help me understand whats going on.
It's exactly as you said.
Possibly confusing because there's no type given in this particular kind of declaration. Personally I think that was an awful design decision, but there we go.
Imagine it says auto counter = 1 instead; the auto is done for you. The variable then becomes a "member" of the lambda object, giving it state.
The code's not great, because the lambda isn't guaranteed to be applied to the container elements in order. A simple for loop would arguably be much simpler, clearer and predictable:
Constructor(const vector<string>& names)
{
int counter = 1;
for (const string& name : names)
nameMapping.emplace(name, counter++);
}
There's really no reason to complicate matters just for the sake of using "fancy" standard algorithms.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64524992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Postgresql - Postgis - how to filter content? I have imported a shapefile that consists of POINT data.
Here is the query:
SELECT a.name,
ST_Distance(ST_GeographyFromText(ST_AsText(a.geom)),
ST_GeographyFromText(ST_AsText(b.geom)))/1000 AS distance
FROM places a, places b
WHERE b.name='Mumbai';
This query displays distances (in KM) of places from 'Mumbai'.
Giving the output:
name | distance
--------------------------------------------------+------------------
Mumbai | 0
New Delhi | 1159.26223973831
Pune | 117.86639722221
Vittalpuram | 1058.49956760668
Kadapakkam | 1064.4166204267
Chellampatty | 1136.24329302432
Srirampur | 205.27117214342
Bhorvadi | 213.69790081481
Vaduj | 227.66082105079
Pushkar | 853.0369297591
Orcha | 927.67801469371
Phillaur | 1369.21450470719
Goraya | 1381.0316667358
Phagwara | 1390.76210842565
Ludhiana | 1358.93226658828
Mohali | 1361.88704243237
Morinda | 1362.40782426879
Kurali | 1368.92321753998
Rupnagar | 1382.46666378301
Moga | 1335.85239784081
Pahalgām | 1689.72733587196
Ambala | 1327.24107571448
Doraha | 1351.41408180716
Entrance of Ranjeet Avenue | 1351.43744476875
Shaheed Jasdev Singh Nagar | 1353.19967929777
Jagbir House | 1357.58692404013
Rania | 1350.48320804851
Pawa | 1354.30374843403
Sreenh | 1347.01369530847
Kaind | 1345.76155280418
Dharour | 1352.71636605571
TIBBA | 1350.96268614694
NAAT | 1351.965780883
Harnampura | 1350.90891035291
Nandpur | 1354.12810806732
Umadpur | 1350.92919575633
Dugri | 1350.23846455405
Dehlon intersection | 1341.15103218979
Alwarpet | 1029.21518660807
Teynampet | 1028.07582220005
Gopalapuram | 1028.37800837912
Nandanam | 1028.41251498301
Raja Annamalai Puram | 1029.83876612634
Abhiramapuram | 1029.72834342923
CIT Colony | 1029.16938386861
Sriperumbudur | 1009.05941189302
Poonamallee | 1015.86523604896
Now I intend to filter out the results so as to view places where distance <= 500. How can I achieve this?
A: Use your query as a subselect:
SELECT *
FROM (SELECT a.name ...) dummy
WHERE distance < 500.0;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44797406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HANA Query: CASE WHEN, without SELECT Statment I want to understand the CASE WHEN Statment in SAP HANA Query.
It is now to write a Value in a Column, only if there is a Value in the Column before.
"$[$3.U_chsBestNr2.0]" is the Column before (i get the value of this Column with this Statement).
CASE WHEN $[$3.U_chsBestNr2.0] <> '' THEN
SELECT T1."Name"
FROM OPOR T0
LEFT JOIN "@CHS_BEL_BELEGTYP" T1 ON T0."U_chsBelTyp" = T1."Code"
WHERE T0."DocEntry" = $[$3.U_chsBestNr2.0] AND T0."DocStatus" = 'O'
END CASE
The Error appear always as follow:
...257 sql error: incorrect syntax near "CASE"..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57474305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Django; 2 model/class/tables pass into one template Forgive me if I ask something foolish, I very new to coding industry
I been working on Django project to create dashboards to show case monitoring of an hydroponics greenhouse.
So I create two model;
class tank_system(models.Model):
PH = models.DecimalField(default=7.5,max_digits=3, decimal_places=1)
EC = models.DecimalField(default=13.3,max_digits=3, decimal_places=1)
Winlet = models.DecimalField(default=20.1, max_digits=3, decimal_places=1)
Woutlet = models.DecimalField(default=20.3,max_digits=3, decimal_places=1)
WaterLevel = models.IntegerField(default=500)
TempWater = models.IntegerField(default=25)
tanks = models.IntegerField(default=1)
datetime = models.DateTimeField(default=timezone.now())
class ambient (models.Model):
TempRoom = models.IntegerField(default=25)
CO2 = models.DecimalField(default=20.0, max_digits=3, decimal_places=1)
O2 = models.DecimalField(default=20.0,max_digits=3, decimal_places=1)
Humdity = models.IntegerField(default=25)
Room = models.IntegerField(default=1)
datetime = models.DateTimeField(default=timezone.now())
and I render the data of two model into one single template
here my views;
from django.shortcuts import render, get_object_or_404
from CGI.models import tank_system, ambient
def index(request):
tank = tank_system.objects.all()
room = ambient.objects.all()
return render(request, 'CGI/Pages/DashBoard.html', {'tank': tank},{'room': room})
when I try this I only got data form 1 table
Here my html template;
{% extends "base.html" %}
{% block content %}
{%load staticfiles%}
{% load static %}
<div class = "containor">
<div class ="row" id = "row1">
<div class ="col-sm-6" style="background-color:">
<h2>Camera</h2>
</div>
<div class ="col-sm-6" style="background-color:">
<h2>Ambinet</h2>
</div>
</div>
<div class = "containor">
<div class="row" id="row2">
<div class ="col-sm-6" id="Cam1" style="background-color:">
<div class="containor">
<video id="livestream" width="550" height="350" autoplay></video>
<canvas class = "my-4 chartjs-render-monitor" id="live_vid" height="1"></canvas>
<script src="{% static 'FrounterWeb/JS-code/Stream.JS' %}" ></script>
</div>
</div>
<div class ="col-sm-2" id="Humdity" style="background-color:">
<div class="containor">
<center>
<picture>
<img src="{% static 'FrounterWeb/img/Humidty_icon.png' %}" alt="RoomTemp">
</picture>
<br>
<h1>
{% for ambient in room %}
{% if forloop.first %}
{{ ambient.Humdity }}
{% endif %}
{% endfor %}
%</h1>
</center>
</div>
</div>
<div class ="col-sm-2" id="Roomtemp" style="background-color:">
<div class="containor">
<center>
<picture>
<img src="{% static 'FrounterWeb/img/RoomTemp.png' %}" alt="RoomTemp">
</picture>
<br>
<h1>
{% for ambient in room %}
{% if forloop.first %}
{{ ambient.TempRoom }}
{% endif %}
{% endfor %}
C</h1>
</center>
</div>
</div>
<div class ="col-sm-2" id="co2" style="background-color:">
<div class="containor">
<center>
<picture>
<img src="{% static 'FrounterWeb/img/co2_icon.png' %}" alt="co2">
</picture>
<br>
<h1>
{% for ambient in room %}
{% if forloop.first %}
{{ ambient.CO2 }}
{% endif %}
{% endfor %}
</h1>
</center>
</div>
</div>
</div>
</div>
<div class = "containor" >
<div class="row" id = "row3" >
<div class ="col" style="background-color:">
<center>
<h2>Water tank</h2>
</center>
</div>
</div>
</div>
</div>
<div class = "containor">
<div class="row" id ="row4" >
<div class ="col-sm-2">
<div class="containor">
<center>
<picture>
<img src="{% static 'FrounterWeb/img/pHicon.png' %}" alt="co2">
</picture>
<br>
<h1>
{% for tank_system in tank %}
{% if forloop.first %}
{{ tank_system.PH }}
{% endif %}
{% endfor %}
</h1>
</center>
</div>
</div>
<div class ="col-sm-2">
<div class="containor">
<center>
<picture>
<img src="{% static 'FrounterWeb/img/EC-icon.png' %}" alt="co2">
</picture>
<br>
<h1>
{% for tank_system in tank %}
{% if forloop.first %}
{{ tank_system.EC }}
{% endif %}
{% endfor %}
%</h1>
</center>
</div>
</div>
<div class ="col-sm-2">
<div class="containor">
<center>
<picture>
<img src="{% static 'FrounterWeb/img/WaterTemp.png' %}" alt="co2">
</picture>
<br>
<h1>
{% for tank_system in tank %}
{% if forloop.first %}
{{ tank_system.TempWater }}
{% endif %}
{% endfor %}
C</h1>
</center>
</div>
</div>
<div class ="col-sm-2">
<div class="containor">
<center>
<picture>
<img src="{% static 'FrounterWeb/img/Flow-icon.png' %}" alt="co2">
</picture>
<br>
<h1>
{% for tank_system in tank %}
{% if forloop.first %}
{{ tank_system.Winlet }}
{% endif %}
{% endfor %}
ml/hr</h1>
</center>
</div>
</div>
<div class ="col-sm-2">
<div class="containor">
<center>
<picture>
<img src="{% static 'FrounterWeb/img/Flow-out-icon.png' %}" alt="co2">
</picture>
<br>
<h1>
{% for tank_system in tank %}
{% if forloop.first %}
{{ tank_system.Woutlet }}
{% endif %}
{% endfor %}
ml/hr</h1>
</center>
</div>
</div>
<div class ="col-sm-2">
<div class="containor">
<center>
<picture>
<img src="{% static 'FrounterWeb/img/waterlevel-icon.png' %}" alt="Waterlevel">
</picture>
<br>
<h1>
{% for tank_system in tank %}
{% if forloop.first %}
{{ tank_system.tanks }}
{% endif %}
{% endfor %}
L</h1>
</center>
</div>
</div>
</div>
</div>
<div class = "containor">
<div class="row" id="row5" >
<div class ="col-sm-6" >
<h1>Water data</h1>
</div>
<div class ="col-sm-6" >
<h1>Room data</h1>
</div>
</div>
</div>
<div class = "containor">
<div class="row" id="row6" >
<div class ="col-sm-6" >
<div class="float-sm-none" id = Waterchart>
</div>
</div>
<div class ="col-sm-6" >
<div class="float-sm-none" id = Roomchart>
</div>
</div>
</div>
</div>
here picture better understanding;
If you could help I, really appreciated
A: You have 4 arguments in your render of which 2 is context. It needs only one dictionary with context or you can make a context dictionary variable and pass it as argument in render.
Try this:
from django.shortcuts import render, get_object_or_404
from CGI.models import tank_system, ambient
def index(request):
tank = tank_system.objects.all()
room = ambient.objects.all()
return render(request, 'CGI/Pages/DashBoard.html', {'tank': tank,'room': room})
OR
from django.shortcuts import render, get_object_or_404
from CGI.models import tank_system, ambient
def index(request):
tank = tank_system.objects.all()
room = ambient.objects.all()
context = {
'tank': tank,
'room': room
}
return render(request, 'CGI/Pages/DashBoard.html',context)
A: You can pass data using two different ways
def index(request):
tank = tank_system.objects.all()
room = ambient.objects.all()
return render(request, 'CGI/Pages/DashBoard.html', {'tank': tank,'room': room})
or
return render(request, 'CGI/Pages/DashBoard.html', locals())
locals() stands for get all local variable/objects and pass to the html as context
A: In your index method, make changes as:
def index(request):
tank = tank_system.objects.all()
room = ambient.objects.all()
return render(request, 'CGI/Pages/DashBoard.html', {'tank': tank, 'room': room})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54760355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to filter join query with Flask and SQLAlchemy Hello I'm trying to query something like this in SQLAlcehmy, Flask and Graphene
select d."name", e."name"
from departments d
join employees e on e.department_id = d.id
where e."name" like '%M%' and d."name" = 'IT'
so, it would return all employee with name contains 'M' in department 'IT'
here's my query in python using sqlalchemy
find_department = graphene.List(Department, name = graphene.String(), employee = graphene.String())
def resolve_find_department(self, info, name, employee):
like_query = '%{0}%'.format(employee)
department = (Department.get_query(info)
.join(EmployeeModel)
.filter(DepartmentModel.name == name)
.filter(EmployeeModel.name.ilike(like_query)))
return department
and in my graphql
{
findDepartment(name:"IT", employee:"M"){
name
employees{
edges{
node{
name
}
}
}
}
}
and the result is it returns all employee instead of 1 with name contains 'M'
{
"data": {
"findDepartment": [
{
"name": "IT",
"employees": {
"edges": [
{
"node": {
"name": "Chris"
}
},
{
"node": {
"name": "Dori"
}
},
{
"node": {
"name": "Mario"
}
}
]
}
}
]
}
}
why is that happening? how to show only 1 just like the SQL query returns?
thanks
UPDATE:
the query from SQLAlchemy was fine
SELECT departments.id AS departments_id, departments.name AS departments_name
FROM departments JOIN employees ON departments.id = employees.department_id
WHERE departments.name = 'IT' AND employees.name ILIKE '%M%'
but somehow when it's called using graphql, with query above, it returns all employee instead of the filtered one
how to return only the filtered Employee?
A: I think you need to use an "and_" filter to make sure sqlalchemy returns only rows which fulfil all the requirements (rather than at least one of the filters):
from sqlalchemy import and_
department = (Department.get_query(info)
.join(EmployeeModel)
.filter(and_(DepartmentModel.name == name, EmployeeModel.name.ilike(like_query)))
not 100% sure if this works with graphene or whatever (i think this is unrelated in this case...). Also check this link: sqlalchemy tutorial
Give it a try!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75576234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: spring boot rest webservice, how to improve a clean code? i started a project on spring boot using a rest a webservice, when i shared it between my team they puted some comments :
*
*get method need to be grouped Ex : get/users & get/users/{id} will be get/users/{id}
*remove put method & just use post Ex: post/users/0 add | post/users/{id} update
*make a helper class for Jdbc Template and call it in the repository classes to centralize the code
pls guys help me to solve this i'm so confused, and thank you
A:
get method need to be grouped Ex : get/users & get/users/{id} will be
get/users/{id}
I do not agree with this. /get/users will be returning List<User> and get/users/{id} will return User that matches with {id}
remove put method & just use post Ex: post/users/0 add |
post/users/{id} update
Post should be used when you create a new resource. POST is not idempotent. Each time you call a post a new resource will be created.
e.g. Calling POST /Users will create a new User every-time.
PUT on other hands works like upsert. Create if the resource is not present and update/replace if present. Put is idempotent and doesn't change the resource's state even if it's called multiple times.
make a helper class for Jdbc Template and call it in the repository
classes to centralize the code
Helper classes help to separate the concerns and achieve single responsibility.
However, JdbcTemplate is a ready to use abstraction of JDBC. I don't see any point in creating Helper. You can create a DataAccessObject (DAO) or Repository which has-a JdbcTemplate. Like the two Dao shown below
public class UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public User findUserById(String id){}
public void addUser(User user){}
}
// -------
public class BooksDao{
@Autowired
private JdbcTemplate jdbcTemplate;
public List<Book> getAllBooksByType(String type){}
public void Book getBookByName(String name){}
}
Now, your Dao objects can be called from Controller or if you need to modify data before/after DB operation, best is to have a Service layer between Controller and Dao.
Don't bother too much about recommendations or rules. Stick to the basic OOPS concepts. Those are really easy to understand and implement.
Always:
*
*Encapsulate data variables and methods working on those variables together
*Make sure your class has a Single Responsibility
*Write smaller and testable methods (if you can't write tests to cover your method, then something is wrong with your method)
*Always keep the concerns separate
*Make sure your objects are loosely coupled. (You are already using spring so just use the spring's auto-wiring)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52693297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to override routes in ng-admin? I want to change url in ng-admin state. For example, I need to add a trailing / at the URL for getting a list of users. (http://localhost/api/v1/users/ instead of http://localhost/api/v1/users)
A: The Entity and View classes offer a baseUrl() method, so it's probably not very hard. Just follow the directions from the documentation:
*
*https://github.com/marmelab/ng-admin/blob/master/doc/Configuration-reference.md#entity-configuration
*https://github.com/marmelab/ng-admin/blob/master/doc/Configuration-reference.md#entity-configuration
*https://github.com/marmelab/ng-admin/blob/master/doc/API-mapping.md
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33274536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to remove a specific factor level to missing value in r? I got a factor data set df that looks like this:
df <- data.frame(attend = c("yes", "no", "no", "iap", "yes", "yes", "iap"),
sex = c("male", "female", "female", "male", "female", "male", "female"))
df$attend <- as.factor(df$attend)
df$sex <- as.factor(df$sex)
df
attend
sex
yes
male
no
female
no
female
iap
male
yes
female
yes
male
iap
female
I want to remove only the iap level from the attend variable.(I don't want to remove the entire row, what I'm looking for is to remove the level iap, so that it becomes a missing value under variable attend)
I tried the below code to remove it but it occurs an error saying:
Error in UseMethod("droplevels") :
no applicable method for 'droplevels' applied to an object of class "character".
df$attend <- droplevels(levels(df$attend)[4])
Much appreciated it if someone can help.
A: You can change the levels of the variable -
levels(df$attend)[levels(df$attend) == 'iap'] <- NA
df
# attend sex
#1 yes male
#2 no female
#3 no female
#4 <NA> male
#5 yes female
#6 yes male
#7 <NA> female
This will also automatically drop the 'iap' as level.
levels(df$attend)
#[1] "no" "yes"
Here we can also use forcats::fct_recode to turn specific values to NA.
df$attend <- forcats::fct_recode(df$attend, NULL = 'iap')
A: Another base R solution would be using exclude:
df$attend <- factor(df$attend, exclude = "iap")
attend sex
1 yes male
2 no female
3 no female
4 <NA> male
5 yes female
6 yes male
7 <NA> female
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68961237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: string-splitting and arrays In this program for storing high scores I want the user to input a player's name and high score in a single line, for example "eric 87".
After the user enters the last player's name and score, it should then list all at once the scores that were entered. I don't know how to do this when splitting strings like "eric 97". Thanks very much for any help!
const int MAX = 20;
static void Main()
{
string[ ] player = new string[MAX];
int index = 0;
Console.WriteLine("High Scores ");
Console.WriteLine("Enter each player's name followed by his or her high score.");
Console.WriteLine("Press enter without input when finished.");
do {
Console.Write("Player name and score: ", index + 1);
string playerScore = Console.ReadLine();
if (playerScore == "")
break;
string[] splitStrings = playerScore.Split();
string n = splitStrings[0];
string m = splitStrings[1];
} while (index < MAX);
Console.WriteLine("The scores of the player are: ");
Console.WriteLine("player \t Score \t");
// Console.WriteLine(name + " \t" + score);
// scores would appear here like:
// george 67
// wendy 93
// jared 14
A: Looking at your code you didn't put your player array to use.
However, I would suggest a more object oriented approach.
public class PlayerScoreModel
{
public int Score{get;set;}
public string Name {get;set;}
}
Store the player and scores in a List<PlayerScoreModel>.
And when the last user and score has been entered.. simply iterate through the list.
do {
Console.Write("Player name and score: ", index + 1);
string playerScore = Console.ReadLine();
if (playerScore == "")
break;
string[] splitStrings = playerScore.Split();
PlayerScoreModel playerScoreModel = new PlayerScoreModel() ;
playerScoreModel.Name = splitStrings[0];
playerScoreModel.Score = int.Parse(splitStrings[1]);
playerScoreModels.Add(playerScoreModel) ;
} while (somecondition);
foreach(var playerScoreModel in playerScoreModels)
{
Console.WriteLine(playerScoreModel.Name +" " playerScoreModel.Score) ;
}
Provide error checking as necessary.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13871992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: TypeError: super() takes at least 1 argument (0 given) With this code: https://github.com/SmBe19/praw-OAuth2Util
It's receiving this error:
Traceback (most recent call last):
File "update_sidebar.py", line 6, in <module>
o = OAuth2Util.OAuth2Util(r)
File "/usr/lib/python2.7/site-packages/OAuth2Util/OAuth2Util.py", line 162, in __init__
self.refresh()
File "/usr/lib/python2.7/site-packages/OAuth2Util/OAuth2Util.py", line 364, in refresh
self._get_new_access_information()
File "/usr/lib/python2.7/site-packages/OAuth2Util/OAuth2Util.py", line 254, in _get_new_access_information
self._start_webserver(url)
File "/usr/lib/python2.7/site-packages/OAuth2Util/OAuth2Util.py", line 229, in _start_webserver
self.server = OAuth2UtilServer(server_address, OAuth2UtilRequestHandler, authorize_url)
File "/usr/lib/python2.7/site-packages/OAuth2Util/OAuth2Util.py", line 58, in __init__
super().__init__(server_adress, handler_class, bind_and_activate)
TypeError: super() takes at least 1 argument (0 given)
By doing:
import praw
import OAuth2Util
user_agent = "sidebar helper"
r = praw.Reddit(user_agent=user_agent)
o = OAuth2Util.OAuth2Util(r)
Is the code missing something?
A: According to @Ryan, your problem is that you are running it in Python 2 instead of Python 3. Running it in Python 3 should fix it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34114004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: CSS responsive design using em for the layout I have to design a (responsive) website, using only HTML5, CSS3, elastic design, and em as unit measurement. I dont know how to apply em on the width and height properties to make the margins of the main wrapper (i.e. div #page) equal on all sides in relation to the actual screen size.
I have tried the width and height properties with different em-values, but that leads to the margins not being equal. I have tried to find some sort of conversion between em and %, but since em is based on font size it's always the percentage of the font size. I have also tried to instead apply the position property to other containers and elements inside #page.
<body>
<div id="page">
<header>
<nav></nav>
</header>
<div id="content">
<article></article>
<article></article>
</div>
<aside></aside>
<footer></footer>
</div>
</body>
#page {
position: relative;
width: 90%;
height: 90%;
top: 1em;
right: 1em;
bottom: 1em;
left: 1em;
}
I want to be able to only use em as measurement unit and have the margins of #page equal in relation to the actual screen size, but the width either becomes longer than the screen size, or the right margin is not equal to the other margins.
Here is a link to JSFiddle with my entire code:
https://jsfiddle.net/binaryglot/8dkn96g0/
A: you can just using margin:0em auto for making the div page stay on the center. But unfortunately you can't make teh height on the center. Here the fiddle for making width and stay on center.
#page {
position: relative;
width: 90%;
height: 90%;
top: 1em;
margin:0em auto;
bottom: 1em;
}
JSfiddle
You can adjust the height using padding--but you can't make it responsive for the height... so far i know.
A: #page {
position: fixed;
width: 90%;
height: 90%;
top: 1em;
right: 1em;
bottom: 1em;
left: 1em;
margin: auto;
}
Using combination of fixed position and auto margin did the trick. Hope this helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56125297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Extract some part from filename as variable I have read some threads about extracting some parts from filename, but still cannot solve my problem.
There are some files named aa - bb.txt, cc - dd.txt, ee - ff.txt, etc.
And the last line in every file is like this:
somewordbbaa
for aa - bb.txt and for cc - dd.txt is:
somewordddcc
Then in ee - ff.txt is:
somewordffee
I want to write a shell script to delete the bbaa, ddcc, ffee in last line of the respective file. I have tried following:
#!/bin/bash
for file in *.txt
do
artist=`echo $file | awk -F'[ .]' '{print $1}'`
name=`echo $file | awk -F'[ .]' '{print $3}'`
echo $artist >> artist
echo $name >> name
sed -i "s/$name$artist//" $file
done
And after I ran it,it threw this
sed: can't read aa: No such file or directory
sed: can't read -: No such file or directory
sed: can't read bb.txt: No such file or directory
sed: can't read cc: No such file or directory
sed: can't read -: No such file or directory
sed: can't read dd.txt: No such file or directory
sed: can't read ee: No such file or directory
sed: can't read -: No such file or directory
sed: can't read ff.txt: No such file or directory
I also tried this
#!/bin/bash
ls *.txt | sed 's/\.txt//' > full_name
cut -f1 -d" " full_name > artist
cut -f3 -d" " full_name > name
for file in `ls -1 *.txt`, item1 in artist, item2 in name #Is this right?
do
tail -n -1 $file | sed 's/$item2$item1//' > $file.last #just the last line
done
It just showed this and had no reaction until pressing Ctrl+c
tail: cannot open `aa' for reading: No such file or directory
I think bash puts the blank of the filename as the separator, reads the $file as aa, -, bb.txt.
Can anyone give me some advice?
A: Because your files have a space in the name, try your original script but change this line:
sed -i "s/$name$artist//" $file
to this:
sed -i "s/$name$artist//" "$file"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29771837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What technique is used to create a div limited by the page fold? Skipping the discussion about the importance of the fold in web design, I'd like to know which technique is used to limit a specific section (could be a div, for example) exactly on the browser fold considering a responsive design. Some websites even use both the mouse scroll and the a button to slide to the section below.
Ex.: Next
My point is not the slide itself, but how each section renders exactly on the fold regardless of the monitor resolution.
A: With:
window.innerHeight
You can know the height of the browser window and style your elements accordingly.
I am assuming that by fold you mean what you see without scrolling.
If you need a more backwards compatible (<I.E9) height and you can use jquery:
$( window ).height();
A: You might try using the css unit of measurement vh. Say you have a div that you only want to take up half the screen (viewport) you would do something like this:
div{
height: 50vh;
}
vh stands for "Viewport Height" and is used like a percentage. So to have the div always take up 100% of the view-able area (viewport), regardless of the screen size or resolution you would do this: div { height: 100vh; }
A: I would use document.documentElement.clientHeight and document.documentElement.clientWidth which are essentially the width and height of the html element:
$('div').css({'height':document.documentElement.clientHeight+'px',
'width':document.documentElement.clientWidth+'px'});
http://jsfiddle.net/L1wsLc2c/1/
You would have to re-execute this code every time the window is resized to keep the bottom of the box flush with the page fold.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30604249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to use @keyframes moving animation from current position to a fixed in CSS3? This css3 code , move a item from current position to 100px lower.
@keyframes movingtocenter
{
from {top:0%;}
to {top:100px;}
}
But i want move my object to CENTER of page.
I have many object on the one page in different locations.
and i want to use this keyframes to move all of them to right-center,in the same position. and can't do this!
anyway to do this?
A: You need to make sure that the parent div covers the entire screen. You can do this with the following css:
.wrapper {
position: fixed;
width: 100%;
min-height: 100%;
}
Then you just need to specify the animation on the appropriate div, give it an absolute position and tell it where to go using keyframes.
.wrapper div {
position: absolute;
-webkit-animation: myfirst 5s; /* Chrome, Safari, Opera */
animation: myfirst 5s;
}
.wrapper div.el1{
right: 200px;
}
.wrapper div.el2 {
right: 500px;
}
/* Chrome, Safari, Opera */
@-webkit-keyframes myfirst {
0% {top:0;}
100% {top: 50%; right: 0;}
}
/* Standard syntax */
@keyframes myfirst {
0% {top:0;}
100% {top:50%; right: 0;}
}
Fiddle
A: You missed one property in your element:
position:absolute;
See this: jsFiddle
Note: Only Some Positioning Styles accept top, left, bottom, etc. properties. See documentation for details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25007133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to import actionscript 3 flash game into flash builder? I'm newbie in this area, and I would like to have an android app that can play my AcionScript game. My actonscript game consist of external sound and image.
How do I import my ActionScript file into flash builder?
Should I import my codes or my SWF file alone is enough?
Where should I import my external files?
Thank you in advance!
A: There are numerous options, such as:
Flash Pro
If your game has already been created in Flash Pro, you could simply target AIR for Android from Flash Pro's publish settings:
ADT Command Line Packager
Likewise, you could simply use the ADT command line packager to build your SWF to an Android distributable.
Flash Builder
Otherwise from Flash Builder, you can create a new ActionScript mobile project:
Select Android, or other target platforms:
Place code and packages relative to the src/ folder, same as you would relative to your FLA:
Your entire Flash app could be published as a SWC, then instantiated from Flash Builder, or individual assets may be exported as SWCs:
Likewise you can programmatically embed SWF assets in ActionScript classes using the embed metadata tag:
[Embed(source="asset.swf", symbol="symbol")]
private var SymbolClass:Class;
var symbol:MovieClip = new SymbolClass();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17037048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Inconsistent Jackson deserialization of String as LocalDateTime I am deserializing a nested collection in JOOQ via Jackson.
The error I am encountering is like this,
Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.LocalDateTime` (no Creators, like default constructor, exist): no String-argument constructor/factory method to deserialize from String value ('2020-12-18T11:29:03.290833') at [Source: (String)"{"wrapped_ts" : "2020-12-18T11:29:03.290833"}"; line: 1, column: 21] (through reference chain: blah.blah.WrappedTimestamp["wrapped_ts"])
This is inconsistent with behavior earlier in the deserialization process. A MRE would be,
=== Function using JOOQ ===
.select(
TOP.ts,
field(
select(
jsonArrayAgg(
jsonObject(
LOWER.lowerTs
)
)
)
.from(LOWER).join(TOP).on(TOP.ID.eq(LOWER.TOP_ID))
).`as`("lowerLevels"),
field(
select(
jsonObject(
WRAPPED.FIRST,
WRAPPED.SECOND
)
)
.from(WRAPPED)
.where(TOP.ID.eq(WRAPPED.TOP_ID))
).`as`("wrapped")
.from(TOP)
.where(condition)
.fetchInto(TopLevel::class.java)
=== Underlying data classes ===
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy::class)
data class TopLevel(
ts: LocalDateTime?,
lowerLevels: List<LowerLevel> = emptyList(),
wrapped: WrappedTimestamp?
)
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy::class)
data class LowerLevel(
lowerTs: LocalDateTime?,
)
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy::class)
data class WrappedTimestamp(
first: LocalDateTime?,
second: LocalDateTime?,
) {
constructor() : this(
null
}
There are three different levels of timestamps. ts and lowerTs both deserialize fine, wrappedTs throws the error above. If it's unclear, my Jackson ObjectMapper does have the JavaTimeModule registered.
In the course of debugging I have created new deserialization targets at the level of WrappedTimestamp that function with no issue. I have also commented out the wrapped section of the select in JOOQ and it also works.
What could be accounting for this inconsistent behavior?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65362169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get a list of all tables that have datatables applied? I need a list of all tables that have jQuery DataTables applied. I searched the docs and the API but I could not find an array or something like that that holds the tables.
A: You're looking for $.fn.dataTable.tables() - DataTables's static function.
It can be useful to be able to get a list of the existing DataTables
on a page, particularly in situations where the table has scrolling
enabled and needs to have its column widths adjusted when it is made
visible. This method provides that ability.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32524861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Limits of parallelization regarding the core number I'm developing a parallel algorithm on a Intel i5-core machine, which has two cores, four threads.
n defines the size of the matrix, on which I perform my calculations on. As you can see from the table below there is almost 50% reduction from 1 thread to 2 threads utilization, but almost no difference between 2 threads and 4 threads. The numbers denote the seconds passed
My compiler is mingw-gcc on windows platform. My parallelization tool is openmp. I'm defining number of threads by omp_set_num_threads(numThreads);in the beginning of the parallel routine.
I have no means to test the algorithm on a "real" 8 core machine. On my i5 machine, At 1 thread, task manager shows 25% of the total cpu power is used. At 2 threads, it's 50%, and at 4 threads, it's 96-99% as expected.
So what might be the reason for that situation? Why doesn't the computation time get halved?
The parallel code segment is to be found below:
#pragma omp parallel for schedule(guided) shared(L,A) \
private(i)
for (i=k+1;i<row;i++){
double dummy = 0;
for (int nn=0;nn<k;nn++){
dummy += L[i][nn]*L[k][nn];
L[i][k] = (A[i][k] - dummy)/L[k][k];
}
}
A: Well, your machine has 2 cores and 4 threads.
You only have 2 cores, so you won't get 4x speedup from 1 - 4 threads.
Secondly, as you scale to more threads, you will likely start hitting resource contention such as maxing out your memory bandwidth.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10057331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CSS html declarations with spaces If there is a simple google search for this question, I apologise now, but I'm unsure of which keywords I'm looking to use. I'm decent with CSS but I think I'm yet to utilise the full power of the language and also completely eradicate code redundancy.
I've come across this code (any similar snippets many other times):
<p class="comment smallertext center-align">
What CSS would this be referring to?
In terms of the comment, smallertext and center-align all being spaced.
Thank you in advance for any replies and guidance!
A: It means that element has all of the following classes: comment, smallertext and center-align. In HTML, spaces separate multiple class names in a single attribute.
In CSS, you can target this element using one or more of .comment, .smallertext or .center-align, either separately or together. Having three separate rules and a single element that has all three classes, all three rules will apply:
.comment {}
.smallertext {}
.center-align {}
You can also combine them together, if necessary, to apply styles specific to elements having all three classes:
.comment.smallertext.center-align {}
A: The code shown in the example links to 3 different css class selectors:
.comment {
}
.smallertext {
}
.center-align {
}
So instead of making lots of non-reusable css selectors, you split them up into lots of small ones that provide 1 functionality that will most likely be used for lots of different parts of your websites. In that example you have one for comments, one for smaller text and one for center aligning text.
A: It's a way of defining multiple classes to a single element. In this case it would match classes comment, smallertext and center-align.
A: Try this short explanation... Multiple classes can make it easier to add special effects to elements without having to create a whole new style for that element.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19426475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I make an uploaded image permanent on a view controller in Swift? I am writing code to allow a user to upload an image on a view controller. The image can be uploaded successfully, but once you navigate away from the view controller and then come back to it, the image they uploaded is gone. How would I make the image a global variable so that when the user returns to the view controller, the image is still present? I am using imagePickerController to select the image for upload. This is my code
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43075606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MYSQL union order in first statement I have this query:
(SELECT * FROM items WHERE duration = 5 ORDER BY date DESC)
UNION
(SELECT * FROM items WHERE duration = 10)
The problem is the "ORDER BY" in the first query is not working.
A: Try this :
select * from (
SELECT * FROM items WHERE duration = 5
UNION
SELECT * FROM items WHERE duration = 10
) odrer by date DESC
A: When you use UNION OR UNION ALL order by not allowed in each select statement. You have to apply order by in outer select statement.
A: Order the UNION result by duration first, then date desc.
select *
from
(
SELECT * FROM items WHERE duration = 5
UNION
SELECT * FROM items WHERE duration = 10
)
order by duration, date DESC
However, there's no need for a UNION (see e4c5's answer).
A: If I understood you from the comments, you want something like this?
SELECT s.* FROM (
SELECT i.*,1 as ord_col FROM items i WHERE duration = 5
UNION
SELECT it.*,2 FROM items it WHERE duration = 10) s
ORDER BY CASE WHEN s.ord_col = 5 THEN s.date
ELSE '1000-01-01'
END DESC
Although this query is inefficient , you can do it with one select :
SELECT i.* FROM items i WHERE i.duration IN(5,10)
ORDER BY CASE WHEN s.ord_col = 5 THEN s.date
ELSE '1000-01-01'
END DESC
If its not dynamic, and 5 will be ordered before 10 and these are constant values , you can simply add the duration column to the query , ORDER BY duration,date although this will also order the second query be date, just after the first one.
A: I think you don't even need to UNION at all and you can refactor your query this way:
SELECT *
FROM items
WHERE duration IN (5, 10)
ORDER BY CASE
WHEN duration = 5 THEN 1
WHEN duration = 10 THEN 2
ELSE NULL
END
, CASE
WHEN duration = 5 THEN [date]
ELSE NULL
END DESC;
This query will sort based on your duration first (the ones with 5 will come first, with 10 second) and then as a second order option it will sort ones with duration = 5 by date in descending order.
Of course this could be more elegant, but meets OPs A/C and does the job.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38866494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Javascript : Problem while passing parameter to a function I am passing a parameter to a javascript function from jsp.
<a href="javascript:void(0)" title="Update"
onclick="fnUpdate(<s:property value='roleTypeUid'/>);">
Now the roleTypeUid is a String with space in between (eg. System Admin) . So it is not working . If I replace the attribute with a no-space string , it gets passed fine.
Am I missing something ?
A: Try like this:
<a href="javascript:void(0)"
title="Update"
onclick="fnUpdate('<s:property value='roleTypeUid'/>');">
A: The called function within onclick has to be a string, you can't reference variables directly in it.
onclick="fnUpdate(\"<s:property value='roleTypeUid'/>\");"
That string is evalled onclick and thus becomes a function. That's why it may be better to add handlers unobtrusive
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5865645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: $match aggregation is giving me None (in terms of Python) If ISO date is not present in query it will give null output $match aggregation is giving me None (in terms of Python) even though I have verified it multiple time entries are present in DB .
In Python pymongo is not recognizing the ISO while I write inside the cursor = {}
making ISO as string and concatenating it with the time also doesn't work it gives the empty list .
same case with all operator gte or lte .
db.cityhistory.find({"updateTime": ISODate("2018-04-20T13:27:39.021+0000"), "countries.city": {"$exists": true}}, {"countries.city": 1})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49949341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: use task method in overriden I would like to know whats the ideal way to call a method that returns a Task inside an override method?
For example:
public Task<string> GetName()
{
return Task.Run(() => {
return "Foo";
});
}
In one of my methods I would just simple do this:
public async Task<string> DoSomething()
{
var res = await GetName();
return res + " rocks";
}
But now I am facing a situation where there is a method delcared like this:
public virtual string DoSomething()
{
//does something...
}
In my inheritance I need to override this method and do some stuff and call a Task method, so my first thought was to do this:
public override async Task<string> DoSomething()
{
//does something...
base.DoSomething();
var res = await GetName();
return res + " rocks";
}
This clearly isnt possible since I changed the return value from a overriden method from string to Task string...
How should I solve my problem?
(Note: I cannot modify the base class, since its not mine. Its an external libary.)
A: You could do this:
public override string DoSomething()
{
//does something...
base.DoSomething();
return GetName().Result;
}
Warning: this can cause a deadlock
See Don't block on async code
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23870795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Matlab: calculate differences between datetime arrays in fractional seconds I'm reading in time data with fractional precision (hundredths of seconds):
For every entry in this datetime array, I want to determine the difference with the first entry, in seconds (with fractional precision):
times=datetime(myCellArray,'InputFormat','HH:mm:ss.SS');
eventtimes=between(starttime,times(2:end));
this returns:
eventtimes =
0h 0m 19.72s
0h 1m 46s
0h 6m 45.9s
0h 6m 53.18s
I want to get from here to a regular array simply holding (fractional) seconds:
[19.72
106
405.9
413.18]
What I've tried so far (split, time), always results is a loss of the fractions.
A: Assuming eventtimes is a cell array of strings, you can do this:
eventtimes={'0h 0m 19.72s'
'0h 1m 46s'
'0h 6m 45.9s'
'0h 6m 53.18s'};
for i=1:length(eventtimes)
%// Read each line of data individually
M(i,:)=sscanf(eventtimes{i},'%d%*s%d%*s%f%*s').';
end
s=(M(:,1)*60+M(:,2))*60+M(:,3) %// Convert into seconds
which gives
s =
19.7200
106.0000
405.9000
413.1800
A: With respect to the answer provided by @David, the last line of code:
s=(M(:,1)*24+M(:,2))*60+M(:,3) %// Convert into seconds
should be:
s=(M(:,1)*60+M(:,2))*60+M(:,3) %// Convert into seconds
Since M(:,1) contains hours, to convert them into seconds, they have to be multiplied by 3600 (60 min. * 60 sec.)
The expected resuls as described in the question and the ones provided by @David seem correct only because all input have "0h".
In case any of the input times last more than 1h, the results will be:
0h 0m 19.72s
2h 1m 46s
3h 6m 45.9s
0h 6m 53.18s
s=
19.72
7306.00
11205.90
413.18
Hope this helps.
A: I've found a solution using etime that bypasses the "between" function and its odd calendarDuration type output:
%read in with fractions
times=datetime(myCellArray(:,1),'InputFormat','HH:mm:ss.SS');
%turn into datevectors (uses today's date: works as long as midnight isn't crossed)
timevect=datevec(times);
%separate start time from subsequent times
starttime=timevect(1,:);
othertimes=timevect(2:end,:);
%use etime with repmat of starttime to get differences:
relativetimes=etime(othertimes,repmat(starttime,[size(othertimes,1) 1]));
relativetimes(1:4)
ans =
19.72
106
405.9
413.18
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30338073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Classic ASP HTTP Post from another server I am litte confused, i want to protect one page in classic asp from being accessed by Get Method.
Is it possible that someone can post data from another server to my page?
If Yes, how to detect that and allow only post from my server.
Thanks for help.
A: If you are currently using Request("ParameterName") to retrieve parameters then you should change to Request.Form("ParameterName") which will only get the parameter if it was POSTed.
Alternatively you can lookup the method used to access the page from the Request.ServerVariables collection and end the script if it is not POST. Here's an example:
If Request.ServerVariables("REQUEST_METHOD") <> "POST" Then Response.End
I noticed that you also said that you want to accept posts only from your server. The above changes will still allow another webpage to be set up to POST to your page. If you want to ensure that only your web page can post then you will need to add some more protection. Here's one way of doing it.
1) When you render your form create a random numbers and create a session variable named by the random number with a value to check for later.
Randomize
strVarName = Int((999999 - 100000 + 1) * Rnd() + 100000)
Session(strVarName) = "Authorised"
2) In your form add a hidden field with the value of the random number.
<input type="hidden" name="varname" value="<%= strVarName %>" />
3) In the script that processes the posted form get the value of the hidden field.
strVarName = Request.Form("varname")
4) Check that the session variable is set and has a value of True.
If Session(strVarName) <> "Authorised" Then
'Failed! Either show the user an error message or stop processing
Response.End
End If
5) Remove the session variable so that the same form cannot be resubmitted.
Session.Items.Remove(strVarName)
You don't need the random number but using it means that the same user can have multiple forms open in different windows/tabs and each one will work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13344797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Segue Popover won't behave properly I'm trying to use Segue to present then dismiss a Popover view a UIBarButtonItem is clicked.
I've created a generic Segue that is not anchored to anything but the view and given it a name
I've Anchored the UIBarButtonItem in the Interface Builder to:
- (IBAction)clickedSettings:(id)sender {
if(self.popSegue != nil) {
[self.popSegue.popoverController dismissPopoverAnimated:YES];
} else {
//Current says only a button may
[self performSegueWithIdentifier:@"Settings" sender:sender];
}
}
But when ever i click the button to display the Segue it gives me an error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'UIStoryboardPopoverSegue must be presented from a bar button item or a view.'
It doesn't even hit my -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
I've read the following questions on stack:
*
*iOS:How to dismiss Popover
*UIBarButtonItem + popover segue creates multiple popovers
But i still get the same error. For the life of me i can't figure out what is going wrong
A: I take no credit for this since I got every bit of it from going through multiple StackOverflow threads, but I got this working with:
@interface MyViewController ()
- (IBAction) toggleSettingsInPopover: (id) sender;
@property (nonatomic, strong) UIStoryboardPopoverSegue *settingsPopoverSegue;
@end
@implementation MyViewController
@synthesize settingsPopoverSegue = _settingsPopoverSegue;
- (IBAction) toggleSettingsInPopover: (id) sender {
if( [self.settingsPopoverSegue.popoverController isPopoverVisible] ) {
[self.settingsPopoverSegue.popoverController dismissPopoverAnimated: YES];
self.settingsPopoverSegue = nil;
} else {
[self performSegueWithIdentifier: @"Settings" sender: sender];
}
}
- (void) prepareForSegue: (UIStoryboardSegue *) segue sender: (id) sender {
if( [segue.identifier isEqualToString: @"Settings"] ) {
if( [segue isKindOfClass: [UIStoryboardPopoverSegue class]] )
self.settingsPopoverSegue = (UIStoryboardPopoverSegue *) segue;
MySettingsViewController *msvc = segue.destinationViewController;
msvc.delegate = self;
}
}
@end
In my storyboard I control-dragged from my settings bar button item to MyViewController and connected it to the toggleSettingsInPopover action. Then I control-dragged from MyViewController to the view for the settings to create the segue, set its type to popover, set its identifier to Settings, set its directions to up and left (the toolbar is at the bottom of the screen and the button is at the right end), then dragged from its Anchor to the bar button item I connected to the action.
A: You have to anchor the segue to the UIBarButton by Ctrl-Dragging the Anchor Field from the segue Attribute Inspector to the UIBarButton.
If you do it the opposite way, Ctrl-Dragging from the Button to the Window to be shown you won't have a possibility to control the behaviour from the Popoverwindow.
(The important part is also in the last sentence of LavaSlider's Reply)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8845272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to clustering based on the distance in Python pandas? I have two dataframes with two groups of stations information. One for the 15 small stations and another for the 5 main stations.
Small Station Information(15*3):
SmallStation_ID longitude latitude
0 dongsi_aq 116.417 39.929
1 tiantan_aq 116.407 39.886
2 guanyuan_aq 116.339 39.929
3 wanshouxigong_aq 116.352 39.878
4 aotizhongxin_aq 116.397 39.982
5 nongzhanguan_aq 116.461 39.937
6 wanliu_aq 116.287 39.987
7 beibuxinqu_aq 116.174 40.090
8 zhiwuyuan_aq 116.207 40.002
9 fengtaihuayuan_aq 116.279 39.863
10 yungang_aq 116.146 39.824
11 gucheng_aq 116.184 39.914
12 fangshan_aq 116.136 39.742
13 daxing_aq 116.404 39.718
14 yizhuang_aq 116.506 39.795
Main Station Information(5*9):
MainStation_id longitude latitude temperature \
0 shunyi_meo 116.615278 40.126667 -1.7
1 hadian_meo 116.290556 39.986944 -1.6
2 yanqing_meo 115.968889 40.449444 -8.8
3 miyun_meo 116.864167 40.377500 -6.6
4 huairou_meo 116.626944 40.357778 -5.2
pressure humidity wind_direction wind_speed weather
0 1028.7 15 215.0 1.6 Sunny/clear
1 1026.1 14 231.0 2.5 Sunny/clear
2 970.8 35 305.0 0.8 Haze
3 1023.3 28 999017.0 0.2 Haze
4 1022.8 27 30.0 0.8 Sunny/clear
I want to classify those small stations into the main stations after I calculate the distance: sqrt((x1-x2)^2+(y1-y2)^2)(Here the x and y are longitude and latitude, respectively). Find the closest neighbor. Then merge these two groups of dataframes to get the main stations external weather information. The head of the final dataframe will seems like,
SmallStation_ID distance temperature pressure humidity wind_direction wind_speed weather
It is a 15*8 dataframe.
Hope I made this question clear.
Thanks!
A: Alright... I solved this by myself...
I am not familiar with iteration and hope someone gives me an easier understand way in some pandas functions.
Small Station is a dataframe called aqstation.
Main Station is a dataframe called meostation.
l = []
# All I want to do is to merge Main Station weather information into Small Stations...
Calculate the Euclidean distance then classify small stations into main stations.
for i in range(len(aqstation)):
station = meostation['station_id'][(((aqstation['longitude'][i]-meostation['longitude'])**2+(aqstation['latitude'][i]-meostation['latitude'])**2)**(0.5)).idxmin()]
l.append(station)
# print(len(l))
aqstation['station_id'] = l
del aqstation['longitude']
del aqstation['latitude']
del meostation['longitude']
del meostation['latitude']
Merge the two dataframes.
aqstation = pd.merge(aqstation, meostation, how='left', on='station_id')
print(aqstation.head(10))
Station ID station_id temperature \
0 dongsi_aq chaoyang_meo -0.7
1 tiantan_aq beijing_meo -2.5
2 guanyuan_aq hadian_meo -1.6
3 wanshouxigong_aq fengtai_meo -1.4
4 aotizhongxin_aq hadian_meo -1.6
5 nongzhanguan_aq chaoyang_meo -0.7
6 wanliu_aq hadian_meo -1.6
7 beibuxinqu_aq pingchang_meo -3.0
8 zhiwuyuan_aq shijingshan_meo -1.8
9 fengtaihuayuan_aq fengtai_meo -1.4
pressure humidity wind_direction wind_speed weather
0 1027.9 13 239.0 2.7 Sunny/clear
1 1028.5 16 225.0 2.4 Haze
2 1026.1 14 231.0 2.5 Sunny/clear
3 1025.2 16 210.0 1.4 Sunny/clear
4 1026.1 14 231.0 2.5 Sunny/clear
5 1027.9 13 239.0 2.7 Sunny/clear
6 1026.1 14 231.0 2.5 Sunny/clear
7 1022.5 17 108.0 1.1 Sunny/clear
8 1024.0 12 201.0 2.5 Sunny/clear
9 1025.2 16 210.0 1.4 Sunny/clear
My code is very lengthy. Hope someone can make it simpler.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49711509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: How to let this media query works the same in different browsers on Samsung Galaxy Note4? I have a HTML code as:
<!DOCTYPE html>
<html lang="en">
<head>
<title>test page</title>
<style>
.hint {width:510px;}
@media only screen and (max-device-width: 720px) {
.hint {width:280px}
}
@media only screen and (max-device-width: 720px) and (orientation: landscape){
.hint {width:350px}
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<div class="hint">just a test
<script>alert($(window).width()); alert($('.hint').css('width'));</script>
</div>
</body>
</html>
It works fine on all iOS devices but behaves weird for some Android devices like Samsung Galaxy Note 4 as I can reproduce the issue.
For the default browser, it works fine. The alert result is 980px and 280px but for some browsers like UC browser, it's 510px.
Is there anything wrong with my media query code?
Thanks for any kind of tips!
A: You should take a look at how "Twitter Bootstrap" outlines their media query structure at http://getbootstrap.com/css/#grid-media-queries
Try comparing those with your own written media query structure, and if you are still stuck, you should check out Chris' written media query set at https://stackoverflow.com/a/21437955/4069464
Hope this helps!
Note: If after you have setup all the proper media query sets, and somehow this is still not working for the UC browser, then you probably have to read out in detail on how UC browser defines their mobile screen size (possibly they might have defined themselves a different set of definition of screen sizes)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31374211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Paper '12mm' is not supported by 'DYMO LabelWriter DUO Label I'm working on a small project that requires printing directly to a DYMO printer using their SDK. I've made other projects before using the same method:
*
*Find DYMO
*Get .label file
*Set label variable object(s)
*Print label
However, I receive the following error from the VB.NET program when calling the label.Print() method:
Paper '12mm' is not supported by 'DYMO LabelWriter DUO Label'
I receive the error delayed, so I'm assuming that the Print() method runs in a separate thread. Therefore I'm also assuming that the error occurs in the Print() method. This method is also the only point that the Label and IPrinter objects are provided in a single method according to the list above.
This error does not make sense, as the DYMO software has successfully printed labels using the same .label template. Is there possibly an incompatibility issue with the V8.+ of the SDK/Software and this model? If so, how/where can I determine a compatible version?
Insight on the fixing the error would be greatly appreciated or even any leads on documentation of error handlers with the DYMO SDK (all I've found are old samples of how to use the SDK).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35704599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Invalid column name - Python pandas I'm a beginner at coding or machine learning and I'm struggling with my code. I would like to remove random word from a column which also contain sometimes integer or float (it's a column of an email exchange), and next ask BERT to add words that match, to do a data augmentation, but I have a problem in my code.
import pandas as pd
import nltk
from nltk.tokenize import word_tokenize
# lire les données de la colonne Excel en utilisant pandas
df = pd.read_excel("Output_Summarization/OUTPUT_ocr_OPENAIGOOD.xlsx", usecols="Open_AI_Text")
# itérer sur chaque ligne de la colonne
for index, row in df.iterrows():
# tokeniser le texte de la ligne en mots individuels
words = word_tokenize(row["Open_AI_Text"])
# choisir un mot au hasard à enlever
word_to_remove = random.choice(words)
# enlever le mot du texte
new_text = row["Open_AI_Text"].replace(word_to_remove, "")
# mettre à jour la ligne dans le DataFrame
df.at[index, "Open_AI_Text"] = new_text
# enregistrer le DataFrame mis à jour dans un nouveau fichier Excel
df.to_excel("Texte_Trou.xlsx", index=False)
I'm 100% it'ss my column name, as I can use it if I write df['Open_AI_Text'].
The problem written is :
ValueError Traceback (most recent call last)
<ipython-input-44-e9ccdb1ab0b2> in <module>
4
5 # lire les données de la colonne Excel en utilisant pandas
----> 6 df = pd.read_excel("Output_Summarization/OUTPUT_ocr_OPENAIGOOD.xlsx", usecols="Open_AI_Text")
7
8 # itérer sur chaque ligne de la colonne
/usr/local/lib64/python3.6/site-packages/pandas/util/_decorators.py in wrapper(*args, **kwargs)
294 )
295 warnings.warn(msg, FutureWarning, stacklevel=stacklevel)
--> 296 return func(*args, **kwargs)
297
298 return wrapper
/usr/local/lib64/python3.6/site-packages/pandas/io/excel/_base.py in read_excel(io, sheet_name, header, names, index_col, usecols, squeeze, dtype, engine, converters, true_values, false_values, skiprows, nrows, na_values, keep_default_na, na_filter, verbose, parse_dates, date_parser, thousands, comment, skipfooter, convert_float, mangle_dupe_cols)
332 skipfooter=skipfooter,
333 convert_float=convert_float,
--> 334 mangle_dupe_cols=mangle_dupe_cols,
335 )
336
/usr/local/lib64/python3.6/site-packages/pandas/io/excel/_base.py in parse(self, sheet_name, header, names, index_col, usecols, squeeze, converters, true_values, false_values, skiprows, nrows, na_values, parse_dates, date_parser, thousands, comment, skipfooter, convert_float, mangle_dupe_cols, **kwds)
924 convert_float=convert_float,
925 mangle_dupe_cols=mangle_dupe_cols,
--> 926 **kwds,
927 )
928
/usr/local/lib64/python3.6/site-packages/pandas/io/excel/_base.py in parse(self, sheet_name, header, names, index_col, usecols, squeeze, dtype, true_values, false_values, skiprows, nrows, na_values, verbose, parse_dates, date_parser, thousands, comment, skipfooter, convert_float, mangle_dupe_cols, **kwds)
442
443 data = self.get_sheet_data(sheet, convert_float)
--> 444 usecols = _maybe_convert_usecols(usecols)
445
446 if not data:
/usr/local/lib64/python3.6/site-packages/pandas/io/excel/_util.py in _maybe_convert_usecols(usecols)
146
147 if isinstance(usecols, str):
--> 148 return _range2cols(usecols)
149
150 return usecols
/usr/local/lib64/python3.6/site-packages/pandas/io/excel/_util.py in _range2cols(areas)
117 cols.extend(range(_excel2num(rng[0]), _excel2num(rng[1]) + 1))
118 else:
--> 119 cols.append(_excel2num(rng))
120
121 return cols
/usr/local/lib64/python3.6/site-packages/pandas/io/excel/_util.py in _excel2num(x)
82
83 if cp < ord("A") or cp > ord("Z"):
---> 84 raise ValueError(f"Invalid column name: {x}")
85
86 index = index * 26 + cp - ord("A") + 1
ValueError: Invalid column name: Open_AI_Text
I tried to just use df[Open_AI_Text] as df but then this problem appeared :
AttributeError Traceback (most recent call last)
<ipython-input-48-17e13b68c999> in <module>
9
10 # itérer sur chaque ligne de la colonne
---> 11 for index, row in df.iterrows():
12 # tokeniser le texte de la ligne en mots individuels
13 words = word_tokenize(row["Open_AI_Text"])
/usr/local/lib64/python3.6/site-packages/pandas/core/generic.py in __getattr__(self, name)
5137 if self._info_axis._can_hold_identifiers_and_holds_name(name):
5138 return self[name]
-> 5139 return object.__getattribute__(self, name)
5140
5141 def __setattr__(self, name: str, value) -> None:
AttributeError: 'Series' object has no attribute 'iterrows'
Sorry again, I'm a total beginner in an internship
A: You’re using the wrong kind of value for the usecols attribute. Check the documentation:
usecols: str, list-like, or callable, default None
If None, then parse all columns.
If str, then indicates comma separated list of Excel column letters and column ranges (e.g. “A:E” or “A,C,E:F”). Ranges are inclusive of both sides.
If list of int, then indicates list of column numbers to be parsed (0-indexed).
If list of string, then indicates list of column names to be parsed.
If callable, then evaluate each column name against it and parse the column if the callable returns True.
Returns a subset of the columns according to behavior above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74951273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Angular 2 Component Library I am trying to create a component library that I can share with anyone via npm. I am building my component lib with webpack. When I try to install my component lib into an Angular 2 project's module, the project's module does not recognize the name of my component lib module.
In my App I do this...
import '@angular/core';
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
//it says it does not recognize the module name, I installed it via npm i bt-module.
import {BarChartComponent} from "BTModule";
@NgModule({
imports: [
BrowserModule,
BTModule
],
declarations: [
AppComponent
],
bootstrap: [AppComponent]
})
export class App {
}
I have the following folder structure for my component lib...
bt-module
|_______src
| |____barchart
| | |____barchart.component.ts
| | |____barchart.styles.scss
| |____bt.module.ts
| |____index.ts
|_______package.json
|_______tsconfig.json
|_______webpack.config.js
My barchart.component.ts is like this...
import {Component, OnInit, ViewChild, ElementRef, Input} from "@angular/core";
import * as d3 from 'd3'
@Component({
selector: 'bar-chart',
styles: [
require('./barchart.styles').toString()
],
template: '<div #barchart class="chart box"></div>'
})
export class BarChartComponent implements OnInit {
@Input('data') data: Array<any>;
@ViewChild('barchart') barchart: ElementRef;
constructor() {
}
ngOnInit() {
//barchart code here...
}
}
My bt.module.ts looks like this...
import '@angular/core';
import {NgModule, ModuleWithProviders} from '@angular/core';
import {BarChartComponent} from "./barchart/barchart.component";
@NgModule({
declarations: [
BarChartComponent
],
exports: [
BarChartComponent
]
})
export class BTModule {
}
My index.ts looks like this...
export * from './barchart/barchart.component'
export * from './avs.module';
My tsconfig.json looks like this...
{
"compilerOptions": {
"declaration": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [
"es6",
"es2015",
"dom"
],
"noImplicitAny": false,
"target": "es5",
"module": "es2015",
"moduleResolution": "node",
"sourceMap": true,
"mapRoot": "",
"outDir": "./release",
"skipLibCheck": true,
"suppressImplicitAnyIndexErrors": true,
"baseUrl": "",
"types": [
"node"
],
"typeRoots": [
"node_modules/@types"
]
},
"compileOnSave": true,
"exclude": [
"node_modules/*",
"**/*-aot.ts"
],
"angularCompilerOptions": {
"skipTemplateCodegen": true,
"debug": true
}
}
Any ideas? What am I missing? I have read many blogs and tutorials (which are all with older versions of angular) and I can't seem to make it work. This is one of the articles I have tried: http://www.dzurico.com/how-to-create-an-angular-library apperantly there is a difference between AOT and NON-AOT, no luck.
A: Make sure the package.json for your library includes the main field (see https://docs.npmjs.com/files/package.json#main), which should be the transpiled .js file that has your module in it.
I created a component library using https://github.com/flauc/angular2-generator and was able to get it to work.
Also, here's an excellent example of creating a component library using the Angular CLI: See https://github.com/nsmolenskii/ng-demo-lib and https://github.com/nsmolenskii/ng-demo-app.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41172357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Have a few questions about caches and cache hits/misses This is a homework problem, but the homework was already due and we were already given the answers, I just have no idea how they actually came up with these answers.
It relates to caches, and I'm just getting a lot of concepts mixed up.
Here is the question:
For a direct-mapped cache design with a 32-bit address, the following bits of the
address are used to access the cache.
From my understanding, the index bits determine which block in the cache a particular location in memory is mapped to. The lowest log(base2) bits off the address determine the cache block, and here there are 5 index bits, so I know that there will be a total of 2^5 blocks in the cache, or 32.
What is the cache block size (in words)?
According to the answers given to us, the cache block size is 8. According to some notes given to us by our TA, the block size is 2^(# of offset bits), which in this case would be 5. However, that gives me as an answer 32, so I do not know where the 8 is coming from. Furthermore, nowhere in this book is the term "offset bits" defined, so can somebody tell me exactly what this means?
**What I'm thinking here is that since the same memory address is never referenced twice, there should be NO hits, since the cache will never already have the data it is looking for within the cache. However, according to the answers, the hit ratio should be .25, so once again I guess I'm not understanding what is going.
Finally, for the last question it says the answer is as follows:
<000001, 0001, mem[1024]>
<000001, 0011, mem[16]>
<001011, 0000, mem[176]>
<001000, 0010, mem[2176]>
<001110, 0000, mem[224]>
<001010, 0000, mem[160]>
Which contains some memory addresses (176, 2176) that weren't even in the original question, so by this point I completely lost about everything. Can somebody help clear some of these things up for me?**
A: In the example the cache block size is 32 bytes, i.e., byte-addressing is being used; with four-byte words, this is 8 words.
Since an entire block is loaded into cache on a miss and the block size is 32 bytes, to get the index one first divides the address by 32 to find the block number in memory. The block number modulo 32 (5-bit index) is the index. The block number divided by 32 is the tag. The trace would look like this:
0 miss <00000, 0000, mem[0..31]>
4 hit <00000, 0000, mem[0..31]>
16 hit <00000, 0000, mem[0..31]>
132 miss <00100, 0000, mem[128..159]>
232 miss <00111, 0000, mem[224..255]>
160 miss <00101, 0000, mem[160..191]>
1024 miss <00000, 0001, mem[1024..1055]>
30 miss <00000, 0000, mem[0..31]>
140 hit <00100, 0000, mem[128..159]>
3100 miss <00000, 0011, mem[3072..3103]>
180 hit <00101, 0000, mem[160..191]>
2180 miss <00100, 0010, mem[2176..2207]>
As you can see there are four hits out of 12 accesses, so the hit rate should be 33%. (It looks like the provider of the answer thought there were 16 accesses.)
Side comment: Since this is starting from an empty cache, there is only one conflict miss (the mem[30] access) and the remaining seven misses are compulsory (first access) misses. However, if this was the body of a loop, in each iteration after the first there would be four conflict misses at index 00000 (address 0, 1024, 30, 3100), two conflict misses at 00100 (addresses 132, 2180), and six hits (addresses 4, 16, 140 are hits whose cache blocks have been reloaded in each iteration, corresponding to conflict misses; addresses 232, 160, 180 are hits whose cache blocks were loaded in the first iteration and not evicted).
Running through this trace, one can find that at the end the following blocks would be valid (being the last accessed for their index):
<00000, 0011, mem[3072..3103]>
<00100, 0010, mem[2176..2207]>
<00101, 0000, mem[160..191]>
<00111, 0000, mem[224..255]>
Note how this differs from the given answer which is clearly wrong because with 32-byte blocks, no block would start at mem[16] and 1024 divided by 32 gives a block number (in memory) of 32, 32 modulo 32 is 0 (not 1) for the index.
Incidentally, providing the byte range cached in the block is probably more helpful than just providing the starting address of the block.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23331910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to add concatenation to transfer learning?
I'm using transfer learning for semantic segmentation.
model=vgg(weights="imagenet")
new_model=Sequential()
for l,n in model.layers:
new_model.add(l)
if(n==18): break
#Upsampling
m1=model.layers[-1].output
new_model.add(Conv2DTranspose(512,(3,3),strides=(2,2),
padding="same"))
m2=new_model.layers[-1].output
concatenate1=concatenate(m1,m2)
Till this step it works fine. Now how can I add this concatenation to the network.
new_model.layers[-1].output=concatenate1.output
new_model.layers[-1].output=concatenate1
# these are wrong
A: You can directly use the functional version of keras that will be easier for you.
You will simply use all the layers to n = 18 and that output will connect to m1.
Finally, you create the model. The code would be the following:
model = vgg(weights="imagenet")
input_ = model.input
for l, n in model.layers:
if n == 18:
last_layer = l
break
#Upsampling
m1 = last_layer
m2 = Conv2DTranspose(512, (3, 3), strides=(2, 2), padding="same")(m1)
concatenate1 = Concatenate(axis=-1)(m1, m2)
new_model = Model(inputs=input_, outputs=concatenate1)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54525351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Bash - Convert comma separated list I'm trying to write a script that works on a list of files. If I want to work on all files in the same directory then
FILES=*.ext
for i in $FILES; do
something on "$i"
done
works OK, the problem comes when I want to work on just a selection of files and not everything. How do I convert a comma separated list of files, which may or may not contain spaces into the same format, so that I can store it in $FILES and use the same code?
Many thanks, in advance
David Shaw
A: The correct thing to do is not use a delimited list of filenames but use an array (and avoid uppercase variable names), this will avoid the problem of filenames containing your separator (e.g. ,) and is the idiomatic approach:
files=( *foo*.ext1 *bar*.ext2 file1 "file 2 with a space" )
for file in "${files[@]}"; do
[ -e "${file}" ] || continue
do_something_with "${file}"
done
Unless you have no control over how $files is populated this is what you want, if your script gets fed a comma-separated list and you absolutely cannot avoid it then you can set IFS accordingly as in @BroSlow's answer.
Since globbing does the right thing when expanding filenames with spaces are not a problem (not even in your example).
You might also want to check extended globbing (extglob) to be able to match more specifically.
A: If I am interpreting your question correctly you can just the internal field separator (IFS) in bash to comma and then have word-splitting take care of the rest, e.g.
#!/bin/bash
FILES="file1,file2 with space,file3,file4 with space"
IFS=','
for i in $FILES; do
echo "File = [$i]"
done
Which would output
File = [file1]
File = [file2 with space]
File = [file3]
File = [file4 with space]
Note, as Adrian Frühwirth pointed out in comments, this will fail if the filenames can contain commas.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22742221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to restore trash mails to original folder in Microsoft Graph API? I have tried this https://graph.microsoft.com/v1.0/me/mailFolders/deleteditems/{messageId}/restore but getting 400 Bad request.
A: As Glen said here there is no method to directly restore trash mails through Graph API. Please raise a feature request for this in the Microsoft Graph Feedback Forum so that the product team could implement it in the future.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64171975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: AlarmManager canceled when app closed but ok after reboot I've an issue with an Alarm Manager. I wan't to execute my service each hour.
Alarm Manager is launched after reboot and work well, even if the app is not open or open and closed (My PhoneStartReceiver call launchBackgroundService one time, after a completed boot).
My problem is when I launch application after installation, without phone reboot. In this case, AlarmManager is killed when application is force closed or destroyed.
Problem is juste between installation, and next reboot. How to maintain AlarmManager enabled until next reboot ?
<receiver
android:name=".helpers.PeriodicalServiceCaller"
android:process=":remote"/>
<receiver
android:name=".helpers.PhoneStartReceiver"
android:process=":remote">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
Here is my launchBackgroundServiceMethod, called in the both cases.
public static void launchBackgroundService(){
// Construct an intent that will execute the PeriodicalServiceCalle
Intent intent = new Intent(getApplicationContext(), PeriodicalServiceCaller.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(getApplicationContext(), PeriodicalServiceCaller.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every minute
long firstMillis = System.currentTimeMillis(); // alarm is set right away
AlarmManager alarm = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
// First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis, 1000L, pIntent);
}
PeriodicallServiceCaller code
public class PeriodicalServiceCaller extends BroadcastReceiver {
public static final int REQUEST_CODE = 12345;
// Triggered by the Alarm periodically (starts the service to run task)
@Override
public void onReceive(Context context, Intent intent) {
Log.i("START-SERVICE", "PeriodicalServiceCaller");
Intent i = new Intent(context, MonitorDataService.class);
context.startService(i);
}
EDIT
My launchBackgroundService is launch by an Acitivity if it's after install and by PhoneStartReceiver if it's after a reboot
A: You need to register a BroadcastReceiver to detect when your are has been updated.
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
</intent-filter>
</receiver>
Take a look at
How to know my Android application has been upgraded in order to reset an alarm?
A: Is launchBackgroundService in a service or run from the activity? If it is run from the service please check this answer Background Service getting killed in android
START_STICKY was the thing I missed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39725715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: php & mysql syntax errors: possibly string? Having a problem with some code and string handling
Syntax error, unexpected end of file...
Can someone help?
<?php
require("common.php");
if(empty($_SESSION['user']))
{
header("Location: login.php");
die("Redirecting to login.php");
}
$query = "
SELECT
id,
username,
email,
gold
FROM users
";
try
{
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
mysqli_query($con,"UPDATE users SET gold = gold + 10
WHERE username= '".$_SESSION['user']['username']."');
header('Location: quests.php');
die();
?>
A: You forgot to close the quoted string:
mysqli_query($con,"UPDATE users SET gold = gold + 10
WHERE username= '".$_SESSION['user']['username']."'");
A: mysqli_query($con,"UPDATE users SET gold = gold + 10 WHERE username= '".$_SESSION['user']['username']."');
You have forgotten to close the quote "
Should be like this:
mysqli_query($con,"UPDATE users SET gold = gold + 10 WHERE username= '".$_SESSION['user']['username']."'");
A: You're missing a closing " on your mysqli_query line:
."');
needs to be
."'");
If your editor doesn't make this very obvious with syntax hilighting, you should use a different editor.
A: Instead of
mysqli_query($con,"UPDATE users SET gold = gold + 10
WHERE username= '".$_SESSION['user']['username']."');
use
mysqli_query($con,"UPDATE users SET gold = gold + 10
WHERE username= '".$_SESSION['user']['username']."'");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22358282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Accessing hidden operator from parent namespace in C++ I want to intercept the operator << inside a namespace to add some additional formatting to basic types before printing them out. Can this be done?
namespace Foo {
std::ostream& operator<<(std::ostream& os, bool b) {
//Can I call std::operator<< here now. Something like:
// os std::<< (b ? 10 : -10) << std::endl;
}
}
Thanks!
A: You can do it using explicit function call syntax. For your case, the call should be os.operator<<(b ? 10 : -10), because the corresponding operator<< is a member function.
However, with your operator<<, you will no longer be able to use expressions such as std::cout << true in namespace Foo, because this will trigger an ambiguity between your Foo::operator<<(std::ostream&, bool) and std::ostream's member function std::ostream::operator<<(bool): both accept an lvalue of type std::ostream as its left operand, and both accept a value of type bool as its right operand, neither is better than the other.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31468907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Gerrit- Git push Error (n/a (unpacker error)) while pushing to gerrit I'm android developer so I had setted up Gerrit Code Review and Github for my Team! So After lots of struggle i got my github projects added to gerrit and also got replication work, but i'm not able to push this one repo. All other repos get pushed fine.
I cloned my github repo and then added my ssh link of project of gerrit with git remote add * and then I typed git push gerrit HEAD:refs/for/ics but i'm getting some unpack error
Here is the whole log:
keyur@keyur-Inspiron-N4010:~/android_device_lge_p350$ git push gerrit HEAD:refs/for/ics
Counting objects: 7, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (5/5), done.
Writing objects: 100% (5/5), 526 bytes, done.
Total 5 (delta 3), reused 0 (delta 0)
fatal: Unpack error, check server log
remote: Resolving deltas: 100% (3/3)
error: unpack failed: error Missing unknown c605ed77d4a43b8389c7bb544c3a5834cf0f64cf
To ssh://[email protected]:6117/android_device_lge_p350.git
! [remote rejected] HEAD -> refs/for/ics (n/a (unpacker error))
error: failed to push some refs to 'ssh://[email protected]:6117/android_device_lge_p350.git'
keyur@keyur-Inspiron-N4010:~/android_device_lge_p350$
And it fails :( I'm able to commit on any other repos :( but not able to get this one work :(
My config file :
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
url = [email protected]:PecanCM/android_device_lge_p350.git
[branch "cm-10.1"]
remote = origin
merge = refs/heads/cm-10.1
[remote "gerrit"]
url = ssh://[email protected]:6117/android_device_lge_p350.git
fetch = +refs/heads/*:refs/remotes/gerrit/*
[branch "ics"]
remote = origin
merge = refs/heads/ics
My Github repo : https://github.com/PecanCM/android_device_lge_p350
My Gerrit Server : http://review.pecancm.insomnia247.nl
A: If you have access to the gerrit server, check whether you have granted enough permissions to the git folder of your gerrit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14200509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: if I have lists for the values in a dictionary, can I perform a conditional zip on these value lists? I have the following dict that I created :
dct = {'T': [[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 1, 0]], 'B': [[0, 1, 0, 0, 0], [0, 0, 0, 0, 1]], 'J': [[0, 0, 1, 0, 0], [0, 0, 0, 0, 1]], 'K': [0, 0, 0, 0, 1]}
Note that each value is either a single list or multiple lists. I am trying to figure out if I can do a conditional zip on the value lists for each key (or some alternative solution that gives me my desired output). The condition is that I only want the value lists to zip together for a given key if the 1s on consecutive value lists are within a distance of 2 index values from each other.
The final output I want from this input dict should look like this:
zp_dict = {'T': [2, 1, 0, 1, 0], 'B': [[0, 1, 0, 0, 0], [0, 1, 0, 0, 0]], 'J': [0, 0, 1, 0, 1], 'K': [0, 0, 0, 0, 1]}
Notice that the value lists for 'T' and 'J' should be zipped together because the non-zero values are no more than 2 indices apart, but the value lists for 'B' should be kept separate because the non-zero values are 3 indices apart, and the 'K' value list should be left alone.
To illustrate what I'm trying to do, consider the following code that almost does what I want to do, but without the condition:
zp_dict = {}
for k, v in dct.items():
zp_dict[k] = [sum(x) for x in zip(*v)]
This produces the following new dict, which is wrong for key 'B':
zp_dict = { 'T': [2, 1, 0, 1, 0], 'B': [0, 1, 0, 0, 1], 'J': [0, 0, 1, 0, 1], 'K': [0, 0, 0, 0, 1]}
A: This technically achieves the result you are asking for. However, I am assuming you want everything to be added together if at least 2 of the lists have numbers within 2 indexes of each other. For example [[1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 1]] would result in [1, 1, 0, 0, 1] NOT [[1, 1, 0, 0, 0], [0, 0, 0, 0, 1]] despite the last list having its number more than 2 indexes away from any other list.
The code sums the lists together, then finds how far apart the first 2 non-zero number are. If they are <= 2 indexes apart, then the summed list is added to zp_dict, else the list of lists (v) remains unchanged, and added to the zp_dict
The code is on OnlineGDB, if you want to tinker with it
Note: I assumed 'K' in the dct you provided had a typo, in that it was supposed to be a list within a list (like the others) - if not, sum(x) for x in zip(*v) would break. If not, it doesn't take much to fix - just validate the number of lists in v.
dct = {
'T': [[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 0, 1, 0]],
'B': [[0, 1, 0, 0, 0], [0, 0, 0, 0, 1]],
'J': [[0, 0, 1, 0, 0], [0, 0, 0, 0, 1]],
'K': [[0, 0, 0, 0, 1]]
}
zp_dict = {}
for k, v in dct.items():
sum_list = [sum(x) for x in zip(*v)]
first_non_zero = next((i for i, n in enumerate(sum_list) if n), 0)
second_non_zero = next((i for i, n in enumerate(sum_list[first_non_zero+1:]) if n), 0)
zp_dict[k] = sum_list if second_non_zero < 2 else v
print(zp_dict)
>>{'T': [2, 1, 0, 1, 0], 'B': [[0, 1, 0, 0, 0], [0, 0, 0, 0, 1]], 'J': [0, 0, 1, 0, 1], 'K',: [0, 0, 0, 0, 1]}
EDIT:
You can also add if statements (with functions inline), if that is what you were looking for.
zp_dict[k] = [sum(x) for x in zip(*v) if conditionTest(v)]
If the conditionTest returns True, it would add the lists together. Although if you were fine with adding functions, I would clean it up and just add the for loop into the function:
zp_dict[k] = sumFunction(v)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50869367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: VBA Code to loop and save as PDF: keep value in first cell, renaming cells beneath I am having trouble writing a loop macro for a Client report. The main column that needs to be changed is column A, essentially a list of Client names. I am trying to have the following be looped:
*
*Starting with the first cell in column A, I would like the loop to keep the name, but rename the cells below it, respetively. I.e. A2 = Bob, A3= Jane, A4 = Tom..I want to keep "Bob" as A2, but rename jane as "Client 2", Tom as "Cient 3"
*Save as PDF to a location, with the PDF having "2022 Report_name" in the PDF name, i.e. "2022 Report_Bob"
*Loop it, so it restarts until everyone in column A has a PDF, but I would like to ensure that the names that already have a a PDF are renamed. I.e. For Jane's file (ideal second PDF), the cell that has "Bob" would be renamed as "Client 1".
Mainly just want to ensure that all the PDFs have only the client's name showing, while the others are renamed to "Client 1, 2"..etc.
Hoping you could assist me.
Thank you in advance! :)
As of now, I only have the save to PDF part:
Sub Report()
'Defining worksheets
Dim ClientSheet As Worksheet
Set ClientSheet = ActiveWorkbook.Sheets("Client")
Application.ScreenUpdating = False
'Looping the through each row
For i = 2 To 43
'Assigning values
SName = ClientSheet.Cells(i, 1)
'Save the PDF file
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
Filename:="\\! Routine Reports\Client\" & SName, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Next i
Application.ScreenUpdating = True
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74394431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Looking for a certain phrase in pandas column I am trying to look for a certain phrase in pandas column using this code:
workfromhome = df.loc[df['Description'].str.contains("work from home",na=False)]
df['Work From Home'] = workfromhome
here is the description column:
About AgodaAgoda is an online travel booking p...
1 DescriptionWe are looking for an experienced B...
2 Key Responsibilities and Accountabilities To w...
3 About AgodaAgoda is an online travel booking p...
4 Data entry InternshipResponsible for adding ne...
5 Siemens EDA is a global technology powerhouse....
6 Job DescriptionThis is a remote position.Excep...
7 Curenta is changing the shape of long-term hea...
8 Job RequirementsBachelors Degree in Computer S...
9 Where You’ll Work Andela is a network of techn...
10 QualificationsPostgraduate, master’s degree or...
11 متاح طوال ايام العمل يقبل العمل بعد فترة الدوا...
12 About The JobYou’re looking for fulfillment, w...
13 About AgodaAgoda is an online travel booking p...
14 Ready to tackle the challenges of the vehicle ...
15 About AgodaAgoda is an online travel booking p...
16 Siemens EDA is a global technology powerhouse....
17 About AgodaAgoda is an online travel booking p...
18 IGNITION is a 12 months program designed to gi...
19 Management Trainee ProgramRotational program f...
20 Siemens EDA is a global technology powerhouse....
21 Siemens EDA is a global technology powerhouse....
22 Votre Mission Chez CegedimWe are looking for a...
23 About AgodaAgoda is an online travel booking p...
24 Votre Mission Chez CegedimWe are looking for a...
25 RequirementsBachelor's degree in Computer Scie...
26 DescriptionWe are looking for an iOS developer...
27 Designs, develops and executes all testing-rel...
28 About AgodaAgoda is an online travel booking p...
29 Auto req ID: 247864BRJob DescriptionDevelop an...
30 Job DescriptionABOUT THIS JOB A Reporting Offi...
31 About AgodaAgoda is an online travel booking p...
32 Job DescriptionProvide technical mentor ship a...
33 About AgodaAgoda is an online travel booking p...
34 Job briefWe are looking for a Java Developer w...
35 About The JobJob DescriptionTo be responsible ...
36 يكون لدية الخبرة فى ادارة وتطوير الشركات Show ...
37 Job ScopeThe job scope covers the execution of...
38 About GemographyJoin Gemography and work direc...
39 About This JobJob DescriptionA Reporting Offic...
40 Job DescriptionVotre mission chez Cegedim :Ove...
41 Essential Job FunctionsResponsibilitiesContrib...
42 DescriptionWe are looking for a Full Stack Dev...
43 DescriptionWe are looking for a passionate Dat...
44 Auto req ID: 248881BRRoleJob DescriptionThe HR...
45 1 Bachelors or diploma in computer engineering...
46 DescriptionWhat are we looking for?We are look...
47 Requirements• Development experience of 8 year...
48 DescriptionWe are looking for Devops engineers...
49 DescriptionSouq.com, an Amazon.com Company, is...
50 Siemens EDA is a global technology powerhouse....
51 ResponsibilitiesParticipates as a member of a ...
52 About AgodaAgoda is an online travel booking p...
53 About AgodaAgoda is an online travel booking p...
54 The ideal candidate will be responsible for cr...
55 DescriptionOLX is on the hunt for an experienc...
56 Siemens EDA is a global technology powerhouse....
57 We are hiring a Senior Backend Developer who m...
58 Company Name:Elsewedy Electric - ISKRAEMECODep...
59 DescriptionSouq.com, an Amazon.com Company, is...
60 Votre Mission Chez CegedimAs a Tester you will...
now when I was looking for the social insurance using the same exact code! it worked no problem! but now when I look for medical insurance or work from home! it returns this error:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2645 try:
-> 2646 return self._engine.get_loc(key)
2647 except KeyError:
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'Work From Home'
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
~\anaconda3\lib\site-packages\pandas\core\internals\managers.py in set(self, item, value)
1070 try:
-> 1071 loc = self.items.get_loc(item)
1072 except KeyError:
~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2647 except KeyError:
-> 2648 return self._engine.get_loc(self._maybe_cast_indexer(key))
2649 indexer = self.get_indexer([key], method=method, tolerance=tolerance)
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'Work From Home'
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
<ipython-input-448-4f0e407389ac> in <module>
1 #df['Social Insurance'] = df.loc[df['Description'].str.contains("social insurance", case=False,na=False)]
2 workfromhome = df.loc[df['Description'].str.contains("work from home",na=False)]
----> 3 df['Work From Home'] = workfromhome
~\anaconda3\lib\site-packages\pandas\core\frame.py in __setitem__(self, key, value)
2936 else:
2937 # set column
-> 2938 self._set_item(key, value)
2939
2940 def _setitem_slice(self, key, value):
~\anaconda3\lib\site-packages\pandas\core\frame.py in _set_item(self, key, value)
2999 self._ensure_valid_index(value)
3000 value = self._sanitize_column(key, value)
-> 3001 NDFrame._set_item(self, key, value)
3002
3003 # check if we are modifying a copy
~\anaconda3\lib\site-packages\pandas\core\generic.py in _set_item(self, key, value)
3622
3623 def _set_item(self, key, value) -> None:
-> 3624 self._data.set(key, value)
3625 self._clear_item_cache()
3626
~\anaconda3\lib\site-packages\pandas\core\internals\managers.py in set(self, item, value)
1072 except KeyError:
1073 # This item wasn't present, just insert at end
-> 1074 self.insert(len(self.items), item, value)
1075 return
1076
~\anaconda3\lib\site-packages\pandas\core\internals\managers.py in insert(self, loc, item, value, allow_duplicates)
1179 new_axis = self.items.insert(loc, item)
1180
-> 1181 block = make_block(values=value, ndim=self.ndim, placement=slice(loc, loc + 1))
1182
1183 for blkno, count in _fast_count_smallints(self._blknos[loc:]):
~\anaconda3\lib\site-packages\pandas\core\internals\blocks.py in make_block(values, placement, klass, ndim, dtype)
3051 values = DatetimeArray._simple_new(values, dtype=dtype)
3052
-> 3053 return klass(values, ndim=ndim, placement=placement)
3054
3055
~\anaconda3\lib\site-packages\pandas\core\internals\blocks.py in __init__(self, values, placement, ndim)
2599 values = np.array(values, dtype=object)
2600
-> 2601 super().__init__(values, ndim=ndim, placement=placement)
2602
2603 @property
~\anaconda3\lib\site-packages\pandas\core\internals\blocks.py in __init__(self, values, placement, ndim)
122
123 if self._validate_ndim and self.ndim and len(self.mgr_locs) != len(self.values):
--> 124 raise ValueError(
125 f"Wrong number of items passed {len(self.values)}, "
126 f"placement implies {len(self.mgr_locs)}"
ValueError: Wrong number of items passed 21, placement implies 1
Help me extract the information please
A: Try define column Description for return Series in variable workfromhome:
workfromhome = df.loc[df['Description'].str.contains("work from home",na=False), 'Description']
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69249741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: HTML5 section tag meanings? I know there are tons of questions about this topic but I can't find an authoritative source for the answer.
This is the official definition and the wiki page, and there there is more documentation, but there they don't explain the correct usage if not in a very simple examples or in different ways.
What I've "understood" so far:
<section> defines a part(section) of the page, like blogrolls, headlines news, blog entries list, comments list, and everything which can be with a common topic.
<article> defines a content which has sense estranged from the rest of the page (?) and which has a single topic (blog entry, comment, article, etc).
But, inside an <article>, we can split parts of it in sections using <section>, and in this case it has the function of container to mark chapters of a bigger text.
The doubt
If these sentences are correct (or partially correct) that means that <section> has two completly different usage cases.
We could have a page written in this way:
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>Fruits</title>
</head>
<body>
<h1>Fruits war blog</h1>
<section id="headlineNews"> <!-- USED AS CONTAINER -->
<h1>What's new about fruits?</h1>
<article><h1>Apples are the best</h1>Apples are better than bananas</article>
<article><h1>Apple's cakes</h1>With apples you can prepare a cake</article>
</section>
<section id="blogEntries"> <!-- USED AS CONTAINER -->
<h1>Articles about fruits</h1>
<article>
<h1>Apples vs Bananas</h1>
<section> <!-- USED AS CHAPTER -->
<h2>Introduction:</h2>
Bananas have always leaded the world but...
</section>
<section> <!-- USED AS CHAPTER -->
<h2>The question:</h2>
Who is the best? We don't know so much about apples...
</section>
</article>
</section>
</body>
</html>
And this is how looks the Outline:
1. Fruits war blog
1. What's new about fruits?
1. Apples are the best
2. Apple's cakes
2. Articles about fruits
1. Apples vs Bananas
1. Introduction:
2. The question:
So the <section> is thought with two completly different and not related semantic meanings?
Is it correct use:
<!-- MY DOUBT -->
<section> <!-- USED AS CONTAINER -->
<article>
<section></section> <!-- USED AS CHAPTER -->
</article>
</section>
in this neasted way?
I've found that is possible to use in the inversed way:
<!-- FROM W3C -->
<article> <!-- BLOG ENTRY -->
<section> <!-- USED AS CHAPTER ABOUT COMMENTS -->
<article></article> <!-- COMMENT -->
</section>
</article>
But I can't find an answer to the way I've written below.
I guess read the discussion where the W3C group has wrote the basis of the <section> tag could be useful but I can't find it.
N.B. I'm looking for replies documented with authorative sources
A: http://www.w3.org/wiki/HTML/Elements/section is not the official definition of section. section is defined in the HTML5 specification, which currently is a Candidate Recommendation (which is a snapshot of the Editor’s Draft).
In the CR, section is defined as:
The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading.
section is a sectioning content element (together with article, aside and nav). Those sectioning elements and the headings (h1-h6) create an outline.
The following three examples are semantically equivalent (same meaning, same outline):
<!-- example 1: using headings only -->
<h1>My first day</h1>
<p>…</p>
<h2>Waking up</h2>
<p>…</p>
<h2>The big moment!</h2>
<p>…</p>
<h2>Going to bed</h2>
<p>…</p>
<!-- example 1: using section elements with corresponding heading levels -->
<section>
<h1>My first day</h1>
<p>…</p>
<section>
<h2>Waking up</h2>
<p>…</p>
</section>
<section>
<h2>The big moment!</h2>
<p>…</p>
</section>
<section>
<h2>Going to bed</h2>
<p>…</p>
</section>
</section>
<!-- example 1: using section elements with h1 everywhere -->
<section>
<h1>My first day</h1>
<p>…</p>
<section>
<h1>Waking up</h1>
<p>…</p>
</section>
<section>
<h1>The big moment!</h1>
<p>…</p>
</section>
<section>
<h1>Going to bed</h1>
<p>…</p>
</section>
</section>
So you can use section whenever (*) you use h1-h6. And you use section when you need a separate entry in the outline but can’t (or don’t want to) use a heading.
Also note that header and footer always belong to its nearest ancestor sectioning content (or sectioning root, like body, if there is no sectioning element) element. In other words: each section/article/aside/nav element can have its own header/footer.
article, aside and nav are, so to say, more specific variants of the section element.
two completly different usage cases
These two use-cases are not that different at all. In the "container" case, you could say that section represents a chapter of the document, while in the "chapter" case section represents a chapter of the article/content (which, ouf course, is part of the document).
In the same way, some headings are used to title web page parts (like "Navigation", "User menu", "Comments", etc.), and some headings are used to title content ("My first day", "My favorite books", etc.).
A: OK so here is what I've gathered from authorative sources.
MDN:
The HTML Section Element () represents a generic section of a document, i.e., a thematic grouping of content, typically with a heading.
Usage notes :
If it makes sense to separately syndicate the content of a element, use an element instead.
Do not use the element as a generic container; this is what is for, especially when the sectioning is only for styling purposes. A rule of thumb is that a section should logically appear in the outline of a document.
Shay Howe's guide:
A section is more likely to get confused with a div than an article. As a block level element, section is defined to represent a generic document or application section.
The best way to determine when to use a section versus a div is to look at the actual content at hand. If the block of content could exist as a record within a database and isn’t explicitly needed as a CSS styling hook then the section element is most applicable. Sections should be used to break a page up, providing a natural hierarchy, and most commonly will have a proper heading.
dev.opera.com
Basically, the article element is for standalone pieces of content that would make sense outside the context of the current page, and could be syndicated nicely. Such pieces of content include blog posts, a video and it's transcript, a news story, or a single part of a serial story.
The section element, on the other hand is for breaking the content of a page into different functions or subjects areas, or breaking an article or story up into different sections.
A: <article> and <section> are both sectioning content. You can nest one sectioning element inside another to slice up the outer element into sections.
HTML Living Standard, 4.4.11:
...
Sectioning content elements are always considered subsections of their nearest ancestor sectioning root or their nearest ancestor element of sectioning content, whichever is nearest, regardless of what implied sections other headings may have created.
...
You can consider a <section> as a generic sectioning element. It's like a <div> that defines a section within its closest sectioning parent (or the nearest sectioning root, which may be the <body>).
An <article> is also a section, but it does have some semantics. Namely, it represents content that is self-contained (that is, it could possibly be its own page and it'd still make sense).
A: Here's the official w3c take on section:
http://www.w3.org/wiki/HTML/Elements/section
Quote: "The [section] element represents a generic section of a document or application."
I guess, in theory if you have an article within an article then your nested selections example might work. But, why would you have an article within an article ? Makes little semantic sense.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18741090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Red5 java error on startup When I started red5 I got the following error message;
Exception in thread "main" java.lang.ClassNotFoundException: org.red5.server.Launcher
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:249)
at org.red5.server.Bootstrap.bootStrap(Bootstrap.java:115)
at org.red5.server.Bootstrap.main(Bootstrap.java:48)
Please help I need this to start up again quickly.
Running Ubuntu and red5 1.0.0
A: From http://code.google.com/p/red5/wiki/ServerWontStart
ClassNotFoundException Launcher
When the Launcher cannot be located, it usually means the server jar
is missing or misnamed. The Red5 server jar must be named like so
until we fix the bootstrap bug: red5-server-1.0.jar
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22177850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Should there be at least one assert in a unit test? If so, why? If we take for example gtest, we have the option to use asserts like ASSERT_NE or checks like EXPECT_NE. One of my colleagues pointed out that I should have at least one assert in my test preferably the condition which checks the main objective.
So, far I was used to using ASSERTs in places where the continuation of test is useless, and EXPECTs in places where the test could continue.
What is the correct way of using ASSERTs and EXPECTs?
A: The main difference between EXPECT_* and ASSERT_* macros is that assertions stop the test immediately if it failed, while expectations allow it to continue.
Here's what GoogleTest Primer says about it:
Usually EXPECT_* are preferred, as they allow more than one failures to be reported in a test. However, you should use ASSERT_* if it doesn't make sense to continue when the assertion in question fails.
So, to illustrate it:
TEST_F(myTest, test1)
{
uut.doSomething();
ASSERT_EQ(uut.field1, expectedvalue1);
ASSERT_EQ(uut.field2, expectedvalue2);
}
If field1 doesn't match assertion, test fails and you have no idea if field2 is correct or not. This makes debugging much more difficult.
Choice between these options is mostly matter of agreement in your team, but I'd stick to GTest proposition of using EXPECT_* as the backbone of all checks and ASSERT_* only if you test something crucial to continue, without which further part of test doesn't make any sense (for example, if your unit under test was not created correctly).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49384472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to change layer.border.top color? In iOS, how can I change layer.border.top color? If I change self.layer.borderColor, all the side change. But If I only want to change one side, and keep other three sides as is, what should I do?
A: how about adding a new layer?
yourView.clipsToBounds = YES;
CALayer *topBorder = [CALayer layer];
topBorder.borderColor = [UIColor redColor].CGColor;
topBorder.borderWidth = 1;
topBorder.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), 2);
[yourView.layer addSublayer:topBorder];
replace yourView with whatever view is contained in your view controller that you want to add the border to.
Also, this related answer might help you out a bit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31498638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP date validation similar to ASP isDate() for user submitted dates, times, or date/time pairs I am converting an ASP application to PHP and am having difficulty transcribing date validation functionality.
In ASP, I have the function isDate(), which allows me to validate a date regardless of its format. So if someone enters any of the following, isDate() returns true:
1/1/2012
January 1, 2012
Jan 12, 2010 1:00 pm
1/1/2012 1:32 pm
The benefit is that I can let the user enter the data and time in whatever format they choose. After that, with minimal effort, I can update a database without doing any post processing (assuming true is returned). E.g.:
UPDATE my_table SET date_field = @date_var WHERE my_id = @id_var
[note: SQL Server 2008]
With PHP, I’m finding that validating a date/time is more complex. I’ve reviewed the assorted questions posted here as well as the documentation and there doesn’t seem to be a straightforward way to validate a date or time or date/time combination easily.
I’m wondering if there are classes available to do the grunt work. Something that will work like isDate() and send me back a true/false based on a user entered date/time/date & time.
Thanks.
A: You can check the return value of strtotime() to see if a date can be parsed:
if(strtotime($date) !== false) {
// valid date/time
}
This is also how to normalize all the dates, by storing them as the return value of strtotime().
A: Perhaps you could use strtotime()?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8646642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Add and commiting a file into SVN using SVN-Kit jar Actually i want to commit source into svn. I need to add and commit new files into svn repository and am using the below code. Code works properly but not able to commit into SVN
String urls = "http://192.168.0.19/svn/cadgraf/Branch/Jobs";
final String url = urls+File.separator+l_users.getSelectedValue().toString()+File.separator+"Active";
System.out.println("svn url------>"+url);
final String destPath = "/home/dev702/Desktop/Jobs-test/Tempfiles";
SVNRepository repository = null;
setupLibrary();
try {
//initiate the reporitory from the url
repository = SVNRepositoryFactory.create(SVNURL.parseURIDecoded(url));
//create authentication data
ISVNAuthenticationManager authManager =
SVNWCUtil.createDefaultAuthenticationManager("xxxxxx", "xxxxxx");
repository.setAuthenticationManager(authManager);
//output some data to verify connection
System.out.println("Repository Root: " + repository.getRepositoryRoot(true));
System.out.println("Repository UUID: " + repository.getRepositoryUUID(true));
//need to identify latest revision
long latestRevision = repository.getLatestRevision();
System.out.println("Repository Latest Revision: " + latestRevision);
//create client manager and set authentication
SVNClientManager ourClientManager = SVNClientManager.newInstance();
ourClientManager.setAuthenticationManager(authManager);
//use SVNUpdateClient to do the export
SVNCommitClient commitClient = ourClientManager.getCommitClient();
commitClient.setIgnoreExternals(false);
commitClient.doCommit(new File[]{new File(destPath)}, false, "Commit message", null, null, false, false, SVNDepth.INFINITY);
SVNCommitClient client = new SVNCommitClient(authManager, null);
SVNCommitInfo info;
info = client.doCommit( new File[]{new File(destPath)}, false, "Commit message", null, null, false, false, SVNDepth.INFINITY);
} catch (SVNException e) {
e.printStackTrace();
} finally {
System.out.println("Done");
}
code works fine but its not commiting files into SVN.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22035383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mysql crate conn.query multi-statement SQL query not returning QueryResult I'm using the mysql crate, to perform a multi-statement SQL query (put a record into a table) and return a value with a select statement. However the QueryResult returned is None. Performing this on a mysql terminal the statement works fine.
let mut row_iter = self
.pool
.get_conn()
.unwrap()
.query(format!(
r#"
SET @next_j_id = (SELECT IFNULL(MAX(j_id), 0) + 1 FROM people);
INSERT INTO people (j_id, name, email)
VALUES (@next_j_id, "{name}", "{email}");
SELECT @next_j_id;
"#,
username = &name,
email = &email
))
.unwrap();
let row_option = row_iter.next();
match row_option {
Some(result_row) => {
let row = result_row.unwrap();
let j_id: u64 = row.get("@next_j_id").unwrap();
Ok(j_id)
}
None => {
debug!("Errored");
Err(Error)
}
}
I expect row_option to be Some(j_id), but the actual output is None.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57729460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Testing println output with JUnit I am testing a simple helloWorld class.
package Codewars;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
And I have a test class as follows (based on the answer ):
import static org.junit.jupiter.api.Assertions.*;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class helloWorldTest {
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
@BeforeEach
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
}
@AfterEach
public void restoreStreams() {
System.setOut(originalOut);
}
@Test
void test() {
HelloWorld.main(null);
assertEquals("Hello World\n", outContent.toString());
}
}
It results in failure with error message as follows:
org.opentest4j.AssertionFailedError: expected: <Hello World
> but was: <Hello World
>
at [email protected]/org.junit.jupiter.api.AssertionUtils.fail(AssertionUtils.java:55)
at [email protected]/org.junit.jupiter.api.AssertionUtils.failNotEqual(AssertionUtils.java:62)
...
It seems like the strings are same and still the error is thrown?
Thank you in advance.
A: Make sure that your line separator is equal to \n on your system.
This is not the case on Windows.
To fix the test, modify it to take system-specific separator into account
assertEquals("Hello World" + System.lineSeparator(), outContent.toString());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60336350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Multiple table Set-based insert with identity column in table1 and foreign key in table2 I am writing an Application that imports configuration data from multiple external systems. To decouple the user-data from imported data y am using an intermediate table. The following tables are simplified for the sake of the argument.
*
*table [connection] (generic connection information referenced by other tables not included)
*table [importConfig] (Connection configuration from one of the external systems)
*table [connectionImportConfig] (intermediate table, linking [connection] and [importConfig]
For each connection in [importConfig] I want to create a row in [connection] with an identity column. Then I want to insert the new IDs from [connection] together with the identifier from [importConfig] in [connectionImportConfig].
Constraint: I don't want to use a cursor. Must be a set-based solution.
The examples I have found on stackoverflow are either not set-based or I found them not applicable for other reasons.
*
*T-SQL Insert into multiple linked tables using a condition and without using a cursor (not valid for multiple rows, using @@IDENTITY)
*How to perform INSERT/UPDATE to Linking (Join) table which has FKs to IDENTITY PKs (not valid for multiple rows. Not telling how to join the identity values with the original data I want to insert)
I have tried a lot and am stuck at the point where I have to insert the new IDs into connectionImportConfig
-- Test tables&data (stripped down version)
CREATE TABLE connection (ConnectionID int identity(1,1) NOT NULL, comment nvarchar(max) null)
CREATE TABLE connectionImportConfig(connectionID int NOT NULL, ConfigCode nvarchar(50) NOT NULL)
CREATE TABLE importConfig (ConfigCode nvarchar(50) NOT NULL)
DECLARE @MyConnection table (ConnectionID int not null);
insert into importConfig values ('a')
insert into importConfig values ('b')
insert into importConfig values ('c')
-- Insert into PK-table creating the IDs
INSERT INTO connection (comment)
OUTPUT INSERTED.ConnectionID INTO @MyConnection
SELECT * from importConfig
-- How do I insert the new IDs together with the ConfigCode? 1 has to be replaced with the ID.
-- JOIN doesn't seem to work because there is no join condition to use
INSERT INTO connectionImportConfig (connectionID, ConfigCode)
SELECT 1, ConfigCode FROM ImportConfig
select * from @MyConnection
select * from connectionImportConfig
-- Cleanup
DROP TABLE importConfig;
DROP TABLE connection;
DROP table connectionImportConfig;
A: Have a look at this. I am sure you could loosely modify this to your needs. I don't typically like inserting right off the output but it really depends on your data. Hope this example helps.
IF OBJECT_ID('tempdb..#ImportConfig') IS NOT NULL DROP TABLE #ImportConfig
IF OBJECT_ID('tempdb..#Config') IS NOT NULL DROP TABLE #Config
IF OBJECT_ID('tempdb..#Connection') IS NOT NULL DROP TABLE #Connection
GO
CREATE TABLE #ImportConfig (ImportConfigID INT PRIMARY KEY IDENTITY(1000,1), ImportConfigMeta VARCHAR(25))
CREATE TABLE #Config (ConfigID INT PRIMARY KEY IDENTITY(2000,1), ImportConfigID INT, ConfigMeta VARCHAR(25))
CREATE TABLE #Connection (ConnectionID INT PRIMARY KEY IDENTITY(3000,1), ConfigID INT, ConnectionString VARCHAR(50))
INSERT INTO #ImportConfig (ImportConfigMeta) VALUES
('IMPORT_ConfigMeta1'),('IMPORT_ConfigMeta2')
;MERGE
INTO #Config AS T
USING #ImportConfig AS S
ON T.ConfigID = S.ImportConfigID
WHEN NOT MATCHED THEN
INSERT (ImportConfigID, ConfigMeta) VALUES (
S.ImportConfigID,
REPLACE(S.ImportConfigMeta,'IMPORT_','')
)
OUTPUT INSERTED.ConfigID, 'CONNECTION_STRING: ' + INSERTED.ConfigMeta INTO #Connection;
SELECT 'IMPORT CONFIG' AS TableName, * FROM #ImportConfig
SELECT 'CONFIG' AS TableName, * FROM #Config
SELECT 'CONNECTION' AS TableName, * FROM #Connection
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26608539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Add custom key in fetched JSON I am making simple blog website in React and when I fetch posts I am getting user id, who posted it. with this id I am making another axios where I get user with given id and then I assign author key to my fetched posts JSON like this:
export const getPosts = async () => {
try {
const { data } = await axios.get(
"https://jsonplaceholder.typicode.com/posts"
);
for (const item of data) {
let user = await getUser(item["userId"]);
item["author"] = user.username;
}
return data;
} catch (err) {
toast.error(err.message);
}
};
export const getUser = async (id) => {
try {
const response = await axios.get(
"https://jsonplaceholder.typicode.com/users/" + id
);
return response.data;
} catch (err) {
toast.error(err.message);
}
};
This method causes 5-10 seconds delay to display posts. I am searching for faster and simpler way to display username to every post.
U also can tell me if there is better way to fetch data and display it.
Thanks!
A: You have done it the exact right way if there is no other endpoint available to fetch multiple post author information at a time.
Well, this is meant to be an answer, but I'd start with a question.
Do you have access to the maintainer or developer handling the Restful API endpoint you are trying to get from?
If yes?
Tell them to simply include the author information on the response for fetching the post(s)
Or simply provide you with an endpoint that allows you to get author information for many posts at a time.
If No
Go over the documentation provided (if any) and see if there is any endpoint that allows you to fetch author information for multiple posts with a single request.
If none of the above option seems to be a way, kindly remember to block the UI When fetching the resources.
You can also fetch for few authors first and display while fetching for more in the background or on request for more by user, that way you would give a better user experience.
Happy hacking and coding
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65511701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I extract a single byte from within a string on iPhone? In Android, I can extract a single byte from within a string using code like the following:
byte[] arrByte = String.getBytes(); .
If I wanted to do this on the iPhone in Objective-C, how could I accomplish the same task? Additionally, how could I get a byte for a given index in the string?
A: If you take a look at the NSString reference you will get various methods to get the data from a string. An example is
NSData *bytes = [yourString dataUsingEncoding:NSUTF8StringEncoding];
You can also make use of the method UTF8String
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7401070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Dropdown menu showing total; need it to show the selected items I have a script that shows total price for each option in dropdown menu. Now I need to show the name of selected menu with the total.
You will find the script below that shows the total price. I need it to show the name in the <option>.
Any idea how to modify this to show the name of each dropdown selected?
//<![CDATA[
$(function() {
$("#type").on("change", function() {
$("select.calculate option").eq(0).prop('selected', true);
calc();
});
$("select.calculate").on("change", calc);
$("input[type=checkbox].calculate").on("click", calc);
function calc() {
var basePrice = 0;
newPrice = basePrice;
$("select.calculate option:selected,input[type=checkbox].calculate:checked").each(function(idx, el) {
newPrice += parseInt($(el).data('price'), 10);
});
newPrice = newPrice.toFixed(2);
$("#item-price").html(newPrice);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="type" name="buyer" class="form-control input-lg form-el">
<option value="">Service Needed</option>
<option value="kite">Car Wash & Detailing</option>
<option value="user">Mechanic visit</option>
<option value="elect">Electrican visit</option>
<option value="tyre">Tyre Service</option>
<option value="bat">Battery Service</option>
</select>
<div style='display:none; ' id='business'>
<select id="type2" name="buyername" class="form-control input-lg form-el calculate">
<option data-price="0" value="">-- Select --</option>
<option data-price="100" value="kite1">Car Wash exterior</option>
<option data-price="150" value="kite1">Car Wash In & Out</option>
<option data-price="1000" value="kite2">Full Detailing</option>
</select>
</div>
<div style='display:none; ' id='tyrem'>
<select id="type2" name="tyrem" class="form-control input-lg form-el calculate">
<option data-price="0" value="">-- Select --</option>
<option data-price="100" value="kite1">Road tyre problem rescue</option>
<option data-price="50" value="kite1">4 Tyre pressure check and adjust</option>
<option data-price="100" value="kite2">tyre 1 plug repair</option>
</select>
</div>
<div style='display:none; ' id='batm'>
<select id="type2" name="batm" class="form-control input-lg form-el calculate">
<option data-price="0" value="">-- Select --</option>
<option data-price="100" value="kite1">Battery rescue / jump start</option>
<option data-price="150" value="kite2">Battery check , jump start or replace - price depends on battery</option>
</select>
<span id="item-price">0</span>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46719580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add different Quality in a Single video in my website? How can I add different Quality in videos. Do I have to embed it in or or any other tag . I mean I want to open a video website. Now I have to post 720p and 1080p. I have to post them separately. But I want them to be posted at once in same video . The people could change the Quality just by choosing like YouTube. Or Is there anyway I can post 2 separate button. 1. 720p 2. 1080p . By Clicking no. 1 a video will be open in the same page. Then clicking no.2 the other Quality video will open in same place as 720p video and forcing the 720p to be hidden
A: There's no way to downscale video on YouTube manually. YouTube does this automatically, just upload the highest quality you can, and the appropriate lower qualities will be "created" in the quality settings.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54447471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-6"
} |
Q: Will scaling down RDS instance preserve data? I have Amazon Aurora for MySQL t3.db.medium instances. I would like to scale down to t3.db.small.
If I modify the instance settings in AWS console, will my DB data be preserved? So can I scale down without service interruption? I think I should be able to do this, but I just wanna make sure. There is prod instance involved.
I have the same question about Elastic Cache (AWS redis). Can I scale that down without service interruption?
A: According to Docs, there is table(DB instance class) which tells which settings can be changed, you can change your instance class for your aurora, as a note An outage occurs during this change.
For redis
according to docs, you can scale down node type of your redis cluster (version 3.2 or newer). During scale down ElastiCache dynamically resizes your cluster while remaining online and serving requests.
In both the cases your data will be preserved.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67936173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python: last item position So I have a huge string and I process it element by element. I want to know how much is left so I try to take the current position word minus the last position word to see how many are left. I tried something like this:
with codecs.open("C:\\dna_chain.txt",'r', "utf-8") as file:
for line in file:
temp_buffer = line.split()
for i,word in enumerate(temp_buffer):
print(enumerate(temp_buffer[i]))
print(enumerate(temp_buffer[-1]))
I get positions in memory and they are the same.
A: enumerate() returns a generator object; you only printed the representation of the object, then discard it again. The second line then reused the same memory location for a now object.
You can just refer directly to the temp_buffer object without enumerate() here:
for i, word in enumerate(temp_buffer):
print(temp_buffer[i])
print(temp_buffer[-1])
but temp_buffer[i] is the same thing as word in that loop. temp_buffer[-1] is the last word in your list.
If you wanted to know how many more words there are to process, use len(temp_buffer) - i, the length of the temp_buffer list, subtracting the current position.
A: You should count the number of items beforehand:
words = len(temp_buffer)
in your code this would look like
import codecs
with codecs.open("C:\\dna_chain.txt",'r', "utf-8") as file:
for line in file:
temp_buffer = line.split()
words = len(temp_buffer)
for i,word in enumerate(temp_buffer):
print(i, word, words-i-1)
this will print the index i, the word word and the number of remaining items in this row words-i-1.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22147083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.